claude-code-session-manager 0.139.0 → 0.141.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 (154) hide show
  1. package/README.md +20 -4
  2. package/dist/assets/AppSettings-DExeJhqQ.js +2 -0
  3. package/dist/assets/History-DJMiuXyK.js +2 -0
  4. package/dist/assets/{HomeClaudeConfig-CGD2Onjv.js → HomeClaudeConfig-CTp2tkZ4.js} +2 -2
  5. package/dist/assets/{Panel-Csyd9HbD.js → Panel-Bf1Cf8UL.js} +1 -1
  6. package/dist/assets/{ProjectClaudeConfig-C-jlYpC_.js → ProjectClaudeConfig-BWPpypf9.js} +1 -1
  7. package/dist/assets/Scheduler-cyr61UAC.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-DcscPXAG.js → SkillReferenceGraph-Ba4TkX2C.js} +1 -1
  9. package/dist/assets/{Skills-BpGRKOcY.js → Skills-C1v91GEO.js} +26 -26
  10. package/dist/assets/{TiptapBody-DSU3769X.js → TiptapBody-BrcWVpiW.js} +1 -1
  11. package/dist/assets/{ViewTabs-C0PRZx4_.js → ViewTabs-DXhOWFG0.js} +1 -1
  12. package/dist/assets/{VoiceButton-D2rMurNg.js → VoiceButton-qivnDV6K.js} +1 -1
  13. package/dist/assets/{historyTotals-TcIQs2sh.js → historyTotals-CMCPTKqC.js} +1 -1
  14. package/dist/assets/index-B2TQz3nd.js +3121 -0
  15. package/dist/assets/{index-BCySPdtU.css → index-DKXdXfka.css} +1 -1
  16. package/dist/index.html +2 -2
  17. package/dist-web/app.css +1 -1
  18. package/dist-web/app.js +423 -426
  19. package/package.json +5 -2
  20. package/plugins/AGENTS.md +60 -0
  21. package/plugins/CLAUDE.md +1 -60
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +4 -2
  23. package/plugins/session-manager-dev/skills/develop/SKILL.md +29 -19
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  26. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  33. package/scripts/README.md +1 -0
  34. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  35. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  36. package/scripts/ops-sweep.cjs +53 -23
  37. package/scripts/scheduler-mcp-server.cjs +205 -18
  38. package/src/main/build-info.json +4 -4
  39. package/src/main/config.cjs +112 -8
  40. package/src/main/docEdit.cjs +6 -1
  41. package/src/main/files.cjs +7 -27
  42. package/src/main/health.cjs +48 -15
  43. package/src/main/historyAggregator.cjs +88 -5
  44. package/src/main/historyDashboard.cjs +69 -4
  45. package/src/main/index.cjs +56 -2
  46. package/src/main/ipcSchemas.cjs +122 -16
  47. package/src/main/lib/AGENTS.md +54 -0
  48. package/src/main/lib/CLAUDE.md +1 -54
  49. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  50. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  51. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  52. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  53. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  54. package/src/main/lib/claude/effectiveModelInfo.cjs +90 -20
  55. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  56. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  57. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  58. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  59. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  60. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  61. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  62. package/src/main/lib/ephemeralCwd.cjs +37 -2
  63. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  64. package/src/main/lib/epic/epicAdminRoutes.cjs +25 -5
  65. package/src/main/lib/epic/epicOutsideRead.cjs +118 -1
  66. package/src/main/lib/epic/epicOutsideState.cjs +2 -2
  67. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  68. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  69. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  70. package/src/main/lib/externalContract.cjs +31 -5
  71. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +55 -1
  72. package/src/main/lib/feedback-remote/crossProjectReply.cjs +106 -11
  73. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +47 -19
  74. package/src/main/lib/feedback-remote/needsYouStore.cjs +6 -2
  75. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  76. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  77. package/src/main/lib/git/branchSweep.cjs +209 -4
  78. package/src/main/lib/git/gitWorktree.cjs +41 -5
  79. package/src/main/lib/guardShims.cjs +1 -1
  80. package/src/main/lib/historyRollup.cjs +26 -0
  81. package/src/main/lib/insideHome.cjs +27 -1
  82. package/src/main/lib/mcpToolCatalog.cjs +132 -13
  83. package/src/main/lib/mdDocCensus.cjs +59 -78
  84. package/src/main/lib/mdDocRefs.cjs +71 -93
  85. package/src/main/lib/mdNetworkScan.cjs +245 -250
  86. package/src/main/lib/mdReviewRecord.cjs +22 -9
  87. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  88. package/src/main/lib/opsOwnership.cjs +18 -2
  89. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  90. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  91. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  92. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  93. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  94. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  95. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  96. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  97. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  98. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  99. package/src/main/lib/prd/prdCreate.cjs +377 -23
  100. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  101. package/src/main/lib/prd/prdFrontmatter.cjs +121 -3
  102. package/src/main/lib/process/loginItem.cjs +171 -0
  103. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  104. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  105. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  106. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  107. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  108. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  109. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  110. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  111. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  112. package/src/main/lib/scheduler/preflightCheck.cjs +97 -0
  113. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  114. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  115. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  116. package/src/main/lib/scheduler/reviewNotice.cjs +39 -0
  117. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  118. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  119. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  120. package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
  121. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  122. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  123. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  124. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  125. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  126. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  127. package/src/main/lib/tasks/taskRun.cjs +313 -0
  128. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  129. package/src/main/loginItemIpc.cjs +35 -0
  130. package/src/main/loopEfficiencyHandlers.cjs +10 -1
  131. package/src/main/projectPages.cjs +6 -15
  132. package/src/main/promptSessionEvents.cjs +9 -1
  133. package/src/main/queueOps.cjs +260 -3
  134. package/src/main/runVerify.cjs +53 -25
  135. package/src/main/scheduler/AGENTS.md +26 -0
  136. package/src/main/scheduler/CLAUDE.md +1 -26
  137. package/src/main/scheduler/budget.cjs +239 -9
  138. package/src/main/scheduler/cancelDependents.cjs +154 -0
  139. package/src/main/scheduler/prdParser.cjs +19 -1
  140. package/src/main/scheduler/reviewLadder.cjs +36 -3
  141. package/src/main/scheduler/starvation.cjs +89 -18
  142. package/src/main/scheduler.cjs +1080 -89
  143. package/src/main/supervisor.cjs +5 -1
  144. package/src/main/templates/PRD_AUTHORING.md +14 -1
  145. package/src/main/validationQualityHandlers.cjs +199 -0
  146. package/src/main/webRemote.cjs +10 -2
  147. package/src/preload/api.d.ts +364 -21
  148. package/src/preload/apiSurface.json +89 -10
  149. package/src/preload/index.cjs +23 -2
  150. package/src/seed/agents/validator.md +19 -8
  151. package/dist/assets/AppSettings-CUfWY9vN.js +0 -2
  152. package/dist/assets/History-DDnqaLyw.js +0 -2
  153. package/dist/assets/Scheduler-NLs08fx7.js +0 -16
  154. package/dist/assets/index-C-d0DCre.js +0 -3124
@@ -51,7 +51,8 @@ const { AsyncLocalStorage } = require('node:async_hooks');
51
51
  const { startDispatchLoop } = require('./lib/scheduler/dispatchLoop.cjs');
52
52
  const schedulerPaths = require('./lib/scheduler/schedulerPaths.cjs');
53
53
  const { randomUUID } = require('node:crypto');
54
- const { execFile, execFileSync } = require('node:child_process');
54
+ const { execFile, execFileSync, spawnSync } = require('node:child_process');
55
+ const { buildJobSandboxSettings, sandboxDependencies, sandboxChildEnv, SANDBOX_PROFILES } = require('./lib/claude/jobSandboxPolicy.cjs');
55
56
  const { ipcMain } = require('electron');
56
57
  const billing = require('./usage.cjs');
57
58
  const { cleanChildEnv, pathWithUserBins } = require('./lib/process/cleanEnv.cjs');
@@ -77,9 +78,15 @@ const {
77
78
  findLiveProcessForJob, logHasOutput, resolvePidlessGateOutcome, resolveCommitGuardOutcome,
78
79
  readSpawnedPidFromLog, readLogMtimeMs, isClaudeArgv,
79
80
  } = require('./lib/scheduler/reaperHelpers.cjs');
80
- const { resolveProjectRoot, ensureRuntimeIgnores, RUNTIME_NAMESPACES, opsPath } = require('./lib/opsOwnership.cjs');
81
+ const { resolveProjectRoot, ensureRuntimeIgnores, RUNTIME_NAMESPACES, opsPath, assertOpsWrite } = require('./lib/opsOwnership.cjs');
81
82
  const { BUILTIN_MACROS } = require('./lib/persona-macro/builtinMacros.cjs');
82
- const { sweepStrandedJobBranches } = require('./lib/git/branchSweep.cjs');
83
+ const {
84
+ sweepStrandedJobBranches,
85
+ loadBranchSweepBackoff,
86
+ saveBranchSweepBackoff,
87
+ takeUnreportedGiveUps,
88
+ emptyBackoffState: emptyBranchSweepBackoffState,
89
+ } = require('./lib/git/branchSweep.cjs');
83
90
  const { detectRateLimitInLog } = require('./lib/claude/rateLimitDetect.cjs');
84
91
  const { stripAppOwnedChurn } = require('./lib/scheduler/jobDirtFilter.cjs');
85
92
  const { GATE_AUTHORITY_VERDICTS, decideGateAuthority } = require('./lib/scheduler/gateAuthority.cjs');
@@ -108,12 +115,11 @@ const prdPaths = require('./scheduler/prdPaths.cjs');
108
115
  const sessionsStore = require('./sessionsStore.cjs');
109
116
  const { enqueueExternalPrompt } = require('./chatRunner.cjs');
110
117
  const { appendResponseEventIfKnown, appendResponseEventWithReason } = require('./promptSessionEvents.cjs');
111
- const { buildReviewNotice, selectDueReviewNotices, formatReviewNotice, holdMsFromEnv } = require('./lib/scheduler/reviewNotice.cjs');
118
+ const { buildReviewNotice, selectDueReviewNotices, formatReviewNotice, holdMsFromEnv, buildPreflightHoldNotice, preflightHoldNoticeKey } = require('./lib/scheduler/reviewNotice.cjs');
112
119
  const epicValidationHook = require('./lib/epic/epicValidationHook.cjs');
113
120
  const prdCreate = require('./lib/prd/prdCreate.cjs');
114
121
  const { resolveProjectContext } = require('./lib/projectRootResolve.cjs');
115
122
  const { expandHome } = require('./lib/util/expandHome.cjs');
116
- const { parseValidationSentinels } = require('./lib/scheduler/validationSentinels.cjs');
117
123
  const { hasDownstreamValidator } = require('./lib/prd/planValidator.cjs');
118
124
  const promptSessionTranscript = require('./promptSessionTranscript.cjs');
119
125
  const { verifyRun, parseLog, scanSentinel, scanForeignWipPathsClaim } = require('./runVerify.cjs');
@@ -123,6 +129,7 @@ const { landedSinceRun, landedOnMainSince } = require('./lib/scheduler/landedSin
123
129
  const { declaredPathsForPrd, issuedAtForPrd } = require('./lib/prd/prdDeclaredPaths.cjs');
124
130
  const { identity: procIdentityOf, isDifferentProcess } = require('./lib/process/procIdentity.cjs');
125
131
  const jobLeftovers = require('./lib/scheduler/jobLeftovers.cjs');
132
+ const { harvestPlanRecords } = require('./lib/scheduler/planRecordHarvest.cjs');
126
133
  const logs = require('./logs.cjs');
127
134
  const { schemas, validated, SCHEDULE_SLUG_RE } = require('./ipcSchemas.cjs');
128
135
  const { readBody, sendJson } = require('./lib/feedback-remote/localAdminHttp.cjs');
@@ -153,16 +160,19 @@ const queueOps = require('./queueOps.cjs');
153
160
  // Plain Node module, no Electron dependency; queuePath/prdsDir defaults already
154
161
  // match ROOT/QUEUE_PATH below since both resolve the same ~/.claude/session-manager
155
162
  // home-dir layout.
156
- const { listEpicPrdDirs, listArchivedPrdDirs, deriveProjectCwdFromPrdPath } = require('./lib/prd/prdLocations.cjs');
163
+ const { listEpicPrdDirs, listArchivedPrdDirs, deriveProjectCwdFromPrdPath, isSafeEpicId } = require('./lib/prd/prdLocations.cjs');
157
164
  const { ensureEpic, appendPrdCreatedEvent, readActiveIndex } = require('./lib/epic/epicMint.cjs');
158
165
  const agentModelResolve = require('./lib/claude/agentModelResolve.cjs');
159
166
  const packSpawnArgs = require('./lib/packs/packSpawnArgs.cjs');
160
167
  const { buildPersonaToolScope, personaToolScopeArgs, personaToolScopeEnv } = require('./lib/claude/personaToolScope.cjs');
168
+ const { VALIDATOR_VERDICT_SCHEMA, parseValidatorVerdict, verdictRowsFromStructured } = require('./lib/scheduler/validatorVerdictSchema.cjs');
161
169
  const { resolveEpicEffort, effortArgs } = require('./lib/claude/agentEffortResolve.cjs');
162
170
  const { transitionJob, STATUS_HISTORY_CAP, LEGAL_TRANSITIONS } = require('./lib/scheduler/scheduleJobTransitions.cjs');
163
171
  const { buildContextDigest, composeExecutorPrompt } = require('./lib/epic/epicContextDigest.cjs');
164
172
  const { JOB_STATUSES } = require('./lib/scheduler/scheduleJobSchema.cjs');
165
173
  const { appendAuditEvent } = require('./lib/telemetry/auditLog.cjs');
174
+ const preflightCheck = require('./lib/scheduler/preflightCheck.cjs');
175
+ const needsYouStore = require('./lib/feedback-remote/needsYouStore.cjs');
166
176
  const { withTimeout } = require('./lib/util/withTimeout.cjs');
167
177
 
168
178
  // ---------- origin session resolution (PRD 832) ----------
@@ -197,8 +207,12 @@ const adoptedRunSupervisor = require('./lib/scheduler/adoptedRunSupervisor.cjs')
197
207
  const { splitFrontmatter, parsePrdFile, serializePrdFile, isArtifactOnlyDeclaration } = require('./lib/prd/prdFrontmatter.cjs');
198
208
  const { applyStructuredPrdPatch } = require('./lib/prd/prdBodyPatch.cjs');
199
209
  const { resolvePersonaDefaultEstimate, DEFAULT_PRD_AGENT_TYPE } = require('./lib/prd/prdAgentType.cjs');
200
- const { resolveDepSlug, findNearMatches } = require('./lib/prd/depSlugResolve.cjs');
210
+ const { resolveDepSlug, findNearMatches, bareSlug } = require('./lib/prd/depSlugResolve.cjs');
211
+ const { writeJsonAtomic, readJsonOrSync } = require('./lib/util/atomicFs.cjs');
212
+ const { writeToolRiskGuardSettingsFile } = require('./lib/epic/guardSpawnSettings.cjs');
213
+ const toolRiskMarks = require('./lib/claude/toolRiskMarks.cjs');
201
214
  const { computeDispositionRewrite, mintPlanId, resolveInheritedPlanId } = require('./lib/prd/prdDisposition.cjs');
215
+ const cancelDependents = require('./scheduler/cancelDependents.cjs');
202
216
  const { allProjectCwds } = require('./lib/activeSessions.cjs');
203
217
 
204
218
  // Captured once at module load so every run's meta sidecar can record how
@@ -392,7 +406,28 @@ const FINISH_ARTIFACT_ONLY_VERDICT_LINE = `
392
406
  const FINISH_ARTIFACT_ONLY_COMMIT_LINE = `
393
407
  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.`;
394
408
 
395
- function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum, isFixPlan = false, isArtifactOnly = false }) {
409
+ /**
410
+ * harvestJobPlanRecords(job, worktreeDir, projectRoot) — copy this run's
411
+ * plan records from its worktree into the main checkout. Logs, never throws.
412
+ */
413
+ function harvestJobPlanRecords(job, worktreeDir, projectRoot) {
414
+ try {
415
+ const epicId = job.epicId || job.sourcePromptId;
416
+ if (!epicId || !worktreeDir || !projectRoot || path.resolve(worktreeDir) === path.resolve(projectRoot)) return;
417
+ const { copied, skipped } = harvestPlanRecords({ worktreeDir, projectRoot, epicId });
418
+ if (copied.length) console.log(`[scheduler] ${job.slug}: harvested ${copied.length} plan record(s) into ${projectRoot}`);
419
+ for (const sk of skipped) console.warn(`[scheduler] ${job.slug}: plan record not harvested: ${sk.path} — ${sk.reason}`);
420
+ } catch (e) {
421
+ console.error(`[scheduler] ${job.slug}: plan record harvest failed`, e);
422
+ }
423
+ }
424
+
425
+ // Validator jobs only (`--json-schema`): the CLI replaces the result text
426
+ // with the JSON, so the scheduler reads the verdict from structured output.
427
+ const FINISH_VALIDATOR_VERDICT_LINE = `
428
+ - Your structured output's schedulerVerdict (and failReason) is what the scheduler reads as this verdict.`;
429
+
430
+ function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum, isFixPlan = false, isArtifactOnly = false, isValidator = false }) {
396
431
  return `${verifyStepNum}. VERIFY — run every command in the PRD's \`# Gate\` section, in order, in the
397
432
  foreground. Each must exit 0. If the PRD has no \`# Gate\` section, run the
398
433
  project's own typecheck, lint and test commands instead. The project's
@@ -406,10 +441,12 @@ ${commitStepNum}. COMMIT — stage only the exact paths you created or changed f
406
441
  jobs' verdicts. Always commit your own work: this rule changes what you
407
442
  stage, never whether you commit.
408
443
  Never run \`git add -f\` or \`git add --force\` on a path git ignores, unless the
409
- PRD's # Files section names that exact path. If git add refuses a path as
444
+ PRD's # Files section names that exact path AND that path is not under
445
+ session-manager-operations/. If git add refuses a path as
410
446
  ignored, leave it out of the commit and name it in your final report.
411
447
  Why: an ignored path is usually live runtime state, not work product.
412
- Never commit any file under these folders, even when the PRD names it:
448
+ A record under session-manager-operations/plan-records/<epic-id>/ is written in this worktree and never staged; the scheduler copies it to the main checkout.
449
+ Never commit any file under these folders (except each folder's top-level README.md, the layout contract), even when the PRD names it:
413
450
  ${FINISH_RUNTIME_FOLDERS}
414
451
  Why: those folders hold the app's live state. A commit of them breaks the
415
452
  running scheduler for every checkout that pulls it.${isArtifactOnly ? FINISH_ARTIFACT_ONLY_COMMIT_LINE : ''}
@@ -418,7 +455,7 @@ ${verdictStepNum}. VERDICT LINE — end your final report with exactly one of th
418
455
  SCHEDULER_VERDICT: PASS
419
456
  SCHEDULER_VERDICT: FAIL <one-line reason>
420
457
  SCHEDULER_VERDICT: BLOCKED_BY_FOREIGN_WIP
421
- - 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 : ''}
458
+ - 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 : ''}
422
459
  - Print FAIL when the gate is red or the commit could not land. Also print
423
460
  FAIL when a step needs something this run cannot reach (live runtime
424
461
  state, credentials, an account or dashboard action, a host install): do
@@ -468,13 +505,13 @@ in your final report.`;
468
505
  * tree, never FAIL for the missing commit. Self job 826 printed exactly that
469
506
  * false FAIL. Omitted/false leaves the text unchanged.
470
507
  */
471
- function buildFinishProtocol({ reviewInRun = true, isFixPlan = false, isArtifactOnly = false } = {}) {
508
+ function buildFinishProtocol({ reviewInRun = true, isFixPlan = false, isArtifactOnly = false, isValidator = false } = {}) {
472
509
  if (reviewInRun) {
473
510
  return buildFinishHead(3) + FINISH_REVIEW_STEPS_IN_RUN
474
- + buildFinishTail({ verifyStepNum: 3, commitStepNum: 4, verdictStepNum: 5, isFixPlan, isArtifactOnly });
511
+ + buildFinishTail({ verifyStepNum: 3, commitStepNum: 4, verdictStepNum: 5, isFixPlan, isArtifactOnly, isValidator });
475
512
  }
476
513
  return buildFinishHead(2) + FINISH_REVIEW_STEP_DEFERRED
477
- + buildFinishTail({ verifyStepNum: 2, commitStepNum: 3, verdictStepNum: 4, isFixPlan, isArtifactOnly });
514
+ + buildFinishTail({ verifyStepNum: 2, commitStepNum: 3, verdictStepNum: 4, isFixPlan, isArtifactOnly, isValidator });
478
515
  }
479
516
 
480
517
  const FINISH_PROTOCOL = buildFinishProtocol({ reviewInRun: true });
@@ -1091,6 +1128,30 @@ function heartbeatTick(deps = {}) {
1091
1128
  // flag masked before (the burrow-vs-others incident this PRD fixes).
1092
1129
  const now = Date.now();
1093
1130
  const stalledCwds = Object.keys(summary.byProject).filter((cwd) => summary.byProject[cwd].stalled);
1131
+ // Dependency-held stall: pending rows that can never dispatch because
1132
+ // every one waits (directly or down its chain) on a failed/cancelled/
1133
+ // unresolved row. computeStallSummary needs 0 pending, so it never saw
1134
+ // Self's 16 rows held behind a cancelled dep (2026-11-22). Classified
1135
+ // from the dispatch tick's cached satisfied map; until one exists, a
1136
+ // refresh is kicked off asynchronously so the heartbeat never blocks.
1137
+ const heldByDependencyByCwd = {};
1138
+ if (lastSatisfiedSlugsByCwd) {
1139
+ const classified = budget.classifyPendingHolds(s.jobs, {
1140
+ satisfiedSlugsByCwd: lastSatisfiedSlugsByCwd,
1141
+ holds: lastTick?.holds ?? [],
1142
+ now,
1143
+ thresholdMs: POLL_INTERVAL_MS,
1144
+ loadGated: lastTick?.reason === 'load-deferred',
1145
+ });
1146
+ Object.assign(heldByDependencyByCwd, budget.findDependencyStalledProjects(s.jobs, classified));
1147
+ applyDepHoldNotices(classified).catch((e) => console.error('[scheduler] dep-hold Needs-you error', e));
1148
+ } else {
1149
+ refreshSatisfiedSlugsCache(s);
1150
+ }
1151
+ for (const cwd of Object.keys(heldByDependencyByCwd)) {
1152
+ if (summary.byProject[cwd]) summary.byProject[cwd].heldByDependency = heldByDependencyByCwd[cwd];
1153
+ if (!stalledCwds.includes(cwd)) stalledCwds.push(cwd);
1154
+ }
1094
1155
  for (const cwd of [...stallSince.keys()]) {
1095
1156
  if (!stalledCwds.includes(cwd)) {
1096
1157
  stallSince.delete(cwd);
@@ -1106,18 +1167,24 @@ function heartbeatTick(deps = {}) {
1106
1167
  }
1107
1168
  }
1108
1169
  if (toAlert.length > 0) {
1170
+ const heldByDependency = toAlert.flatMap((cwd) => (heldByDependencyByCwd[cwd] ?? []).map((h) => ({ cwd, ...h })));
1109
1171
  console.error(
1110
- `[scheduler] STALL DETECTED in project(s): ${toAlert.join(', ')} — 0 running, 0 pending, not paused, `
1172
+ `[scheduler] STALL DETECTED in project(s): ${toAlert.join(', ')} — nothing dispatchable `
1173
+ + `(0 running + 0 pending, or every pending row held by a dead dependency), not paused, `
1111
1174
  + `for >= ${Math.round(POLL_INTERVAL_MS / 1000)}s`,
1112
1175
  summary.byProject,
1113
1176
  );
1114
- appendAuditEvent('scheduler_stall_detected', { projects: toAlert, total: summary.total, byProject: summary.byProject });
1177
+ appendAuditEvent('scheduler_stall_detected', {
1178
+ projects: toAlert, total: summary.total, byProject: summary.byProject, heldByDependency,
1179
+ });
1115
1180
  if (mainWindow && !mainWindow.isDestroyed()) {
1181
+ const rootPhrases = toAlert.map((cwd) => rootBlockerPhrase(starveRootFor(projectRowsFor(s.jobs, cwd)).root)).join('');
1116
1182
  sendIfAlive(mainWindow, 'schedule:stall', {
1117
- message: `Scheduler stall in ${toAlert.length} project(s): ${toAlert.join(', ')}. Check the Scheduler tab.`,
1183
+ message: `Scheduler stall in ${toAlert.length} project(s): ${toAlert.join(', ')}.${rootPhrases} Check the Scheduler tab.`,
1118
1184
  projects: toAlert,
1119
1185
  total: summary.total,
1120
1186
  byProject: summary.byProject,
1187
+ heldByDependency,
1121
1188
  });
1122
1189
  }
1123
1190
  }
@@ -1904,6 +1971,7 @@ async function reconcilePass(state) {
1904
1971
  deliverable: p.deliverable ?? job.deliverable ?? null,
1905
1972
  artifactPaths: p.artifactPaths ?? job.artifactPaths ?? null,
1906
1973
  effort: p.effort ?? job.effort ?? null,
1974
+ preflight: p.preflight ?? null,
1907
1975
  };
1908
1976
  // Adopt path: a row parked 'quarantined' (no createdVia provenance when
1909
1977
  // discovered) whose PRD file now carries a stamp — written via the
@@ -2031,6 +2099,7 @@ async function reconcilePass(state) {
2031
2099
  deliverable: p.deliverable ?? inv.row?.deliverable ?? null,
2032
2100
  artifactPaths: p.artifactPaths ?? inv.row?.artifactPaths ?? null,
2033
2101
  effort: p.effort ?? inv.row?.effort ?? null,
2102
+ preflight: p.preflight ?? null,
2034
2103
  };
2035
2104
  const reason = `reconcile: repaired invalid status ${JSON.stringify(oldStatus)}`;
2036
2105
  // A repair is not a lifecycle transition — the corrupted `status` was
@@ -2186,6 +2255,7 @@ async function reconcilePass(state) {
2186
2255
  deliverable: p.deliverable ?? null,
2187
2256
  artifactPaths: p.artifactPaths ?? null,
2188
2257
  effort: p.effort ?? null,
2258
+ preflight: p.preflight ?? null,
2189
2259
  status: 'pending',
2190
2260
  // Enqueue time (PRD 1086/1087): the cross-project fairness tiebreak and
2191
2261
  // the starvation escalation both need a provable age for a pending row;
@@ -2210,6 +2280,12 @@ async function reconcilePass(state) {
2210
2280
  // (commitGuardVerdict, isFixPlanBeyondDepthCap, the fix-plan-completion
2211
2281
  // checks) reads this stamp instead of re-deriving it from the name.
2212
2282
  entry.isFixPlan = classifyDiscoveredFixPlan(p, slug);
2283
+ // Validator-quality provenance: the PRD's `fixes` frontmatter rides on the
2284
+ // row (and into history.jsonl) so validationQuality never re-reads PRD
2285
+ // files. Absent/empty → no key at all.
2286
+ if (Array.isArray(p.fixes) && p.fixes.length > 0) {
2287
+ entry.fixes = p.fixes.map((f) => ({ prd: f.prd, missKind: f.missKind, reason: f.reason }));
2288
+ }
2213
2289
  // Stamp investigationDepth relative to the original job it heals, so
2214
2290
  // selectAutoFixTargets/spawnInvestigation can bound the fix-of-a-fix
2215
2291
  // recursion (see MAX_INVESTIGATION_DEPTH). Non-fix-plan jobs get no
@@ -2321,6 +2397,16 @@ async function reconcilePass(state) {
2321
2397
  } catch (e) {
2322
2398
  console.warn('[scheduler] autoArchiveCompleted failed', e?.message);
2323
2399
  }
2400
+ // Auto-dismiss cancelled rows of closed Epics (PRD 3492). In place on
2401
+ // state.jobs — this runs inside a mutate body, so it must never mutate().
2402
+ try {
2403
+ const dismissResult = await queueOps.autoDismissCancelled(state);
2404
+ if (dismissResult.dismissed?.length > 0) {
2405
+ console.log(`[scheduler] auto-dismissed ${dismissResult.dismissed.length} cancelled row(s) of closed Epics: ${dismissResult.dismissed.join(', ')}`);
2406
+ }
2407
+ } catch (e) {
2408
+ console.warn('[scheduler] autoDismissCancelled failed', e?.message);
2409
+ }
2324
2410
  phaseMs.queueWrite = Date.now() - phaseStartMs;
2325
2411
 
2326
2412
  const totalMs = Date.now() - reconcileStartMs;
@@ -2571,6 +2657,90 @@ let dispatchLoopHandle = null;
2571
2657
  // stalled) rather than every 60s heartbeat tick.
2572
2658
  let stallSince = new Map();
2573
2659
  let stallToasted = new Map();
2660
+ // Latest budget.computeDepHistorySatisfaction map — set by every dispatch tick
2661
+ // (and by refreshSatisfiedSlugsCache when the heartbeat runs before any tick)
2662
+ // so the heartbeat's dependency-held stall check never does its own fs read.
2663
+ let lastSatisfiedSlugsByCwd = null;
2664
+ // Dependency-hold Needs-you notices (one per (cwd, blocking slug) episode).
2665
+ // Ids of the notices this process has open; null until seeded from the store
2666
+ // on first use, so a restart withdraws a notice whose hold cleared while down
2667
+ // instead of orphaning it. budget.selectDepHoldNotices decides; this applies.
2668
+ const DEP_HOLD_NEEDS_YOU_APP = 'session-manager';
2669
+ let depHoldOpen = null; // Map<id, { cwd, blockerSlug, blockerStatus, heldSlugs } | null>
2670
+ let depHoldApplyInFlight = false;
2671
+ /**
2672
+ * applyDepHoldNotices(classified, deps?) — side-effect half of the dep-hold
2673
+ * notice: post/withdraw through needsYouStore (the same store the
2674
+ * /admin/needs-you routes use), audit stall_dep_hold_posted /
2675
+ * stall_dep_hold_withdrawn, and broadcast needsYou:changed. Never mints an
2676
+ * Epic or PRD. `deps` ({ store, audit, onChanged, thresholdMs }) is a test seam.
2677
+ */
2678
+ async function applyDepHoldNotices(classified, deps = {}) {
2679
+ const store = deps.store ?? needsYouStore;
2680
+ const audit = deps.audit ?? appendAuditEvent;
2681
+ const onChanged = deps.onChanged ?? (() => { if (mainWindow) sendIfAlive(mainWindow, 'needsYou:changed', {}); });
2682
+ if (depHoldApplyInFlight) return;
2683
+ depHoldApplyInFlight = true;
2684
+ try {
2685
+ if (depHoldOpen === null) {
2686
+ const items = await store.listNeedsYou({ app: DEP_HOLD_NEEDS_YOU_APP, status: 'open' });
2687
+ depHoldOpen = new Map(items
2688
+ .filter((it) => typeof it.id === 'string' && it.id.startsWith(budget.DEP_HOLD_NOTICE_ID_PREFIX))
2689
+ .map((it) => [it.id, null]));
2690
+ }
2691
+ const { post, withdraw } = budget.selectDepHoldNotices(classified, depHoldOpen.keys(), {
2692
+ thresholdMs: deps.thresholdMs ?? budget.DEP_HOLD_NOTICE_MS,
2693
+ });
2694
+ let changed = false;
2695
+ for (const p of post) {
2696
+ const { title, why } = budget.formatDepHoldNotice(p);
2697
+ let result;
2698
+ try {
2699
+ result = await store.postNeedsYou({ app: DEP_HOLD_NEEDS_YOU_APP, id: p.id, title, why });
2700
+ } catch (e) {
2701
+ console.error(`[scheduler] dep-hold Needs-you post failed for ${p.blockerSlug} in ${p.cwd}`, e?.message ?? e);
2702
+ continue; // not marked open — retried next heartbeat
2703
+ }
2704
+ depHoldOpen.set(p.id, p);
2705
+ audit('stall_dep_hold_posted', {
2706
+ id: p.id, cwd: p.cwd, blockerSlug: p.blockerSlug, blockerStatus: p.blockerStatus,
2707
+ heldSlugs: p.heldSlugs, created: result.created, changed: result.changed,
2708
+ });
2709
+ if (result.changed) changed = true;
2710
+ }
2711
+ for (const id of withdraw) {
2712
+ const meta = depHoldOpen.get(id) ?? null;
2713
+ let item;
2714
+ try {
2715
+ item = await store.withdrawNeedsYou({ app: DEP_HOLD_NEEDS_YOU_APP, id });
2716
+ } catch (e) {
2717
+ console.error(`[scheduler] dep-hold Needs-you withdraw failed for ${id}`, e?.message ?? e);
2718
+ continue;
2719
+ }
2720
+ depHoldOpen.delete(id);
2721
+ audit('stall_dep_hold_withdrawn', {
2722
+ id, cwd: meta?.cwd ?? null, blockerSlug: meta?.blockerSlug ?? null, wasOpen: item != null,
2723
+ });
2724
+ if (item) changed = true;
2725
+ }
2726
+ if (changed) onChanged();
2727
+ } finally {
2728
+ depHoldApplyInFlight = false;
2729
+ }
2730
+ }
2731
+ function _resetDepHoldNoticesForTests() {
2732
+ depHoldOpen = null;
2733
+ depHoldApplyInFlight = false;
2734
+ }
2735
+ let satisfiedRefreshInFlight = false;
2736
+ function refreshSatisfiedSlugsCache(state) {
2737
+ if (satisfiedRefreshInFlight) return;
2738
+ satisfiedRefreshInFlight = true;
2739
+ budget.computeDepHistorySatisfaction(state)
2740
+ .then((m) => { if (!lastSatisfiedSlugsByCwd) lastSatisfiedSlugsByCwd = m; })
2741
+ .catch((e) => console.error('[scheduler] satisfied-slugs cache refresh failed', e))
2742
+ .finally(() => { satisfiedRefreshInFlight = false; });
2743
+ }
2574
2744
  // (The 5-minute feedback sweep that used to piggyback on this heartbeat is
2575
2745
  // gone: it scanned each active project's session-manager-operations/feedback/
2576
2746
  // and auto-queued a /process-feedback PRD. Both the folder and that skill are
@@ -2610,6 +2780,10 @@ let lastMemGate = null;
2610
2780
  // predicate after pool → project cap → memory. Withholds launches only.
2611
2781
  let loadGate = createLoadGate();
2612
2782
  function _setLoadGateForTests(gate) { loadGate = gate; }
2783
+ // tickBody's dispatch goes through this indirection so a test can record launches
2784
+ // without forking a real child job (whose completion tick races the next test).
2785
+ let dispatchSpawnJob = (...args) => spawnJob(...args);
2786
+ function _setSpawnJobForTests(fn) { dispatchSpawnJob = fn || ((...args) => spawnJob(...args)); }
2613
2787
 
2614
2788
  // Last tickQueue outcome, kept for the UI. tickQueue already computes a precise
2615
2789
  // reason for every way a batch can come back empty (dependency holds, slot
@@ -2683,7 +2857,9 @@ function formatLoadGateDetail(load) {
2683
2857
  function loadGateAuditFields(load) {
2684
2858
  return {
2685
2859
  loadavg1: load.loadavg1, cores: load.cores, ratio: load.ratio, threshold: load.threshold,
2686
- cpuBusy: load.cpuBusy, cpuIowait: load.cpuIowait, cpuWindowMs: load.cpuWindowMs, heldMs: load.heldMs,
2860
+ // cpuBusy is the decision value: net of the app's own process tree (PRD 3495).
2861
+ cpuBusy: load.cpuBusy, cpuBusyRaw: load.cpuBusyRaw, cpuBusyNet: load.cpuBusyNet, cpuOwnBusy: load.cpuOwnBusy,
2862
+ cpuIowait: load.cpuIowait, cpuWindowMs: load.cpuWindowMs, heldMs: load.heldMs,
2687
2863
  };
2688
2864
  }
2689
2865
 
@@ -2735,9 +2911,11 @@ function buildScheduleStatePayload(state) {
2735
2911
  // UI can disable its own control when the env has taken over.
2736
2912
  effectiveConcurrency: (() => {
2737
2913
  const snap = sessionSlots.snapshot();
2914
+ // jobCapacity() excludes the held interactive-Task slot, so a held
2915
+ // slot never reads as free capacity the queue failed to use.
2738
2916
  return {
2739
2917
  cap: snap.total,
2740
- free: Math.max(0, snap.total - snap.inUse),
2918
+ free: jobFreeSlots(snap),
2741
2919
  source: snap.envOverride ? 'env' : 'pool',
2742
2920
  };
2743
2921
  })(),
@@ -2745,6 +2923,17 @@ function buildScheduleStatePayload(state) {
2745
2923
  return payload;
2746
2924
  }
2747
2925
 
2926
+ /**
2927
+ * Slots a scheduler job could still take: the pool's free slots, bounded by
2928
+ * jobCapacity() (cap minus the held interactive-Task slot) less the
2929
+ * non-interactive holders already counted against it.
2930
+ * @param {{ total: number, inUse: number, holders: Array<{ lane?: string }> }} snap
2931
+ */
2932
+ function jobFreeSlots(snap) {
2933
+ const nonInteractive = snap.holders.filter((h) => h.lane !== 'task-interactive').length;
2934
+ return Math.max(0, Math.min(snap.total - snap.inUse, sessionSlots.jobCapacity() - nonInteractive));
2935
+ }
2936
+
2748
2937
  // Trailing-edge debounce for the `schedule:state` IPC push: a burst of
2749
2938
  // broadcast() calls (boot reverify healing several rows, poll-loop refreshes,
2750
2939
  // queue-linter fixups) arms one BROADCAST_COALESCE_MS timer and sends a
@@ -3028,6 +3217,10 @@ function resetJobFields(job, errorMsg, opts = {}) {
3028
3217
  // Durable cancel (2026-10-19 git-viewer incident): a human-cancelled row is
3029
3218
  // revived only by an explicit human reset, never by an automated pass.
3030
3219
  if (reviewLadder.isCancelledJob(job) && opts.source !== 'remote:resetJob' && opts.source !== 'ipc:schedule:reset-job') return false;
3220
+ // Reset means "re-check the precondition now": the hold is dropped even
3221
+ // when the row is already pending (pending→pending is not a transition).
3222
+ delete job.preflightHold;
3223
+ if (job.status === 'pending' && typeof job.heldReason === 'string' && job.heldReason.startsWith('waiting on precondition:')) delete job.heldReason;
3031
3224
  if (!transitionJob(job, 'pending', { reason: errorMsg ?? 'reset to pending', source: opts.source ?? 'resetJobFields' })) return false;
3032
3225
  delete job.cancelledAt;
3033
3226
  delete job.cancelledRunId;
@@ -3347,6 +3540,35 @@ function extractResultTextFromLog(logPath) {
3347
3540
  }
3348
3541
  }
3349
3542
 
3543
+ /**
3544
+ * Same tail scan as extractResultTextFromLog, but returns the last result
3545
+ * event's `structured_output` object (set by `claude -p --json-schema`), or
3546
+ * null for a missing file, a torn line, or no such field. Never throws.
3547
+ */
3548
+ function extractStructuredOutputFromLog(logPath) {
3549
+ if (!logPath) return null;
3550
+ try {
3551
+ const tail = readTail(logPath, RESULT_TEXT_TAIL_BYTES);
3552
+ if (!tail) return null;
3553
+ const lines = tail.split('\n');
3554
+ for (let i = lines.length - 1; i >= 0; i--) {
3555
+ const line = lines[i].trim();
3556
+ if (!line || !line.includes('"type":"result"')) continue;
3557
+ try {
3558
+ const parsed = JSON.parse(line);
3559
+ if (!parsed || parsed.type !== 'result') continue;
3560
+ const so = parsed.structured_output;
3561
+ return so && typeof so === 'object' && !Array.isArray(so) ? so : null;
3562
+ } catch {
3563
+ // torn/partial line — keep scanning backward
3564
+ }
3565
+ }
3566
+ return null;
3567
+ } catch {
3568
+ return null;
3569
+ }
3570
+ }
3571
+
3350
3572
  /**
3351
3573
  * resolveNotifyPrd(job, parsePrdRaw) → Promise<parsed PRD | null>
3352
3574
  *
@@ -3467,7 +3689,9 @@ function defaultScheduleSettle({ cwd, epicId }) {
3467
3689
  const deps = {
3468
3690
  loadJobs: async () => (await readQueue()).jobs || [],
3469
3691
  loadHistory: () => queueHistory.readHistory({ limit: 500 }),
3470
- createPrd: (input) => prdCreate.createPrd(input, remote),
3692
+ // Scheduler-internal mint: validate-sweep validator slugs are timestamped and
3693
+ // have collided across Epics before, so the cross-Epic duplicate guard is skipped.
3694
+ createPrd: (input) => prdCreate.createPrd(input, remote, { internalMint: true }),
3471
3695
  resolveBaseSha: async (c, commit) => {
3472
3696
  try {
3473
3697
  return String(await execGitAt(c, ['rev-parse', `${commit}^`])).trim() || null;
@@ -3513,10 +3737,28 @@ function armSettleAfterValidatorBudgetKill(job, { scheduleSettle = defaultSchedu
3513
3737
  const MACRO_ARTIFACT_RE = /^session-manager-operations\/project-pages\/(videos|knowledge)\/([a-z0-9-]+)\/index\.html$/;
3514
3738
  const MACRO_META_MAX_BYTES = 256 * 1024;
3515
3739
 
3740
+ // A Project Video tool's review stage (macroJobDispatch.cjs REVIEW_MATERIAL_REL)
3741
+ // saves review material, not the video: any path ending in this names one.
3742
+ const MACRO_REVIEW_MATERIAL_RE = /\/review\/material\.json(?=$|["'`\s)])/;
3743
+
3744
+ function isMacroReviewStage(prd) {
3745
+ const strings = [];
3746
+ for (const k of ['artifactPaths', 'files', 'gate']) {
3747
+ const v = prd[k];
3748
+ if (typeof v === 'string') strings.push(v);
3749
+ else if (Array.isArray(v)) for (const x of v) if (typeof x === 'string') strings.push(x);
3750
+ }
3751
+ if (typeof prd.body === 'string') {
3752
+ const m = /```gate\r?\n([\s\S]*?)```/.exec(prd.body);
3753
+ if (m) strings.push(...m[1].split(/\r?\n/));
3754
+ }
3755
+ return strings.some((s) => MACRO_REVIEW_MATERIAL_RE.test(s.trim()));
3756
+ }
3757
+
3516
3758
  function macroLabelFor(prd) {
3517
3759
  const builtin = BUILTIN_MACROS.find((m) => m && m.id === prd.macroId);
3518
3760
  if (builtin && typeof builtin.label === 'string' && builtin.label) return builtin.label;
3519
- const title = typeof prd.title === 'string' ? prd.title.replace(/:\s*background build\s*$/i, '').trim() : '';
3761
+ const title = typeof prd.title === 'string' ? prd.title.replace(/:\s*(?:background build|review material)\s*$/i, '').trim() : '';
3520
3762
  return title || prd.macroId;
3521
3763
  }
3522
3764
 
@@ -3530,6 +3772,7 @@ function readMacroBuildOutput(cwd, prd) {
3530
3772
  if (!cwd) return null;
3531
3773
  const first = Array.isArray(prd.artifactPaths) ? prd.artifactPaths[0] : null;
3532
3774
  if (typeof first !== 'string') return null;
3775
+ if (MACRO_REVIEW_MATERIAL_RE.test(first.trim())) return null;
3533
3776
  const m = MACRO_ARTIFACT_RE.exec(first.trim());
3534
3777
  if (!m) return null;
3535
3778
  const dir = m[1];
@@ -3546,20 +3789,44 @@ function readMacroBuildOutput(cwd, prd) {
3546
3789
  }
3547
3790
 
3548
3791
  /**
3549
- * macroBuildNotice(job, prd) → { message, notice, buildOutput? } | null
3792
+ * macroBuildNotice(job, prd) → Promise<{ message, notice, buildOutput? } | null>
3550
3793
  * null for any PRD without a `macroId`, or a status other than completed/failed.
3794
+ * A failed job that is the approved 'final' run of a video review points at
3795
+ * that entry's Retry button (pressing the tool again would restart the
3796
+ * review). Async because videoReview.listReviews is; never rejects.
3551
3797
  */
3552
- function macroBuildNotice(job, prd) {
3798
+ async function macroBuildNotice(job, prd) {
3553
3799
  if (!prd || typeof prd.macroId !== 'string' || !prd.macroId) return null;
3554
3800
  if (job.status !== 'completed' && job.status !== 'failed') return null;
3555
3801
  const label = macroLabelFor(prd);
3556
3802
  if (job.status === 'failed') {
3557
3803
  const reason = job.error || job.verifierVerdict || job.status;
3804
+ try {
3805
+ if (job.cwd && job.slug) {
3806
+ const videoReview = require('./lib/project-pages/videoReview.cjs');
3807
+ const reviews = await videoReview.listReviews(job.cwd);
3808
+ const hit = reviews.find((r) => r && r.dispatch && r.dispatch.stage === 'final' && r.dispatch.slug === job.slug);
3809
+ if (hit) {
3810
+ return {
3811
+ message: `FAILED — ${label}: the approved final run for entry ${hit.entryId} failed (${reason}). Press Retry on it in Project Home ▸ Video; your approval is kept.`,
3812
+ notice: 'build-failed',
3813
+ };
3814
+ }
3815
+ }
3816
+ } catch {
3817
+ // fall through to the generic failed message
3818
+ }
3558
3819
  return {
3559
3820
  message: `FAILED — ${label}: the background build failed (${reason}). Press it again in Project Home to retry.`,
3560
3821
  notice: 'build-failed',
3561
3822
  };
3562
3823
  }
3824
+ if (isMacroReviewStage(prd)) {
3825
+ return {
3826
+ message: `WAITING — ${label}: the review material is saved. Approve it or ask for changes in Project Home ▸ Video.`,
3827
+ notice: 'build-review',
3828
+ };
3829
+ }
3563
3830
  const out = readMacroBuildOutput(job.cwd, prd);
3564
3831
  if (!out) return { message: `DONE — ${label} finished.`, notice: 'build-done' };
3565
3832
  const buildOutput = { kind: out.kind, id: out.id, title: out.title };
@@ -3615,6 +3882,8 @@ async function notifyOriginatingTab(job, {
3615
3882
  appendResponseEvent = appendResponseEventIfKnown,
3616
3883
  appendTranscriptTurn = promptSessionTranscript.appendTurn,
3617
3884
  readResultFromLog = extractResultTextFromLog,
3885
+ readStructuredFromLog = extractStructuredOutputFromLog,
3886
+ writeVerdictsFile = writeJsonAtomic,
3618
3887
  scheduleSettle = defaultScheduleSettle,
3619
3888
  } = {}) {
3620
3889
  try {
@@ -3635,7 +3904,7 @@ async function notifyOriginatingTab(job, {
3635
3904
  message = `PRD ${job.slug} was skipped: its PRD source could not be found on disk. Blocked dependents: ${shown}${more}.`
3636
3905
  + ' If the PRD file exists, run scheduler_reset_job with force:true; if it was intentionally removed, archive it with scheduler_archive_prd.';
3637
3906
  }
3638
- const macroNotice = macroBuildNotice(job, prd);
3907
+ const macroNotice = await macroBuildNotice(job, prd);
3639
3908
  if (macroNotice) message = macroNotice.message;
3640
3909
 
3641
3910
  // The EPIC this check-in belongs to. Deliberately does NOT consider
@@ -3673,9 +3942,9 @@ async function notifyOriginatingTab(job, {
3673
3942
  const needsResultText = (epicIdForTranscript && job.cwd)
3674
3943
  || (job.agentType === 'validator' && job.status === 'completed');
3675
3944
  let resultText = null;
3945
+ const logPath = job.runId ? path.join(schedulerPaths.runsDir(), job.runId, `${job.slug}.log`) : null;
3676
3946
  if (needsResultText) {
3677
3947
  try {
3678
- const logPath = job.runId ? path.join(schedulerPaths.runsDir(), job.runId, `${job.slug}.log`) : null;
3679
3948
  resultText = readResultFromLog(logPath);
3680
3949
  } catch (e) {
3681
3950
  console.error('[scheduler] notifyOriginatingTab readResultFromLog error', job?.slug, e);
@@ -3693,13 +3962,31 @@ async function notifyOriginatingTab(job, {
3693
3962
  }
3694
3963
  }
3695
3964
 
3696
- // PRD 1407: a plan-level validator job ends its run with one
3697
- // `VALIDATION: <slug> VERIFIED`/`REFUTED` line per PRD it checked.
3698
- // Parsed only for a completed validator job; every ordinary work-item
3699
- // job gets an empty array here and behaves exactly as before.
3700
- const verdicts = (job.agentType === 'validator' && job.status === 'completed')
3701
- ? parseValidationSentinels(resultText)
3702
- : [];
3965
+ // PRD 1407: a plan-level validator job reports one verdict per PRD it
3966
+ // checked. Since `--json-schema` (PRD 3614) the verdicts come from the
3967
+ // result event's structured_output, checked by parseValidatorVerdict —
3968
+ // the CLI replaces the result text with the JSON string, so VALIDATION:
3969
+ // lines are no longer there. Missing/invalid output → no verdict events.
3970
+ // Every ordinary work-item job gets an empty array and behaves as before.
3971
+ /** @type {{ slug: string, verdict: string, reason: string, missKinds: string[] }[]} */
3972
+ let verdicts = [];
3973
+ /** @type {any} */
3974
+ let checkedVerdict = null;
3975
+ if (job.agentType === 'validator' && job.status === 'completed') {
3976
+ let structured = null;
3977
+ try {
3978
+ structured = readStructuredFromLog(logPath);
3979
+ } catch (e) {
3980
+ console.error('[scheduler] notifyOriginatingTab readStructuredFromLog error', job?.slug, e);
3981
+ }
3982
+ const checked = parseValidatorVerdict(structured);
3983
+ if (checked.ok) {
3984
+ checkedVerdict = checked.value;
3985
+ verdicts = verdictRowsFromStructured(checked.value);
3986
+ } else {
3987
+ console.error(`[scheduler] notifyOriginatingTab: validator ${job.slug} structured output rejected — ${checked.error}`);
3988
+ }
3989
+ }
3703
3990
 
3704
3991
  if (!epicId && verdicts.length > 0) {
3705
3992
  // No Epic to attach these to (unresolved sourcePromptId/epicId, same
@@ -3724,12 +4011,41 @@ async function notifyOriginatingTab(job, {
3724
4011
  job.cwd || null,
3725
4012
  epicId,
3726
4013
  `Validation ${v.verdict.toUpperCase()}: ${v.slug}${v.reason ? ` — ${v.reason}` : ''}`,
3727
- { prdSlug: v.slug, outcome: 'completed', validation: v.verdict },
4014
+ {
4015
+ prdSlug: v.slug,
4016
+ outcome: 'completed',
4017
+ validation: v.verdict,
4018
+ reason: typeof v.reason === 'string' ? v.reason : '',
4019
+ missKinds: Array.isArray(v.missKinds) ? v.missKinds : [],
4020
+ validator: job.slug,
4021
+ },
3728
4022
  );
3729
4023
  } catch (e) {
3730
4024
  console.error('[scheduler] notifyOriginatingTab verdict appendResponseEvent error', job?.slug, v.slug, e);
3731
4025
  }
3732
4026
  }
4027
+ }
4028
+ if (epicId && checkedVerdict && job.cwd && !isSafeEpicId(epicId)) {
4029
+ // PRD 3688: mirror epicOutsideRead.readVerdictFiles — an unsafe id
4030
+ // ('../x', 'a/b') must never be concatenated into a write path.
4031
+ console.error('[scheduler] notifyOriginatingTab verdicts file skipped: unsafe epicId', job?.slug, JSON.stringify(epicId));
4032
+ } else if (epicId && checkedVerdict && job.cwd) {
4033
+ // PRD 3614: keep the checked object beside the Markdown plan record.
4034
+ try {
4035
+ const file = opsPath(job.cwd, 'plan-records', epicId, `${bareSlug(job.slug)}.verdicts.json`);
4036
+ assertOpsWrite(file, 'scheduler');
4037
+ await writeVerdictsFile(file, {
4038
+ validator: job.slug,
4039
+ runId: job.runId || null,
4040
+ at: new Date().toISOString(),
4041
+ schedulerVerdict: checkedVerdict.schedulerVerdict,
4042
+ verdicts: checkedVerdict.verdicts,
4043
+ });
4044
+ } catch (e) {
4045
+ console.error('[scheduler] notifyOriginatingTab verdicts file write error', job?.slug, e);
4046
+ }
4047
+ }
4048
+ if (epicId) {
3733
4049
  // PRD 986: the check-in event is born validation:'unvalidated' — never
3734
4050
  // 'verified' — regardless of the job's self-reported outcome. The
3735
4051
  // check-in is a request to validate, not an assertion of done.
@@ -4710,6 +5026,12 @@ const HEADLESS_DISALLOWED_TOOLS = Object.freeze([
4710
5026
  * `--disallowedTools` takes a variadic list, so another flag must always
4711
5027
  * follow it to end that list — `--output-format` does, right after. Never
4712
5028
  * put `--disallowedTools` last.
5029
+ * `jsonSchema` (object; validator jobs only) adds `--json-schema <json>` right
5030
+ * before `--dangerously-skip-permissions`; the caller must also grant
5031
+ * StructuredOutput in the tool scope — probe 2026-11-22 (CLI 2.1.325): a scoped
5032
+ * run without it silently ignores the schema. null/absent = today's argv.
5033
+ * `sandboxArgs` (buildJobSandboxSettings(...).argv) replaces the single
5034
+ * `--dangerously-skip-permissions` element at the same position; null/empty = today's argv.
4713
5035
  * The prompt is NOT in argv: callers send it on the child's stdin
4714
5036
  * (withChildAndLog's `stdinText`). Linux caps a single argv element at 128 KB,
4715
5037
  * and a large prompt failed with spawn E2BIG before the job started (the
@@ -4722,7 +5044,64 @@ function knownMcpServers() {
4722
5044
  return { [seed.SERVER_NAME]: seed.schedulerServerEntry() };
4723
5045
  }
4724
5046
 
4725
- function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope, pluginDirArgs = [] }) {
5047
+ /**
5048
+ * The CLI keeps only the LAST --settings value, and the job sandbox argv
5049
+ * already carries one inline JSON --settings. When it does, fold the
5050
+ * tool-risk guard file's PreToolUse hooks into that JSON instead of adding a
5051
+ * second --settings that would silently drop one of the two. Returns null
5052
+ * when there is nothing to merge into (or the guard file cannot be read).
5053
+ * @param {string[]} sandboxArgs
5054
+ * @param {string} riskGuardSettingsPath
5055
+ * @returns {string[]|null}
5056
+ */
5057
+ function mergeRiskGuardIntoSandboxArgs(sandboxArgs, riskGuardSettingsPath) {
5058
+ const i = sandboxArgs.indexOf('--settings');
5059
+ if (i === -1 || typeof sandboxArgs[i + 1] !== 'string') return null;
5060
+ let inline;
5061
+ try { inline = JSON.parse(sandboxArgs[i + 1]); } catch { return null; }
5062
+ if (!inline || typeof inline !== 'object' || Array.isArray(inline)) return null;
5063
+ const guard = readJsonOrSync(riskGuardSettingsPath, null);
5064
+ const guardHooks = guard && guard.hooks && Array.isArray(guard.hooks.PreToolUse) ? guard.hooks.PreToolUse : null;
5065
+ if (!guardHooks) return null;
5066
+ const hooks = inline.hooks && typeof inline.hooks === 'object' ? inline.hooks : {};
5067
+ const pre = Array.isArray(hooks.PreToolUse) ? hooks.PreToolUse : [];
5068
+ const merged = { ...inline, hooks: { ...hooks, PreToolUse: [...pre, ...guardHooks] } };
5069
+ const out = sandboxArgs.slice();
5070
+ out[i + 1] = JSON.stringify(merged);
5071
+ return out;
5072
+ }
5073
+
5074
+ /**
5075
+ * A job's tool-risk clearance list (env SM_SCHEDULER_JOB_RISK_TOOLS): the
5076
+ * PRD's riskTools plus the persona's tools, keeping only entries
5077
+ * toolRiskMarks.parseRule accepts (MCP names, Bash(...) rules). Deduped,
5078
+ * order-preserving. Never throws.
5079
+ * @param {unknown} prdRiskTools
5080
+ * @param {unknown} personaTools
5081
+ * @returns {string[]}
5082
+ */
5083
+ function jobRiskToolsClearance(prdRiskTools, personaTools) {
5084
+ const out = [];
5085
+ const seen = new Set();
5086
+ for (const list of [prdRiskTools, personaTools]) {
5087
+ if (!Array.isArray(list)) continue;
5088
+ for (const t of list) {
5089
+ if (typeof t !== 'string' || seen.has(t) || !toolRiskMarks.parseRule(t)) continue;
5090
+ seen.add(t);
5091
+ out.push(t);
5092
+ }
5093
+ }
5094
+ return out;
5095
+ }
5096
+
5097
+ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope, pluginDirArgs = [], jsonSchema = null, sandboxArgs = null, riskGuardSettingsPath = null }) {
5098
+ let permissionArgs = Array.isArray(sandboxArgs) && sandboxArgs.length ? sandboxArgs : ['--dangerously-skip-permissions'];
5099
+ let riskArgs = [];
5100
+ if (typeof riskGuardSettingsPath === 'string' && riskGuardSettingsPath) {
5101
+ const merged = mergeRiskGuardIntoSandboxArgs(permissionArgs, riskGuardSettingsPath);
5102
+ if (merged) permissionArgs = merged;
5103
+ else riskArgs = ['--settings', riskGuardSettingsPath];
5104
+ }
4726
5105
  return [
4727
5106
  '-p',
4728
5107
  '--model', model,
@@ -4730,7 +5109,9 @@ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt,
4730
5109
  ...(systemPrompt ? ['--append-system-prompt', systemPrompt] : []),
4731
5110
  ...personaToolScopeArgs(toolScope, { mcpServers: knownMcpServers() }),
4732
5111
  ...(Array.isArray(pluginDirArgs) ? pluginDirArgs : []),
4733
- '--dangerously-skip-permissions',
5112
+ ...(jsonSchema && typeof jsonSchema === 'object' ? ['--json-schema', JSON.stringify(jsonSchema)] : []),
5113
+ ...riskArgs,
5114
+ ...permissionArgs,
4734
5115
  ...headlessPermissionArgs(),
4735
5116
  '--disallowedTools', HEADLESS_DISALLOWED_TOOLS.join(','),
4736
5117
  '--output-format', 'stream-json',
@@ -4739,6 +5120,41 @@ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt,
4739
5120
  ];
4740
5121
  }
4741
5122
 
5123
+ // ---------- job sandbox dependencies ----------
5124
+
5125
+ // Computed once per process: which OS-sandbox binaries exist, and (linux)
5126
+ // whether bwrap can actually create namespaces here. Never throws — any
5127
+ // failure degrades to the tool-rules level with the reason recorded.
5128
+ /** @type {{ available: boolean, missing: string[] }|null} */
5129
+ let jobSandboxDeps = null;
5130
+
5131
+ function whichOnPath(name) {
5132
+ const dirs = String(process.env.PATH || '').split(path.delimiter).filter(Boolean);
5133
+ for (const dir of dirs) {
5134
+ const candidate = path.join(dir, name);
5135
+ try { fs.accessSync(candidate, fs.constants.X_OK); return candidate; } catch { /* next */ }
5136
+ }
5137
+ return null;
5138
+ }
5139
+
5140
+ function resolveJobSandboxDeps() {
5141
+ if (process.env.SM_JOB_SANDBOX === '0') return { available: false, missing: ['disabled by SM_JOB_SANDBOX=0'] };
5142
+ if (jobSandboxDeps) return jobSandboxDeps;
5143
+ try {
5144
+ let deps = sandboxDependencies({ platform: process.platform, which: whichOnPath });
5145
+ if (deps.available && process.platform === 'linux') {
5146
+ const r = spawnSync(whichOnPath('bwrap') || 'bwrap',
5147
+ ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--unshare-net', '--unshare-pid', '--', 'true'],
5148
+ { timeout: 5000, stdio: 'ignore' });
5149
+ if (r.error || r.status !== 0) deps = { available: false, missing: ['bwrap self-test failed'] };
5150
+ }
5151
+ jobSandboxDeps = deps;
5152
+ } catch (e) {
5153
+ jobSandboxDeps = { available: false, missing: [`sandbox dependency probe failed: ${(e && e.message) || e}`] };
5154
+ }
5155
+ return jobSandboxDeps;
5156
+ }
5157
+
4742
5158
  // ---------- execution ----------
4743
5159
 
4744
5160
  // Allocates the runId/dir pair at dispatch time WITHOUT creating the
@@ -4859,6 +5275,10 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4859
5275
  // the scheduler's own short status chip (that's notifyOriginatingTab's job
4860
5276
  // for the assistant side).
4861
5277
  let parsedPrdMeta = null;
5278
+ // The PRD file's own riskTools frontmatter (tool-risk clearance). Fresh
5279
+ // spawns fill it from the isArtifactOnly read; resume spawns re-resolve the
5280
+ // PRD file below so a resumed session keeps the same clearance.
5281
+ let prdRiskTools = [];
4862
5282
  if (resumeTarget) {
4863
5283
  // Resume mode (PRD 1111): a short deterministic preamble naming the
4864
5284
  // recorded dirty paths, NEVER the original PRD body — the resumed
@@ -5025,11 +5445,13 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5025
5445
  try {
5026
5446
  const fm = parsePrdFile(await fsp.readFile(prdPath, 'utf8')).frontmatter;
5027
5447
  isArtifactOnly = isArtifactOnlyDeclaration(fm);
5448
+ // Tool-risk clearance (PRD scheduler-tool-risk-wiring): same read.
5449
+ prdRiskTools = Array.isArray(fm && fm.riskTools) ? fm.riskTools : [];
5028
5450
  } catch {
5029
5451
  isArtifactOnly = false;
5030
5452
  }
5031
5453
  }
5032
- prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun, isFixPlan: resolveIsFixPlan(job.slug, job.isFixPlan), isArtifactOnly }) });
5454
+ prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun, isFixPlan: resolveIsFixPlan(job.slug, job.isFixPlan), isArtifactOnly, isValidator: job.agentType === 'validator' }) });
5033
5455
 
5034
5456
  // Foreign-WIP manifest (starry-night-ships PRD 148 postmortem): the
5035
5457
  // scheduler already knows, at spawn time, which dirty paths this job did
@@ -5059,9 +5481,31 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5059
5481
  // a dangling/absent agentType falls back to no persona + FALLBACK_MODEL
5060
5482
  // and is logged once by resolvePrdPersonaForSpawn itself.
5061
5483
  const personaResolution = await agentModelResolve.resolvePrdPersonaForSpawn({ cwd, agentType: job.agentType });
5484
+ if (resumeTarget) {
5485
+ try {
5486
+ const dir = await prdPaths.findPrdDirForJob(job);
5487
+ const file = dir ? path.join(dir, `${job.slug}.md`) : prdPaths.prdPathForJob(job);
5488
+ const fm = parsePrdFile(await fsp.readFile(file, 'utf8')).frontmatter;
5489
+ prdRiskTools = Array.isArray(fm && fm.riskTools) ? fm.riskTools : [];
5490
+ } catch {
5491
+ prdRiskTools = [];
5492
+ }
5493
+ }
5494
+ // Tool-risk guard (PRD scheduler-tool-risk-wiring): a job worktree never
5495
+ // sees the project's untracked .claude/settings.json, so guard-tool-risk
5496
+ // loads via --settings <file>. Resolved once per job; null never blocks
5497
+ // the spawn.
5498
+ const jobRiskTools = jobRiskToolsClearance(prdRiskTools, personaResolution.tools);
5499
+ const riskGuardSettingsPath = await writeToolRiskGuardSettingsFile({ homeDir: os.homedir() });
5500
+ if (!riskGuardSettingsPath) {
5501
+ safeLog(`[scheduler] tool-risk guard settings unavailable for ${job.slug}; spawning without guard-tool-risk\n`);
5502
+ }
5062
5503
  const effortResolution = resolveEpicEffort({ cwd, agentType: job.agentType, prdEffort: job.effort });
5063
5504
  const personaEffort = effortResolution.effort;
5064
- const personaToolScope = buildPersonaToolScope(personaResolution.tools, { disallowed: HEADLESS_DISALLOWED_TOOLS });
5505
+ // Validator jobs (fresh and resume) return a schema-checked verdict:
5506
+ // --json-schema + StructuredOutput in scope (PRD 3613).
5507
+ const isValidator = job.agentType === 'validator';
5508
+ const personaToolScope = buildPersonaToolScope(personaResolution.tools, { disallowed: HEADLESS_DISALLOWED_TOOLS, structuredOutput: isValidator });
5065
5509
  // Epic context packs (PRD 3154): the job's Epic's selected packs load as
5066
5510
  // --plugin-dir per pack, and their laws are appended AFTER the (already
5067
5511
  // capped) persona body — the persona cap never applies to laws. Fresh and
@@ -5119,6 +5563,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5119
5563
  SM_SCHEDULER_JOB_SLUG: job.slug,
5120
5564
  SM_SCHEDULER_JOB_MAY_QUEUE: job.agentType === 'architect' ? '1' : '0',
5121
5565
  ...personaToolScopeEnv(personaToolScope),
5566
+ SM_SCHEDULER_JOB_RISK_TOOLS: JSON.stringify(jobRiskTools),
5122
5567
  BASH_DEFAULT_TIMEOUT_MS: String(BASH_DEFAULT_TIMEOUT_MS),
5123
5568
  BASH_MAX_TIMEOUT_MS: String(BASH_MAX_TIMEOUT_MS),
5124
5569
  ...(launchEnv && typeof launchEnv === 'object' ? launchEnv : {}),
@@ -5289,7 +5734,43 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5289
5734
 
5290
5735
  // Distinct comm (`sm-claude-job`) + slug-labelled argv0 for System Monitor.
5291
5736
  // Both keep the word `claude`, which the /\bclaude\b/ reaper gates need.
5737
+ // An os-sandbox job gets its own private temp dir as its only tmp write
5738
+ // root (TMPDIR/TMP/TEMP point at it), so its Bash cannot write into other
5739
+ // /tmp dirs. Kept short and directly under os.tmpdir(): the CLI puts its
5740
+ // proxy unix sockets under $TMPDIR and socket paths cap at 108 bytes —
5741
+ // never move it under the run directory.
5742
+ const sandboxDeps = resolveJobSandboxDeps();
5743
+ const sandboxAgentType = job.agentType || 'dev-lead';
5744
+ /** @type {string|null} */
5745
+ let sandboxTmpDir = null;
5746
+ if (sandboxDeps.available && Object.prototype.hasOwnProperty.call(SANDBOX_PROFILES, sandboxAgentType)) {
5747
+ try {
5748
+ sandboxTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'smj-'));
5749
+ } catch (e) {
5750
+ sandboxTmpDir = null;
5751
+ safeLog(`[scheduler] sandbox: private tmp dir not created (${(e && e.message) || e}); using ${os.tmpdir()}\n`);
5752
+ }
5753
+ }
5754
+ const removeSandboxTmp = () => {
5755
+ if (!sandboxTmpDir) return;
5756
+ try { fs.rmSync(sandboxTmpDir, { recursive: true, force: true }); } catch { /* never throws */ }
5757
+ };
5758
+ const sandboxPolicy = buildJobSandboxSettings({
5759
+ agentType: sandboxAgentType,
5760
+ worktreeDir: spawnCwd,
5761
+ projectRoot: cwd,
5762
+ homeDir: os.homedir(),
5763
+ tmpDir: sandboxTmpDir || os.tmpdir(),
5764
+ deps: sandboxDeps,
5765
+ });
5766
+ // childEnv was built (and cleanChildEnv already ran) above.
5767
+ Object.assign(childEnv, sandboxChildEnv(sandboxPolicy, sandboxTmpDir || os.tmpdir()));
5768
+ const sandboxMeta = { ...sandboxPolicy.summary, tmpDir: sandboxTmpDir };
5769
+ safeLog(`[scheduler] sandbox: level=${sandboxMeta.level} profile=${sandboxMeta.profile ?? 'none'} ` +
5770
+ `network=${sandboxMeta.network ? (sandboxMeta.network.join(',') || 'none') : 'unrestricted'} reason=${sandboxMeta.reason ?? 'none'} ` +
5771
+ `tmp=${sandboxTmpDir ?? 'none'}\n`);
5292
5772
  const jobArgs = buildClaudeSpawnArgs({
5773
+ sandboxArgs: sandboxPolicy.argv,
5293
5774
  model: personaResolution.model,
5294
5775
  effort: personaEffort,
5295
5776
  sessionId,
@@ -5297,6 +5778,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5297
5778
  systemPrompt: jobSystemPrompt,
5298
5779
  toolScope: personaToolScope,
5299
5780
  pluginDirArgs: packArgs.pluginDirArgs,
5781
+ jsonSchema: isValidator ? VALIDATOR_VERDICT_SCHEMA : null,
5782
+ riskGuardSettingsPath,
5300
5783
  });
5301
5784
  const jobSpawn = claudeSpawnTarget('job', job.slug, claudeBin, jobArgs);
5302
5785
 
@@ -5306,7 +5789,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5306
5789
  const errMsg = `argv too large: ${oversized.flag} is ${oversized.bytes} bytes, over the ${launchFailure.MAX_ARG_BYTES}-byte per-argument limit; not spawned`;
5307
5790
  safeLog(`[scheduler] ${errMsg}\n`);
5308
5791
  closeFd();
5309
- config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: errMsg, startedAt, finishedAt: Date.now(), durationMs: 0, ...SCHEDULER_META_IDENTITY, ...setupMeta });
5792
+ config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: errMsg, startedAt, finishedAt: Date.now(), durationMs: 0, sandbox: sandboxMeta, ...SCHEDULER_META_IDENTITY, ...setupMeta });
5793
+ removeSandboxTmp();
5310
5794
  resolve({ exitCode: -1, durationMs: 0, error: errMsg, launchError: 'argv_too_large', sessionId });
5311
5795
  return;
5312
5796
  }
@@ -5358,7 +5842,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5358
5842
  sl(`\n[scheduler] ${errMsg}\n`);
5359
5843
  // Sync write: inside a Promise executor callback; must flush meta
5360
5844
  // before resolve() so the spawnJob mutate() that follows sees it.
5361
- config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: errMsg, startedAt, finishedAt: Date.now(), durationMs, leakedDescendants: leaked, ...SCHEDULER_META_IDENTITY, ...setupMeta, originSessionId, contextDigestApplied });
5845
+ config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: errMsg, startedAt, finishedAt: Date.now(), durationMs, leakedDescendants: leaked, sandbox: sandboxMeta, ...SCHEDULER_META_IDENTITY, ...setupMeta, originSessionId, contextDigestApplied });
5846
+ removeSandboxTmp();
5362
5847
  resolve({ exitCode: -1, durationMs, error: errMsg, leakedDescendants: leaked, sessionId,
5363
5848
  ...(launchFailure.isArgvTooLargeSpawnError(error?.message) ? { launchError: 'argv_too_large' } : {}) });
5364
5849
  return;
@@ -5421,9 +5906,11 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5421
5906
  startedAt, finishedAt: Date.now(), durationMs, leakedDescendants: leaked,
5422
5907
  agentResultSubtype, mappedFromSignal: mappedToSuccess ? signal || `code=${exitCode}` : null,
5423
5908
  killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
5909
+ sandbox: sandboxMeta,
5424
5910
  ...SCHEDULER_META_IDENTITY, ...setupMeta,
5425
5911
  originSessionId, contextDigestApplied,
5426
5912
  });
5913
+ removeSandboxTmp();
5427
5914
  resolve({
5428
5915
  exitCode: effectiveCode, durationMs, rateLimited, networkError, launchFailure: launchFailed, resultStats,
5429
5916
  leakedDescendants: leaked, sessionId, killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
@@ -5734,6 +6221,12 @@ function readRunOutcomeSidecars(runDir, slug) {
5734
6221
  const INVESTIGATION_LAUNCH_KEY = 'investigation';
5735
6222
 
5736
6223
  async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {}) {
6224
+ // A row waiting on its own red preflight spends nothing on the model
6225
+ // ladder: the precondition is the cause, not the work.
6226
+ if (reviewLadder.hasActivePreflightHold(failedJob)) {
6227
+ console.log(`[scheduler] skip investigation: ${failedJob.slug} is held on its preflight`);
6228
+ return { deferred: false };
6229
+ }
5737
6230
  // The probe launches with the same CLI as the job it diagnoses. While
5738
6231
  // that CLI cannot launch at all (launch circuit breaker, issue #11 list
5739
6232
  // B1: probes e4f82da2/d374e6bf died on the same HTTP 400 as the runs
@@ -5911,7 +6404,7 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
5911
6404
  await mutate((s) => {
5912
6405
  const j = s.jobs.find((x) => x.slug === failedJob.slug);
5913
6406
  if (!j) return;
5914
- const statusEligible = (j.status === 'needs_review' || j.status === 'failed') && !reviewLadder.isCancelledJob(j);
6407
+ const statusEligible = (j.status === 'needs_review' || j.status === 'failed') && !reviewLadder.isCancelledJob(j) && !reviewLadder.hasActivePreflightHold(j);
5915
6408
  const transitioned = statusEligible && transitionJob(j, 'investigating', { reason: 'spawning investigation probe', source: 'spawnInvestigation:start' });
5916
6409
  liveCheck = { ok: statusEligible && transitioned, status: j.status };
5917
6410
  });
@@ -5967,7 +6460,10 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
5967
6460
  args: [
5968
6461
  '-p',
5969
6462
  '--model', 'opus',
5970
- '--dangerously-skip-permissions',
6463
+ ...buildJobSandboxSettings({
6464
+ agentType: 'investigation', worktreeDir: cwd, projectRoot: cwd,
6465
+ homeDir: os.homedir(), tmpDir: os.tmpdir(), deps: resolveJobSandboxDeps(),
6466
+ }).argv,
5971
6467
  ...headlessPermissionArgs(),
5972
6468
  '--disallowedTools', HEADLESS_DISALLOWED_TOOLS.join(','),
5973
6469
  '--output-format', 'stream-json',
@@ -6052,7 +6548,9 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
6052
6548
  // status here) is otherwise reset-refused by design.
6053
6549
  if (deadChild) {
6054
6550
  const child = s.jobs.find((x) => x.slug === deadChild.slug);
6055
- if (child) {
6551
+ // A child held on its own red preflight is left alone — the
6552
+ // reset would drop the hold and re-fire it into the same wall.
6553
+ if (child && !reviewLadder.hasActivePreflightHold(child)) {
6056
6554
  resetJobFields(child, 'reset by dead-fix-plan reopen: parent investigation authored a new plan', {
6057
6555
  force: true, source: 'spawnInvestigation:dead-fix-plan-reopen',
6058
6556
  });
@@ -6414,6 +6912,151 @@ function guardedTick(fn, label) {
6414
6912
  }
6415
6913
  }
6416
6914
 
6915
+ /**
6916
+ * Pending rows whose preflight hold is not yet due → Map<slug, heldReason>,
6917
+ * in the same shape computeLaunchHolds returns, so the picker skips them
6918
+ * (and they never shadow a pickable sibling) while a dependent of a held
6919
+ * row still sees it as a blocking dep.
6920
+ */
6921
+ function computePreflightHolds(jobs, now = Date.now()) {
6922
+ const held = new Map();
6923
+ for (const j of jobs || []) {
6924
+ if (!j || j.status !== 'pending' || !j.preflightHold) continue;
6925
+ const next = Date.parse(j.preflightHold.nextAt ?? '');
6926
+ if (Number.isFinite(next) && next > now) {
6927
+ held.set(j.slug, j.heldReason || `waiting on precondition: ${j.preflight} — re-check at ${j.preflightHold.nextAt}`);
6928
+ }
6929
+ }
6930
+ return held;
6931
+ }
6932
+
6933
+ /**
6934
+ * Run job.preflight (cwd = the job's project cwd, no shell) and record the
6935
+ * outcome on the queue row. Returns 'held' when the job must not launch
6936
+ * (check failed, or the hold is not yet due), else 'pass'.
6937
+ */
6938
+ async function runPreflightGate(job, defaultCwd, { now = Date.now } = {}) {
6939
+ const command = job.preflight.trim();
6940
+ const prevHold = job.preflightHold || null;
6941
+ const dueAt = prevHold ? Date.parse(prevHold.nextAt ?? '') : NaN;
6942
+ if (Number.isFinite(dueAt) && dueAt > now()) return 'held';
6943
+ const result = await preflightCheck.runPreflight({ command, cwd: job.cwd || defaultCwd });
6944
+ if (result.ok) {
6945
+ const attempts = prevHold && Number.isFinite(prevHold.attempts) ? prevHold.attempts : 0;
6946
+ await mutate((s) => {
6947
+ const row = s.jobs.find((x) => x.slug === job.slug);
6948
+ if (!row) return;
6949
+ delete row.preflightHold;
6950
+ delete row.heldReason;
6951
+ });
6952
+ delete job.preflightHold;
6953
+ delete job.heldReason;
6954
+ try { appendAuditEvent('preflight_pass', { slug: job.slug, attempts }); } catch { /* audit must not break dispatch */ }
6955
+ return 'pass';
6956
+ }
6957
+ const heldAt = now();
6958
+ let hold = null;
6959
+ let projectRows = [];
6960
+ await mutate((s) => {
6961
+ const row = s.jobs.find((x) => x.slug === job.slug);
6962
+ hold = armPreflightHoldOnRow(row, prevHold, result, command, heldAt, `make \`${command}\` exit 0`);
6963
+ projectRows = snapshotProjectRows(s.jobs, row || job);
6964
+ });
6965
+ job.preflightHold = hold;
6966
+ auditPreflightHold(job.slug, command, result, hold);
6967
+ await broadcast({ flush: true });
6968
+ await sendPreflightHoldNotice(job, hold, projectRows);
6969
+ return 'held';
6970
+ }
6971
+
6972
+ /** Shallow copies of `job`'s project rows (for heldSlugs) — safe outside mutate(). */
6973
+ function snapshotProjectRows(jobs, job) {
6974
+ const cwd = job?.cwd || DEFAULT_PROJECT_CWD;
6975
+ return projectRowsFor(jobs, cwd).map((j) => ({ ...j }));
6976
+ }
6977
+
6978
+ // Preflight hold notices already sent this process, by preflightHoldNoticeKey.
6979
+ const preflightHoldNoticesSent = new Set();
6980
+ let preflightHoldNoticeSender = null;
6981
+ function _setPreflightHoldNoticeSenderForTests(fn) { preflightHoldNoticeSender = fn || null; }
6982
+ function _resetPreflightHoldNoticesForTests() { preflightHoldNoticesSent.clear(); }
6983
+
6984
+ /**
6985
+ * sendPreflightHoldNotice(job, hold, projectRows) → Promise<boolean>
6986
+ *
6987
+ * The ONE informational Epic notice for a preflight hold, sent the moment it
6988
+ * first arms (hold.attempts === 1) — not behind SM_REVIEW_NOTICE_HOLD_MINUTES.
6989
+ * Same Epic delivery as the grouped needs_review notice
6990
+ * (appendResponseEventWithReason, allowInactive), tagged notice:
6991
+ * 'preflight-hold' with no outcome, so it never asks for input. Deduped by
6992
+ * preflightHoldNoticeKey(slug, hold.since); a re-check failure (attempts > 1)
6993
+ * sends nothing. heldSlugs = the row itself plus every pending row whose root
6994
+ * blocker it is. Never throws.
6995
+ */
6996
+ async function sendPreflightHoldNotice(job, hold, projectRows = []) {
6997
+ try {
6998
+ if (!job || !hold || hold.attempts !== 1) return false;
6999
+ const key = preflightHoldNoticeKey(job.slug, hold.since);
7000
+ if (preflightHoldNoticesSent.has(key)) return false;
7001
+ preflightHoldNoticesSent.add(key);
7002
+ const cwd = job.cwd || DEFAULT_PROJECT_CWD;
7003
+ const epicId = job.sourcePromptId || job.epicId || null;
7004
+ if (!epicId || !cwd) {
7005
+ console.log(`[scheduler] ${job.slug}: preflight hold notice — no authoring Epic, report only`);
7006
+ return false;
7007
+ }
7008
+ const roots = starvation.rootBlockersForProject(Array.isArray(projectRows) ? projectRows : []);
7009
+ const mine = roots.find((r) => r.slug === job.slug);
7010
+ const heldSlugs = [job.slug, ...(mine ? mine.heldSlugs.filter((x) => x !== job.slug) : [])];
7011
+ const text = buildPreflightHoldNotice({
7012
+ slug: job.slug,
7013
+ failText: hold.failText,
7014
+ preflight: typeof job.preflight === 'string' ? job.preflight.trim() : '',
7015
+ heldSlugs,
7016
+ nextAt: hold.nextAt,
7017
+ });
7018
+ const send = preflightHoldNoticeSender || appendResponseEventWithReason;
7019
+ const result = await send(cwd, epicId, text, {
7020
+ prdSlug: job.slug,
7021
+ validation: 'unvalidated',
7022
+ notice: 'preflight-hold',
7023
+ digestKey: key,
7024
+ allowInactive: true,
7025
+ });
7026
+ const ok = typeof result === 'boolean' ? result : !!result?.ok;
7027
+ if (!ok) console.warn(`[scheduler] ${job.slug}: preflight hold notice not delivered (${result?.reason ?? 'refused'})`);
7028
+ return ok;
7029
+ } catch (e) {
7030
+ console.error('[scheduler] sendPreflightHoldNotice error', job?.slug, e);
7031
+ return false;
7032
+ }
7033
+ }
7034
+
7035
+ /**
7036
+ * Arm (or climb) the preflight hold on a queue row from a red runPreflight
7037
+ * result. Sync — call inside mutate(). Shared by the dispatch gate and the
7038
+ * sentinel_fail park reroute so both write the same hold + heldReason shape.
7039
+ * Returns the hold (also when `row` is null, from `prevHold`).
7040
+ */
7041
+ function armPreflightHoldOnRow(row, prevHold, result, command, heldAt, failText) {
7042
+ const code = result.exitCode ?? (result.timedOut ? 'timeout' : 'null');
7043
+ const base = row ? (row.preflightHold || null) : (prevHold || null);
7044
+ const hold = preflightCheck.armPreflightHold(base, result, heldAt, failText);
7045
+ if (row) {
7046
+ row.preflightHold = hold;
7047
+ row.heldReason = `waiting on precondition: ${command} exited ${code} — re-check at ${hold.nextAt}`;
7048
+ }
7049
+ return hold;
7050
+ }
7051
+
7052
+ function auditPreflightHold(slug, command, result, hold, extra = {}) {
7053
+ const code = result.exitCode ?? (result.timedOut ? 'timeout' : 'null');
7054
+ console.log(`[scheduler] ${slug}: preflight hold — ${command} exited ${code}; re-check at ${hold.nextAt}`);
7055
+ try {
7056
+ appendAuditEvent('preflight_hold', { slug, attempts: hold.attempts, nextAt: hold.nextAt, exitCode: result.exitCode, ...extra });
7057
+ } catch { /* audit must not break dispatch */ }
7058
+ }
7059
+
6417
7060
  async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, siblingJobs = null) {
6418
7061
  // PRD 1408: the queue rows in scope at dispatch (tickQueue's own
6419
7062
  // state.jobs, threaded straight down — never re-read here or inside
@@ -6426,7 +7069,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6426
7069
  // Session-Manager owns the machine-wide `claude -p` pool (sessionSlots.cjs)
6427
7070
  // — the scheduler REQUESTS capacity, it doesn't own a private cap. A miss
6428
7071
  // leaves the job pending; the next tick retries when a slot frees up.
6429
- const slotToken = sessionSlots.acquire(`scheduler:${job.slug}`, { claimedAt: Date.now() });
7072
+ const slotToken = sessionSlots.acquire(`scheduler:${job.slug}`, { claimedAt: Date.now(), lane: 'job' });
6430
7073
  if (!slotToken) {
6431
7074
  console.log(`[scheduler] no session slot free for ${job.slug} — deferring (${JSON.stringify(sessionSlots.snapshot().holders.map((h) => h.owner))})`);
6432
7075
  return;
@@ -6443,6 +7086,17 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6443
7086
  // silently.
6444
7087
  const quietLeaseAcquired = job.quietMachine === true && quietMachineLease.acquire(job.slug);
6445
7088
  try {
7089
+ // Preflight hold (preflightCheck.cjs): a PRD whose work needs an external
7090
+ // precondition a person controls declares one cheap command. Checked
7091
+ // BEFORE the worktree is created and before the 'running' transition, so
7092
+ // a red precondition costs no claude -p run and no checkout — the row
7093
+ // stays 'pending' with a preflightHold and is re-checked on the
7094
+ // 10/20/40/60-min-then-hourly backoff. Exit 0 clears the hold and
7095
+ // dispatch continues unchanged, so dependents flow with no manual reset.
7096
+ if (!resumeTarget && typeof job.preflight === 'string' && job.preflight.trim()) {
7097
+ const gate = await runPreflightGate(job, defaultCwd);
7098
+ if (gate === 'held') return;
7099
+ }
6446
7100
  // Worktree isolation cap check (PRD 1112) — probed BEFORE the job is
6447
7101
  // marked 'running', so a job that can't get isolation right now is a
6448
7102
  // DEFERRAL, not a fallback: it stays 'pending' and is retried on the
@@ -6857,6 +7511,10 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6857
7511
  }, reviewInRun, worktree.ok ? worktree.setup : { ran: false, ok: false, reason: 'in-place', waitedMs: 0, ms: 0, commands: [] });
6858
7512
  } finally {
6859
7513
  if (worktree.ok) {
7514
+ // Plan records are written in the worktree and never committed; copy
7515
+ // them to the main checkout before verify and before the checkout is
7516
+ // removed. Never throws (planRecordHarvest.cjs).
7517
+ harvestJobPlanRecords(job, worktree.dir, job.cwd || defaultCwd);
6860
7518
  ({ worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha, worktreeHead, uncommittedSnapshot } =
6861
7519
  await finalizeJobWorktree({ job, runId, runDir, worktree, guardCwd, carriedPaths }));
6862
7520
  } else {
@@ -7335,6 +7993,25 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7335
7993
  }
7336
7994
  }
7337
7995
 
7996
+ // Preflight park reroute: a run with a `preflight` that ended in an
7997
+ // executor SCHEDULER_VERDICT: FAIL re-checks its precondition once. Red →
7998
+ // the precondition is the cause; the row goes back to pending with a
7999
+ // preflightHold (below, inside mutate) and spends nothing on the model
8000
+ // ladder. Green or check error → the ordinary park runs unchanged.
8001
+ // I/O here, outside mutate(), like every other pre-finalize check.
8002
+ let preflightRerouteResult = null;
8003
+ const preflightRerouteCmd = typeof job.preflight === 'string' ? job.preflight.trim() : '';
8004
+ if (preflightRerouteCmd && res.exitCode === 0 && !res.rateLimited && verifyResult?.verdict === 'sentinel_fail') {
8005
+ try {
8006
+ const r = await preflightCheck.runPreflight({ command: preflightRerouteCmd, cwd: job.cwd || defaultCwd });
8007
+ if (r && r.ok === false) preflightRerouteResult = r;
8008
+ } catch (e) {
8009
+ reportSchedulerError('preflight park re-check failed', job.slug, e);
8010
+ }
8011
+ }
8012
+ let preflightRerouteHold = null;
8013
+ let preflightRerouteRows = [];
8014
+
7338
8015
  let actuallyFailed = false;
7339
8016
  let failedJobSnapshot = null;
7340
8017
  let needsInvestigationNow = false;
@@ -7515,6 +8192,23 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7515
8192
  effectiveStatus = 'needs_review';
7516
8193
  }
7517
8194
 
8195
+ if (
8196
+ preflightRerouteResult
8197
+ && effectiveStatus === 'needs_review'
8198
+ && !sigtermOverrideReason
8199
+ && !capParkVerdict
8200
+ && verifyResult?.verdict === 'sentinel_fail'
8201
+ ) {
8202
+ const row = s.jobs[i2];
8203
+ const failText = String(verifyResult.reason || '').replace(/^executor reported\s+/, '') || 'SCHEDULER_VERDICT: FAIL';
8204
+ if (jobLandedCommitThisRun) row.landedCommit = jobLandedCommitThisRun;
8205
+ if (resetJobFields(row, `preflight red after SCHEDULER_VERDICT: FAIL — ${failText}`, { source: 'scheduler:preflight-hold' })) {
8206
+ preflightRerouteHold = armPreflightHoldOnRow(row, null, preflightRerouteResult, preflightRerouteCmd, Date.now(), failText);
8207
+ preflightRerouteRows = snapshotProjectRows(s.jobs, row);
8208
+ return; // row is pending + held; no park, no ladder
8209
+ }
8210
+ }
8211
+
7518
8212
  // already_satisfied_on_main names the satisfying sha in its own
7519
8213
  // reason — surface that on the completed row's statusHistory
7520
8214
  // instead of the generic "run finished with exit 0" every other
@@ -7772,7 +8466,9 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7772
8466
  for (const { slug, cwd } of newlyCompletedPrds) {
7773
8467
  await prdPaths.archiveCompletedPrd(slug, cwd);
7774
8468
  }
8469
+ if (preflightRerouteHold) auditPreflightHold(job.slug, preflightRerouteCmd, preflightRerouteResult, preflightRerouteHold, { after: 'sentinel_fail' });
7775
8470
  await broadcast({ flush: true });
8471
+ if (preflightRerouteHold) await sendPreflightHoldNotice(job, preflightRerouteHold, preflightRerouteRows);
7776
8472
 
7777
8473
  // Per-run outcome sidecar (issue #11 list B5): turns/tokens/verdict in one
7778
8474
  // small JSON next to the log so fleet health never needs a transcript parse.
@@ -8224,11 +8920,13 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8224
8920
  // degraded cap minus what's already running.
8225
8921
  runReservationExpiryPass(state.jobs, tickStartedAt);
8226
8922
  const freeSlots = degradedConcurrencyCapValue != null
8227
- ? Math.max(0, Math.min(sessionSlots.available(), degradedConcurrencyCapValue - runningSet.size))
8228
- : sessionSlots.available();
8923
+ ? Math.max(0, Math.min(sessionSlots.availableFor('job'), degradedConcurrencyCapValue - runningSet.size))
8924
+ : sessionSlots.availableFor('job');
8229
8925
  const heldSlugs = await computeLaunchHolds(state);
8926
+ for (const [slug, why] of computePreflightHolds(state.jobs)) if (!heldSlugs.has(slug)) heldSlugs.set(slug, why);
8230
8927
  if (stale()) return STALE_TICK;
8231
8928
  const satisfiedSlugsByCwd = await budget.computeDepHistorySatisfaction(state);
8929
+ lastSatisfiedSlugsByCwd = satisfiedSlugsByCwd;
8232
8930
  if (stale()) return STALE_TICK;
8233
8931
  const { batch, reason: holdReason, holds } = pickNextBatch(state.jobs, runningSet, freeSlots, {
8234
8932
  leaseHeld: quietMachineLease.isHeld(),
@@ -8391,7 +9089,7 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8391
9089
  const mins = Math.round(load.heldMs / 60_000);
8392
9090
  console.warn(`[scheduler] load gate: held ${gatedBatch.length} job(s) for ${mins}m with slots and memory free — letting ${launchBatch[0].slug} through; top CPU: ${top.length ? top.join(' | ') : 'n/a'}`);
8393
9091
  } else if (load.standDown) {
8394
- console.log(`[scheduler] load gate: stood down — loadavg1=${load.loadavg1} cores=${load.cores} ratio=${load.ratio} > ${load.threshold} but CPU ${Math.round(load.cpuBusy * 100)}% busy over ${Math.round(load.cpuWindowMs / 1000)}s`);
9092
+ console.log(`[scheduler] load gate: stood down — loadavg1=${load.loadavg1} cores=${load.cores} ratio=${load.ratio} > ${load.threshold} but CPU ${Math.round(load.cpuBusy * 100)}% busy net of this app (${Math.round((load.cpuBusyRaw ?? load.cpuBusy) * 100)}% raw) over ${Math.round(load.cpuWindowMs / 1000)}s`);
8395
9093
  if (load.shouldAuditStandDown) {
8396
9094
  appendAuditEvent('load_gate_stood_down', loadGateAuditFields(load));
8397
9095
  }
@@ -8415,7 +9113,7 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8415
9113
  // state.jobs is the queue's rows in scope at THIS dispatch (PRD 1408) —
8416
9114
  // threaded straight through so spawnJob's hasDownstreamValidator check
8417
9115
  // never re-reads the queue itself.
8418
- spawnJob(job, runId, runDir, state.config.defaultCwd, null, state.jobs).catch((e) => reportSchedulerError('spawnJob dispatch rejected', job.slug, e));
9116
+ dispatchSpawnJob(job, runId, runDir, state.config.defaultCwd, null, state.jobs).catch((e) => reportSchedulerError('spawnJob dispatch rejected', job.slug, e));
8419
9117
  issued += 1;
8420
9118
  }
8421
9119
  if (issued > 0) {
@@ -8655,12 +9353,85 @@ const starveEscalated = new Set();
8655
9353
  * gate. Exported for direct unit testing (attach a fake window via
8656
9354
  * attachWindow() first to assert the toast send).
8657
9355
  */
9356
+ function projectRowsFor(jobs, cwd) {
9357
+ return (Array.isArray(jobs) ? jobs : []).filter((j) => j && (j.cwd || DEFAULT_PROJECT_CWD) === cwd);
9358
+ }
9359
+
9360
+ /**
9361
+ * starveRootFor(projectRows, oldestPendingSlug) → { root, knownWait }
9362
+ *
9363
+ * `root`: the root blocker (starvation.rootBlockersForProject) holding the
9364
+ * oldest pending row, else the first one found, else null. `knownWait`: every
9365
+ * pending row is either itself preflight-held or waits on a preflight-held
9366
+ * root — the scheduler re-checks those on its own backoff, so the project is
9367
+ * waiting on a precondition, not starved.
9368
+ */
9369
+ function starveRootFor(projectRows, oldestPendingSlug = null) {
9370
+ const roots = starvation.rootBlockersForProject(projectRows);
9371
+ const root = roots.find((r) => r.heldSlugs.includes(oldestPendingSlug)) ?? roots[0] ?? null;
9372
+ let knownWait = false;
9373
+ if (roots.length > 0 && roots.every((r) => r.preflightHeld)) {
9374
+ const waiting = new Set(roots.flatMap((r) => r.heldSlugs));
9375
+ for (const r of roots) waiting.add(r.slug);
9376
+ knownWait = projectRows.every((j) => j.status !== 'pending' || waiting.has(j.slug) || (j.preflightHold && typeof j.preflightHold === 'object'));
9377
+ }
9378
+ return { root, knownWait };
9379
+ }
9380
+
9381
+ function rootBlockingFields(root) {
9382
+ return {
9383
+ rootBlockingSlug: root?.slug ?? null,
9384
+ rootBlockingStatus: root?.status ?? null,
9385
+ rootBlockingReason: root?.reason ?? null,
9386
+ };
9387
+ }
9388
+
9389
+ /** Toast/log phrase naming the root blocker, or '' when there is none. */
9390
+ function rootBlockerPhrase(root) {
9391
+ if (!root) return '';
9392
+ return ` Waiting on ${root.slug} (${root.status}${root.reason ? `: ${root.reason}` : ''}).`;
9393
+ }
9394
+
9395
+ /**
9396
+ * reportStarvedProjects(starvedProjects, jobs, launchBlocks) — the per-sweep
9397
+ * project_starved WARN + audit (each naming the root blocker), then the
9398
+ * bounded escalation. A known wait (starveRootFor) is skipped by both.
9399
+ */
9400
+ function reportStarvedProjects(starvedProjects, jobs = [], launchBlocks = {}) {
9401
+ for (const sp of starvedProjects) {
9402
+ const { root, knownWait } = starveRootFor(projectRowsFor(jobs, sp.cwd), sp.oldestPendingSlug);
9403
+ if (knownWait) continue;
9404
+ console.warn(
9405
+ `[scheduler] PROJECT STARVED: project=${sp.cwd} pending=${sp.pendingCount} oldest=${sp.oldestPendingSlug} `
9406
+ + `waiting=${Math.round(sp.ageMs / 60_000)}m (>= ${Math.round(STARVATION_ESCALATE_MS / 60_000)}m threshold) `
9407
+ + `while other projects are running${root ? ` — root blocker ${root.slug} (${root.status}${root.reason ? `: ${root.reason}` : ''})` : ' — check the cross-project fairness rule in pickNextBatch'}`,
9408
+ );
9409
+ appendAuditEvent('project_starved', {
9410
+ cwd: sp.cwd, pendingCount: sp.pendingCount, oldestPendingSlug: sp.oldestPendingSlug, ageMs: sp.ageMs, ...rootBlockingFields(root),
9411
+ });
9412
+ }
9413
+ // Bounded, automated consequence for a starve that outlives the WARN
9414
+ // above (PRD: the 2026-09-12 19h Bilko starve had ~115 identical
9415
+ // project_starved rows and zero consequence). STARVE_ESCALATION_MS is
9416
+ // strictly later than STARVATION_ESCALATE_MS, so this only ever fires on
9417
+ // a subset of the rows already reported above — same verdict, no
9418
+ // re-derivation.
9419
+ runStarveEscalationSweep(starvedProjects, jobs, launchBlocks);
9420
+ }
9421
+
8658
9422
  function runStarveEscalationSweep(starvedProjects, jobs = [], launchBlocks = {}) {
8659
- const { toEscalate, toClear } = starvation.selectStarveEscalations(starvedProjects, starveEscalated, STARVE_ESCALATION_MS);
9423
+ const rootByCwd = new Map();
9424
+ const reportable = starvedProjects.filter((sp) => {
9425
+ const r = starveRootFor(projectRowsFor(jobs, sp.cwd), sp.oldestPendingSlug);
9426
+ rootByCwd.set(sp.cwd, r.root);
9427
+ return !r.knownWait;
9428
+ });
9429
+ const { toEscalate, toClear } = starvation.selectStarveEscalations(reportable, starveEscalated, STARVE_ESCALATION_MS);
8660
9430
  for (const cwd of toClear) starveEscalated.delete(cwd);
8661
9431
  for (const sp of toEscalate) {
8662
9432
  starveEscalated.add(sp.cwd);
8663
- const projectRows = (Array.isArray(jobs) ? jobs : []).filter((j) => j && (j.cwd || DEFAULT_PROJECT_CWD) === sp.cwd);
9433
+ const projectRows = projectRowsFor(jobs, sp.cwd);
9434
+ const root = rootByCwd.get(sp.cwd) ?? null;
8664
9435
  const holdReason = starvation.describeStarveHold({ projectRows, launchBlocks, lastTick, lastHoldTick });
8665
9436
  const mins = Math.round(sp.ageMs / 60_000);
8666
9437
  console.error(
@@ -8669,11 +9440,11 @@ function runStarveEscalationSweep(starvedProjects, jobs = [], launchBlocks = {})
8669
9440
  + 'a bounded escalation only; nothing was auto-reset, cancelled, or dispatched',
8670
9441
  );
8671
9442
  appendAuditEvent('project_starve_escalated', {
8672
- cwd: sp.cwd, pendingCount: sp.pendingCount, oldestPendingSlug: sp.oldestPendingSlug, ageMs: sp.ageMs, holdReason,
9443
+ cwd: sp.cwd, pendingCount: sp.pendingCount, oldestPendingSlug: sp.oldestPendingSlug, ageMs: sp.ageMs, holdReason, ...rootBlockingFields(root),
8673
9444
  });
8674
9445
  sendIfAlive(mainWindow, 'schedule:stall', {
8675
9446
  message: `Project starved: ${sp.cwd} has ${sp.pendingCount} pending PRD(s), no dispatch for ~${mins}m `
8676
- + `(hold reason: ${holdReason}) — check the Scheduler tab.`,
9447
+ + `(hold reason: ${holdReason}).${rootBlockerPhrase(root)} Check the Scheduler tab.`,
8677
9448
  total: sp.pendingCount,
8678
9449
  byProject: { [sp.cwd]: { starved: sp.pendingCount } },
8679
9450
  });
@@ -8748,29 +9519,63 @@ function runQueueHealthSweep(jobs) {
8748
9519
  }
8749
9520
 
8750
9521
  // Cross-cycle "already attempted" memory for the branch sweep (PRD 1135) —
8751
- // in-memory only, keyed `"<cwd>::<branch>"`. Resets on restart, same as
8752
- // consecutiveRapidRateLimitsBySlug above; the goal is "don't retry a
8753
- // permanently-conflicting branch every cycle forever" while the process
8754
- // stays up, not durability across a restart.
9522
+ // in-memory only, keyed `"<cwd>::<branch>"`: at most one attempt per branch
9523
+ // per process lifetime. Durability across restarts is the persisted backoff
9524
+ // state below (PRD 3494), not this set.
8755
9525
  const branchSweepAttempted = new Set();
9526
+ // Fallback backoff state for a project whose ops root cannot be written
9527
+ // (ephemeral/unprovable cwd) — keyed by cwd, lives for the process only.
9528
+ const branchSweepBackoffFallback = new Map();
9529
+ const BRANCH_SWEEP_NEEDS_YOU_APP = 'session-manager';
9530
+ const BRANCH_SWEEP_BACKOFF_FILE = 'branch-sweep-backoff.json';
9531
+
9532
+ /** Persisted backoff file for `cwd` (scheduler namespace), or null when unwritable. */
9533
+ function branchSweepBackoffFile(cwd) {
9534
+ try {
9535
+ const file = opsPath(cwd, 'scheduler', BRANCH_SWEEP_BACKOFF_FILE);
9536
+ assertOpsWrite(file, 'scheduler');
9537
+ return file;
9538
+ } catch {
9539
+ return null;
9540
+ }
9541
+ }
8756
9542
 
8757
9543
  /**
8758
9544
  * Recover any `sm-job/*` branch left stranded (unmerged, owning row terminal
8759
9545
  * or gone) across every known project — the other half of PRD 1135's
8760
9546
  * invariant alongside the reaper's liveness check above: that check stops
8761
9547
  * NEW stranding, this sweep recovers anything stranded before it (or by a
8762
- * crash the liveness check can't cover). Read-only reporting plus AT MOST one
8763
- * bounded integrateBranch attempt per branch per process lifetime (see
8764
- * branchSweepAttempted) — never forces anything, never deletes a branch.
8765
- * Hangs off the same cadence as runQueueHealthSweep. Never throws.
9548
+ * crash the liveness check can't cover). At most one bounded integrateBranch
9549
+ * attempt per branch per process lifetime (branchSweepAttempted), gated by a
9550
+ * persisted per-(cwd, branch) failure count with exponential backoff
9551
+ * (PRD 3494): after BRANCH_SWEEP_MAX_FAILURES failures, or once the owning
9552
+ * PRD is skipped/superseded, the branch is given up on — one
9553
+ * branch_sweep_gave_up audit row per branch, then one cleanup summary (audit
9554
+ * row + Needs-you notice) for the pass that stopped any, never one per boot.
9555
+ * Never forces anything, never deletes a branch. Never throws.
8766
9556
  */
8767
- async function runBranchSweep(jobs) {
9557
+ async function runBranchSweep(jobs, deps = {}) {
8768
9558
  if (process.env.SM_BRANCH_SWEEP_DISABLE === '1') return;
9559
+ const audit = deps.audit ?? appendAuditEvent;
9560
+ const store = deps.store ?? needsYouStore;
9561
+ const now = deps.now ?? Date.now();
9562
+ const stopped = [];
8769
9563
  try {
8770
- for (const cwd of allProjectCwds()) {
9564
+ for (const cwd of (deps.cwds ?? allProjectCwds())) {
9565
+ const file = branchSweepBackoffFile(cwd);
9566
+ let state;
9567
+ try {
9568
+ state = file
9569
+ ? await loadBranchSweepBackoff(file)
9570
+ : (branchSweepBackoffFallback.get(cwd) ?? emptyBranchSweepBackoffState());
9571
+ } catch {
9572
+ state = emptyBranchSweepBackoffState();
9573
+ }
8771
9574
  let sweep;
8772
9575
  try {
8773
- sweep = await sweepStrandedJobBranches({ cwd, jobs, attemptedBranches: branchSweepAttempted });
9576
+ sweep = await sweepStrandedJobBranches({
9577
+ cwd, jobs, attemptedBranches: branchSweepAttempted, backoff: { state, now },
9578
+ });
8774
9579
  } catch (e) {
8775
9580
  console.warn(`[scheduler] branch sweep error for ${cwd}`, e?.message);
8776
9581
  continue;
@@ -8778,10 +9583,12 @@ async function runBranchSweep(jobs) {
8778
9583
  for (const r of sweep.results) {
8779
9584
  if (r.action === 'integrated') {
8780
9585
  console.log(`[scheduler] branch-sweep: merged stranded branch ${r.branch} into ${cwd} HEAD`);
8781
- appendAuditEvent('branch_sweep_integrated', { cwd, branch: r.branch, slug: r.slug });
9586
+ audit('branch_sweep_integrated', { cwd, branch: r.branch, slug: r.slug });
8782
9587
  } else if (r.action === 'conflict') {
8783
- console.warn(`[scheduler] branch-sweep: ${r.branch} could not be integrated: ${r.integration?.reason}`);
8784
- appendAuditEvent('branch_sweep_conflict', { cwd, branch: r.branch, slug: r.slug, reason: r.integration?.reason });
9588
+ console.warn(`[scheduler] branch-sweep: ${r.branch} could not be integrated (failure ${r.failures}): ${r.integration?.reason}`);
9589
+ audit('branch_sweep_conflict', {
9590
+ cwd, branch: r.branch, slug: r.slug, reason: r.integration?.reason, failures: r.failures,
9591
+ });
8785
9592
  if (r.slug) {
8786
9593
  await mutate((s) => {
8787
9594
  const j = s.jobs.find((x) => x.slug === r.slug);
@@ -8790,12 +9597,59 @@ async function runBranchSweep(jobs) {
8790
9597
  }
8791
9598
  }
8792
9599
  }
9600
+ const gaveUp = takeUnreportedGiveUps(state);
9601
+ for (const g of gaveUp) {
9602
+ console.warn(`[scheduler] branch-sweep: gave up on ${g.branch} in ${cwd} (${g.reason}); branch left in place`);
9603
+ audit('branch_sweep_gave_up', { cwd, branch: g.branch, slug: g.slug, reason: g.reason, failures: g.failures });
9604
+ stopped.push({ cwd, ...g });
9605
+ }
9606
+ if (sweep.changed || gaveUp.length) {
9607
+ if (file) {
9608
+ try {
9609
+ await saveBranchSweepBackoff(file, state);
9610
+ } catch (e) {
9611
+ console.warn(`[scheduler] branch sweep backoff save failed for ${cwd}`, e?.message);
9612
+ }
9613
+ } else {
9614
+ branchSweepBackoffFallback.set(cwd, state);
9615
+ }
9616
+ }
8793
9617
  }
9618
+ if (stopped.length) await reportBranchSweepGaveUp(stopped, { audit, store, now });
8794
9619
  } catch (e) {
8795
9620
  console.warn('[scheduler] branch sweep error', e?.message);
8796
9621
  }
8797
9622
  }
8798
9623
 
9624
+ /**
9625
+ * One cleanup summary for the branches a sweep pass stopped retrying: a
9626
+ * branch_sweep_cleanup_summary audit row plus one Needs-you notice. Only
9627
+ * called for a pass that newly gave up on something, so a reboot with nothing
9628
+ * new reports nothing.
9629
+ */
9630
+ async function reportBranchSweepGaveUp(stopped, { audit, store, now }) {
9631
+ const lines = stopped.map((s) => `${s.cwd}: ${s.branch} (${s.reason})`);
9632
+ audit('branch_sweep_cleanup_summary', {
9633
+ count: stopped.length,
9634
+ branches: stopped.map((s) => ({ cwd: s.cwd, branch: s.branch, slug: s.slug, reason: s.reason })),
9635
+ });
9636
+ const head = 'Stopped retrying these sm-job branches (conflicted 3 times or their PRD was skipped/superseded). '
9637
+ + 'Nothing was deleted — merge or delete each by hand:\n';
9638
+ let why = head + lines.join('\n');
9639
+ if (why.length > 1000) why = `${why.slice(0, 980)}\n… (${stopped.length} total)`;
9640
+ try {
9641
+ const result = await store.postNeedsYou({
9642
+ app: BRANCH_SWEEP_NEEDS_YOU_APP,
9643
+ id: `branch-sweep-gave-up-${now}`,
9644
+ title: `Branch sweep gave up on ${stopped.length} stranded branch${stopped.length === 1 ? '' : 'es'}`,
9645
+ why,
9646
+ });
9647
+ if (result?.changed && mainWindow) sendIfAlive(mainWindow, 'needsYou:changed', {});
9648
+ } catch (e) {
9649
+ console.error('[scheduler] branch-sweep cleanup Needs-you post failed', e?.message ?? e);
9650
+ }
9651
+ }
9652
+
8799
9653
  /**
8800
9654
  * Scan running jobs, identify those whose claude process is provably dead OR
8801
9655
  * whose spawn never got far enough to record a runtime.pid in the first
@@ -10338,6 +11192,15 @@ let gateShadowPending = null;
10338
11192
  let gateShadowSlug = null;
10339
11193
 
10340
11194
 
11195
+ // Boot-reverify park errors, keyed by the verifierVerdict they pair with.
11196
+ // They state only what happened: the self-heal ladder may still reopen the
11197
+ // job, so they must not claim a human has to act.
11198
+ const PARK_ERRORS = Object.freeze({
11199
+ no_run_artifacts: 'no run artifacts — parked',
11200
+ autofix_no_plan: 'auto-fix investigation produced no fix plan after retry — parked',
11201
+ autofix_plan_unqueued: 'auto-fix investigation produced a fix plan that never reached the queue — parked',
11202
+ });
11203
+
10341
11204
  async function reverifyNeedsReview() {
10342
11205
  const snap = await readQueue();
10343
11206
  // isGuardParkedWithoutAutoFix rows are NOT isRescanCandidate (their
@@ -10629,25 +11492,25 @@ async function reverifyNeedsReview() {
10629
11492
  for (const j of s.jobs) {
10630
11493
  if (unresolvableSet.has(j.slug)) {
10631
11494
  j.verifierVerdict = 'no_run_artifacts';
10632
- j.error = 'no run artifacts — manual review';
11495
+ j.error = PARK_ERRORS.no_run_artifacts;
10633
11496
  } else if (exhaustedSet.has(j.slug)) {
10634
11497
  j.verifierVerdict = 'autofix_no_plan';
10635
- j.error = 'auto-fix investigation produced no fix plan after retry — manual review';
11498
+ j.error = PARK_ERRORS.autofix_no_plan;
10636
11499
  } else if (planUnqueuedSet.has(j.slug)) {
10637
11500
  j.verifierVerdict = 'autofix_plan_unqueued';
10638
- j.error = 'auto-fix investigation produced a fix plan that never reached the queue — manual review';
11501
+ j.error = PARK_ERRORS.autofix_plan_unqueued;
10639
11502
  }
10640
11503
  }
10641
11504
  });
10642
11505
  if (unresolvable.length) {
10643
- console.log(`[scheduler] boot reverify: no run artifacts for ${unresolvable.map((j) => j.slug).join(', ')} — flagged for manual review`);
11506
+ console.log(`[scheduler] boot reverify: no run artifacts for ${unresolvable.map((j) => j.slug).join(', ')} — parked`);
10644
11507
  }
10645
11508
  if (exhaustedAutoFix.length) {
10646
- console.log(`[scheduler] boot reverify: auto-fix retry exhausted for ${exhaustedAutoFix.map((j) => j.slug).join(', ')} — flagged for manual review`);
11509
+ console.log(`[scheduler] boot reverify: auto-fix retry exhausted for ${exhaustedAutoFix.map((j) => j.slug).join(', ')} — parked`);
10647
11510
  }
10648
11511
  if (planUnqueued.length) {
10649
11512
  for (const j of planUnqueued) {
10650
- console.log(`[scheduler] boot reverify: auto-fix plan never queued for ${j.slug} — flagged for manual review`);
11513
+ console.log(`[scheduler] boot reverify: auto-fix plan never queued for ${j.slug} — parked`);
10651
11514
  }
10652
11515
  }
10653
11516
  await broadcast();
@@ -10889,7 +11752,7 @@ function registerScheduleHandlers() {
10889
11752
  }
10890
11753
  const now = Date.now();
10891
11754
  const slotSnapshot = sessionSlots.snapshot();
10892
- const freeSlots = Math.max(0, slotSnapshot.total - slotSnapshot.inUse);
11755
+ const freeSlots = jobFreeSlots(slotSnapshot);
10893
11756
  const verdict = starvation.classifyQueueHealth({
10894
11757
  jobs: state.jobs,
10895
11758
  paused: upgradeDrain.effectivePaused(state),
@@ -11304,21 +12167,8 @@ function rescheduleIntervalTick() {
11304
12167
  // started" — the 2026-09-01 NN-ordering starvation ran 3.5 h unnoticed.
11305
12168
  // Escalation only, same shape as the quarantine/overrun warnings above.
11306
12169
  const starvedProjects = findStarvedProjects(s.jobs, Date.now(), STARVATION_ESCALATE_MS, s.lastDispatchAtByCwd);
11307
- for (const sp of starvedProjects) {
11308
- console.warn(
11309
- `[scheduler] PROJECT STARVED: project=${sp.cwd} pending=${sp.pendingCount} oldest=${sp.oldestPendingSlug} `
11310
- + `waiting=${Math.round(sp.ageMs / 60_000)}m (>= ${Math.round(STARVATION_ESCALATE_MS / 60_000)}m threshold) `
11311
- + `while other projects are running — check the cross-project fairness rule in pickNextBatch`,
11312
- );
11313
- appendAuditEvent('project_starved', { cwd: sp.cwd, pendingCount: sp.pendingCount, oldestPendingSlug: sp.oldestPendingSlug, ageMs: sp.ageMs });
11314
- }
11315
- // Bounded, automated consequence for a starve that outlives the WARN
11316
- // above (PRD: the 2026-09-12 19h Bilko starve had ~115 identical
11317
- // project_starved rows and zero consequence). STARVE_ESCALATION_MS is
11318
- // strictly later than STARVATION_ESCALATE_MS, so this only ever fires on
11319
- // a subset of the rows already reported above — same verdict, no
11320
- // re-derivation.
11321
- runStarveEscalationSweep(starvedProjects, s.jobs, s.launchBlocks);
12170
+ // Each event names the root blocker; a known preflight wait is skipped.
12171
+ reportStarvedProjects(starvedProjects, s.jobs, s.launchBlocks);
11322
12172
 
11323
12173
  // Bounded failed -> pending auto-reset (PRD 1151), plus the stuck-failed
11324
12174
  // escalation now narrowed to only the rows that auto-reset gave up on.
@@ -11710,7 +12560,11 @@ async function init() {
11710
12560
  // archivedStatus); `fields=full` restores them.
11711
12561
  function toCompactPrdEntry(entry) {
11712
12562
  const { slug, title, cwd, mtimeMs, archived, status, agentType } = entry;
11713
- return { slug, title, cwd, mtimeMs, archived, status, agentType };
12563
+ const out = { slug, title, cwd, mtimeMs, archived, status, agentType };
12564
+ // Only when set, so the compact page stays small.
12565
+ if (entry.heldReason) out.heldReason = entry.heldReason;
12566
+ if (entry.waitingOn) out.waitingOn = entry.waitingOn;
12567
+ return out;
11714
12568
  }
11715
12569
 
11716
12570
  /**
@@ -11829,6 +12683,29 @@ async function listPrdsInternal({ cwd: rawCwd } = {}) {
11829
12683
  queueHistory.historyTerminalBySlug().catch(() => new Map()),
11830
12684
  ]);
11831
12685
  const liveStatusBySlug = new Map(state.jobs.map((j) => [j.slug, j.status]));
12686
+ // heldReason (the live row's own) + waitingOn (the root blocker slug of a
12687
+ // dependency-blocked pending row, starvation.rootBlockersForProject).
12688
+ const liveRowBySlug = new Map(state.jobs.map((j) => [j.slug, j]));
12689
+ const waitingOnBySlug = new Map();
12690
+ const jobsByCwd = new Map();
12691
+ for (const j of state.jobs) {
12692
+ if (!j) continue;
12693
+ const key = j.cwd || DEFAULT_PROJECT_CWD;
12694
+ if (!jobsByCwd.has(key)) jobsByCwd.set(key, []);
12695
+ jobsByCwd.get(key).push(j);
12696
+ }
12697
+ for (const rows of jobsByCwd.values()) {
12698
+ if (!rows.some((j) => j.status === 'pending' && Array.isArray(j.dependsOn) && j.dependsOn.length > 0)) continue;
12699
+ for (const r of starvation.rootBlockersForProject(rows)) {
12700
+ for (const held of r.heldSlugs) waitingOnBySlug.set(held, r.slug);
12701
+ }
12702
+ }
12703
+ for (let i = 0; i < archivedStart; i++) {
12704
+ const entry = out[i];
12705
+ const live = liveRowBySlug.get(entry.slug);
12706
+ entry.heldReason = live && typeof live.heldReason === 'string' && live.heldReason ? flatString(live.heldReason) : null;
12707
+ entry.waitingOn = waitingOnBySlug.get(entry.slug) ?? null;
12708
+ }
11832
12709
  for (let i = 0; i < out.length; i++) {
11833
12710
  const entry = out[i];
11834
12711
  // `entry` is a freshly-synthesized PRD-listing row, not a persisted
@@ -12047,7 +12924,17 @@ const remote = {
12047
12924
 
12048
12925
  async listJobs() {
12049
12926
  const state = await readQueue();
12050
- return state.jobs.map((j) => ({ slug: j.slug, title: j.title, status: j.status, cwd: j.cwd, agentType: j.agentType ?? null }));
12927
+ // epicId + sourcePromptId are what epicOutsideState.buildKnownPrds joins
12928
+ // rows to an Epic on — dropping them made GET /admin/epic count no rows.
12929
+ return state.jobs.map((j) => ({
12930
+ slug: j.slug,
12931
+ title: j.title,
12932
+ status: j.status,
12933
+ cwd: j.cwd,
12934
+ agentType: j.agentType ?? null,
12935
+ epicId: j.epicId ?? null,
12936
+ sourcePromptId: j.sourcePromptId ?? null,
12937
+ }));
12051
12938
  },
12052
12939
 
12053
12940
  // Single queue row lookup, used by cancelJob/updatePrd's status guards and
@@ -12240,8 +13127,23 @@ const remote = {
12240
13127
 
12241
13128
  const { frontmatter: fm, body: origBody } = parsePrdFile(raw);
12242
13129
  if (frontmatter) {
13130
+ // riskTools: same validator createPrd uses (prdCreate.normalizeRiskTools),
13131
+ // so update and create can never disagree. Refused before any write; an
13132
+ // explicit [] removes the key.
13133
+ const clearRiskTools = Array.isArray(frontmatter.riskTools) && frontmatter.riskTools.length === 0;
13134
+ let riskTools;
13135
+ if (frontmatter.riskTools !== undefined && !clearRiskTools) {
13136
+ const rt = prdCreate.normalizeRiskTools(frontmatter.riskTools);
13137
+ if (!rt.ok) return { ok: false, error: rt.error };
13138
+ riskTools = rt.value;
13139
+ }
12243
13140
  for (const key of Object.keys(frontmatter)) {
12244
13141
  if (frontmatter[key] === undefined) continue;
13142
+ if (key === 'riskTools') {
13143
+ if (clearRiskTools) delete fm.riskTools;
13144
+ else fm.riskTools = riskTools;
13145
+ continue;
13146
+ }
12245
13147
  fm[key] = frontmatter[key];
12246
13148
  }
12247
13149
  }
@@ -12322,6 +13224,49 @@ const remote = {
12322
13224
  if (job.status === 'completed' || job.status === 'failed' || job.status === 'needs_review' || job.status === 'skipped') {
12323
13225
  return { ok: false, error: `job already terminal (status: "${job.status}") — nothing to cancel` };
12324
13226
  }
13227
+ // Dependents choice (PRD 3499): cancelling a row that pending PRDs depend
13228
+ // on would strand them behind a dead row (Self stall, 2026-11-22). Refuse
13229
+ // unless the caller says what happens to them; apply that choice BEFORE
13230
+ // the target is cancelled, aborting on any failure.
13231
+ const depCwd = job.cwd ?? null;
13232
+ const pendingDependents = cancelDependents.findPendingDependents(state.jobs, slug, depCwd);
13233
+ let depPlan = null;
13234
+ if (pendingDependents.length > 0) {
13235
+ const names = pendingDependents.map((d) => d.slug);
13236
+ if (!opts.dependents) {
13237
+ return {
13238
+ ok: false,
13239
+ error: `job "${slug}" has ${names.length} pending dependent(s): ${names.join(', ')}. `
13240
+ + 'Pass dependents: { action: "cascade" } to cancel them too, '
13241
+ + '{ action: "repoint", to: "<slug>" } to make them depend on another PRD instead, '
13242
+ + 'or { action: "clear" } to drop the dependency.',
13243
+ dependents: names,
13244
+ choices: [...cancelDependents.DEPENDENTS_ACTIONS],
13245
+ };
13246
+ }
13247
+ depPlan = cancelDependents.planDependentsUpdate(state.jobs, slug, opts.dependents, depCwd);
13248
+ if (!depPlan.ok) return { ok: false, error: depPlan.error, dependents: names };
13249
+ const applied = [];
13250
+ for (const edit of depPlan.edits) {
13251
+ if (edit.action !== 'setDependsOn') continue;
13252
+ const res = await this.updatePrd({ slug: edit.slug, cwd: depCwd ?? undefined, frontmatter: { dependsOn: edit.dependsOn } });
13253
+ if (!res?.ok) {
13254
+ // Best-effort rollback of edits already written, so an aborted
13255
+ // cancel leaves the dependents as they were.
13256
+ for (const done of applied.reverse()) {
13257
+ await this.updatePrd({ slug: done.slug, cwd: depCwd ?? undefined, frontmatter: { dependsOn: done.previous } }).catch(() => null);
13258
+ }
13259
+ return {
13260
+ ok: false,
13261
+ error: `could not update dependent ${edit.slug}: ${res?.error ?? 'unknown error'} — "${slug}" was not cancelled`,
13262
+ dependents: names,
13263
+ };
13264
+ }
13265
+ applied.push(edit);
13266
+ }
13267
+ }
13268
+ const cascadeEdits = depPlan?.action === 'cascade' ? depPlan.edits : [];
13269
+ const dependsOnEdits = depPlan && depPlan.action !== 'cascade' ? depPlan.edits : [];
12325
13270
  const wasRunning = job.status === 'running';
12326
13271
  const pid = job.runtime?.pid;
12327
13272
  // Evidence-before-failure guard, scoped to an actually-running job being
@@ -12345,6 +13290,24 @@ const remote = {
12345
13290
  : 'cancelled via admin API';
12346
13291
  const cancelledAt = new Date().toISOString();
12347
13292
  await mutate((s) => {
13293
+ // Dependents first (same mutate, so the target never lands cancelled
13294
+ // while its dependents still point at it).
13295
+ for (const edit of cascadeEdits) {
13296
+ const d = s.jobs.find((x) => x.slug === edit.slug && x.cwd === job.cwd);
13297
+ if (!d || d.status !== 'pending') continue;
13298
+ if (!transitionJob(d, 'failed', { reason: edit.reason, source: 'remote:cancelJob' })) continue;
13299
+ d.error = edit.reason;
13300
+ d.cancelledAt = cancelledAt;
13301
+ d.finishedAt = new Date().toISOString();
13302
+ d.exitCode = d.exitCode ?? null;
13303
+ delete d.runtime;
13304
+ }
13305
+ // Mirror the rewritten dependsOn onto the rows now; reconcile() would
13306
+ // refresh it from the PRD file on its next pass anyway.
13307
+ for (const edit of dependsOnEdits) {
13308
+ const d = s.jobs.find((x) => x.slug === edit.slug && x.cwd === job.cwd);
13309
+ if (d) d.dependsOn = edit.dependsOn;
13310
+ }
12348
13311
  const idx = s.jobs.findIndex((j) => j.slug === slug);
12349
13312
  if (idx < 0) return;
12350
13313
  const j = s.jobs[idx];
@@ -12361,6 +13324,12 @@ const remote = {
12361
13324
  if (wasRunning && pid) killOrphanClaudePid(pid);
12362
13325
  await broadcast({ flush: true });
12363
13326
  const result = { ok: true, slug, status: targetStatus, wasRunning, cwd: job.cwd ?? null, cancelledAt };
13327
+ if (depPlan) {
13328
+ appendAuditEvent('job_cancel_dependents', {
13329
+ slug, cwd: job.cwd ?? null, action: depPlan.action, to: depPlan.to ?? null, dependents: depPlan.dependents,
13330
+ });
13331
+ result.dependents = { action: depPlan.action, to: depPlan.to ?? null, slugs: depPlan.dependents };
13332
+ }
12364
13333
  if (wasRunning) {
12365
13334
  // Whatever the executor committed before SIGTERM stays on its job
12366
13335
  // branch (never integrated); tell the caller where. Known residual: a
@@ -12450,7 +13419,20 @@ function registerAdminRoutes(adminHttp, remoteObj = remote) {
12450
13419
  });
12451
13420
  }
12452
13421
 
13422
+ // queueOps.dismissCancelled needs the serialized queue writer; queueOps
13423
+ // cannot require this module (circular), so it is bound here (PRD 3492).
13424
+ queueOps.bindQueueAccess({
13425
+ readQueue,
13426
+ mutate,
13427
+ broadcast: (opts) => broadcast(opts),
13428
+ updatePrd: (args) => remote.updatePrd(args),
13429
+ transitionJob,
13430
+ });
13431
+
12453
13432
  module.exports = {
13433
+ PARK_ERRORS,
13434
+ applyDepHoldNotices,
13435
+ _resetDepHoldNoticesForTests,
12454
13436
  readValidatorGateMs,
12455
13437
  resolveValidatorEstimate,
12456
13438
  planJobScope,
@@ -12466,6 +13448,10 @@ module.exports = {
12466
13448
  rescheduleIntervalTick,
12467
13449
  runQueueStarvationWatchdog,
12468
13450
  runStarveEscalationSweep,
13451
+ reportStarvedProjects,
13452
+ sendPreflightHoldNotice,
13453
+ _setPreflightHoldNoticeSenderForTests,
13454
+ _resetPreflightHoldNoticesForTests,
12469
13455
  runJobLeftoverSweep,
12470
13456
  stripAppOwnedChurn,
12471
13457
  BUDGET_WARNING_FRACTION,
@@ -12479,6 +13465,7 @@ module.exports = {
12479
13465
  writeQueue,
12480
13466
  _setPeriodicReverifyEnabledForTests,
12481
13467
  _setLoadGateForTests,
13468
+ _setSpawnJobForTests,
12482
13469
  _mutateForTests: mutate, // mutate() has no other exported call site; test-only seam.
12483
13470
  reconcile,
12484
13471
  broadcast,
@@ -12552,6 +13539,7 @@ module.exports = {
12552
13539
  isNotifiableTerminalStatus,
12553
13540
  armSettleAfterValidatorBudgetKill,
12554
13541
  extractResultTextFromLog,
13542
+ extractStructuredOutputFromLog,
12555
13543
  resolveVerifyPrdPath,
12556
13544
  resolveFixPlanPath,
12557
13545
  resolveNotifyPrd,
@@ -12576,6 +13564,7 @@ module.exports = {
12576
13564
  INVESTIGATION_MAX_MS,
12577
13565
  buildResumeRecoveryPreamble,
12578
13566
  buildClaudeSpawnArgs,
13567
+ jobRiskToolsClearance,
12579
13568
  HEADLESS_DISALLOWED_TOOLS,
12580
13569
  spawnResumeRecovery,
12581
13570
  resolveHeadShasForPass,
@@ -12585,6 +13574,8 @@ module.exports = {
12585
13574
  performLeftoverQuarantine,
12586
13575
  spawnInvestigation,
12587
13576
  computeLaunchHolds,
13577
+ computePreflightHolds,
13578
+ runPreflightGate,
12588
13579
  handleLaunchFailure,
12589
13580
  applyLaunchFailure,
12590
13581
  setPaused,