claude-code-session-manager 0.142.0 → 0.144.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 (162) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +22 -107
  3. package/dist/assets/AppSettings-Z68gQiVE.js +2 -0
  4. package/dist/assets/{History-DpZuJXi1.js → History-C3E6y_7t.js} +2 -2
  5. package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +5 -0
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-CnfWs46Z.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-CP0Wsg-H.js +26 -0
  8. package/dist/assets/Scheduler-D8un7N3B.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-DRtZV1Al.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-Bg5O2Hyn.js} +23 -23
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-BdzoBmqu.js} +27 -27
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-Dt5K1OXt.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-CTLyRgdF.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-B2_KWBga.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-446b69rr.js} +715 -714
  16. package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +438 -435
  20. package/package.json +6 -4
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +23 -16
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +16 -2
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +87 -0
  26. package/scripts/README.md +1 -0
  27. package/scripts/scheduler-mcp-server.cjs +381 -6
  28. package/src/main/adminRouteRegistry.cjs +16 -0
  29. package/src/main/agentLibrary.cjs +60 -11
  30. package/src/main/agentsIpc.cjs +19 -0
  31. package/src/main/build-info.json +4 -4
  32. package/src/main/chatRunner.cjs +214 -7
  33. package/src/main/config.cjs +5 -1
  34. package/src/main/health.cjs +92 -14
  35. package/src/main/index.cjs +16 -4
  36. package/src/main/ipcSchemas.cjs +61 -1
  37. package/src/main/lib/claude/agentArmory.cjs +128 -0
  38. package/src/main/lib/claude/agentModelResolve.cjs +3 -2
  39. package/src/main/lib/claude/agentSnapshot.cjs +24 -3
  40. package/src/main/lib/claude/builtinTools.cjs +110 -0
  41. package/src/main/lib/claude/environmentProfiles.cjs +1 -1
  42. package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
  43. package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
  44. package/src/main/lib/claude/personaToolScope.cjs +77 -6
  45. package/src/main/lib/demo-video-kit/cast.md +10 -1
  46. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  47. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  48. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  49. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  50. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  51. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  52. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  53. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  54. package/src/main/lib/epic/artifactStore.cjs +78 -35
  55. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  56. package/src/main/lib/epic/epicDepsSync.cjs +66 -0
  57. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  58. package/src/main/lib/epic/epicOutsideRead.cjs +38 -1
  59. package/src/main/lib/epic/epicSettle.cjs +48 -4
  60. package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
  61. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  62. package/src/main/lib/epic/epicValidationHook.cjs +22 -3
  63. package/src/main/lib/epic/planReviewInput.cjs +123 -0
  64. package/src/main/lib/epic/restorableSessions.cjs +1 -0
  65. package/src/main/lib/epic/scriptStartedBy.cjs +71 -0
  66. package/src/main/lib/externalContract.cjs +24 -1
  67. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  68. package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
  69. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +24 -2
  70. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  71. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +54 -3
  72. package/src/main/lib/feedback-remote/pendingReplies.cjs +22 -0
  73. package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
  74. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  75. package/src/main/lib/feedback-remote/replyClaims.cjs +168 -0
  76. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +29 -1
  77. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
  78. package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
  79. package/src/main/lib/feedback-remote/servicePairings.cjs +47 -7
  80. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +99 -1
  81. package/src/main/lib/git/gitWorktree.cjs +8 -0
  82. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  83. package/src/main/lib/git/worktreeDeps.cjs +119 -10
  84. package/src/main/lib/mcpToolCatalog.cjs +144 -12
  85. package/src/main/lib/mcpToolsProbe.cjs +19 -2
  86. package/src/main/lib/opsOwnership.cjs +113 -28
  87. package/src/main/lib/packs/packCatalog.cjs +98 -5
  88. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
  89. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  90. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
  91. package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
  92. package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
  93. package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
  94. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
  95. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +140 -0
  96. package/src/main/lib/prd/prdCreate.cjs +395 -229
  97. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  98. package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
  99. package/src/main/lib/prd/prdMcpReachWarnings.cjs +44 -0
  100. package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
  101. package/src/main/lib/process/peerChatSession.cjs +165 -0
  102. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  103. package/src/main/lib/project-pages/videoScriptPress.cjs +266 -0
  104. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +371 -0
  105. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  106. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  107. package/src/main/lib/promptSessionSchema.cjs +2 -0
  108. package/src/main/lib/scheduler/baselineGate.cjs +31 -2
  109. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  110. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  111. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  112. package/src/main/lib/scheduler/planRecordHarvest.cjs +215 -55
  113. package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
  114. package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
  115. package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
  116. package/src/main/lib/scheduler/planReviewStore.cjs +128 -0
  117. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  118. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  119. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  120. package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
  121. package/src/main/lib/scheduler/scheduleJobSchema.cjs +15 -0
  122. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  123. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  124. package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
  125. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  126. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +28 -7
  127. package/src/main/lib/tasks/memoryConsolidation.cjs +123 -39
  128. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  129. package/src/main/lib/tasks/taskAdminRoutes.cjs +104 -17
  130. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  131. package/src/main/lib/tasks/taskRun.cjs +3 -1
  132. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +178 -0
  133. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  134. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  135. package/src/main/lib/util/atomicFs.cjs +2 -2
  136. package/src/main/projectPages.cjs +22 -14
  137. package/src/main/promptSessionEvents.cjs +16 -1
  138. package/src/main/pty.cjs +14 -2
  139. package/src/main/queueOps.cjs +1 -1
  140. package/src/main/runVerify.cjs +4 -3
  141. package/src/main/scheduler/planReviewHold.cjs +140 -0
  142. package/src/main/scheduler/prdParser.cjs +1 -0
  143. package/src/main/scheduler/reviewLadder.cjs +2 -0
  144. package/src/main/scheduler/utilizationHold.cjs +101 -6
  145. package/src/main/scheduler.cjs +1055 -107
  146. package/src/main/seedAgentPersonas.cjs +11 -6
  147. package/src/main/seedStatus.cjs +1 -1
  148. package/src/main/templates/PRD_AUTHORING.md +22 -2
  149. package/src/main/webRemote.cjs +47 -7
  150. package/src/preload/api.d.ts +118 -2
  151. package/src/preload/apiSurface.json +42 -0
  152. package/src/preload/index.cjs +11 -0
  153. package/src/seed/agents/architect.md +28 -43
  154. package/src/seed/agents/demo-video-builder.md +15 -8
  155. package/src/seed/agents/dev-lead.md +3 -1
  156. package/src/seed/agents/md-network-curator.md +27 -0
  157. package/src/seed/agents/plan-reviewer.md +47 -0
  158. package/src/seed/agents/validator.md +21 -19
  159. package/dist/assets/AppSettings-BcZgIvvY.js +0 -2
  160. package/dist/assets/HomeClaudeConfig-D32ZJtU-.js +0 -3
  161. package/dist/assets/ProjectClaudeConfig-BTClYV6i.js +0 -26
  162. package/dist/assets/Scheduler-DPobKx1Z.js +0 -16
@@ -69,6 +69,7 @@ const { headlessPermissionArgs, ensureCliCapsProbed } = require('./lib/claude/cl
69
69
  // as the authoritative guarantee.
70
70
  ensureCliCapsProbed().catch(() => {});
71
71
  const launchFailure = require('./lib/scheduler/launchFailure.cjs');
72
+ const { sandboxLimitFromStreamJson, environmentLimitStamp, ENVIRONMENT_LIMIT_MESSAGE } = require('./lib/scheduler/sandboxEnvironmentLimit.cjs');
72
73
  const { decideVerifyDowngrade } = require('./lib/scheduler/refireCap.cjs');
73
74
  const { finalizeReasonFor } = require('./lib/scheduler/finalizeReason.cjs');
74
75
  const { shouldRunFlatSweep, FLAT_SWEEP_INTERVAL_MS } = require('./lib/scheduler/flatSweepThrottle.cjs');
@@ -130,6 +131,7 @@ const { buildReviewNotice, selectDueReviewNotices, formatReviewNotice, holdMsFro
130
131
  const { phaseOfJob } = require('./lib/phaseProjection.cjs');
131
132
  const epicValidationHook = require('./lib/epic/epicValidationHook.cjs');
132
133
  const prdCreate = require('./lib/prd/prdCreate.cjs');
134
+ const { mcpReachWarnings } = require('./lib/prd/prdMcpReachWarnings.cjs');
133
135
  const { resolveProjectContext } = require('./lib/projectRootResolve.cjs');
134
136
  const { expandHome } = require('./lib/util/expandHome.cjs');
135
137
  const { hasDownstreamValidator } = require('./lib/prd/planValidator.cjs');
@@ -141,6 +143,9 @@ const { landedSinceRun, landedOnMainSince } = require('./lib/scheduler/landedSin
141
143
  const { declaredPathsForPrd, issuedAtForPrd } = require('./lib/prd/prdDeclaredPaths.cjs');
142
144
  const { identity: procIdentityOf, isDifferentProcess } = require('./lib/process/procIdentity.cjs');
143
145
  const jobLeftovers = require('./lib/scheduler/jobLeftovers.cjs');
146
+ const planReviewHold = require('./scheduler/planReviewHold.cjs');
147
+ const planReviewStore = require('./lib/scheduler/planReviewStore.cjs');
148
+ const { buildPlanReviewInput } = require('./lib/epic/planReviewInput.cjs');
144
149
  const { harvestPlanRecords, saveValidatorVerdicts } = require('./lib/scheduler/planRecordHarvest.cjs');
145
150
  const artifactStore = require('./lib/epic/artifactStore.cjs');
146
151
  const prdOutcomeRecord = require('./lib/scheduler/prdOutcomeRecord.cjs');
@@ -169,7 +174,7 @@ const { runDefinitionOfDoneOnDrain } = require('./lib/scheduler/dodDrainHook.cjs
169
174
  const { writeRcaReport, extractRcaBlock } = require('./lib/scheduler/rcaReport.cjs');
170
175
  const queueHistory = require('./lib/scheduler/queueHistory.cjs');
171
176
  const { resolveGate, runGateSequence, gateTimeoutMs } = require('./lib/scheduler/definitionOfDone.cjs');
172
- const { runCriteriaChecks } = require('./lib/scheduler/criteriaChecks.cjs');
177
+ const { runCriteriaChecks, HTTP_RETRY_ATTEMPTS, HTTP_RETRY_DELAY_MS } = require('./lib/scheduler/criteriaChecks.cjs');
173
178
  const queueOps = require('./queueOps.cjs');
174
179
  // Feedback-auto-PRD sweep — formerly only run by the external scheduler-watchdog
175
180
  // while the app was down (PRD 686 moved it in-app so it also runs while alive).
@@ -181,13 +186,18 @@ const { ensureEpic, appendPrdCreatedEvent, readActiveIndex } = require('./lib/ep
181
186
  const agentModelResolve = require('./lib/claude/agentModelResolve.cjs');
182
187
  const agentSnapshot = require('./lib/claude/agentSnapshot.cjs');
183
188
  const packSpawnArgs = require('./lib/packs/packSpawnArgs.cjs');
184
- const { buildPersonaToolScope, personaToolScopeArgs, personaToolScopeEnv, resolvedMcpServerNames } = require('./lib/claude/personaToolScope.cjs');
189
+ const { resolveHeadlessMcpServers } = require('./lib/claude/headlessMcpServers.cjs');
190
+ const { buildPersonaToolScope, personaToolScopeArgs, personaToolScopeEnv, resolvedMcpServerNames, resolveSkillDeny } = require('./lib/claude/personaToolScope.cjs');
191
+ const { PLAN_REVIEW_SCHEMA, parsePlanReview, isAllOk: isAllOkPlanReview } = require('./lib/scheduler/planReviewSchema.cjs');
192
+ const { readSettingsModel } = require('./lib/claude/modelCatalog.cjs');
185
193
  const { VALIDATOR_VERDICT_SCHEMA, parseValidatorVerdict, verdictRowsFromStructured, expectedFromCriteria, formatCriteriaChecksSection } = require('./lib/scheduler/validatorVerdictSchema.cjs');
186
194
  const { resolveEpicEffort, effortArgs } = require('./lib/claude/agentEffortResolve.cjs');
187
195
  const { transitionJob, emitJobEvent, STATUS_HISTORY_CAP, LEGAL_TRANSITIONS } = require('./lib/scheduler/scheduleJobTransitions.cjs');
188
196
  const { buildContextDigest, composeExecutorPrompt } = require('./lib/epic/epicContextDigest.cjs');
189
197
  const { JOB_STATUSES } = require('./lib/scheduler/scheduleJobSchema.cjs');
190
198
  const { appendAuditEvent } = require('./lib/telemetry/auditLog.cjs');
199
+ const heldSchedulerTurns = require('./lib/scheduler/heldSchedulerTurns.cjs');
200
+ const autoStartedSession = require('./lib/feedback-remote/autoStartedSession.cjs');
191
201
  const preflightCheck = require('./lib/scheduler/preflightCheck.cjs');
192
202
  const needsYouStore = require('./lib/feedback-remote/needsYouStore.cjs');
193
203
  const { withTimeout } = require('./lib/util/withTimeout.cjs');
@@ -424,15 +434,39 @@ const FINISH_ARTIFACT_ONLY_VERDICT_LINE = `
424
434
  const FINISH_ARTIFACT_ONLY_COMMIT_LINE = `
425
435
  This job is artifact-only: its output is git-excluded, so there is nothing to stage. Skip the commit and go to the next step.`;
426
436
 
437
+ /**
438
+ * jobDeclaredArtifactPaths(job) → Promise<string[]> — the job PRD's
439
+ * frontmatter artifactPaths (live PRD, else its archived copy). [] on any
440
+ * read/parse error; never throws.
441
+ */
442
+ async function jobDeclaredArtifactPaths(job) {
443
+ try {
444
+ const prdPath = (await resolveVerifyPrdPath(job)) ?? prdPaths.archivedPrdPathForJob(job);
445
+ if (!prdPath) return [];
446
+ const fm = parsePrdFile(fs.readFileSync(prdPath, 'utf8')).frontmatter;
447
+ if (!fm || !Array.isArray(fm.artifactPaths)) return [];
448
+ // Only plan-records entries are this harvest's; every other declared
449
+ // artifact belongs to harvestJobArtifacts and must not log a refusal here.
450
+ return fm.artifactPaths.filter((p) => typeof p === 'string'
451
+ && path.posix.normalize(p.replace(/\\/g, '/')).startsWith(ARTIFACT_PLAN_RECORDS_PREFIX));
452
+ } catch {
453
+ return [];
454
+ }
455
+ }
456
+
427
457
  /**
428
458
  * harvestJobPlanRecords(job, worktreeDir, projectRoot) — copy this run's
429
- * plan records from its worktree into the main checkout. Logs, never throws.
459
+ * plan records from its worktree into the main checkout: the job's own
460
+ * plan-records/<epicId>/ folder plus every plan record its PRD declares in
461
+ * frontmatter artifactPaths (which may sit in another Epic's folder).
462
+ * Logs, never throws.
430
463
  */
431
- function harvestJobPlanRecords(job, worktreeDir, projectRoot) {
464
+ async function harvestJobPlanRecords(job, worktreeDir, projectRoot) {
432
465
  try {
433
466
  const epicId = job.epicId || job.sourcePromptId;
434
467
  if (!epicId || !worktreeDir || !projectRoot || path.resolve(worktreeDir) === path.resolve(projectRoot)) return;
435
- const { copied, skipped } = harvestPlanRecords({ worktreeDir, projectRoot, epicId });
468
+ const declaredPaths = await jobDeclaredArtifactPaths(job);
469
+ const { copied, skipped } = harvestPlanRecords({ worktreeDir, projectRoot, epicId, declaredPaths });
436
470
  if (copied.length) console.log(`[scheduler] ${job.slug}: harvested ${copied.length} plan record(s) into ${projectRoot}`);
437
471
  for (const sk of skipped) console.warn(`[scheduler] ${job.slug}: plan record not harvested: ${sk.path} — ${sk.reason}`);
438
472
  } catch (e) {
@@ -521,7 +555,12 @@ async function harvestJobArtifacts(job, worktreeDir, projectRoot, { runId = job
521
555
  const FINISH_VALIDATOR_VERDICT_LINE = `
522
556
  - Your structured output's schedulerVerdict (and failReason) is what the scheduler reads as this verdict.`;
523
557
 
524
- function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum, isFixPlan = false, isArtifactOnly = false, isValidator = false }) {
558
+ // Plan-reviewer jobs (`--json-schema` PLAN_REVIEW_SCHEMA): the structured
559
+ // object is the whole deliverable; there is nothing to commit.
560
+ const FINISH_PLAN_REVIEWER_LINE = `
561
+ - PLAN REVIEWER: your deliverable is the structured output object (PLAN_REVIEW_SCHEMA) ONLY. Do not commit, do not edit files; the scheduler reads the object, not this verdict line.`;
562
+
563
+ function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum, isFixPlan = false, isArtifactOnly = false, isValidator = false, isPlanReviewer = false }) {
525
564
  return `${verifyStepNum}. VERIFY — run every command in the PRD's \`# Gate\` section, in order, in the
526
565
  foreground. Each must exit 0. If the PRD has no \`# Gate\` section, run the
527
566
  project's own typecheck, lint and test commands instead. The project's
@@ -553,7 +592,7 @@ ${verdictStepNum}. VERDICT LINE — end your final report with exactly one of th
553
592
  SCHEDULER_VERDICT: PASS
554
593
  SCHEDULER_VERDICT: FAIL <one-line reason>
555
594
  SCHEDULER_VERDICT: BLOCKED_BY_FOREIGN_WIP
556
- - Print PASS only when the gate is green AND the commit from step ${commitStepNum} landed.${isFixPlan ? FINISH_FIX_PLAN_VERDICT_LINE : ''}${isArtifactOnly ? FINISH_ARTIFACT_ONLY_VERDICT_LINE : ''}${isValidator ? FINISH_VALIDATOR_VERDICT_LINE : ''}
595
+ - Print PASS only when the gate is green AND the commit from step ${commitStepNum} landed.${isFixPlan ? FINISH_FIX_PLAN_VERDICT_LINE : ''}${isArtifactOnly ? FINISH_ARTIFACT_ONLY_VERDICT_LINE : ''}${isValidator ? FINISH_VALIDATOR_VERDICT_LINE : ''}${isPlanReviewer ? FINISH_PLAN_REVIEWER_LINE : ''}
557
596
  - Print FAIL when the gate is red or the commit could not land. Also print
558
597
  FAIL when a step needs something this run cannot reach (live runtime
559
598
  state, credentials, an account or dashboard action, a host install): do
@@ -603,13 +642,13 @@ in your final report.`;
603
642
  * tree, never FAIL for the missing commit. Self job 826 printed exactly that
604
643
  * false FAIL. Omitted/false leaves the text unchanged.
605
644
  */
606
- function buildFinishProtocol({ reviewInRun = true, isFixPlan = false, isArtifactOnly = false, isValidator = false } = {}) {
645
+ function buildFinishProtocol({ reviewInRun = true, isFixPlan = false, isArtifactOnly = false, isValidator = false, isPlanReviewer = false } = {}) {
607
646
  if (reviewInRun) {
608
647
  return buildFinishHead(3) + FINISH_REVIEW_STEPS_IN_RUN
609
- + buildFinishTail({ verifyStepNum: 3, commitStepNum: 4, verdictStepNum: 5, isFixPlan, isArtifactOnly, isValidator });
648
+ + buildFinishTail({ verifyStepNum: 3, commitStepNum: 4, verdictStepNum: 5, isFixPlan, isArtifactOnly, isValidator, isPlanReviewer });
610
649
  }
611
650
  return buildFinishHead(2) + FINISH_REVIEW_STEP_DEFERRED
612
- + buildFinishTail({ verifyStepNum: 2, commitStepNum: 3, verdictStepNum: 4, isFixPlan, isArtifactOnly, isValidator });
651
+ + buildFinishTail({ verifyStepNum: 2, commitStepNum: 3, verdictStepNum: 4, isFixPlan, isArtifactOnly, isValidator, isPlanReviewer });
613
652
  }
614
653
 
615
654
  const FINISH_PROTOCOL = buildFinishProtocol({ reviewInRun: true });
@@ -1063,6 +1102,7 @@ function loadSchedulerState() {
1063
1102
  ? s.cachedUtilizationKnown
1064
1103
  : typeof cachedUtilization === 'number';
1065
1104
  restoredUsageWindows = isValidUsageWindowList(s.usageWindows) ? s.usageWindows : null;
1105
+ openAutoDispatchHold = restoreOpenAutoDispatchHold(s.openAutoDispatchHold);
1066
1106
  } catch { /* first boot or corrupt — start fresh */ }
1067
1107
  }
1068
1108
 
@@ -1071,6 +1111,118 @@ function getSchedulerStateSnapshot() {
1071
1111
  return { lastPollOk, lastFailureKind, backoffNextAt, cachedUtilization, cachedBindingWindowName };
1072
1112
  }
1073
1113
 
1114
+ /** A persisted open hold is trusted only with a string holdKey and a parseable startedAt; restored ones are marked. */
1115
+ function restoreOpenAutoDispatchHold(v) {
1116
+ if (!v || typeof v !== 'object' || typeof v.holdKey !== 'string') return null;
1117
+ if (typeof v.startedAt !== 'string' || !Number.isFinite(Date.parse(v.startedAt))) return null;
1118
+ return {
1119
+ holdKey: v.holdKey,
1120
+ reason: typeof v.reason === 'string' ? v.reason : null,
1121
+ window: typeof v.window === 'string' ? v.window : null,
1122
+ threshold: Number.isFinite(v.threshold) ? v.threshold : null,
1123
+ resetsAt: typeof v.resetsAt === 'string' ? v.resetsAt : null,
1124
+ lastResetsAt: typeof v.lastResetsAt === 'string' ? v.lastResetsAt : (typeof v.resetsAt === 'string' ? v.resetsAt : null),
1125
+ startedAt: v.startedAt,
1126
+ maxPercent: Number.isFinite(v.maxPercent) ? v.maxPercent : null,
1127
+ heldTicks: Number.isFinite(v.heldTicks) ? v.heldTicks : 0,
1128
+ restored: true,
1129
+ };
1130
+ }
1131
+
1132
+ /** Test-only seam: the open audit hold, and a reset that drops it from memory (a simulated process exit). */
1133
+ function _getOpenAutoDispatchHoldForTests() { return openAutoDispatchHold; }
1134
+ function _forgetOpenAutoDispatchHoldForTests() { openAutoDispatchHold = null; }
1135
+ /** Test-only seam: a fresh process — no previous tick. */
1136
+ function _resetPreviousTickUnheldForTests() { previousTickUnheld = false; }
1137
+
1138
+ const HOLD_RESET_CONTINUITY_MS = 60_000;
1139
+
1140
+ /**
1141
+ * Whether `hold` continues the open audit hold: same reason and window, and
1142
+ * resetsAt within 60 s (equal strings when either is unparseable). Not
1143
+ * holdIdentityKey equality — its nearest-minute rounding flips when a reset
1144
+ * near hh:mm:30 jitters by under a second.
1145
+ * @param {{ reason?: string | null, window?: string | null, resetsAt?: string | null } | null} open
1146
+ * @param {{ reason?: string | null, window?: string | null, resetsAt?: string | number | null } | null} hold
1147
+ */
1148
+ function continuesOpenHold(open, hold) {
1149
+ if (!open || !hold) return false;
1150
+ if ((open.reason ?? null) !== (hold.reason ?? null)) return false;
1151
+ if ((open.window ?? null) !== (hold.window ?? null)) return false;
1152
+ const a = open.lastResetsAt ?? open.resetsAt ?? null;
1153
+ const b = hold.resetsAt ?? null;
1154
+ const ta = a == null ? NaN : Date.parse(String(a));
1155
+ const tb = b == null ? NaN : Date.parse(String(b));
1156
+ if (Number.isFinite(ta) && Number.isFinite(tb)) return Math.abs(ta - tb) <= HOLD_RESET_CONTINUITY_MS;
1157
+ return (a == null ? null : String(a)) === (b == null ? null : String(b));
1158
+ }
1159
+
1160
+ /**
1161
+ * Track the auto-dispatch hold in audit-log.jsonl: one started event when a
1162
+ * hold opens, one ended event when it lifts or its identity changes. Never
1163
+ * throws (an audit failure must not break the tick).
1164
+ * @param {object | null} hold currentAutoDispatchHold() result
1165
+ * @param {number} pending pending-row count for the started event
1166
+ */
1167
+ function trackAutoDispatchHoldAudit(hold, pending, startObserved = false) {
1168
+ try {
1169
+ const identity = hold ? autoDispatchHold.holdIdentityKey(hold) : null;
1170
+ const open = openAutoDispatchHold;
1171
+ if (open && continuesOpenHold(open, hold)) {
1172
+ if (Number.isFinite(hold.percent) && (open.maxPercent == null || hold.percent > open.maxPercent)) open.maxPercent = hold.percent;
1173
+ open.heldTicks += 1;
1174
+ open.lastResetsAt = hold.resetsAt ?? open.lastResetsAt;
1175
+ persistSchedulerState();
1176
+ return;
1177
+ }
1178
+ if (open) {
1179
+ appendAuditEvent('auto_dispatch_hold_ended', {
1180
+ reason: open.reason,
1181
+ window: open.window,
1182
+ threshold: open.threshold,
1183
+ resetsAt: open.resetsAt,
1184
+ lastResetsAt: open.lastResetsAt ?? open.resetsAt,
1185
+ holdKey: open.holdKey,
1186
+ startedAt: open.startedAt,
1187
+ endedAt: new Date().toISOString(),
1188
+ maxPercent: open.maxPercent,
1189
+ heldTicks: open.heldTicks,
1190
+ ...(open.restored ? { endedAcrossRestart: true } : {}),
1191
+ });
1192
+ openAutoDispatchHold = null;
1193
+ }
1194
+ if (hold) {
1195
+ appendAuditEvent('auto_dispatch_hold_started', {
1196
+ reason: hold.reason,
1197
+ window: hold.window ?? null,
1198
+ percent: hold.percent ?? null,
1199
+ threshold: hold.threshold ?? null,
1200
+ baseThreshold: hold.baseThreshold ?? null,
1201
+ resetsAt: hold.resetsAt ?? null,
1202
+ holdKey: identity,
1203
+ pending,
1204
+ startObserved,
1205
+ version: SCHEDULER_BUILD_IDENTITY.version,
1206
+ });
1207
+ openAutoDispatchHold = {
1208
+ holdKey: identity,
1209
+ reason: hold.reason,
1210
+ window: hold.window ?? null,
1211
+ threshold: hold.threshold ?? null,
1212
+ baseThreshold: hold.baseThreshold ?? null,
1213
+ resetsAt: hold.resetsAt ?? null,
1214
+ lastResetsAt: hold.resetsAt ?? null,
1215
+ startedAt: new Date().toISOString(),
1216
+ maxPercent: Number.isFinite(hold.percent) ? hold.percent : null,
1217
+ heldTicks: 1,
1218
+ };
1219
+ }
1220
+ persistSchedulerState();
1221
+ } catch (e) {
1222
+ console.warn('[scheduler] auto-dispatch hold audit failed', e?.message);
1223
+ }
1224
+ }
1225
+
1074
1226
  /** A persisted usageWindows list is trusted only if every entry names a window with a finite percent. */
1075
1227
  function isValidUsageWindowList(v) {
1076
1228
  return Array.isArray(v) && v.every((w) => w && typeof w.window === 'string' && Number.isFinite(w.percent));
@@ -1118,6 +1270,19 @@ function persistSchedulerState() {
1118
1270
  // the binding session window.
1119
1271
  cachedUtilizationKnown,
1120
1272
  usageWindows: utilizationReading().windows,
1273
+ openAutoDispatchHold: openAutoDispatchHold
1274
+ ? {
1275
+ holdKey: openAutoDispatchHold.holdKey,
1276
+ reason: openAutoDispatchHold.reason,
1277
+ window: openAutoDispatchHold.window,
1278
+ threshold: openAutoDispatchHold.threshold,
1279
+ resetsAt: openAutoDispatchHold.resetsAt,
1280
+ lastResetsAt: openAutoDispatchHold.lastResetsAt,
1281
+ startedAt: openAutoDispatchHold.startedAt,
1282
+ maxPercent: openAutoDispatchHold.maxPercent,
1283
+ heldTicks: openAutoDispatchHold.heldTicks,
1284
+ }
1285
+ : null,
1121
1286
  });
1122
1287
  } catch (e) {
1123
1288
  console.warn('[scheduler] failed to persist scheduler state', e?.message);
@@ -1205,6 +1370,8 @@ async function driveUpgradeDrain(state) {
1205
1370
  queueSnapshot: drainSnapshot(state.jobs),
1206
1371
  drainState: state.drain,
1207
1372
  now: Date.now(),
1373
+ // A request older than this process asked for a restart that already happened.
1374
+ bootedAt: SCHEDULER_BOOTED_AT,
1208
1375
  });
1209
1376
  if (action === 'none' || action === 'wait') { drainActive = Boolean(state.drain?.active); return; }
1210
1377
  if (action === 'pause') {
@@ -1261,9 +1428,9 @@ async function driveUpgradeDrain(state) {
1261
1428
  /** Boot: clear a leftover drain whose request is complete (the restart happened) or gone. */
1262
1429
  async function clearStaleDrainAtBoot(boot) {
1263
1430
  const request = upgradeDrain.readRestartRequest();
1264
- const action = upgradeDrain.bootDrainAction({ drainState: boot.drain, request });
1431
+ const action = upgradeDrain.bootDrainAction({ drainState: boot.drain, request, bootedAt: SCHEDULER_BOOTED_AT });
1265
1432
  upgradeDrain.clearRestartingMarker();
1266
- if (request?.drainCompletedAt) upgradeDrain.retireRestartRequest();
1433
+ if (request && (request.drainCompletedAt || (action === 'clear' && upgradeDrain.requestPredatesBoot(request, SCHEDULER_BOOTED_AT)))) upgradeDrain.retireRestartRequest();
1267
1434
  if (action === 'clear') await mutate((s) => { s.drain = null; });
1268
1435
  drainActive = action === 'keep';
1269
1436
  }
@@ -1431,6 +1598,14 @@ function heartbeatTick(deps = {}) {
1431
1598
  // this log can't otherwise tell a 5h hold from a weekly one.
1432
1599
  utilizationWindow: cachedBindingWindowName,
1433
1600
  utilizationHold,
1601
+ // Scheduler chat turns the usage hold is keeping (heldSchedulerTurns.cjs).
1602
+ heldSchedulerTurns: (() => {
1603
+ const sum = heldSchedulerTurns.summary() || {};
1604
+ return {
1605
+ count: Number(sum.count) || 0,
1606
+ tabs: Array.isArray(sum.tabs) ? sum.tabs : [],
1607
+ };
1608
+ })(),
1434
1609
  consecutiveFailures,
1435
1610
  // Why a memory-held tick held (PRD 4019): the new job's reservation, the
1436
1611
  // shared spike buffer and the running jobs' growth term. null = not gated.
@@ -1455,6 +1630,11 @@ function heartbeatTick(deps = {}) {
1455
1630
  entry = { ts: Date.now(), pid: process.pid, build: heartbeatBuild(), degraded: true, errors };
1456
1631
  }
1457
1632
  appendHeartbeat(entry);
1633
+ // Deliver held scheduler turns once the hold has cleared (no-op while held).
1634
+ guard('held-scheduler-turns-drain', () => {
1635
+ const run = deps.drainHeldSchedulerTurns ?? drainHeldSchedulerTurns;
1636
+ Promise.resolve(run()).catch(() => {});
1637
+ });
1458
1638
  return entry;
1459
1639
  }
1460
1640
 
@@ -1578,9 +1758,16 @@ function normalizeConfig(cfg) {
1578
1758
  return cfg;
1579
1759
  }
1580
1760
 
1761
+ // Last config object a queue read produced — the same object tickBody hands
1762
+ // currentAutoDispatchHold (state.config). The held-turns store's hold provider
1763
+ // reads it synchronously; undefined before the first read (DEFAULT_CONFIG applies).
1764
+ let lastSeenConfig;
1765
+ function _forgetLastSeenConfigForTests() { lastSeenConfig = undefined; }
1766
+
1581
1767
  function readQueueSync() {
1582
1768
  const s = queueStore.readMergedSync();
1583
1769
  s.config = normalizeConfig({ ...DEFAULT_CONFIG, ...(s.config || {}) });
1770
+ lastSeenConfig = s.config;
1584
1771
  return flagUnreadable(s);
1585
1772
  }
1586
1773
 
@@ -1590,6 +1777,7 @@ function readQueueSync() {
1590
1777
  async function readQueue() {
1591
1778
  const s = await queueStore.readMerged();
1592
1779
  s.config = normalizeConfig({ ...DEFAULT_CONFIG, ...(s.config || {}) });
1780
+ lastSeenConfig = s.config;
1593
1781
  return flagUnreadable(s);
1594
1782
  }
1595
1783
 
@@ -1991,7 +2179,7 @@ async function reconcilePass(state) {
1991
2179
  try { roots.add(resolveProjectRoot(c)); } catch { /* ephemeral/invalid cwd */ }
1992
2180
  }
1993
2181
  for (const r of roots) {
1994
- try { ensureRuntimeIgnores(r); } catch { /* best-effort */ }
2182
+ try { ensureRuntimeIgnores(r); } catch (e) { console.warn('[scheduler] runtime self-ignore failed for', r, e && e.message); }
1995
2183
  }
1996
2184
  } catch { /* best-effort */ }
1997
2185
  phaseMs.flatPrdSweep = Date.now() - phaseStartMs;
@@ -2147,6 +2335,7 @@ async function reconcilePass(state) {
2147
2335
  effort: p.effort ?? job.effort ?? null,
2148
2336
  voiceId: p.voiceId ?? job.voiceId ?? null,
2149
2337
  preflight: p.preflight ?? null,
2338
+ planReview: p.planReview ?? null,
2150
2339
  };
2151
2340
  // Adopt path: a row parked 'quarantined' (no createdVia provenance when
2152
2341
  // discovered) whose PRD file now carries a stamp — written via the
@@ -2276,6 +2465,7 @@ async function reconcilePass(state) {
2276
2465
  effort: p.effort ?? inv.row?.effort ?? null,
2277
2466
  voiceId: p.voiceId ?? inv.row?.voiceId ?? null,
2278
2467
  preflight: p.preflight ?? null,
2468
+ planReview: p.planReview ?? null,
2279
2469
  };
2280
2470
  const reason = `reconcile: repaired invalid status ${JSON.stringify(oldStatus)}`;
2281
2471
  // A repair is not a lifecycle transition — the corrupted `status` was
@@ -2433,6 +2623,7 @@ async function reconcilePass(state) {
2433
2623
  effort: p.effort ?? null,
2434
2624
  voiceId: p.voiceId ?? null,
2435
2625
  preflight: p.preflight ?? null,
2626
+ planReview: p.planReview ?? null,
2436
2627
  status: 'pending',
2437
2628
  // Enqueue time (PRD 1086/1087): the cross-project fairness tiebreak and
2438
2629
  // the starvation escalation both need a provable age for a pending row;
@@ -2619,6 +2810,18 @@ let utilizationHold = null;
2619
2810
  // `${reason}|${window}|${percent}` of the hold last logged — the hold line is
2620
2811
  // written when the hold starts or changes, not on every 30 s tick.
2621
2812
  let lastAutoDispatchHoldKey = null;
2813
+ // The auto-dispatch hold currently open in audit-log.jsonl (one
2814
+ // auto_dispatch_hold_started written, its _ended not yet): { holdKey, reason,
2815
+ // window, threshold, resetsAt, lastResetsAt, startedAt, maxPercent, heldTicks, restored? },
2816
+ // continued under continuesOpenHold (same reason + window, resetsAt within
2817
+ // 60 s of the last-seen resetsAt, not the opening one) so percent changes and
2818
+ // reset jitter write nothing. Persisted in scheduler-state.json so a restart
2819
+ // neither re-opens nor loses it (the heartbeat log keeps only ~15-37 h).
2820
+ let openAutoDispatchHold = null;
2821
+ // True when this process's immediately preceding tick found no auto-dispatch
2822
+ // hold: a hold opening now was seen to start (startObserved: true); one that
2823
+ // replaces another hold, or is in force on the first tick after boot, was not.
2824
+ let previousTickUnheld = false;
2622
2825
  // ms timestamp of the last FRESH reset observation (see recordObservedReset)
2623
2826
  // — distinct from Date.now(), so persistSchedulerState never re-stamps a
2624
2827
  // stale cachedNextReset as "just observed" on every poll cycle.
@@ -2712,6 +2915,38 @@ function currentAutoDispatchHold(config) {
2712
2915
  });
2713
2916
  }
2714
2917
 
2918
+ /**
2919
+ * The saved 'pause above' threshold (config.utilizationThreshold), read from
2920
+ * the machine-runtime scheduler state file only — never every project's queue
2921
+ * shard — so timers and routes can call it cheaply. DEFAULT_CONFIG's value
2922
+ * when unset, non-finite or unreadable.
2923
+ */
2924
+ function usageHoldThreshold() {
2925
+ try {
2926
+ const t = queueStore.readMachineConfigSync().utilizationThreshold;
2927
+ return typeof t === 'number' && Number.isFinite(t) ? t : DEFAULT_CONFIG.utilizationThreshold;
2928
+ } catch {
2929
+ return DEFAULT_CONFIG.utilizationThreshold;
2930
+ }
2931
+ }
2932
+
2933
+ /**
2934
+ * The usage hold in force right now for claude -p runs started OUTSIDE the PRD
2935
+ * queue: Tasks (POST /admin/tasks), their timers, and outside readers. Applies
2936
+ * the same utilization rule as currentAutoDispatchHold over the last real
2937
+ * reading at usageHoldThreshold(), but never firePolicy — firePolicy is the PRD
2938
+ * queue's own setting. null, or { reason: 'utilization-held', window, percent,
2939
+ * threshold, resetsAt, detail }; never 'manual-fire-policy'.
2940
+ */
2941
+ function currentUsageHold() {
2942
+ return autoDispatchHold.evaluateAutoDispatchHold({
2943
+ firePolicy: null,
2944
+ threshold: usageHoldThreshold(),
2945
+ reading: utilizationReading(),
2946
+ now: Date.now(),
2947
+ });
2948
+ }
2949
+
2715
2950
  /**
2716
2951
  * The auto-fix investigation probe is an automatic `claude -p` too, but it is
2717
2952
  * launched from spawnJob's failure path and the periodic auto-fix pass, never
@@ -2747,8 +2982,12 @@ function utilizationReading() {
2747
2982
  };
2748
2983
  }
2749
2984
 
2750
- /** Fetches latest usage from billing API. Throws on any error — callers handle it. */
2751
- async function refreshNextReset() {
2985
+ /**
2986
+ * Fetches latest usage from billing API and returns its binding window as one
2987
+ * paired reading ({ window, resetsAt }). Throws on any error — callers handle it.
2988
+ * @returns {Promise<{ window: string | null, resetsAt: string | null }>}
2989
+ */
2990
+ async function refreshBindingReading() {
2752
2991
  const r = await billing.fetchUsage();
2753
2992
  if (r.kind !== 'ok') throw new Error(`usage fetch failed (${r.kind}): ${r.message ?? ''}`);
2754
2993
  const window = bindingWindow(r.data?.usage);
@@ -2762,7 +3001,12 @@ async function refreshNextReset() {
2762
3001
  cachedBindingWindowName = window.name;
2763
3002
  cachedUtilizationKnown = true;
2764
3003
  lastGoodUsagePayload = r.data?.usage ?? lastGoodUsagePayload;
2765
- return cachedNextReset;
3004
+ return { window: window.name ?? null, resetsAt: cachedNextReset };
3005
+ }
3006
+
3007
+ /** Fetches latest usage from billing API. Throws on any error — callers handle it. */
3008
+ async function refreshNextReset() {
3009
+ return (await refreshBindingReading()).resetsAt;
2766
3010
  }
2767
3011
 
2768
3012
  /**
@@ -2797,6 +3041,41 @@ function resolveRateLimitPauseReset(logPath, billingResetIso, nowMs = Date.now()
2797
3041
  return null;
2798
3042
  }
2799
3043
 
3044
+ /**
3045
+ * The 'pause above' a rate_limit pause compares the billing binding window
3046
+ * with: the same pro-rated threshold the auto-dispatch hold uses
3047
+ * (utilizationHold.proRatedThreshold) for THAT window and its reset, so a
3048
+ * weekly window in its last days is not read as over a flat cap the hold
3049
+ * itself has already raised. Window name and reset come from the SAME
3050
+ * reading (the caller's refreshed billing reading) — pairing a cached name
3051
+ * with a fresh reset pro-rates against the wrong window length. The cached
3052
+ * pair is used only when no reading is passed. Non-numeric base passes
3053
+ * through unchanged.
3054
+ * @param {unknown} base
3055
+ * @param {{ window?: string | null, resetsAt?: string | null } | null | undefined} reading
3056
+ * @param {number} nowMs
3057
+ */
3058
+ function bindingWindowPauseThreshold(base, reading, nowMs) {
3059
+ if (typeof base !== 'number' || !Number.isFinite(base)) return base;
3060
+ const pair = reading ?? { window: cachedBindingWindowName, resetsAt: cachedNextReset };
3061
+ return autoDispatchHold.proRatedThreshold({ base, window: pair.window ?? null, resetsAt: pair.resetsAt ?? null, now: nowMs });
3062
+ }
3063
+
3064
+ /**
3065
+ * Effective 'pause above' for the binding window of the last known reading
3066
+ * (renderer snapshot field effectiveUtilizationThreshold); null with no known
3067
+ * reading or no numeric base.
3068
+ * @param {unknown} base
3069
+ * @param {number} [nowMs]
3070
+ * @returns {number | null}
3071
+ */
3072
+ function effectiveUtilizationThreshold(base, nowMs = Date.now()) {
3073
+ if (typeof base !== 'number' || !Number.isFinite(base)) return null;
3074
+ const reading = utilizationReading();
3075
+ if (reading.known !== true || typeof reading.percent !== 'number' || !Number.isFinite(reading.percent)) return null;
3076
+ return autoDispatchHold.proRatedThreshold({ base, window: reading.window, resetsAt: reading.resetsAt, now: nowMs });
3077
+ }
3078
+
2800
3079
  /** Logs when a fresh billing reset was discarded because its reading is under threshold. */
2801
3080
  function logBillingResetRejected(billingResetIso, billingUtilization, threshold) {
2802
3081
  if (!billingResetIso || !Number.isFinite(threshold)) return;
@@ -2814,8 +3093,19 @@ function logBillingResetRejected(billingResetIso, billingUtilization, threshold)
2814
3093
  * itself still rejects that cached value if it has since gone stale).
2815
3094
  */
2816
3095
  async function billingResetForPause() {
2817
- if (billing.usageCircuit.state() === 'open') return cachedNextReset;
2818
- return refreshNextReset().catch(() => cachedNextReset);
3096
+ return (await billingReadingForPause()).resetsAt;
3097
+ }
3098
+
3099
+ /**
3100
+ * billingResetForPause's reading with its binding window name kept beside the
3101
+ * reset ({ window, resetsAt }), so both come from one reading — the refreshed
3102
+ * one, or the cached pair when the circuit is open or the refresh fails.
3103
+ * @returns {Promise<{ window: string | null, resetsAt: string | null }>}
3104
+ */
3105
+ async function billingReadingForPause() {
3106
+ const cached = () => ({ window: cachedBindingWindowName ?? null, resetsAt: cachedNextReset });
3107
+ if (billing.usageCircuit.state() === 'open') return cached();
3108
+ return refreshBindingReading().catch(cached);
2819
3109
  }
2820
3110
 
2821
3111
  // ---------- health / poll state ----------
@@ -3028,6 +3318,40 @@ function drainDeferredInvestigation() {
3028
3318
  return;
3029
3319
  }
3030
3320
  }
3321
+
3322
+ /**
3323
+ * drainHeldSchedulerTurns(deps?) → Promise<Array<{ tabId, delivered, dropped }>>
3324
+ *
3325
+ * Deliver the scheduler chat turns the usage hold kept (heldSchedulerTurns.cjs)
3326
+ * once no hold is in force — each tab's held messages as one turn. An
3327
+ * auto-start follow-up is dropped when its session no longer needs a plan.
3328
+ * Every tab the drain touched is audited. Single-flight lives in the store.
3329
+ * Never rejects. Deps are injectable for tests.
3330
+ */
3331
+ async function drainHeldSchedulerTurns(deps = {}) {
3332
+ const hold = deps.hold ?? (() => currentAutoDispatchHold(lastSeenConfig));
3333
+ const send = deps.send ?? enqueueExternalPrompt;
3334
+ const needsPlan = deps.needsPlan ?? autoStartedSession.autoStartNeedsPlan;
3335
+ const audit = deps.audit ?? appendAuditEvent;
3336
+ try {
3337
+ if (hold()) return [];
3338
+ if (heldSchedulerTurns.summary().count <= 0) return [];
3339
+ const isStillNeeded = (entry) => (entry && entry.kind === 'auto-start-follow-up'
3340
+ ? needsPlan(entry.cwd, entry.sessionId)
3341
+ : true);
3342
+ const results = await heldSchedulerTurns.drain({ send, isStillNeeded });
3343
+ for (const r of results || []) {
3344
+ try {
3345
+ audit('scheduler_turns_delivered', { tabId: r.tabId, delivered: r.delivered, dropped: r.dropped });
3346
+ } catch { /* audit must not break the drain */ }
3347
+ }
3348
+ return results || [];
3349
+ } catch (e) {
3350
+ console.error('[scheduler] drainHeldSchedulerTurns error', e?.message ?? e);
3351
+ return [];
3352
+ }
3353
+ }
3354
+
3031
3355
  let cancelToken = { cancelled: false };
3032
3356
  // Last memory-gate observation; included in snapshot for renderer visibility.
3033
3357
  let lastMemGate = null;
@@ -3148,6 +3472,8 @@ function buildScheduleStatePayload(state) {
3148
3472
  utilization: cachedUtilization,
3149
3473
  utilizationWindow: cachedBindingWindowName,
3150
3474
  utilizationHold,
3475
+ // Pro-rated 'pause above' for the binding window (utilizationHold.proRatedThreshold).
3476
+ effectiveUtilizationThreshold: effectiveUtilizationThreshold(state.config?.utilizationThreshold),
3151
3477
  pollHealth: {
3152
3478
  lastPollAt,
3153
3479
  lastPollOk,
@@ -3988,16 +4314,75 @@ async function readStoredCriteriaChecks(cwd, epicId, slug) {
3988
4314
  return [];
3989
4315
  }
3990
4316
 
4317
+ /**
4318
+ * runDispatchCriteriaChecks(cwd, epicId, slug, criteria, stored, { httpRetry }?) → merged checks.
4319
+ * Runs the PRD's http + file criteria fresh in `cwd` (outside the job
4320
+ * sandbox, whose Bash cannot reach host loopback), never command or manual
4321
+ * ones. A failed http check is retried (default HTTP_RETRY_ATTEMPTS,
4322
+ * HTTP_RETRY_DELAY_MS apart; `httpRetry` overrides, tests only) because a
4323
+ * local dev server may be mid-reload just after a landing; each http row
4324
+ * keeps its `attempts`. http bodies go to a sidecar file (writeCheckBody); the row keeps
4325
+ * only bodyPath/bodyBytes/truncated. Fresh rows replace stored ones by id;
4326
+ * the exact-slug outcome record (when one exists) is updated in place.
4327
+ * Falls back to `stored` on any error. Never rejects.
4328
+ * @param {string} cwd
4329
+ * @param {string} epicId
4330
+ * @param {string} slug
4331
+ * @param {Record<string, unknown>[]} criteria
4332
+ * @param {Record<string, unknown>[]} stored
4333
+ * @param {{ httpRetry?: import('./lib/scheduler/criteriaChecks.cjs').HttpRetry }} [opts]
4334
+ * @returns {Promise<Record<string, unknown>[]>}
4335
+ */
4336
+ async function runDispatchCriteriaChecks(cwd, epicId, slug, criteria, stored, { httpRetry } = {}) {
4337
+ try {
4338
+ const subset = criteria.filter((c) => c && c.check && (c.check.kind === 'http' || c.check.kind === 'file'));
4339
+ if (!subset.length) return stored;
4340
+ const ranAt = new Date().toISOString();
4341
+ const rows = await runCriteriaChecks({
4342
+ criteria: subset,
4343
+ cwd,
4344
+ keepBody: true,
4345
+ httpRetry: httpRetry || { attempts: HTTP_RETRY_ATTEMPTS, delayMs: HTTP_RETRY_DELAY_MS },
4346
+ });
4347
+ const fresh = [];
4348
+ for (const r of rows) {
4349
+ const { body, ...rest } = r;
4350
+ /** @type {Record<string, unknown>} */
4351
+ const row = { ...rest, ranAt, stage: 'validator-dispatch' };
4352
+ if (typeof body === 'string') {
4353
+ const bodyPath = await prdOutcomeRecord.writeCheckBody({ cwd, epicId, slug, id: r.id, body });
4354
+ if (bodyPath) row.bodyPath = bodyPath;
4355
+ }
4356
+ fresh.push(row);
4357
+ }
4358
+ const freshIds = new Set(fresh.map((c) => c.id));
4359
+ const merged = [...(Array.isArray(stored) ? stored : []).filter((c) => !(c && freshIds.has(c.id))), ...fresh];
4360
+ let exactExists = false;
4361
+ try { exactExists = !!(await readJsonOr(prdOutcomeRecord.outcomeRecordPath(cwd, epicId, slug), null)); } catch { exactExists = false; }
4362
+ if (exactExists) await prdOutcomeRecord.mergeOutcomeChecks({ cwd, epicId, slug, checks: fresh });
4363
+ return merged;
4364
+ } catch (e) {
4365
+ console.error('[scheduler] runDispatchCriteriaChecks error', slug, e && e.message ? e.message : e);
4366
+ return stored;
4367
+ }
4368
+ }
4369
+
3991
4370
  /**
3992
4371
  * loadValidatorCriteriaContext(job) → { expected, section } for a validator
3993
4372
  * job: per judged PRD (job.dependsOn) with frontmatter `criteria`, the
3994
4373
  * { 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.
4374
+ * prompt section listing each criterion's check result — http + file checks
4375
+ * run fresh here at dispatch (runDispatchCriteriaChecks), command results as
4376
+ * stored. Empty when
4377
+ * nothing is structured. Never rejects. With `runChecks: false` (the notify
4378
+ * fallback for a row without a dispatch-time stamp) it reads the stored
4379
+ * checks only: no http request, no outcome record or body file write.
4380
+ * `httpRetry` overrides the dispatch retry defaults (tests only).
3997
4381
  * @param {any} job
4382
+ * @param {{ runChecks?: boolean, httpRetry?: import('./lib/scheduler/criteriaChecks.cjs').HttpRetry }} [opts]
3998
4383
  * @returns {Promise<{ expected: Record<string, { ids: string[], failedIds: string[] }>, section: string }>}
3999
4384
  */
4000
- async function loadValidatorCriteriaContext(job) {
4385
+ async function loadValidatorCriteriaContext(job, { runChecks = true, httpRetry } = {}) {
4001
4386
  /** @type {Record<string, { ids: string[], failedIds: string[] }>} */
4002
4387
  const expected = {};
4003
4388
  try {
@@ -4012,7 +4397,8 @@ async function loadValidatorCriteriaContext(job) {
4012
4397
  let criteria = null;
4013
4398
  try { criteria = parsePrdFile(text).frontmatter.criteria; } catch { criteria = null; }
4014
4399
  if (!Array.isArray(criteria) || !criteria.length) continue;
4015
- const checks = await readStoredCriteriaChecks(job.cwd, epicId, slug);
4400
+ const stored = await readStoredCriteriaChecks(job.cwd, epicId, slug);
4401
+ const checks = runChecks ? await runDispatchCriteriaChecks(job.cwd, epicId, slug, criteria, stored, { httpRetry }) : stored;
4016
4402
  const exp = expectedFromCriteria(criteria, checks);
4017
4403
  if (exp) expected[slug] = exp;
4018
4404
  prds.push({ slug, criteria, checks });
@@ -4040,7 +4426,7 @@ function defaultScheduleSettle({ cwd, epicId }) {
4040
4426
  },
4041
4427
  readGateMs: readValidatorGateMs,
4042
4428
  jobBudget: { factor: budget.JOB_BUDGET_FACTOR, ceilingMs: budget.JOB_BUDGET_CEILING_MS },
4043
- sendPrompt: (tabId, prompt) => enqueueExternalPrompt(tabId, prompt, { origin: 'scheduler' }),
4429
+ sendPrompt: (tabId, prompt, extra) => enqueueExternalPrompt(tabId, prompt, { ...(extra || {}), origin: 'scheduler' }),
4044
4430
  appendResponseEvent: appendResponseEventIfKnown,
4045
4431
  };
4046
4432
  epicValidationHook.scheduleEpicSettle({ cwd, epicId }, (args) => epicValidationHook.runEpicSettle(args, deps));
@@ -4225,6 +4611,8 @@ async function notifyOriginatingTab(job, {
4225
4611
  writeVerdictsFile = writeJsonAtomic,
4226
4612
  scheduleSettle = defaultScheduleSettle,
4227
4613
  loadValidatorCriteria = loadValidatorCriteriaContext,
4614
+ planReviewRows = undefined,
4615
+ planReviewStoreImpl = undefined,
4228
4616
  } = {}) {
4229
4617
  try {
4230
4618
  const prd = await resolveNotifyPrd(job, parsePrdRaw);
@@ -4322,9 +4710,14 @@ async function notifyOriginatingTab(job, {
4322
4710
  // Cross-check per-criterion entries against the judged PRDs' frontmatter
4323
4711
  // criteria + stored check results: a missing id or met-on-failed-check
4324
4712
  // refuses the whole verdict.
4713
+ // The dispatch-time stamp (job.validatorCriteriaExpected) is what the
4714
+ // validator was shown; re-running the http/file checks here would judge
4715
+ // it against results it never saw and overwrite the outcome record.
4325
4716
  let expected = null;
4326
4717
  try {
4327
- const ctx = await loadValidatorCriteria(job);
4718
+ const stamp = job && job.validatorCriteriaExpected;
4719
+ const isPlain = !!stamp && typeof stamp === 'object' && !Array.isArray(stamp);
4720
+ const ctx = isPlain ? { expected: stamp } : await loadValidatorCriteria(job, { runChecks: false });
4328
4721
  if (ctx && ctx.expected && Object.keys(ctx.expected).length) expected = ctx.expected;
4329
4722
  } catch (e) {
4330
4723
  console.error('[scheduler] notifyOriginatingTab loadValidatorCriteria error', job?.slug, e);
@@ -4400,6 +4793,9 @@ async function notifyOriginatingTab(job, {
4400
4793
  console.error('[scheduler] notifyOriginatingTab verdicts file write error', job?.slug, e);
4401
4794
  }
4402
4795
  }
4796
+ if (job.agentType === 'plan-reviewer' && (job.status === 'completed' || job.status === 'failed')) {
4797
+ await harvestPlanReview(job, epicId, logPath, { readStructured: readStructuredFromLog, sendPrompt, rows: planReviewRows, store: planReviewStoreImpl });
4798
+ }
4403
4799
  if (epicId) {
4404
4800
  // PRD 986: the check-in event is born validation:'unvalidated' — never
4405
4801
  // 'verified' — regardless of the job's self-reported outcome. The
@@ -4451,12 +4847,108 @@ async function notifyOriginatingTab(job, {
4451
4847
  return;
4452
4848
  }
4453
4849
 
4454
- sendPrompt(targetTabId, message, { origin: 'scheduler' });
4850
+ sendPrompt(targetTabId, message, { origin: 'scheduler', heldKind: 'job-notice' });
4455
4851
  } catch (e) {
4456
4852
  console.error('[scheduler] notifyOriginatingTab error', job?.slug, e);
4457
4853
  }
4458
4854
  }
4459
4855
 
4856
+ /** Digest text for one harvested plan review (pure). */
4857
+ function buildPlanReviewDigest({ validateSlug, round, outcome, review, error }) {
4858
+ const head = `PLAN REVIEWED: ${validateSlug} (round ${round})`;
4859
+ if (outcome === 'failed') {
4860
+ return `${head}\nThe independent review failed (${error || 'no structured output'}) — the plan was released without review (review-failed). Its PRDs are free to dispatch.`;
4861
+ }
4862
+ if (outcome === 'ok') {
4863
+ return `${head}\nEvery PRD is ok and there are no plan findings — the plan was released automatically. Its PRDs are free to dispatch.`;
4864
+ }
4865
+ const lines = [head, 'The reviewer asks for changes before the PRDs dispatch.'];
4866
+ for (const p of review.prds) {
4867
+ lines.push('', `${p.prd}: ${p.decision}`);
4868
+ for (const f of p.findings) {
4869
+ lines.push(` - [${f.severity}] ${f.check}: ${f.text}`);
4870
+ if (f.suggestedEdit) lines.push(` suggested edit: ${f.suggestedEdit}`);
4871
+ }
4872
+ }
4873
+ if (review.planFindings.length) {
4874
+ lines.push('', 'Plan findings:');
4875
+ for (const f of review.planFindings) lines.push(` - [${f.severity}] ${f.check}: ${f.text}`);
4876
+ }
4877
+ lines.push('', 'Apply the suggested edits with scheduler_update_prd, then call scheduler_release_plan with a one-line reason for each finding you reject.');
4878
+ return lines.join('\n');
4879
+ }
4880
+
4881
+ /**
4882
+ * harvestPlanReview — a finished plan-reviewer job: parse its structured output,
4883
+ * save the round, auto-release an all-ok plan (an unusable review releases as
4884
+ * 'review-failed'), and send the planner's Epic ONE digest per (validateSlug,
4885
+ * round). The sent round is persisted in the record (`digestSent`) so a restart
4886
+ * does not resend. Never throws.
4887
+ */
4888
+ async function harvestPlanReview(job, epicId, logPath, deps = {}) {
4889
+ const store = deps.store || planReviewStore;
4890
+ try {
4891
+ if (!epicId || !job.cwd || !isSafeEpicId(epicId)) return;
4892
+ const m = /^plan-review-(.+?)(?:-r(\d+))?$/.exec(bareSlug(job.slug));
4893
+ if (!m) return;
4894
+ const round = m[2] ? Number(m[2]) : 1;
4895
+ const rows = (deps.rows || (await readQueue()).jobs || []);
4896
+ const validator = rows.find((r) => r && r.agentType === 'validator' && r.planReview === 'required'
4897
+ && bareSlug(r.slug) === m[1] && (!r.cwd || r.cwd === job.cwd));
4898
+ if (!validator) {
4899
+ console.error('[scheduler] harvestPlanReview: no validate row for', job.slug);
4900
+ return;
4901
+ }
4902
+ const validateSlug = validator.slug;
4903
+ const prior = store.readPlanReview(job.cwd, epicId, validateSlug);
4904
+ const sentBefore = prior && Array.isArray(prior.digestSent) ? prior.digestSent.slice() : [];
4905
+ if (sentBefore.includes(round)) return;
4906
+
4907
+ const members = planReviewHold.planMembers(validator, rows).map((r) => r.slug);
4908
+ let structured = null;
4909
+ try { structured = (deps.readStructured || extractStructuredOutputFromLog)(logPath); } catch { structured = null; }
4910
+ const checked = job.status === 'completed' && structured
4911
+ ? parsePlanReview(structured, { expected: members })
4912
+ : { ok: false, error: job.status === 'completed' ? 'no structured output' : `reviewer ${job.status}` };
4913
+
4914
+ let outcome;
4915
+ if (checked.ok) {
4916
+ await store.savePlanReviewResult({
4917
+ cwd: job.cwd, epicId, validateSlug, round, reviewer: job.slug,
4918
+ runId: job.runId || null, model: job.model || null, review: checked.value,
4919
+ });
4920
+ if (isAllOkPlanReview(checked.value)) {
4921
+ outcome = 'ok';
4922
+ await store.recordPlanRelease({ cwd: job.cwd, epicId, validateSlug, by: 'auto', accepted: 0 });
4923
+ } else {
4924
+ outcome = 'amend';
4925
+ }
4926
+ } else {
4927
+ outcome = 'failed';
4928
+ console.error(`[scheduler] harvestPlanReview: ${job.slug} review rejected — ${checked.error}`);
4929
+ await store.recordPlanRelease({
4930
+ cwd: job.cwd, epicId, validateSlug, by: 'timeout',
4931
+ rejected: [{ finding: 'plan-review', reason: 'review-failed' }],
4932
+ });
4933
+ }
4934
+
4935
+ // Persist the dedupe key (the store's own writes rebuild the record without it).
4936
+ const rec = store.readPlanReview(job.cwd, epicId, validateSlug);
4937
+ if (rec) {
4938
+ const file = store.planReviewPath(job.cwd, epicId, validateSlug);
4939
+ assertOpsWrite(file, 'scheduler');
4940
+ await writeJsonAtomic(file, { ...rec, digestSent: [...new Set([...sentBefore, round])] });
4941
+ }
4942
+ const text = buildPlanReviewDigest({
4943
+ validateSlug, round, outcome,
4944
+ review: checked.ok ? checked.value : null, error: checked.ok ? null : checked.error,
4945
+ });
4946
+ (deps.sendPrompt || enqueueExternalPrompt)(epicId, text, { origin: 'scheduler', heldKind: 'scheduler-notice' });
4947
+ } catch (e) {
4948
+ console.error('[scheduler] harvestPlanReview error', job?.slug, e);
4949
+ }
4950
+ }
4951
+
4460
4952
  // Single-flight guard for flushDueReviewNotices — same shape as
4461
4953
  // gateShadowPending above: a module-level flag rather than a class, so two
4462
4954
  // triggers landing close together (an auto-resolve skip right next to the
@@ -4626,9 +5118,11 @@ const TRANSIENT_RETRY_CAP = 2;
4626
5118
  * transient (PRD 543/545 incident) — same bounded-retry treatment, not a
4627
5119
  * second parallel classifier.
4628
5120
  */
4629
- function classifyFailureOutcome({ exitCode, networkError, durationMs, transientRetries, newlyDirtyCount, launchError }) {
5121
+ function classifyFailureOutcome({ exitCode, networkError, durationMs, transientRetries, newlyDirtyCount, launchError, environmentLimit }) {
4630
5122
  // The run never started (argv too large): not transient, not investigable.
4631
5123
  if (launchError) return { action: 'fail-launch', launchError };
5124
+ // The job sandbox refused the run: not a code bug, and an investigation would hit the same wall.
5125
+ if (environmentLimit) return { action: 'fail-environment', environmentLimit };
4632
5126
  const signalTransient = (exitCode === 143 || exitCode === 137) && durationMs < IDLE_OUTPUT_KILL_MS;
4633
5127
  const networkTransient = networkError === true;
4634
5128
  const transient = signalTransient || networkTransient;
@@ -5426,13 +5920,6 @@ const HEADLESS_DISALLOWED_TOOLS = Object.freeze([
5426
5920
  * and a large prompt failed with spawn E2BIG before the job started (the
5427
5921
  * 2026-10-26 incident). `claude -p` with no positional prompt reads stdin.
5428
5922
  */
5429
- // MCP servers whose definition the scheduler knows. Lazy require: avoids a
5430
- // load-order cycle with seedSchedulerMcp.cjs.
5431
- function knownMcpServers() {
5432
- const seed = require('./seedSchedulerMcp.cjs');
5433
- return { [seed.SERVER_NAME]: seed.schedulerServerEntry() };
5434
- }
5435
-
5436
5923
  /**
5437
5924
  * The CLI keeps only the LAST --settings value, and the job sandbox argv
5438
5925
  * already carries one inline JSON --settings. When it does, fold the
@@ -5483,7 +5970,7 @@ function jobRiskToolsClearance(prdRiskTools, personaTools) {
5483
5970
  return out;
5484
5971
  }
5485
5972
 
5486
- function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope, mcpServerNames = [], pluginDirArgs = [], jsonSchema = null, sandboxArgs = null, riskGuardSettingsPath = null }) {
5973
+ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope, mcpServerNames = [], pluginDirArgs = [], jsonSchema = null, sandboxArgs = null, riskGuardSettingsPath = null, skillDeny = [], knownServers }) {
5487
5974
  let permissionArgs = Array.isArray(sandboxArgs) && sandboxArgs.length ? sandboxArgs : ['--dangerously-skip-permissions'];
5488
5975
  let riskArgs = [];
5489
5976
  if (typeof riskGuardSettingsPath === 'string' && riskGuardSettingsPath) {
@@ -5498,13 +5985,14 @@ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt,
5498
5985
  ...(systemPrompt ? ['--append-system-prompt', systemPrompt] : []),
5499
5986
  // Always strict: exactly the persona's resolved servers (dispatch already
5500
5987
  // parked any job whose set names an unknown server — capability_unknown).
5501
- ...personaToolScopeArgs(toolScope, { mcpServers: knownMcpServers(), declaredServers: mcpServerNames }).args,
5988
+ ...personaToolScopeArgs(toolScope, { mcpServers: knownServers, declaredServers: mcpServerNames }).args,
5502
5989
  ...(Array.isArray(pluginDirArgs) ? pluginDirArgs : []),
5503
5990
  ...(jsonSchema && typeof jsonSchema === 'object' ? ['--json-schema', JSON.stringify(jsonSchema)] : []),
5504
5991
  ...riskArgs,
5505
5992
  ...permissionArgs,
5506
5993
  ...headlessPermissionArgs(),
5507
5994
  '--disallowedTools', HEADLESS_DISALLOWED_TOOLS.join(','),
5995
+ ...(Array.isArray(skillDeny) ? skillDeny : []),
5508
5996
  '--output-format', 'stream-json',
5509
5997
  '--verbose',
5510
5998
  ...(resume ? ['--resume', sessionId] : ['--session-id', sessionId]),
@@ -5609,11 +6097,20 @@ function ensureTimeoutShimOnce() {
5609
6097
  * @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
6098
  */
5611
6099
  async function resolveJobAgentSnapshot(job, cwd, packs) {
6100
+ let repinFrom = null;
6101
+ let pinnedSnap = null;
5612
6102
  if (typeof job.agentSnapshotId === 'string' && job.agentSnapshotId) {
5613
- const snap = await agentSnapshot.readAgentSnapshot(cwd, job.agentSnapshotId);
5614
- if (!snap) {
6103
+ pinnedSnap = await agentSnapshot.readAgentSnapshot(cwd, job.agentSnapshotId);
6104
+ if (!pinnedSnap) {
5615
6105
  return { refusal: { code: 'agent_snapshot_missing', detail: `pinned agent snapshot ${job.agentSnapshotId} is missing or does not match its id` } };
5616
6106
  }
6107
+ // An explicit persona change (the PRD's agentType moved) is an audited re-pin.
6108
+ if (pinnedSnap.name && pinnedSnap.name !== (job.agentType || DEFAULT_PRD_AGENT_TYPE)) {
6109
+ repinFrom = job.agentSnapshotId;
6110
+ }
6111
+ }
6112
+ if (pinnedSnap && !repinFrom) {
6113
+ const snap = pinnedSnap;
5617
6114
  return {
5618
6115
  refusal: null,
5619
6116
  systemPrompt: snap.body || null,
@@ -5621,6 +6118,7 @@ async function resolveJobAgentSnapshot(job, cwd, packs) {
5621
6118
  tools: Array.isArray(snap.tools) ? snap.tools : null,
5622
6119
  mcpServers: Array.isArray(snap.mcpServers) ? snap.mcpServers.map(String) : [],
5623
6120
  packs: Array.isArray(snap.packs) ? snap.packs.map(String) : [],
6121
+ loadout: typeof snap.loadout === 'string' ? snap.loadout : null,
5624
6122
  personaPath: null,
5625
6123
  agentSnapshotId: job.agentSnapshotId,
5626
6124
  pinned: true,
@@ -5649,6 +6147,7 @@ async function resolveJobAgentSnapshot(job, cwd, packs) {
5649
6147
  id = (await agentSnapshot.writeAgentSnapshot(cwd, snap)).id;
5650
6148
  job.agentSnapshotId = id;
5651
6149
  } catch (err) {
6150
+ if (repinFrom) job.agentSnapshotId = null;
5652
6151
  console.error(`[scheduler] agent snapshot write failed for ${job.slug} (spawning unpinned): ${err?.message ?? err}`);
5653
6152
  }
5654
6153
  return {
@@ -5658,9 +6157,11 @@ async function resolveJobAgentSnapshot(job, cwd, packs) {
5658
6157
  tools: snap.tools,
5659
6158
  mcpServers: snap.mcpServers,
5660
6159
  packs: snap.packs,
6160
+ loadout: typeof snap.loadout === 'string' ? snap.loadout : null,
5661
6161
  personaPath: null,
5662
6162
  agentSnapshotId: id,
5663
6163
  pinned: false,
6164
+ ...(repinFrom && id ? { repinned: { from: repinFrom, to: id, reason: 'agentType_changed' } } : {}),
5664
6165
  };
5665
6166
  }
5666
6167
 
@@ -6002,14 +6503,17 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6002
6503
  isArtifactOnly = false;
6003
6504
  }
6004
6505
  }
6005
- // Validator: list each judged PRD's structured criteria with their stored
6006
- // mechanical check results, so its per-criterion verdict entries use the
6506
+ // Validator: list each judged PRD's structured criteria with their
6507
+ // mechanical check results (http + file run fresh here, outside the sandbox), so its per-criterion verdict entries use the
6007
6508
  // same ids and never mark a failed check met (parseValidatorVerdict refuses that).
6008
6509
  if (job.agentType === 'validator') {
6009
- const { section } = await loadValidatorCriteriaContext({ ...job, cwd: job.cwd || cwd });
6510
+ const { section, expected } = await loadValidatorCriteriaContext({ ...job, cwd: job.cwd || cwd });
6511
+ // Stamped onto the queue row (spawnJob onPid) so notifyOriginatingTab
6512
+ // cross-checks the verdict against exactly these results.
6513
+ job.validatorCriteriaExpected = expected;
6010
6514
  if (section) prompt = `${prompt}\n\n${section}`;
6011
6515
  }
6012
- prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun, isFixPlan: resolveIsFixPlan(job.slug, job.isFixPlan), isArtifactOnly, isValidator: job.agentType === 'validator' }) });
6516
+ prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun, isFixPlan: resolveIsFixPlan(job.slug, job.isFixPlan), isArtifactOnly: isArtifactOnly || job.agentType === 'plan-reviewer', isValidator: job.agentType === 'validator', isPlanReviewer: job.agentType === 'plan-reviewer' }) });
6013
6517
 
6014
6518
  // Foreign-WIP manifest (starry-night-ships PRD 148 postmortem): the
6015
6519
  // scheduler already knows, at spawn time, which dirty paths this job did
@@ -6084,7 +6588,17 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6084
6588
  // Validator jobs (fresh and resume) return a schema-checked verdict:
6085
6589
  // --json-schema + StructuredOutput in scope (PRD 3613).
6086
6590
  const isValidator = job.agentType === 'validator';
6087
- const personaToolScope = buildPersonaToolScope(personaResolution.tools, { disallowed: HEADLESS_DISALLOWED_TOOLS, structuredOutput: isValidator });
6591
+ // Plan-reviewer jobs return a schema-checked review (PLAN_REVIEW_SCHEMA) on a
6592
+ // model that differs from the planner Epic's.
6593
+ const isPlanReviewer = job.agentType === 'plan-reviewer';
6594
+ let spawnModel = personaResolution.model;
6595
+ if (isPlanReviewer) {
6596
+ const plannerModel = (packEpic && typeof packEpic.model === 'string' && packEpic.model.trim())
6597
+ || readSettingsModel(cwd) || 'opus';
6598
+ spawnModel = planReviewHold.reviewerModelFor(personaResolution.model, plannerModel);
6599
+ job.model = spawnModel;
6600
+ }
6601
+ const personaToolScope = buildPersonaToolScope(personaResolution.tools, { loadout: personaResolution.loadout, disallowed: HEADLESS_DISALLOWED_TOOLS, structuredOutput: isValidator || isPlanReviewer });
6088
6602
  // Epic context packs (PRD 3154): the job's Epic's selected packs load as
6089
6603
  // --plugin-dir per pack, and their laws are appended AFTER the (already
6090
6604
  // capped) persona body — the persona cap never applies to laws. Fresh and
@@ -6107,19 +6621,37 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6107
6621
  } catch (err) {
6108
6622
  safeLog(`[scheduler] context packs skipped for ${job.slug}: ${err && err.message ? err.message : String(err)}\n`);
6109
6623
  }
6624
+ // Skills ride only inside packs: refuse every installed skill the persona's
6625
+ // packs (snapshot-pinned when pinned) do not carry.
6626
+ const skillDeny = await resolveSkillDeny({ packs: personaResolution.packs || [], loadout: personaResolution.loadout });
6627
+ safeLog(`[scheduler] skills=${skillDeny.denied} denied for ${job.slug}\n`);
6110
6628
  // 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;
6629
+ // missing from the resolved known map, or an unknown persona-declared pack,
6630
+ // parks the job needs_review 'capability_unknown: <name>'; a credential-bearing
6631
+ // one parks 'capability_credentialed'. Never spawned with a widened config.
6632
+ const mcpResolution = resolveHeadlessMcpServers({ cwd, projectRoot: job.cwd || defaultCwd });
6633
+ let capRefusal = null;
6634
+ for (const name of resolvedMcpServerNames(personaToolScope?.tools, personaResolution.mcpServers || [])) {
6635
+ if (Object.prototype.hasOwnProperty.call(mcpResolution.credentialed, name)) {
6636
+ capRefusal = { code: 'capability_credentialed', detail: mcpResolution.credentialed[name] };
6637
+ break;
6638
+ }
6639
+ }
6640
+ if (!capRefusal) {
6641
+ const capabilityCheck = personaToolScopeArgs(personaToolScope, {
6642
+ mcpServers: mcpResolution.known,
6643
+ declaredServers: personaResolution.mcpServers || [],
6644
+ packs: unknownPacks ? personaPackIds : [],
6645
+ knownPacks: unknownPacks ? personaPackIds.filter((p) => !unknownPacks.includes(p)) : [],
6646
+ });
6647
+ if (capabilityCheck.refusal) {
6648
+ const { code, name } = capabilityCheck.refusal;
6649
+ const isPack = Array.isArray(unknownPacks) && unknownPacks.includes(String(name));
6650
+ capRefusal = { code, detail: code === 'capability_unknown' && !isPack ? `${name} (MCP server not defined in ~/.claude.json, <project>/.mcp.json or the project's local scope)` : name };
6651
+ }
6652
+ }
6653
+ if (capRefusal) {
6654
+ const { code, detail } = capRefusal;
6123
6655
  const refusalError = `${code}: ${detail}`;
6124
6656
  safeLog(`[scheduler] capability refused for ${job.slug} — not spawned: ${refusalError}\n`);
6125
6657
  closeFd();
@@ -6129,7 +6661,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6129
6661
  const jobSystemPrompt = packArgs.laws
6130
6662
  ? (personaResolution.systemPrompt ? `${personaResolution.systemPrompt}\n\n${packArgs.laws}` : packArgs.laws)
6131
6663
  : personaResolution.systemPrompt;
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`);
6664
+ safeLog(`[scheduler] agentType=${job.agentType || '(none)'} agentSnapshot=${personaResolution.agentSnapshotId || '(unpinned)'}${personaResolution.pinned ? ' (pinned)' : ''}${personaResolution.repinned ? ` (re-pinned from ${personaResolution.repinned.from.slice(0, 8)}: agentType changed)` : ''} persona=${personaResolution.personaPath || '(from snapshot)'} model=${personaResolution.model}${personaEffort ? ` effort=${personaEffort}${effortResolution.source === 'prd' ? ' (prd)' : ''}` : ''} ${personaToolScope ? `tools=${personaToolScope.tools.length} scoped` : 'tools=unscoped'}\n`);
6133
6665
 
6134
6666
  // Authoritative guarantee that buildClaudeSpawnArgs (a pure sync helper,
6135
6667
  // called below via withChildAndLog) sees a resolved --permission-prompts
@@ -6433,7 +6965,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6433
6965
  `tmp=${sandboxTmpDir ?? 'none'}\n`);
6434
6966
  const jobArgs = buildClaudeSpawnArgs({
6435
6967
  sandboxArgs: sandboxPolicy.argv,
6436
- model: personaResolution.model,
6968
+ model: spawnModel,
6437
6969
  effort: personaEffort,
6438
6970
  sessionId,
6439
6971
  resume: !!resumeTarget,
@@ -6441,8 +6973,10 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6441
6973
  toolScope: personaToolScope,
6442
6974
  mcpServerNames: personaResolution.mcpServers || [],
6443
6975
  pluginDirArgs: packArgs.pluginDirArgs,
6444
- jsonSchema: isValidator ? VALIDATOR_VERDICT_SCHEMA : null,
6976
+ jsonSchema: isValidator ? VALIDATOR_VERDICT_SCHEMA : (isPlanReviewer ? PLAN_REVIEW_SCHEMA : null),
6445
6977
  riskGuardSettingsPath,
6978
+ skillDeny: skillDeny.args,
6979
+ knownServers: mcpResolution.known,
6446
6980
  });
6447
6981
  const jobSpawn = claudeSpawnTarget('job', job.slug, claudeBin, jobArgs);
6448
6982
 
@@ -6610,10 +7144,15 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6610
7144
  ...SCHEDULER_META_IDENTITY, ...setupMeta,
6611
7145
  originSessionId, contextDigestApplied,
6612
7146
  agentSnapshotId: personaResolution.agentSnapshotId || null,
7147
+ ...(personaResolution.repinned ? { agentSnapshotRepinned: personaResolution.repinned } : {}),
7148
+ ...(isPlanReviewer ? { agentType: 'plan-reviewer', model: spawnModel } : {}),
6613
7149
  });
6614
7150
  removeSandboxTmp();
7151
+ // Only the OS-sandboxed run can hit a sandbox refusal; stamped at finalize if the row ends failed/needs_review.
7152
+ const sandboxLimit = sandboxMeta.level === 'os-sandbox'
7153
+ ? sandboxLimitFromStreamJson(readTail(logPath, 16384)) : null;
6615
7154
  resolve({
6616
- exitCode: effectiveCode, durationMs, rateLimited, networkError, launchFailure: launchFailed, resultStats,
7155
+ exitCode: effectiveCode, durationMs, rateLimited, networkError, sandboxLimit, launchFailure: launchFailed, resultStats,
6617
7156
  leakedDescendants: leaked, sessionId, killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
6618
7157
  ...(memoryCapReason ? { error: memoryCapReason, memoryCapReason } : {}),
6619
7158
  });
@@ -6714,6 +7253,36 @@ function healTargetForFix(fixSlug, jobs) {
6714
7253
  return jobs.find((x) => x.slug === originalSlug && isPromotableOriginal(x.status) && !isCancelledRow(x)) || null;
6715
7254
  }
6716
7255
 
7256
+ /**
7257
+ * A fix plan succeeded for `orig`. An artifact-only parent (PRD declares
7258
+ * deliverable: artifact) is re-queued to pending for a fresh run, because
7259
+ * promoting it would mark it done without its record (4418: live probe never
7260
+ * re-run, artifactEvidence stayed ok:false). Any other parent is promoted to
7261
+ * completed as before. Returns 'requeued' | 'completed' | 'skipped'
7262
+ * ('skipped' = already re-queued once for this fix plan; a repeat boot pass
7263
+ * must not loop the parent back to pending after it failed again).
7264
+ */
7265
+ function applyFixSuccessToOriginal(orig, fixSlug, { promoteReason, promoteSource, requeueSource }) {
7266
+ if (orig.deliverable === 'artifact') {
7267
+ if (orig.requeuedByFix === fixSlug) return 'skipped';
7268
+ const ok = resetJobFields(orig, `requeued: fix plan ${fixSlug} succeeded`, { source: requeueSource });
7269
+ if (ok) {
7270
+ orig.error = null; // the reason lives on the transition, not as a row error
7271
+ orig.requeuedByFix = fixSlug;
7272
+ delete orig.completedBy;
7273
+ delete orig.looksDone;
7274
+ return 'requeued';
7275
+ }
7276
+ return 'skipped';
7277
+ }
7278
+ transitionJob(orig, 'completed', { reason: promoteReason, source: promoteSource });
7279
+ orig.exitCode = 0;
7280
+ orig.error = null;
7281
+ orig.completedBy = fixSlug;
7282
+ delete orig.looksDone;
7283
+ return 'completed';
7284
+ }
7285
+
6717
7286
  /**
6718
7287
  * Build the Opus investigation prompt. Pure/hermetic so its content can be
6719
7288
  * unit-tested (no spawn, no fs). Inputs are the already-resolved values that
@@ -7676,6 +8245,159 @@ async function recordInterruptLeftovers(slug, runId, { dirtyPaths, salvagePatch
7676
8245
  }
7677
8246
  }
7678
8247
 
8248
+ const PLAN_REVIEW_HELD_PREFIX = 'held: plan-review';
8249
+ const planReviewTimeoutNoticesSent = new Set();
8250
+
8251
+ /** Parse one member PRD's text into the shape buildPlanReviewInput expects. */
8252
+ function planReviewMemberFromPrd(row, text, prdPath) {
8253
+ let fm = {};
8254
+ let body = String(text || '');
8255
+ try { const p = parsePrdFile(body); fm = p.frontmatter || {}; body = p.body || ''; } catch { /* keep raw */ }
8256
+ const section = (name) => {
8257
+ const m = body.match(new RegExp(`^#{1,3}\\s*${name}[^\\n]*\\n([\\s\\S]*?)(?=^#{1,3}\\s|(?![\\s\\S]))`, 'im'));
8258
+ return m ? m[1] : '';
8259
+ };
8260
+ const bullets = (txt) => txt.split('\n').map((l) => l.match(/^\s*(?:[-*]|\d+\.)\s+(?:\[[ xX]\]\s+)?(.*\S)\s*$/)?.[1]).filter(Boolean);
8261
+ const gateTxt = section('Gate');
8262
+ const gate = (gateTxt.match(/```[^\n]*\n([\s\S]*?)```/)?.[1] || '').split('\n').map((l) => l.trim()).filter(Boolean);
8263
+ return {
8264
+ slug: row.slug,
8265
+ title: fm.title || row.title || '',
8266
+ prdPath: prdPath || `${row.slug}.md`,
8267
+ goal: section('Goal').trim().split('\n')[0] || '',
8268
+ acceptanceCriteria: bullets(section('Acceptance criteria')),
8269
+ files: bullets(section('Files')).map((f) => f.replace(/^`|`$/g, '')),
8270
+ gate,
8271
+ dependsOn: Array.isArray(row.dependsOn) ? row.dependsOn : [],
8272
+ };
8273
+ }
8274
+
8275
+ /**
8276
+ * Per-tick plan-review orchestration. Merges computePlanReviewHolds into the
8277
+ * returned held Map, creates each missing plan-review PRD once (idempotent by
8278
+ * slug), and releases + notifies on timeout. Pending member rows carry
8279
+ * `heldReason` ('held: plan-review …') so epic settle and starvation see a known
8280
+ * wait; the field is cleared when the hold ends. Never throws.
8281
+ * deps: { now, holdMs, readReview, createPrd, recordRelease, notify, gitHead, readPrdTexts, audit, mutateRows }
8282
+ */
8283
+ async function applyPlanReviewHolds(state, deps = {}) {
8284
+ const held = new Map();
8285
+ try {
8286
+ const rows = state.jobs || [];
8287
+ const now = deps.now ?? Date.now();
8288
+ const holdMs = deps.holdMs ?? planReviewHold.holdMsFromEnv();
8289
+ const readReview = deps.readReview || ((cwd, epicId, slug) => planReviewStore.readPlanReview(cwd, epicId, slug));
8290
+ const createPrd = deps.createPrd || ((input) => prdCreate.createPrd(input, remote, { internalMint: true }));
8291
+ const recordRelease = deps.recordRelease || ((a) => planReviewStore.recordPlanRelease(a));
8292
+ const notify = deps.notify || ((cwd, epicId, text, extra) => appendResponseEventIfKnown(cwd, epicId, text, extra));
8293
+ const gitHead = deps.gitHead || (async (cwd) => { try { return String(await execGitAt(cwd, ['rev-parse', 'HEAD'])).trim() || null; } catch { return null; } });
8294
+ const readPrdTexts = deps.readPrdTexts || ((cwd, epicId, slugs) => prdPaths.readEpicPrdTexts(cwd, epicId, slugs));
8295
+ const audit = deps.audit || ((k, d) => { try { appendAuditEvent(k, d); } catch { /* audit never breaks dispatch */ } });
8296
+ const readEpicGoal = deps.readEpicGoal || ((cwd, epicId) => {
8297
+ try {
8298
+ const sessions = readActiveIndex(cwd).sessions;
8299
+ const sess = sessions && Object.prototype.hasOwnProperty.call(sessions, epicId) ? sessions[epicId] : null;
8300
+ const t = sess && typeof sess.goalText === 'string' ? sess.goalText.trim() : '';
8301
+ return t;
8302
+ } catch { return ''; }
8303
+ });
8304
+ const resolvePrdPath = deps.resolvePrdPath || (async (m, cwd, epicId) => {
8305
+ try {
8306
+ const dir = await prdPaths.findPrdDirForJob({ ...m, cwd: m.cwd || cwd, epicId: m.epicId || epicId });
8307
+ if (dir) return path.join(dir, `${m.slug}.md`);
8308
+ } catch { /* fall through to the canonical live path */ }
8309
+ return opsPath(cwd, 'scheduler', 'epics', epicId, 'prds', `${m.slug}.md`);
8310
+ });
8311
+ const heldReasons = new Map();
8312
+
8313
+ const reviews = {};
8314
+ const validators = rows.filter((r) => r && r.status === 'pending' && r.agentType === 'validator' && r.planReview === 'required');
8315
+ for (const v of validators) {
8316
+ const epicId = v.sourcePromptId || v.epicId;
8317
+ if (!epicId || !v.cwd) continue;
8318
+ const rec = readReview(v.cwd, epicId, v.slug);
8319
+ if (rec) reviews[bareSlug(v.slug)] = { ...rec, released: !!rec.release || rec.released === true };
8320
+ }
8321
+ const { held: holds, needsReview, expired } = planReviewHold.computePlanReviewHolds(rows, reviews, { now, holdMs });
8322
+ const expiredSet = new Set(expired);
8323
+ const byVSlug = new Map(validators.map((v) => [v.slug, v]));
8324
+
8325
+ // Expired plans release by timeout; their members are not held this tick.
8326
+ const releasedMembers = new Set();
8327
+ for (const vslug of expired) {
8328
+ const v = byVSlug.get(vslug);
8329
+ if (!v) continue;
8330
+ const epicId = v.sourcePromptId || v.epicId;
8331
+ const members = planReviewHold.planMembers(v, rows);
8332
+ try {
8333
+ const out = await recordRelease({ cwd: v.cwd, epicId, validateSlug: v.slug, by: 'timeout' });
8334
+ for (const m of members) releasedMembers.add(m.slug);
8335
+ if (!out || !out.alreadyReleased) {
8336
+ audit('plan_review_timeout', { validateSlug: v.slug, epicId, holdMs });
8337
+ const key = `${epicId}:${v.slug}`;
8338
+ if (!planReviewTimeoutNoticesSent.has(key)) {
8339
+ planReviewTimeoutNoticesSent.add(key);
8340
+ await notify(v.cwd, epicId, `PLAN REVIEW TIMED OUT — released without review. Plan ${bareSlug(v.slug)} waited ${Math.round(holdMs / 60000)} minutes for its independent review; its PRDs are now free to dispatch.`, { prdSlug: v.slug, validation: 'unvalidated', notice: 'plan-review-timeout', allowInactive: true });
8341
+ }
8342
+ }
8343
+ } catch (e) {
8344
+ console.error('[scheduler] plan review timeout release failed', vslug, e?.message || e);
8345
+ }
8346
+ }
8347
+ for (const [slug, why] of holds) {
8348
+ if (releasedMembers.has(slug)) continue;
8349
+ held.set(slug, why);
8350
+ heldReasons.set(slug, why);
8351
+ }
8352
+
8353
+ // Create the review PRD for plans that have none yet (round 1), and r2 on request.
8354
+ const wanted = [];
8355
+ for (const vslug of needsReview) if (!expiredSet.has(vslug)) wanted.push({ vslug, round: 1 });
8356
+ for (const v of validators) {
8357
+ const rec = reviews[bareSlug(v.slug)];
8358
+ if (rec && rec.rereviewRequested === true && !rec.release && !expiredSet.has(v.slug)) wanted.push({ vslug: v.slug, round: 2 });
8359
+ }
8360
+ for (const { vslug, round } of wanted) {
8361
+ const v = byVSlug.get(vslug);
8362
+ if (!v) continue;
8363
+ const epicId = v.sourcePromptId || v.epicId;
8364
+ const reviewSlug = `plan-review-${bareSlug(vslug)}${round >= 2 ? `-r${round}` : ''}`;
8365
+ if (rows.some((r) => r && bareSlug(r.slug) === reviewSlug)) continue;
8366
+ try {
8367
+ const memberRows = planReviewHold.planMembers(v, rows);
8368
+ const texts = await readPrdTexts(v.cwd, epicId, memberRows.map((m) => m.slug));
8369
+ const members = [];
8370
+ for (const m of memberRows) members.push(planReviewMemberFromPrd(m, texts.get(m.slug), await resolvePrdPath(m, v.cwd, epicId)));
8371
+ const epicGoal = String((await readEpicGoal(v.cwd, epicId)) || '');
8372
+ const baseSha = await gitHead(v.cwd);
8373
+ const input = buildPlanReviewInput({ epicId, cwd: v.cwd, epicGoal, validateSlug: v.slug, members, baseSha, round });
8374
+ const res = await createPrd(input);
8375
+ if (res && res.ok === false) console.warn('[scheduler] plan review PRD not created', reviewSlug, res.error || res.reason || '');
8376
+ } catch (e) {
8377
+ console.error('[scheduler] plan review PRD create failed', reviewSlug, e?.message || e);
8378
+ }
8379
+ }
8380
+
8381
+ // Stamp / clear heldReason on pending rows so settle + starvation see a known wait.
8382
+ const mutateRows = deps.mutateRows || ((fn) => mutate((s) => fn(s.jobs)));
8383
+ const dirty = rows.some((r) => r && r.status === 'pending' && (
8384
+ (heldReasons.has(r.slug) && !r.preflightHold && r.heldReason !== heldReasons.get(r.slug))
8385
+ || (!heldReasons.has(r.slug) && typeof r.heldReason === 'string' && r.heldReason.startsWith(PLAN_REVIEW_HELD_PREFIX))));
8386
+ if (dirty) {
8387
+ await mutateRows((list) => {
8388
+ for (const r of list) {
8389
+ if (!r || r.status !== 'pending') continue;
8390
+ if (heldReasons.has(r.slug) && !r.preflightHold) r.heldReason = heldReasons.get(r.slug);
8391
+ else if (typeof r.heldReason === 'string' && r.heldReason.startsWith(PLAN_REVIEW_HELD_PREFIX)) delete r.heldReason;
8392
+ }
8393
+ });
8394
+ }
8395
+ } catch (e) {
8396
+ console.error('[scheduler] applyPlanReviewHolds error', e?.message || e);
8397
+ }
8398
+ return held;
8399
+ }
8400
+
7679
8401
  function computePreflightHolds(jobs, now = Date.now()) {
7680
8402
  const held = new Map();
7681
8403
  for (const j of jobs || []) {
@@ -8034,14 +8756,16 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8034
8756
  source: 'spawnJob:dispatch',
8035
8757
  });
8036
8758
  delete s.jobs[idx].heldReason;
8037
- // A fresh dispatch means any gateShadow, looksDone, or
8038
- // evidenceScannedAt on this row was computed for an earlier
8039
- // runId/startedAt — never let any of them linger and read as this
8040
- // run's result (looksDone stale here would let rung 6 complete this
8041
- // run on the PREVIOUS run's evidence).
8759
+ // A fresh dispatch means any gateShadow, looksDone,
8760
+ // evidenceScannedAt, or artifactEvidence on this row was computed for
8761
+ // an earlier runId/startedAt — never let any of them linger and read
8762
+ // as this run's result (looksDone stale here would let rung 6
8763
+ // complete this run on the PREVIOUS run's evidence; a running row
8764
+ // must never carry another run's artifactEvidence).
8042
8765
  delete s.jobs[idx].gateShadow;
8043
8766
  delete s.jobs[idx].looksDone;
8044
8767
  delete s.jobs[idx].evidenceScannedAt;
8768
+ delete s.jobs[idx].artifactEvidence;
8045
8769
  s.jobs[idx].runId = runId;
8046
8770
  s.jobs[idx].startedAt = new Date().toISOString();
8047
8771
  // Dispatch-phase breadcrumb (PRD: dispatch-region diagnostic
@@ -8257,6 +8981,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8257
8981
  if (idx >= 0) {
8258
8982
  s.jobs[idx].sessionId = sessionId;
8259
8983
  if (job.agentSnapshotId) s.jobs[idx].agentSnapshotId = job.agentSnapshotId;
8984
+ if (job.validatorCriteriaExpected) s.jobs[idx].validatorCriteriaExpected = job.validatorCriteriaExpected;
8260
8985
  s.jobs[idx].runtime = { pid, runId, startedAt: s.jobs[idx].startedAt, sessionId, cwd };
8261
8986
  s.jobs[idx].dispatchPhase = 'spawned';
8262
8987
  s.jobs[idx].dispatchPhaseAt = new Date().toISOString();
@@ -8277,7 +9002,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8277
9002
  // Plan records are written in the worktree and never committed; copy
8278
9003
  // them to the main checkout before verify and before the checkout is
8279
9004
  // removed. Never throws (planRecordHarvest.cjs).
8280
- harvestJobPlanRecords(job, worktree.dir, job.cwd || defaultCwd);
9005
+ await harvestJobPlanRecords(job, worktree.dir, job.cwd || defaultCwd);
8281
9006
  // Capture artifact evidence before the worktree is removed: a
8282
9007
  // git-ignored artifact may live only here. Never breaks teardown.
8283
9008
  try {
@@ -8401,9 +9126,10 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8401
9126
  // poller's own reads).
8402
9127
  billing.usageCircuit.recordFailure('executor_429');
8403
9128
  const logPath = path.join(runDir, `${job.slug}.log`);
8404
- const billingResetIso = await billingResetForPause();
9129
+ const billingReading = await billingReadingForPause();
9130
+ const billingResetIso = billingReading.resetsAt;
8405
9131
  const pauseState = await readQueue().catch(() => null);
8406
- const pauseThreshold = pauseState?.config?.utilizationThreshold;
9132
+ const pauseThreshold = bindingWindowPauseThreshold(pauseState?.config?.utilizationThreshold, billingReading, Date.now());
8407
9133
  const resetIso = resolveRateLimitPauseReset(logPath, billingResetIso, Date.now(), { billingUtilization: cachedUtilization, threshold: pauseThreshold });
8408
9134
  if (resetIso == null) logBillingResetRejected(billingResetIso, cachedUtilization, pauseThreshold);
8409
9135
  const observedAt = dispatchStartedAtMs;
@@ -9066,6 +9792,21 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9066
9792
  } else {
9067
9793
  delete s.jobs[i2].uncommittedSnapshot;
9068
9794
  }
9795
+ // Persist this run's artifact evidence, bound to its runId, so the
9796
+ // stale needs_review rescan (reverifyNeedsReview) can verify a
9797
+ // worktree-only artifact after the worktree is gone. Cleared when
9798
+ // this run captured none so an older run's evidence never leaks.
9799
+ if (artifactEvidence) {
9800
+ s.jobs[i2].artifactEvidence = {
9801
+ runId,
9802
+ ok: artifactEvidence.ok,
9803
+ verified: artifactEvidence.verified,
9804
+ paths: artifactEvidence.paths,
9805
+ capturedAt: artifactEvidence.capturedAt,
9806
+ };
9807
+ } else {
9808
+ delete s.jobs[i2].artifactEvidence;
9809
+ }
9069
9810
  // Closed-set outcome taxonomy (issue #11 list A2) so a queue row
9070
9811
  // says WHY it ended without anyone opening the transcript.
9071
9812
  s.jobs[i2].terminalReason = launchFailure.deriveTerminalReason({
@@ -9143,6 +9884,13 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9143
9884
  // attribute" via its Array.isArray guard, same as an empty array.
9144
9885
  applyLeftoverFields(s.jobs[i2], newlyDirtyAll);
9145
9886
 
9887
+ const envStamp = environmentLimitStamp(res.sandboxLimit, effectiveStatus);
9888
+ if (envStamp.environmentLimit) {
9889
+ s.jobs[i2].environmentLimit = envStamp.environmentLimit;
9890
+ s.jobs[i2].error = envStamp.error;
9891
+ } else {
9892
+ delete s.jobs[i2].environmentLimit;
9893
+ }
9146
9894
  if (effectiveStatus === 'completed' || effectiveStatus === 'failed' || effectiveStatus === 'needs_review') {
9147
9895
  outcomeRecordSnapshot = { ...s.jobs[i2] };
9148
9896
  }
@@ -9246,16 +9994,18 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9246
9994
  const orig = healTargetForFix(job.slug, s.jobs);
9247
9995
  if (orig) {
9248
9996
  const priorStatus = orig.status;
9249
- console.log(`[scheduler] auto-promote: ${orig.slug} (${priorStatus}) → completed because ${job.slug} succeeded`);
9250
- transitionJob(orig, 'completed', { reason: `auto-promoted: fix plan ${job.slug} succeeded`, source: 'spawnJob:auto-promote' });
9251
- orig.exitCode = 0;
9252
- orig.error = null;
9253
- orig.completedBy = job.slug;
9254
- delete orig.looksDone;
9255
- if (priorStatus === 'needs_review') {
9256
- delete orig.verifierVerdict;
9997
+ const outcome = applyFixSuccessToOriginal(orig, job.slug, {
9998
+ promoteReason: `auto-promoted: fix plan ${job.slug} succeeded`,
9999
+ promoteSource: 'spawnJob:auto-promote',
10000
+ requeueSource: 'spawnJob:auto-promote',
10001
+ });
10002
+ console.log(`[scheduler] auto-promote: ${orig.slug} (${priorStatus}) → ${outcome} because ${job.slug} succeeded`);
10003
+ if (outcome === 'completed') {
10004
+ if (priorStatus === 'needs_review') {
10005
+ delete orig.verifierVerdict;
10006
+ }
10007
+ newlyCompletedPrds.push({ slug: orig.slug, cwd: orig.cwd });
9257
10008
  }
9258
- newlyCompletedPrds.push({ slug: orig.slug, cwd: orig.cwd });
9259
10009
  }
9260
10010
  }
9261
10011
  }
@@ -9405,6 +10155,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9405
10155
  transientRetries: retries,
9406
10156
  newlyDirtyCount,
9407
10157
  launchError: res.launchError,
10158
+ environmentLimit: failedJobSnapshot.environmentLimit,
9408
10159
  });
9409
10160
 
9410
10161
  if (decision.action === 'fail-launch') {
@@ -9416,6 +10167,13 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9416
10167
  }
9417
10168
  });
9418
10169
  await broadcast({ flush: true });
10170
+ } else if (decision.action === 'fail-environment') {
10171
+ console.log(`[scheduler] environment limit (${decision.environmentLimit.kind}) for ${job.slug} — no investigation`);
10172
+ await mutate((s) => {
10173
+ const i = s.jobs.findIndex((x) => x.slug === job.slug);
10174
+ if (i >= 0) s.jobs[i].error = ENVIRONMENT_LIMIT_MESSAGE;
10175
+ });
10176
+ await broadcast({ flush: true });
9419
10177
  } else if (decision.action === 'retry') {
9420
10178
  console.log(`[scheduler] transient failure (${decision.transientKind} dur=${res.durationMs}ms) — auto-retry ${decision.retries + 1}/${TRANSIENT_RETRY_CAP} for ${job.slug}`);
9421
10179
  await mutate((s) => {
@@ -9597,13 +10355,91 @@ const toolConfirmationHeldKeys = new Map();
9597
10355
  // slug -> hold key under which its 'investigation_held' / 'resume_recovery_held'
9598
10356
  // audit event was already appended (one event per row per hold). A row's key
9599
10357
  // is removed when no hold is in force for it (it launches), so a later hold
9600
- // audits it once again.
10358
+ // audits it once again; every tick also clears both Maps when no hold is in
10359
+ // force and drops slugs no longer in the queue (pruneRowHeldKeys).
9601
10360
  const investigationHeldKeys = new Map();
9602
10361
  const resumeRecoveryHeldKeys = new Map();
9603
10362
 
9604
- /** Identity of one auto-dispatch hold: reason + window + resetsAt. */
10363
+ /**
10364
+ * Identity of one auto-dispatch hold: reason + window + reset rounded to the
10365
+ * minute (utilizationHold.holdIdentityKey — the usage API jitters resets_at
10366
+ * by about ±0.5 s from fetch to fetch).
10367
+ */
9605
10368
  function autoDispatchHoldKey(hold) {
9606
- return `${hold.reason}|${hold.window ?? ''}|${hold.resetsAt ?? ''}`;
10369
+ return autoDispatchHold.holdIdentityKey(hold);
10370
+ }
10371
+
10372
+ /** The audited fields of one auto-dispatch hold (null when none is in force). */
10373
+ function holdAuditFields(hold) {
10374
+ if (!hold) return null;
10375
+ return {
10376
+ reason: hold.reason,
10377
+ window: hold.window ?? null,
10378
+ percent: hold.percent ?? null,
10379
+ threshold: hold.threshold ?? null,
10380
+ baseThreshold: hold.baseThreshold ?? null,
10381
+ resetsAt: hold.resetsAt ?? null,
10382
+ holdKey: openAutoDispatchHold && continuesOpenHold(openAutoDispatchHold, hold)
10383
+ ? openAutoDispatchHold.holdKey
10384
+ : autoDispatchHold.holdIdentityKey(hold),
10385
+ };
10386
+ }
10387
+
10388
+ /**
10389
+ * One 'scheduler_human_press' audit event for a Run now / Fire next batch now
10390
+ * press, naming the auto-dispatch hold in force at press time (null = none),
10391
+ * so a human launch under a usage hold is told apart from a leak. Never throws.
10392
+ * @param {'run-now' | 'force-tick'} press
10393
+ */
10394
+ async function auditHumanPress(press) {
10395
+ try {
10396
+ // lastSeenConfig is refreshed by every queue read/write; only a press before
10397
+ // the first read pays for a queue read just to audit itself.
10398
+ let config = lastSeenConfig;
10399
+ if (config == null) {
10400
+ try { config = (await readQueue()).config; } catch { /* DEFAULT_CONFIG applies */ }
10401
+ }
10402
+ appendAuditEvent('scheduler_human_press', { press, hold: holdAuditFields(currentAutoDispatchHold(config)) });
10403
+ } catch (e) {
10404
+ console.error('[scheduler] human press audit failed', e?.message ?? String(e));
10405
+ }
10406
+ }
10407
+
10408
+ /**
10409
+ * One 'auto_dispatch_hold_bypassed' audit event for a human tick that passed
10410
+ * through `hold`, naming the slugs of the batch it launches. Never throws.
10411
+ */
10412
+ function auditHoldBypassed(hold, batch) {
10413
+ try {
10414
+ appendAuditEvent('auto_dispatch_hold_bypassed', {
10415
+ ...holdAuditFields(hold),
10416
+ dispatched: (batch || []).map((j) => j.slug),
10417
+ });
10418
+ } catch (e) {
10419
+ console.error('[scheduler] hold bypass audit failed', e?.message ?? String(e));
10420
+ }
10421
+ }
10422
+
10423
+ /**
10424
+ * Tick-level bound on the per-row held-key Maps. No hold in force → clear
10425
+ * both (a later hold audits every row once again); a hold in force → drop
10426
+ * slugs that are no longer a queue row (cancelled or archived while held).
10427
+ * `rawHold` is the tick's own hold decision, before any human bypass.
10428
+ * @param {any[] | undefined} jobs
10429
+ * @param {any} rawHold
10430
+ */
10431
+ function pruneRowHeldKeys(jobs, rawHold) {
10432
+ if (!rawHold) {
10433
+ investigationHeldKeys.clear();
10434
+ resumeRecoveryHeldKeys.clear();
10435
+ return;
10436
+ }
10437
+ const liveSlugs = new Set((jobs || []).map((j) => j.slug));
10438
+ for (const keys of [investigationHeldKeys, resumeRecoveryHeldKeys]) {
10439
+ for (const slug of keys.keys()) {
10440
+ if (!liveSlugs.has(slug)) keys.delete(slug);
10441
+ }
10442
+ }
9607
10443
  }
9608
10444
 
9609
10445
  /**
@@ -9646,6 +10482,8 @@ async function processToolConfirmationAnswers(state, { human = false } = {}) {
9646
10482
  // tick that bypasses a hold in force does not count as the hold clearing.
9647
10483
  const rawHold = currentAutoDispatchHold(state.config);
9648
10484
  if (!rawHold) toolConfirmationHeldKeys.clear();
10485
+ // Same bound for the per-row investigation / resume-recovery held keys.
10486
+ pruneRowHeldKeys(state.jobs, rawHold);
9649
10487
  if (!pending.length) return;
9650
10488
  // Same hold decision as the tick running this pass: an approval starts a
9651
10489
  // `claude -p --resume`, so an automatic tick under the hold leaves it
@@ -9913,18 +10751,26 @@ async function tickBody(gen, { bypassLoadGate, lastResort, human = false }) {
9913
10751
  // watchdog, boot/resume runDueJobs — holds at or above the threshold on
9914
10752
  // ANY live window of the last real reading, and under firePolicy
9915
10753
  // 'manual'. Only a human Run now / Fire next batch now passes through.
10754
+ // bypassedHold = the hold a human tick passed through (audited after the picker).
10755
+ let bypassedHold = null;
9916
10756
  {
9917
10757
  const hold = currentAutoDispatchHold(state.config);
9918
10758
  const nextHold = hold && hold.reason === 'utilization-held'
9919
- ? { window: hold.window, percent: hold.percent, threshold: hold.threshold, resetsAt: hold.resetsAt }
10759
+ ? { window: hold.window, percent: hold.percent, threshold: hold.threshold, baseThreshold: hold.baseThreshold ?? null, resetsAt: hold.resetsAt }
9920
10760
  : null;
9921
10761
  const holdKey = hold ? `${hold.reason}|${hold.window ?? ''}|${String(hold.percent)}` : null;
9922
10762
  const holdChanged = holdKey !== lastAutoDispatchHoldKey;
9923
10763
  utilizationHold = nextHold;
9924
10764
  lastAutoDispatchHoldKey = holdKey;
10765
+ const pendingCount = hold || openAutoDispatchHold
10766
+ ? state.jobs.filter((j) => j.status === 'pending' && !runningSet.has(j.slug)).length
10767
+ : 0;
10768
+ const startObserved = previousTickUnheld;
10769
+ previousTickUnheld = hold == null;
10770
+ if (hold || openAutoDispatchHold) trackAutoDispatchHoldAudit(hold, pendingCount, startObserved);
9925
10771
  if (hold) {
9926
- const pendingCount = state.jobs.filter((j) => j.status === 'pending' && !runningSet.has(j.slug)).length;
9927
10772
  if (human) {
10773
+ bypassedHold = hold;
9928
10774
  console.log(`[scheduler] ${hold.reason}: ${hold.detail} — human run bypassed the hold`);
9929
10775
  } else {
9930
10776
  if (holdChanged) {
@@ -9946,6 +10792,10 @@ async function tickBody(gen, { bypassLoadGate, lastResort, human = false }) {
9946
10792
  const heldSlugs = await computeLaunchHolds(state);
9947
10793
  for (const [slug, why] of computePreflightHolds(state.jobs)) if (!heldSlugs.has(slug)) heldSlugs.set(slug, why);
9948
10794
  for (const [slug, why] of computeInterruptHolds(state.jobs)) if (!heldSlugs.has(slug)) heldSlugs.set(slug, why);
10795
+ if (planReviewHold.planReviewEnabled()) {
10796
+ const prHeld = await applyPlanReviewHolds(state, {});
10797
+ for (const [slug, why] of prHeld) if (!heldSlugs.has(slug)) heldSlugs.set(slug, why);
10798
+ }
9949
10799
  if (stale()) return STALE_TICK;
9950
10800
  const satisfiedSlugsByCwd = await budget.computeDepHistorySatisfaction(state);
9951
10801
  lastSatisfiedSlugsByCwd = satisfiedSlugsByCwd;
@@ -9957,6 +10807,7 @@ async function tickBody(gen, { bypassLoadGate, lastResort, human = false }) {
9957
10807
  heldSlugs,
9958
10808
  satisfiedSlugsByCwd,
9959
10809
  });
10810
+ if (bypassedHold) auditHoldBypassed(bypassedHold, batch);
9960
10811
  if (batch.length === 0 && freeSlots === 0) {
9961
10812
  const snap = sessionSlots.snapshot();
9962
10813
  const pendingCount = state.jobs.filter((j) => j.status === 'pending').length;
@@ -10393,6 +11244,10 @@ function projectRowsFor(jobs, cwd) {
10393
11244
  * root — the scheduler re-checks those on its own backoff, so the project is
10394
11245
  * waiting on a precondition, not starved.
10395
11246
  */
11247
+ function isPlanReviewHeldRow(j) {
11248
+ return !!j && j.status === 'pending' && typeof j.heldReason === 'string' && j.heldReason.startsWith(PLAN_REVIEW_HELD_PREFIX);
11249
+ }
11250
+
10396
11251
  function starveRootFor(projectRows, oldestPendingSlug = null) {
10397
11252
  const roots = starvation.rootBlockersForProject(projectRows);
10398
11253
  const root = roots.find((r) => r.heldSlugs.includes(oldestPendingSlug)) ?? roots[0] ?? null;
@@ -10400,7 +11255,16 @@ function starveRootFor(projectRows, oldestPendingSlug = null) {
10400
11255
  if (roots.length > 0 && roots.every((r) => r.preflightHeld)) {
10401
11256
  const waiting = new Set(roots.flatMap((r) => r.heldSlugs));
10402
11257
  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'));
11258
+ knownWait = projectRows.every((j) => j.status !== 'pending' || waiting.has(j.slug) || (j.preflightHold && typeof j.preflightHold === 'object') || isPlanReviewHeldRow(j));
11259
+ }
11260
+ // Every pending row is waiting on an independent plan review (or behind one that is).
11261
+ if (!knownWait) {
11262
+ const pending = projectRows.filter((j) => j.status === 'pending');
11263
+ if (pending.some(isPlanReviewHeldRow)) {
11264
+ const waiting = new Set(roots.flatMap((r) => [r.slug, ...r.heldSlugs]));
11265
+ knownWait = roots.every((r) => r.preflightHeld || isPlanReviewHeldRow(projectRows.find((j) => j.slug === r.slug)))
11266
+ && pending.every((j) => isPlanReviewHeldRow(j) || waiting.has(j.slug) || (j.preflightHold && typeof j.preflightHold === 'object'));
11267
+ }
10404
11268
  }
10405
11269
  return { root, knownWait };
10406
11270
  }
@@ -10862,8 +11726,9 @@ async function reapDeadRunningJobs() {
10862
11726
  // observed 429 as a live one, and must open the same shared circuit.
10863
11727
  billing.usageCircuit.recordFailure('executor_429');
10864
11728
  const triggering = dead.find((d) => d.outcome === 'rate_limited');
10865
- const billingResetIso = await billingResetForPause();
10866
- const pauseThreshold = state.config?.utilizationThreshold;
11729
+ const billingReading = await billingReadingForPause();
11730
+ const billingResetIso = billingReading.resetsAt;
11731
+ const pauseThreshold = bindingWindowPauseThreshold(state.config?.utilizationThreshold, billingReading, Date.now());
10867
11732
  const resetIso = resolveRateLimitPauseReset(triggering.logPath, billingResetIso, Date.now(), { billingUtilization: cachedUtilization, threshold: pauseThreshold });
10868
11733
  if (resetIso == null) logBillingResetRejected(billingResetIso, cachedUtilization, pauseThreshold);
10869
11734
  const triggeringRow = triggering ? state.jobs.find((x) => x.slug === triggering.slug) : null;
@@ -11632,7 +12497,8 @@ function applyNeedsReviewAutoResolve(j, jobsInProject = []) {
11632
12497
  if ((j.exhaustedResolveAttempts ?? 0) > reviewLadder.NEEDS_REVIEW_RESOLVE_CAP) return null;
11633
12498
  const originIsGuardParked = !reviewLadder.isExhaustedAutoFix(j) && reviewLadder.isGuardParkedWithoutAutoFix(j);
11634
12499
 
11635
- if (j.looksDone) {
12500
+ // A looksDone stamped before PRD 4500 must never complete a FAIL row.
12501
+ if (j.looksDone && j.verifierVerdict !== 'sentinel_fail') {
11636
12502
  const attempt = j.exhaustedResolveAttempts ?? 0;
11637
12503
  const reason = originIsGuardParked
11638
12504
  ? `needs_review auto-resolve: guard verdict '${j.verifierVerdict}' with landed commit and looksDone evidence (${j.looksDone.rule}) — `
@@ -11843,6 +12709,10 @@ async function attributeLandedCommits(job, pathCommits, cwd) {
11843
12709
  * @returns {Promise<{commits: string[], paths: string[], detectedAt: string, rule: string} | null>}
11844
12710
  */
11845
12711
  async function computeLooksDone(job, fetchedCwds) {
12712
+ // An explicit executor FAIL is authoritative: the run said the work is not
12713
+ // done, so its own commits (often just a record of the blocker) are never
12714
+ // evidence that it is (PRD 4500; starry-night-2 863-fix, eac6e7e).
12715
+ if (job?.verifierVerdict === 'sentinel_fail') return null;
11846
12716
  const prdPath = (await resolveVerifyPrdPath(job)) ?? prdPaths.archivedPrdPathForJob(job);
11847
12717
  const paths = declaredPathsForPrd(prdPath);
11848
12718
  if (!paths.length) return null;
@@ -11997,6 +12867,8 @@ async function runGateShadow(job) {
11997
12867
  // still complete when every HEAD failure already failed at the job's base
11998
12868
  // commit. The base run is memoized per HEAD on gateShadow.baseline.
11999
12869
  let baselineDecision = null;
12870
+ const runId = job.runId || reviewLadder.resolveRunId(job);
12871
+ const verdictsPath = runId ? path.join(schedulerPaths.runsDir(), runId, `${job.slug}.verdicts.json`) : null;
12000
12872
  if (
12001
12873
  job.verifierVerdict === 'sentinel_fail'
12002
12874
  && outcome.status === 'red' && definitive
@@ -12043,21 +12915,19 @@ async function runGateShadow(job) {
12043
12915
  try { await execGitAt(job.cwd, ['worktree', 'prune'], { timeout: 30_000 }); } catch { /* best-effort */ }
12044
12916
  }
12045
12917
  }
12046
- baselineDecision = decideBaselineAuthority({ job, headOutcome: outcome, baseOutcome, evidenceOk, ancestorOk, cleanOk, headStable });
12918
+ // The run's recorded FAIL reason (read-only; runVerify owns the sidecar).
12919
+ const sidecar = verdictsPath ? readJsonOrSync(verdictsPath, null) : null;
12920
+ const failReason = sidecar && typeof sidecar.reason === 'string' ? sidecar.reason : '';
12921
+ baselineDecision = decideBaselineAuthority({ job, headOutcome: outcome, baseOutcome, evidenceOk, ancestorOk, cleanOk, headStable, failReason });
12047
12922
  gateShadow.baseline = { head: headBefore, base: job.guardHeadBefore, outcome: baseOutcome, setup: baseSetup, ...baselineDecision };
12048
12923
  }
12049
12924
 
12050
- const runId = job.runId || reviewLadder.resolveRunId(job);
12051
- if (runId) {
12052
- const verdictsPath = path.join(schedulerPaths.runsDir(), runId, `${job.slug}.verdicts.json`);
12053
- // Read-merge (single-writer law: runVerify owns the sidecar's other keys).
12054
- // Only merge into an existing run dir — never conjure one.
12055
- if (fs.existsSync(path.dirname(verdictsPath))) {
12056
- let existing = {};
12057
- try { existing = JSON.parse(fs.readFileSync(verdictsPath, 'utf8')) || {}; } catch { /* absent/unparseable → fresh */ }
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 */ }
12060
- }
12925
+ // Read-merge (single-writer law: runVerify owns the sidecar's other keys).
12926
+ // Only merge into an existing run dir — never conjure one.
12927
+ if (verdictsPath && fs.existsSync(path.dirname(verdictsPath))) {
12928
+ const existing = readJsonOrSync(verdictsPath, {}) || {}; // absent/unparseable → fresh
12929
+ const criteriaRecord = gateShadow.criteriaChecks ? { criteriaChecks: { head: headBefore, ranAt: gateShadow.ranAt, results: gateShadow.criteriaChecks } } : {};
12930
+ try { config.writeJsonSync(verdictsPath, { ...existing, gateShadow, ...criteriaRecord }); } catch { /* best-effort */ }
12061
12931
  }
12062
12932
 
12063
12933
  const headShort = headBefore ? headBefore.slice(0, 7) : 'unknown';
@@ -12255,6 +13125,24 @@ const PARK_ERRORS = Object.freeze({
12255
13125
  autofix_plan_unqueued: 'auto-fix investigation produced a fix plan that never reached the queue — parked',
12256
13126
  });
12257
13127
 
13128
+ /**
13129
+ * The artifact evidence persisted on a job row by spawnJob's finalize, but only
13130
+ * when it was captured for `runId` — the run the rescan is re-verifying.
13131
+ * Never throws.
13132
+ * @param {object} job
13133
+ * @param {string} runId
13134
+ * @returns {object|null}
13135
+ */
13136
+ function rescanArtifactEvidence(job, runId) {
13137
+ try {
13138
+ const ev = job?.artifactEvidence;
13139
+ if (!ev || typeof ev !== 'object' || Array.isArray(ev)) return null;
13140
+ return ev.runId === runId ? ev : null;
13141
+ } catch {
13142
+ return null;
13143
+ }
13144
+ }
13145
+
12258
13146
  async function reverifyNeedsReview() {
12259
13147
  const snap = await readQueue();
12260
13148
  // isGuardParkedWithoutAutoFix rows are NOT isRescanCandidate (their
@@ -12321,7 +13209,8 @@ async function reverifyNeedsReview() {
12321
13209
  }
12322
13210
  continue;
12323
13211
  }
12324
- const runDir = path.join(schedulerPaths.runsDir(), job.runId || reviewLadder.resolveRunId(job));
13212
+ const rescanRunId = job.runId || reviewLadder.resolveRunId(job);
13213
+ const runDir = path.join(schedulerPaths.runsDir(), rescanRunId);
12325
13214
  const prdPath = (await resolveVerifyPrdPath(job)) ?? prdPaths.archivedPrdPathForJob(job);
12326
13215
  // Derive committedDuringRun from the recorded run window. The live
12327
13216
  // commit-guard uses gitTreeGuard.gitHead() (before/after HEAD diff); here the run is
@@ -12344,6 +13233,9 @@ async function reverifyNeedsReview() {
12344
13233
  committedDuringRun,
12345
13234
  allowPreSentinelHeal: true,
12346
13235
  priorLandedCommit,
13236
+ // Evidence captured before this run's worktree was removed — only
13237
+ // when it belongs to the run being re-verified.
13238
+ artifactEvidence: rescanArtifactEvidence(job, rescanRunId),
12347
13239
  // job.landedCommit is THIS row's own last-run attribution (stamped by
12348
13240
  // spawnJob's finalize, survives resetJobFields) — the same
12349
13241
  // ground-truth-outranks-heuristics evidence spawnJob passes live,
@@ -12499,14 +13391,17 @@ async function reverifyNeedsReview() {
12499
13391
  const orig = healTargetForFix(job.slug, s.jobs);
12500
13392
  if (!orig) continue;
12501
13393
  const priorStatus = orig.status;
12502
- transitionJob(orig, 'completed', { reason: `auto-promoted: fix plan ${job.slug} already completed`, source: 'reverifyNeedsReview:auto-promote' });
12503
- orig.exitCode = 0;
12504
- orig.error = null;
12505
- orig.completedBy = job.slug;
12506
- delete orig.looksDone;
12507
- if (priorStatus === 'needs_review') delete orig.verifierVerdict;
12508
- promoted.push(`${orig.slug} (was ${priorStatus}, via ${job.slug})`);
12509
- promotedPrds.push({ slug: orig.slug, cwd: orig.cwd });
13394
+ const outcome = applyFixSuccessToOriginal(orig, job.slug, {
13395
+ promoteReason: `auto-promoted: fix plan ${job.slug} already completed`,
13396
+ promoteSource: 'reverifyNeedsReview:auto-promote',
13397
+ requeueSource: 'reverifyNeedsReview:auto-promote',
13398
+ });
13399
+ if (outcome === 'skipped') continue;
13400
+ if (outcome === 'completed') {
13401
+ if (priorStatus === 'needs_review') delete orig.verifierVerdict;
13402
+ promotedPrds.push({ slug: orig.slug, cwd: orig.cwd });
13403
+ }
13404
+ promoted.push(`${orig.slug} (was ${priorStatus}, ${outcome} via ${job.slug})`);
12510
13405
  }
12511
13406
  });
12512
13407
  for (const { slug, cwd } of promotedPrds) {
@@ -12854,6 +13749,7 @@ function registerScheduleHandlers() {
12854
13749
  });
12855
13750
 
12856
13751
  ipcMain.handle('schedule:force-tick', async () => {
13752
+ await auditHumanPress('force-tick');
12857
13753
  // Bypass the billing-poll gate entirely — fire pending jobs immediately regardless of meter state.
12858
13754
  // Clears any existing pause first (same semantics as run-now).
12859
13755
  await clearPause('run-now');
@@ -12950,6 +13846,7 @@ function registerScheduleHandlers() {
12950
13846
  }));
12951
13847
 
12952
13848
  ipcMain.handle('schedule:run-now', async () => {
13849
+ await auditHumanPress('run-now');
12953
13850
  // Manual run-now overrides any auto-pause. Clear it first.
12954
13851
  await clearPause('run-now');
12955
13852
  runDueJobs({ bypassLoadGate: true, human: true }).catch((e) => logs.writeLine({ level: 'error', scope: 'scheduler', message: 'runDueJobs error (run-now)', meta: { error: e?.message } }));
@@ -13345,6 +14242,9 @@ function _setPeriodicReverifyEnabledForTests(enabled) {
13345
14242
 
13346
14243
  async function init() {
13347
14244
  ensureDirs();
14245
+ // Held scheduler turns (heldSchedulerTurns.cjs) consult the same auto-dispatch
14246
+ // hold tickBody applies — registered before boot reconcile can finish a job.
14247
+ heldSchedulerTurns.setHoldProvider(() => currentAutoDispatchHold(lastSeenConfig));
13348
14248
  // Boot phase — reconciliation, migrations, self-heal, first reset probe.
13349
14249
  // Guarded as a unit: everything below installs the timers that ARE the
13350
14250
  // running scheduler (poll loop, heartbeat, supervisor). A throw in here
@@ -13540,6 +14440,10 @@ async function init() {
13540
14440
  });
13541
14441
 
13542
14442
  await rescheduleTimer();
14443
+
14444
+ // Once after boot reconciliation: deliver any turns held across a restart
14445
+ // whose hold has since cleared (never rejects).
14446
+ drainHeldSchedulerTurns();
13543
14447
  } catch (e) {
13544
14448
  console.error('[scheduler] boot phase failed — starting timers anyway:', e?.message);
13545
14449
  try {
@@ -14019,6 +14923,14 @@ const remote = {
14019
14923
  return JSON.parse(JSON.stringify(Array.isArray(state?.jobs) ? state.jobs : []));
14020
14924
  },
14021
14925
 
14926
+ // listJobRows after any in-flight mutate() has written queue.json. A mutate
14927
+ // body appends job.status_changed BEFORE writeQueue, so the epic-state
14928
+ // emitter's recompute must wait for the write. Never calls mutate().
14929
+ async listJobRowsSettled() {
14930
+ try { await mutateTail; } catch { /* chain errors are not ours */ }
14931
+ return remote.listJobRows();
14932
+ },
14933
+
14022
14934
  // Single queue row lookup, used by cancelJob/updatePrd's status guards and
14023
14935
  // the admin GET /admin/scheduler/prds?slug= route (PRD 1024).
14024
14936
  async getJob(slug) {
@@ -14036,7 +14948,15 @@ const remote = {
14036
14948
  // long as the underlying PRD set doesn't change mid-page.
14037
14949
  async listPrds(filter = {}) {
14038
14950
  const filterCwd = normalizeListCwd(filter.cwd);
14039
- const all = await listPrdsShared({ cwd: filterCwd });
14951
+ // fresh: true (strictly the boolean) skips the single-flight and scans
14952
+ // now. It exists for the PRD-create cross-Epic guard, which reads under a
14953
+ // per-project lock and must never reuse a scan that began before another
14954
+ // create's write (2026-11-24: Bilko PRD 2005 duplicated 2001). In-process
14955
+ // callers only — the admin route never forwards it, since outside callers
14956
+ // piling up full scans is the 2026-11-08 heap incident the single-flight fixed.
14957
+ const all = filter.fresh === true
14958
+ ? await listPrdsInternal({ cwd: filterCwd })
14959
+ : await listPrdsShared({ cwd: filterCwd });
14040
14960
  const filtered = all.filter((entry) => {
14041
14961
  if (filterCwd && entry.cwd !== filterCwd) return false;
14042
14962
  if (filter.epicId && entry.epicId !== filter.epicId) return false;
@@ -14244,6 +15164,12 @@ const remote = {
14244
15164
  try {
14245
15165
  await config.writeTextAtomic(filePath, newRaw, { writer: 'scheduler' });
14246
15166
  const stat = await fsp.stat(filePath);
15167
+ try {
15168
+ patchWarnings = patchWarnings.concat(mcpReachWarnings(
15169
+ { agentType: fm.agentType, riskTools: fm.riskTools, cwd: fm.cwd || cwd },
15170
+ prdCreate.mcpReachDeps,
15171
+ ));
15172
+ } catch { /* advisory only — never fails the update */ }
14247
15173
  return patchWarnings.length
14248
15174
  ? { ok: true, slug, bytesWritten: stat.size, warnings: patchWarnings }
14249
15175
  : { ok: true, slug, bytesWritten: stat.size };
@@ -14521,7 +15447,7 @@ const remote = {
14521
15447
  return {
14522
15448
  ok: false,
14523
15449
  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 },
15450
+ hold: { reason: hold.reason, window: hold.window, percent: hold.percent, threshold: hold.threshold, baseThreshold: hold.baseThreshold ?? null, resetsAt: hold.resetsAt },
14525
15451
  };
14526
15452
  }
14527
15453
  const target = {
@@ -14644,6 +15570,9 @@ queueOps.bindQueueAccess({
14644
15570
 
14645
15571
  module.exports = {
14646
15572
  PARK_ERRORS,
15573
+ applyPlanReviewHolds,
15574
+ starveRootFor,
15575
+ rescanArtifactEvidence,
14647
15576
  harvestJobArtifacts,
14648
15577
  jobArtifactRunId,
14649
15578
  applyDepHoldNotices,
@@ -14683,8 +15612,15 @@ module.exports = {
14683
15612
  loadSchedulerState,
14684
15613
  persistSchedulerState,
14685
15614
  getSchedulerStateSnapshot,
15615
+ _getOpenAutoDispatchHoldForTests,
15616
+ _auditHumanPressForTests: auditHumanPress,
15617
+ _forgetLastSeenConfigForTests,
15618
+ _forgetOpenAutoDispatchHoldForTests,
15619
+ _resetPreviousTickUnheldForTests,
14686
15620
  computeDegradedBudget,
14687
15621
  utilizationReading,
15622
+ usageHoldThreshold,
15623
+ currentUsageHold,
14688
15624
  writeQueue,
14689
15625
  _setPeriodicReverifyEnabledForTests,
14690
15626
  _setLoadGateForTests,
@@ -14727,6 +15663,7 @@ module.exports = {
14727
15663
  isPromotableOriginal,
14728
15664
  applyRcaClassification,
14729
15665
  healTargetForFix,
15666
+ applyFixSuccessToOriginal,
14730
15667
  buildInvestigationPrompt,
14731
15668
  readRunOutcomeSidecars,
14732
15669
  isFixPlanSlug,
@@ -14757,6 +15694,7 @@ module.exports = {
14757
15694
  applyOrphanOutcome,
14758
15695
  registerAdminRoutes,
14759
15696
  notifyOriginatingTab,
15697
+ drainHeldSchedulerTurns,
14760
15698
  flushDueReviewNotices,
14761
15699
  isNotifiableTerminalStatus,
14762
15700
  armSettleAfterValidatorBudgetKill,
@@ -14821,11 +15759,21 @@ module.exports = {
14821
15759
  pickRunDir,
14822
15760
  resolveRateLimitPauseReset,
14823
15761
  billingResetForPause,
15762
+ billingReadingForPause,
14824
15763
  computeEffectiveResumeAt,
14825
15764
  computeResumeDelay,
14826
15765
  FOREIGN_WIP_BLOCK_STREAK_LIMIT,
14827
15766
  validateForeignWipBlockClaim,
14828
15767
  requeueForeignWipBlockedJobs,
15768
+ __test: { bindingWindowPauseThreshold },
15769
+ // Test-only seams (schedulerPlanRecordHarvest.test.cjs).
15770
+ __jobDeclaredArtifactPaths: jobDeclaredArtifactPaths,
15771
+ __harvestJobPlanRecords: harvestJobPlanRecords,
15772
+ __driveUpgradeDrain: driveUpgradeDrain,
15773
+ __clearStaleDrainAtBoot: clearStaleDrainAtBoot,
15774
+ __getDrainActive: () => drainActive,
15775
+ __setDrainActiveForTests: (v) => { drainActive = Boolean(v); },
15776
+ __setRestartHandlerForTests: setRestartHandler,
14829
15777
  };
14830
15778
 
14831
15779
  // Lazy path getters: resolved from SM_SCHEDULER_HOME at each read, never frozen