claude-code-session-manager 0.138.0 → 0.140.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 (194) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +352 -79
  3. package/dist/assets/AppSettings-CMFEM68R.js +2 -0
  4. package/dist/assets/History--JwsFnbn.js +2 -0
  5. package/dist/assets/HomeClaudeConfig-ijEXs--3.js +3 -0
  6. package/dist/assets/{Panel-CeDiyuNn.js → Panel-CALyU0pe.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-sdlA-fUb.js +26 -0
  8. package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
  9. package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
  10. package/dist/assets/Skills-DtRzghn5.js +67 -0
  11. package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DApeu7x8.js} +60 -54
  12. package/dist/assets/ViewTabs-B7qLXRAH.js +1 -0
  13. package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-DtStfv1H.js} +1 -1
  14. package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-ydfnwepc.js} +1 -1
  15. package/dist/assets/index-CtxruO1L.js +3121 -0
  16. package/dist/assets/{index-62tyjEQB.css → index-DKXdXfka.css} +1 -1
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +467 -451
  20. package/package.json +17 -6
  21. package/plugins/AGENTS.md +60 -0
  22. package/plugins/CLAUDE.md +1 -60
  23. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  24. package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
  25. package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
  26. package/plugins/session-manager-dev/skills/develop/SKILL.md +36 -22
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  34. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  35. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  36. package/scripts/README.md +2 -0
  37. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  38. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  39. package/scripts/ops-sweep.cjs +53 -23
  40. package/scripts/scheduler-mcp-server.cjs +360 -35
  41. package/src/main/build-info.json +4 -4
  42. package/src/main/chatRunner.cjs +2 -2
  43. package/src/main/config.cjs +112 -8
  44. package/src/main/docEdit.cjs +6 -1
  45. package/src/main/exchanges.cjs +70 -5
  46. package/src/main/files.cjs +7 -27
  47. package/src/main/health.cjs +48 -15
  48. package/src/main/historyAggregator.cjs +172 -63
  49. package/src/main/historyDashboard.cjs +87 -17
  50. package/src/main/index.cjs +78 -4
  51. package/src/main/ipcSchemas.cjs +233 -20
  52. package/src/main/lib/AGENTS.md +54 -0
  53. package/src/main/lib/CLAUDE.md +1 -54
  54. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  55. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  56. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  57. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  58. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  59. package/src/main/lib/claude/effectiveModelInfo.cjs +92 -22
  60. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  61. package/src/main/lib/claude/modelPricing.cjs +148 -0
  62. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  63. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  64. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  65. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  66. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  67. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  68. package/src/main/lib/ephemeralCwd.cjs +37 -2
  69. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  70. package/src/main/lib/epic/epicAdminRoutes.cjs +121 -0
  71. package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
  72. package/src/main/lib/epic/epicOutsideRead.cjs +423 -0
  73. package/src/main/lib/epic/epicOutsideState.cjs +233 -0
  74. package/src/main/lib/epic/epicSettle.cjs +1 -1
  75. package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
  76. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  77. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  78. package/src/main/lib/epic/externalRef.cjs +37 -0
  79. package/src/main/lib/epic/externalRefIndex.cjs +136 -0
  80. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  81. package/src/main/lib/epic/restorableSessions.cjs +151 -17
  82. package/src/main/lib/epic/transcriptUsage.cjs +197 -0
  83. package/src/main/lib/externalContract.cjs +137 -0
  84. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +176 -5
  85. package/src/main/lib/feedback-remote/crossProjectReply.cjs +186 -9
  86. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
  87. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
  88. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
  89. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
  90. package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
  91. package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
  92. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +167 -21
  93. package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
  94. package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
  95. package/src/main/lib/feedback-remote/needsYouStore.cjs +285 -0
  96. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  97. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  98. package/src/main/lib/git/branchSweep.cjs +209 -4
  99. package/src/main/lib/git/gitWorktree.cjs +41 -5
  100. package/src/main/lib/guardShims.cjs +1 -1
  101. package/src/main/lib/historyRollup.cjs +58 -5
  102. package/src/main/lib/insideHome.cjs +27 -1
  103. package/src/main/lib/mcpToolCatalog.cjs +232 -25
  104. package/src/main/lib/mdDocCensus.cjs +59 -78
  105. package/src/main/lib/mdDocRefs.cjs +71 -93
  106. package/src/main/lib/mdNetworkScan.cjs +245 -250
  107. package/src/main/lib/mdReviewRecord.cjs +22 -9
  108. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  109. package/src/main/lib/opsOwnership.cjs +18 -2
  110. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  111. package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
  112. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  113. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  114. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  115. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  116. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  117. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  118. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  119. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  120. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  121. package/src/main/lib/prd/prdCreate.cjs +351 -23
  122. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  123. package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
  124. package/src/main/lib/process/loginItem.cjs +171 -0
  125. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  126. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  127. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  128. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  129. package/src/main/lib/promptSessionSchema.cjs +4 -0
  130. package/src/main/lib/remoteTranscriptTail.cjs +32 -1
  131. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  132. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  133. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  134. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  135. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  136. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  137. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  138. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  139. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  140. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  141. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  142. package/src/main/lib/scheduler/schedulerPaths.cjs +12 -0
  143. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  144. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  145. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  146. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  147. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  148. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  149. package/src/main/lib/tasks/taskRun.cjs +313 -0
  150. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  151. package/src/main/lib/telemetry/auditEvents.cjs +176 -0
  152. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
  153. package/src/main/loginItemIpc.cjs +35 -0
  154. package/src/main/loopEfficiencyHandlers.cjs +11 -2
  155. package/src/main/projectPages.cjs +6 -15
  156. package/src/main/promptSessionEvents.cjs +9 -1
  157. package/src/main/queueOps.cjs +260 -3
  158. package/src/main/runVerify.cjs +53 -25
  159. package/src/main/scheduler/AGENTS.md +26 -0
  160. package/src/main/scheduler/CLAUDE.md +1 -26
  161. package/src/main/scheduler/budget.cjs +239 -9
  162. package/src/main/scheduler/cancelDependents.cjs +154 -0
  163. package/src/main/scheduler/prdParser.cjs +4 -1
  164. package/src/main/scheduler/starvation.cjs +20 -18
  165. package/src/main/scheduler.cjs +774 -64
  166. package/src/main/supervisor.cjs +5 -1
  167. package/src/main/templates/PRD_AUTHORING.md +7 -1
  168. package/src/main/transcripts.cjs +62 -7
  169. package/src/main/validationQualityHandlers.cjs +199 -0
  170. package/src/main/webRemote.cjs +132 -20
  171. package/src/preload/api.d.ts +434 -28
  172. package/src/preload/apiSurface.cjs +7 -0
  173. package/src/preload/apiSurface.json +485 -81
  174. package/src/preload/index.cjs +38 -5
  175. package/src/seed/agents/validator.md +19 -8
  176. package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
  177. package/dist/assets/AppSettings-CgDhqrsU.js +0 -2
  178. package/dist/assets/Button-Bk23rEnZ.js +0 -1
  179. package/dist/assets/DocumentEditorPane-BqY5Nq6W.js +0 -1
  180. package/dist/assets/Extensions-CXem-uwI.js +0 -2
  181. package/dist/assets/History-BwO3coo4.js +0 -2
  182. package/dist/assets/Library-BDV69fSe.js +0 -32
  183. package/dist/assets/ListDetail-CD-Fm6mh.js +0 -1
  184. package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +0 -25
  185. package/dist/assets/ProvenanceBadge-Bu8NmI_R.js +0 -1
  186. package/dist/assets/Scheduler-CkhTvG7C.js +0 -16
  187. package/dist/assets/Settings-COT34hBF.js +0 -2
  188. package/dist/assets/Skills-BgexoUkQ.js +0 -29
  189. package/dist/assets/SourceChip-BXjcdeb1.js +0 -1
  190. package/dist/assets/SystemPrompt-CeeH3EeW.js +0 -1
  191. package/dist/assets/Toggle-CENi19iK.js +0 -1
  192. package/dist/assets/ViewTabs-DDBb0x96.js +0 -1
  193. package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
  194. package/dist/assets/index-CgCxpunJ.js +0 -3116
@@ -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');
@@ -113,7 +120,6 @@ 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,18 @@ 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 needsYouStore = require('./lib/feedback-remote/needsYouStore.cjs');
166
175
  const { withTimeout } = require('./lib/util/withTimeout.cjs');
167
176
 
168
177
  // ---------- origin session resolution (PRD 832) ----------
@@ -197,8 +206,12 @@ const adoptedRunSupervisor = require('./lib/scheduler/adoptedRunSupervisor.cjs')
197
206
  const { splitFrontmatter, parsePrdFile, serializePrdFile, isArtifactOnlyDeclaration } = require('./lib/prd/prdFrontmatter.cjs');
198
207
  const { applyStructuredPrdPatch } = require('./lib/prd/prdBodyPatch.cjs');
199
208
  const { resolvePersonaDefaultEstimate, DEFAULT_PRD_AGENT_TYPE } = require('./lib/prd/prdAgentType.cjs');
200
- const { resolveDepSlug, findNearMatches } = require('./lib/prd/depSlugResolve.cjs');
209
+ const { resolveDepSlug, findNearMatches, bareSlug } = require('./lib/prd/depSlugResolve.cjs');
210
+ const { writeJsonAtomic, readJsonOrSync } = require('./lib/util/atomicFs.cjs');
211
+ const { writeToolRiskGuardSettingsFile } = require('./lib/epic/guardSpawnSettings.cjs');
212
+ const toolRiskMarks = require('./lib/claude/toolRiskMarks.cjs');
201
213
  const { computeDispositionRewrite, mintPlanId, resolveInheritedPlanId } = require('./lib/prd/prdDisposition.cjs');
214
+ const cancelDependents = require('./scheduler/cancelDependents.cjs');
202
215
  const { allProjectCwds } = require('./lib/activeSessions.cjs');
203
216
 
204
217
  // Captured once at module load so every run's meta sidecar can record how
@@ -392,7 +405,28 @@ const FINISH_ARTIFACT_ONLY_VERDICT_LINE = `
392
405
  const FINISH_ARTIFACT_ONLY_COMMIT_LINE = `
393
406
  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
407
 
395
- function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum, isFixPlan = false, isArtifactOnly = false }) {
408
+ /**
409
+ * harvestJobPlanRecords(job, worktreeDir, projectRoot) — copy this run's
410
+ * plan records from its worktree into the main checkout. Logs, never throws.
411
+ */
412
+ function harvestJobPlanRecords(job, worktreeDir, projectRoot) {
413
+ try {
414
+ const epicId = job.epicId || job.sourcePromptId;
415
+ if (!epicId || !worktreeDir || !projectRoot || path.resolve(worktreeDir) === path.resolve(projectRoot)) return;
416
+ const { copied, skipped } = harvestPlanRecords({ worktreeDir, projectRoot, epicId });
417
+ if (copied.length) console.log(`[scheduler] ${job.slug}: harvested ${copied.length} plan record(s) into ${projectRoot}`);
418
+ for (const sk of skipped) console.warn(`[scheduler] ${job.slug}: plan record not harvested: ${sk.path} — ${sk.reason}`);
419
+ } catch (e) {
420
+ console.error(`[scheduler] ${job.slug}: plan record harvest failed`, e);
421
+ }
422
+ }
423
+
424
+ // Validator jobs only (`--json-schema`): the CLI replaces the result text
425
+ // with the JSON, so the scheduler reads the verdict from structured output.
426
+ const FINISH_VALIDATOR_VERDICT_LINE = `
427
+ - Your structured output's schedulerVerdict (and failReason) is what the scheduler reads as this verdict.`;
428
+
429
+ function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum, isFixPlan = false, isArtifactOnly = false, isValidator = false }) {
396
430
  return `${verifyStepNum}. VERIFY — run every command in the PRD's \`# Gate\` section, in order, in the
397
431
  foreground. Each must exit 0. If the PRD has no \`# Gate\` section, run the
398
432
  project's own typecheck, lint and test commands instead. The project's
@@ -406,10 +440,12 @@ ${commitStepNum}. COMMIT — stage only the exact paths you created or changed f
406
440
  jobs' verdicts. Always commit your own work: this rule changes what you
407
441
  stage, never whether you commit.
408
442
  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
443
+ PRD's # Files section names that exact path AND that path is not under
444
+ session-manager-operations/. If git add refuses a path as
410
445
  ignored, leave it out of the commit and name it in your final report.
411
446
  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:
447
+ 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.
448
+ 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
449
  ${FINISH_RUNTIME_FOLDERS}
414
450
  Why: those folders hold the app's live state. A commit of them breaks the
415
451
  running scheduler for every checkout that pulls it.${isArtifactOnly ? FINISH_ARTIFACT_ONLY_COMMIT_LINE : ''}
@@ -418,7 +454,7 @@ ${verdictStepNum}. VERDICT LINE — end your final report with exactly one of th
418
454
  SCHEDULER_VERDICT: PASS
419
455
  SCHEDULER_VERDICT: FAIL <one-line reason>
420
456
  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 : ''}
457
+ - 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
458
  - Print FAIL when the gate is red or the commit could not land. Also print
423
459
  FAIL when a step needs something this run cannot reach (live runtime
424
460
  state, credentials, an account or dashboard action, a host install): do
@@ -468,13 +504,13 @@ in your final report.`;
468
504
  * tree, never FAIL for the missing commit. Self job 826 printed exactly that
469
505
  * false FAIL. Omitted/false leaves the text unchanged.
470
506
  */
471
- function buildFinishProtocol({ reviewInRun = true, isFixPlan = false, isArtifactOnly = false } = {}) {
507
+ function buildFinishProtocol({ reviewInRun = true, isFixPlan = false, isArtifactOnly = false, isValidator = false } = {}) {
472
508
  if (reviewInRun) {
473
509
  return buildFinishHead(3) + FINISH_REVIEW_STEPS_IN_RUN
474
- + buildFinishTail({ verifyStepNum: 3, commitStepNum: 4, verdictStepNum: 5, isFixPlan, isArtifactOnly });
510
+ + buildFinishTail({ verifyStepNum: 3, commitStepNum: 4, verdictStepNum: 5, isFixPlan, isArtifactOnly, isValidator });
475
511
  }
476
512
  return buildFinishHead(2) + FINISH_REVIEW_STEP_DEFERRED
477
- + buildFinishTail({ verifyStepNum: 2, commitStepNum: 3, verdictStepNum: 4, isFixPlan, isArtifactOnly });
513
+ + buildFinishTail({ verifyStepNum: 2, commitStepNum: 3, verdictStepNum: 4, isFixPlan, isArtifactOnly, isValidator });
478
514
  }
479
515
 
480
516
  const FINISH_PROTOCOL = buildFinishProtocol({ reviewInRun: true });
@@ -1091,6 +1127,30 @@ function heartbeatTick(deps = {}) {
1091
1127
  // flag masked before (the burrow-vs-others incident this PRD fixes).
1092
1128
  const now = Date.now();
1093
1129
  const stalledCwds = Object.keys(summary.byProject).filter((cwd) => summary.byProject[cwd].stalled);
1130
+ // Dependency-held stall: pending rows that can never dispatch because
1131
+ // every one waits (directly or down its chain) on a failed/cancelled/
1132
+ // unresolved row. computeStallSummary needs 0 pending, so it never saw
1133
+ // Self's 16 rows held behind a cancelled dep (2026-11-22). Classified
1134
+ // from the dispatch tick's cached satisfied map; until one exists, a
1135
+ // refresh is kicked off asynchronously so the heartbeat never blocks.
1136
+ const heldByDependencyByCwd = {};
1137
+ if (lastSatisfiedSlugsByCwd) {
1138
+ const classified = budget.classifyPendingHolds(s.jobs, {
1139
+ satisfiedSlugsByCwd: lastSatisfiedSlugsByCwd,
1140
+ holds: lastTick?.holds ?? [],
1141
+ now,
1142
+ thresholdMs: POLL_INTERVAL_MS,
1143
+ loadGated: lastTick?.reason === 'load-deferred',
1144
+ });
1145
+ Object.assign(heldByDependencyByCwd, budget.findDependencyStalledProjects(s.jobs, classified));
1146
+ applyDepHoldNotices(classified).catch((e) => console.error('[scheduler] dep-hold Needs-you error', e));
1147
+ } else {
1148
+ refreshSatisfiedSlugsCache(s);
1149
+ }
1150
+ for (const cwd of Object.keys(heldByDependencyByCwd)) {
1151
+ if (summary.byProject[cwd]) summary.byProject[cwd].heldByDependency = heldByDependencyByCwd[cwd];
1152
+ if (!stalledCwds.includes(cwd)) stalledCwds.push(cwd);
1153
+ }
1094
1154
  for (const cwd of [...stallSince.keys()]) {
1095
1155
  if (!stalledCwds.includes(cwd)) {
1096
1156
  stallSince.delete(cwd);
@@ -1106,18 +1166,23 @@ function heartbeatTick(deps = {}) {
1106
1166
  }
1107
1167
  }
1108
1168
  if (toAlert.length > 0) {
1169
+ const heldByDependency = toAlert.flatMap((cwd) => (heldByDependencyByCwd[cwd] ?? []).map((h) => ({ cwd, ...h })));
1109
1170
  console.error(
1110
- `[scheduler] STALL DETECTED in project(s): ${toAlert.join(', ')} — 0 running, 0 pending, not paused, `
1171
+ `[scheduler] STALL DETECTED in project(s): ${toAlert.join(', ')} — nothing dispatchable `
1172
+ + `(0 running + 0 pending, or every pending row held by a dead dependency), not paused, `
1111
1173
  + `for >= ${Math.round(POLL_INTERVAL_MS / 1000)}s`,
1112
1174
  summary.byProject,
1113
1175
  );
1114
- appendAuditEvent('scheduler_stall_detected', { projects: toAlert, total: summary.total, byProject: summary.byProject });
1176
+ appendAuditEvent('scheduler_stall_detected', {
1177
+ projects: toAlert, total: summary.total, byProject: summary.byProject, heldByDependency,
1178
+ });
1115
1179
  if (mainWindow && !mainWindow.isDestroyed()) {
1116
1180
  sendIfAlive(mainWindow, 'schedule:stall', {
1117
1181
  message: `Scheduler stall in ${toAlert.length} project(s): ${toAlert.join(', ')}. Check the Scheduler tab.`,
1118
1182
  projects: toAlert,
1119
1183
  total: summary.total,
1120
1184
  byProject: summary.byProject,
1185
+ heldByDependency,
1121
1186
  });
1122
1187
  }
1123
1188
  }
@@ -1477,6 +1542,28 @@ function quarantinedCwdSet(state) {
1477
1542
  return new Set((state?.unreadableCwds ?? []).map((u) => u.cwd));
1478
1543
  }
1479
1544
 
1545
+ /**
1546
+ * Best-effort epic_state_changed emission for the tick (lib/epic/epicStateWatcher.cjs).
1547
+ * Watches every known project cwd except quarantined shards. Never rejects:
1548
+ * any failure is logged as a warning so it can never hold up dispatch.
1549
+ * SM_EPIC_STATE_WATCH_DISABLE=1 turns it off. `deps` is a test seam.
1550
+ * @param {any} state
1551
+ * @param {{ watch?: (o: { cwds: string[], jobs: any }) => Promise<unknown>, listCwds?: () => string[] }} [deps]
1552
+ * @returns {Promise<void>}
1553
+ */
1554
+ async function runEpicStateWatchForTick(state, deps = {}) {
1555
+ if (process.env.SM_EPIC_STATE_WATCH_DISABLE === '1') return;
1556
+ try {
1557
+ const watch = deps.watch ?? require('./lib/epic/epicStateWatcher.cjs').runEpicStateWatch;
1558
+ const listCwds = deps.listCwds ?? allProjectCwds;
1559
+ const quarantined = quarantinedCwdSet(state);
1560
+ const cwds = listCwds().filter((c) => !quarantined.has(c));
1561
+ await watch({ cwds, jobs: state?.jobs });
1562
+ } catch (e) {
1563
+ console.warn('[scheduler] epic state watch failed', /** @type {any} */ (e)?.message);
1564
+ }
1565
+ }
1566
+
1480
1567
  /**
1481
1568
  * Atomically mint a brand-new parallel-group NN for a PRD about to be
1482
1569
  * authored under the given project's own PRDs dir (falls back to
@@ -2188,6 +2275,12 @@ async function reconcilePass(state) {
2188
2275
  // (commitGuardVerdict, isFixPlanBeyondDepthCap, the fix-plan-completion
2189
2276
  // checks) reads this stamp instead of re-deriving it from the name.
2190
2277
  entry.isFixPlan = classifyDiscoveredFixPlan(p, slug);
2278
+ // Validator-quality provenance: the PRD's `fixes` frontmatter rides on the
2279
+ // row (and into history.jsonl) so validationQuality never re-reads PRD
2280
+ // files. Absent/empty → no key at all.
2281
+ if (Array.isArray(p.fixes) && p.fixes.length > 0) {
2282
+ entry.fixes = p.fixes.map((f) => ({ prd: f.prd, missKind: f.missKind, reason: f.reason }));
2283
+ }
2191
2284
  // Stamp investigationDepth relative to the original job it heals, so
2192
2285
  // selectAutoFixTargets/spawnInvestigation can bound the fix-of-a-fix
2193
2286
  // recursion (see MAX_INVESTIGATION_DEPTH). Non-fix-plan jobs get no
@@ -2299,6 +2392,16 @@ async function reconcilePass(state) {
2299
2392
  } catch (e) {
2300
2393
  console.warn('[scheduler] autoArchiveCompleted failed', e?.message);
2301
2394
  }
2395
+ // Auto-dismiss cancelled rows of closed Epics (PRD 3492). In place on
2396
+ // state.jobs — this runs inside a mutate body, so it must never mutate().
2397
+ try {
2398
+ const dismissResult = await queueOps.autoDismissCancelled(state);
2399
+ if (dismissResult.dismissed?.length > 0) {
2400
+ console.log(`[scheduler] auto-dismissed ${dismissResult.dismissed.length} cancelled row(s) of closed Epics: ${dismissResult.dismissed.join(', ')}`);
2401
+ }
2402
+ } catch (e) {
2403
+ console.warn('[scheduler] autoDismissCancelled failed', e?.message);
2404
+ }
2302
2405
  phaseMs.queueWrite = Date.now() - phaseStartMs;
2303
2406
 
2304
2407
  const totalMs = Date.now() - reconcileStartMs;
@@ -2549,6 +2652,90 @@ let dispatchLoopHandle = null;
2549
2652
  // stalled) rather than every 60s heartbeat tick.
2550
2653
  let stallSince = new Map();
2551
2654
  let stallToasted = new Map();
2655
+ // Latest budget.computeDepHistorySatisfaction map — set by every dispatch tick
2656
+ // (and by refreshSatisfiedSlugsCache when the heartbeat runs before any tick)
2657
+ // so the heartbeat's dependency-held stall check never does its own fs read.
2658
+ let lastSatisfiedSlugsByCwd = null;
2659
+ // Dependency-hold Needs-you notices (one per (cwd, blocking slug) episode).
2660
+ // Ids of the notices this process has open; null until seeded from the store
2661
+ // on first use, so a restart withdraws a notice whose hold cleared while down
2662
+ // instead of orphaning it. budget.selectDepHoldNotices decides; this applies.
2663
+ const DEP_HOLD_NEEDS_YOU_APP = 'session-manager';
2664
+ let depHoldOpen = null; // Map<id, { cwd, blockerSlug, blockerStatus, heldSlugs } | null>
2665
+ let depHoldApplyInFlight = false;
2666
+ /**
2667
+ * applyDepHoldNotices(classified, deps?) — side-effect half of the dep-hold
2668
+ * notice: post/withdraw through needsYouStore (the same store the
2669
+ * /admin/needs-you routes use), audit stall_dep_hold_posted /
2670
+ * stall_dep_hold_withdrawn, and broadcast needsYou:changed. Never mints an
2671
+ * Epic or PRD. `deps` ({ store, audit, onChanged, thresholdMs }) is a test seam.
2672
+ */
2673
+ async function applyDepHoldNotices(classified, deps = {}) {
2674
+ const store = deps.store ?? needsYouStore;
2675
+ const audit = deps.audit ?? appendAuditEvent;
2676
+ const onChanged = deps.onChanged ?? (() => { if (mainWindow) sendIfAlive(mainWindow, 'needsYou:changed', {}); });
2677
+ if (depHoldApplyInFlight) return;
2678
+ depHoldApplyInFlight = true;
2679
+ try {
2680
+ if (depHoldOpen === null) {
2681
+ const items = await store.listNeedsYou({ app: DEP_HOLD_NEEDS_YOU_APP, status: 'open' });
2682
+ depHoldOpen = new Map(items
2683
+ .filter((it) => typeof it.id === 'string' && it.id.startsWith(budget.DEP_HOLD_NOTICE_ID_PREFIX))
2684
+ .map((it) => [it.id, null]));
2685
+ }
2686
+ const { post, withdraw } = budget.selectDepHoldNotices(classified, depHoldOpen.keys(), {
2687
+ thresholdMs: deps.thresholdMs ?? budget.DEP_HOLD_NOTICE_MS,
2688
+ });
2689
+ let changed = false;
2690
+ for (const p of post) {
2691
+ const { title, why } = budget.formatDepHoldNotice(p);
2692
+ let result;
2693
+ try {
2694
+ result = await store.postNeedsYou({ app: DEP_HOLD_NEEDS_YOU_APP, id: p.id, title, why });
2695
+ } catch (e) {
2696
+ console.error(`[scheduler] dep-hold Needs-you post failed for ${p.blockerSlug} in ${p.cwd}`, e?.message ?? e);
2697
+ continue; // not marked open — retried next heartbeat
2698
+ }
2699
+ depHoldOpen.set(p.id, p);
2700
+ audit('stall_dep_hold_posted', {
2701
+ id: p.id, cwd: p.cwd, blockerSlug: p.blockerSlug, blockerStatus: p.blockerStatus,
2702
+ heldSlugs: p.heldSlugs, created: result.created, changed: result.changed,
2703
+ });
2704
+ if (result.changed) changed = true;
2705
+ }
2706
+ for (const id of withdraw) {
2707
+ const meta = depHoldOpen.get(id) ?? null;
2708
+ let item;
2709
+ try {
2710
+ item = await store.withdrawNeedsYou({ app: DEP_HOLD_NEEDS_YOU_APP, id });
2711
+ } catch (e) {
2712
+ console.error(`[scheduler] dep-hold Needs-you withdraw failed for ${id}`, e?.message ?? e);
2713
+ continue;
2714
+ }
2715
+ depHoldOpen.delete(id);
2716
+ audit('stall_dep_hold_withdrawn', {
2717
+ id, cwd: meta?.cwd ?? null, blockerSlug: meta?.blockerSlug ?? null, wasOpen: item != null,
2718
+ });
2719
+ if (item) changed = true;
2720
+ }
2721
+ if (changed) onChanged();
2722
+ } finally {
2723
+ depHoldApplyInFlight = false;
2724
+ }
2725
+ }
2726
+ function _resetDepHoldNoticesForTests() {
2727
+ depHoldOpen = null;
2728
+ depHoldApplyInFlight = false;
2729
+ }
2730
+ let satisfiedRefreshInFlight = false;
2731
+ function refreshSatisfiedSlugsCache(state) {
2732
+ if (satisfiedRefreshInFlight) return;
2733
+ satisfiedRefreshInFlight = true;
2734
+ budget.computeDepHistorySatisfaction(state)
2735
+ .then((m) => { if (!lastSatisfiedSlugsByCwd) lastSatisfiedSlugsByCwd = m; })
2736
+ .catch((e) => console.error('[scheduler] satisfied-slugs cache refresh failed', e))
2737
+ .finally(() => { satisfiedRefreshInFlight = false; });
2738
+ }
2552
2739
  // (The 5-minute feedback sweep that used to piggyback on this heartbeat is
2553
2740
  // gone: it scanned each active project's session-manager-operations/feedback/
2554
2741
  // and auto-queued a /process-feedback PRD. Both the folder and that skill are
@@ -2661,7 +2848,9 @@ function formatLoadGateDetail(load) {
2661
2848
  function loadGateAuditFields(load) {
2662
2849
  return {
2663
2850
  loadavg1: load.loadavg1, cores: load.cores, ratio: load.ratio, threshold: load.threshold,
2664
- cpuBusy: load.cpuBusy, cpuIowait: load.cpuIowait, cpuWindowMs: load.cpuWindowMs, heldMs: load.heldMs,
2851
+ // cpuBusy is the decision value: net of the app's own process tree (PRD 3495).
2852
+ cpuBusy: load.cpuBusy, cpuBusyRaw: load.cpuBusyRaw, cpuBusyNet: load.cpuBusyNet, cpuOwnBusy: load.cpuOwnBusy,
2853
+ cpuIowait: load.cpuIowait, cpuWindowMs: load.cpuWindowMs, heldMs: load.heldMs,
2665
2854
  };
2666
2855
  }
2667
2856
 
@@ -2713,9 +2902,11 @@ function buildScheduleStatePayload(state) {
2713
2902
  // UI can disable its own control when the env has taken over.
2714
2903
  effectiveConcurrency: (() => {
2715
2904
  const snap = sessionSlots.snapshot();
2905
+ // jobCapacity() excludes the held interactive-Task slot, so a held
2906
+ // slot never reads as free capacity the queue failed to use.
2716
2907
  return {
2717
2908
  cap: snap.total,
2718
- free: Math.max(0, snap.total - snap.inUse),
2909
+ free: jobFreeSlots(snap),
2719
2910
  source: snap.envOverride ? 'env' : 'pool',
2720
2911
  };
2721
2912
  })(),
@@ -2723,6 +2914,17 @@ function buildScheduleStatePayload(state) {
2723
2914
  return payload;
2724
2915
  }
2725
2916
 
2917
+ /**
2918
+ * Slots a scheduler job could still take: the pool's free slots, bounded by
2919
+ * jobCapacity() (cap minus the held interactive-Task slot) less the
2920
+ * non-interactive holders already counted against it.
2921
+ * @param {{ total: number, inUse: number, holders: Array<{ lane?: string }> }} snap
2922
+ */
2923
+ function jobFreeSlots(snap) {
2924
+ const nonInteractive = snap.holders.filter((h) => h.lane !== 'task-interactive').length;
2925
+ return Math.max(0, Math.min(snap.total - snap.inUse, sessionSlots.jobCapacity() - nonInteractive));
2926
+ }
2927
+
2726
2928
  // Trailing-edge debounce for the `schedule:state` IPC push: a burst of
2727
2929
  // broadcast() calls (boot reverify healing several rows, poll-loop refreshes,
2728
2930
  // queue-linter fixups) arms one BROADCAST_COALESCE_MS timer and sends a
@@ -3325,6 +3527,35 @@ function extractResultTextFromLog(logPath) {
3325
3527
  }
3326
3528
  }
3327
3529
 
3530
+ /**
3531
+ * Same tail scan as extractResultTextFromLog, but returns the last result
3532
+ * event's `structured_output` object (set by `claude -p --json-schema`), or
3533
+ * null for a missing file, a torn line, or no such field. Never throws.
3534
+ */
3535
+ function extractStructuredOutputFromLog(logPath) {
3536
+ if (!logPath) return null;
3537
+ try {
3538
+ const tail = readTail(logPath, RESULT_TEXT_TAIL_BYTES);
3539
+ if (!tail) return null;
3540
+ const lines = tail.split('\n');
3541
+ for (let i = lines.length - 1; i >= 0; i--) {
3542
+ const line = lines[i].trim();
3543
+ if (!line || !line.includes('"type":"result"')) continue;
3544
+ try {
3545
+ const parsed = JSON.parse(line);
3546
+ if (!parsed || parsed.type !== 'result') continue;
3547
+ const so = parsed.structured_output;
3548
+ return so && typeof so === 'object' && !Array.isArray(so) ? so : null;
3549
+ } catch {
3550
+ // torn/partial line — keep scanning backward
3551
+ }
3552
+ }
3553
+ return null;
3554
+ } catch {
3555
+ return null;
3556
+ }
3557
+ }
3558
+
3328
3559
  /**
3329
3560
  * resolveNotifyPrd(job, parsePrdRaw) → Promise<parsed PRD | null>
3330
3561
  *
@@ -3445,7 +3676,9 @@ function defaultScheduleSettle({ cwd, epicId }) {
3445
3676
  const deps = {
3446
3677
  loadJobs: async () => (await readQueue()).jobs || [],
3447
3678
  loadHistory: () => queueHistory.readHistory({ limit: 500 }),
3448
- createPrd: (input) => prdCreate.createPrd(input, remote),
3679
+ // Scheduler-internal mint: validate-sweep validator slugs are timestamped and
3680
+ // have collided across Epics before, so the cross-Epic duplicate guard is skipped.
3681
+ createPrd: (input) => prdCreate.createPrd(input, remote, { internalMint: true }),
3449
3682
  resolveBaseSha: async (c, commit) => {
3450
3683
  try {
3451
3684
  return String(await execGitAt(c, ['rev-parse', `${commit}^`])).trim() || null;
@@ -3491,10 +3724,28 @@ function armSettleAfterValidatorBudgetKill(job, { scheduleSettle = defaultSchedu
3491
3724
  const MACRO_ARTIFACT_RE = /^session-manager-operations\/project-pages\/(videos|knowledge)\/([a-z0-9-]+)\/index\.html$/;
3492
3725
  const MACRO_META_MAX_BYTES = 256 * 1024;
3493
3726
 
3727
+ // A Project Video tool's review stage (macroJobDispatch.cjs REVIEW_MATERIAL_REL)
3728
+ // saves review material, not the video: any path ending in this names one.
3729
+ const MACRO_REVIEW_MATERIAL_RE = /\/review\/material\.json(?=$|["'`\s)])/;
3730
+
3731
+ function isMacroReviewStage(prd) {
3732
+ const strings = [];
3733
+ for (const k of ['artifactPaths', 'files', 'gate']) {
3734
+ const v = prd[k];
3735
+ if (typeof v === 'string') strings.push(v);
3736
+ else if (Array.isArray(v)) for (const x of v) if (typeof x === 'string') strings.push(x);
3737
+ }
3738
+ if (typeof prd.body === 'string') {
3739
+ const m = /```gate\r?\n([\s\S]*?)```/.exec(prd.body);
3740
+ if (m) strings.push(...m[1].split(/\r?\n/));
3741
+ }
3742
+ return strings.some((s) => MACRO_REVIEW_MATERIAL_RE.test(s.trim()));
3743
+ }
3744
+
3494
3745
  function macroLabelFor(prd) {
3495
3746
  const builtin = BUILTIN_MACROS.find((m) => m && m.id === prd.macroId);
3496
3747
  if (builtin && typeof builtin.label === 'string' && builtin.label) return builtin.label;
3497
- const title = typeof prd.title === 'string' ? prd.title.replace(/:\s*background build\s*$/i, '').trim() : '';
3748
+ const title = typeof prd.title === 'string' ? prd.title.replace(/:\s*(?:background build|review material)\s*$/i, '').trim() : '';
3498
3749
  return title || prd.macroId;
3499
3750
  }
3500
3751
 
@@ -3508,6 +3759,7 @@ function readMacroBuildOutput(cwd, prd) {
3508
3759
  if (!cwd) return null;
3509
3760
  const first = Array.isArray(prd.artifactPaths) ? prd.artifactPaths[0] : null;
3510
3761
  if (typeof first !== 'string') return null;
3762
+ if (MACRO_REVIEW_MATERIAL_RE.test(first.trim())) return null;
3511
3763
  const m = MACRO_ARTIFACT_RE.exec(first.trim());
3512
3764
  if (!m) return null;
3513
3765
  const dir = m[1];
@@ -3524,20 +3776,44 @@ function readMacroBuildOutput(cwd, prd) {
3524
3776
  }
3525
3777
 
3526
3778
  /**
3527
- * macroBuildNotice(job, prd) → { message, notice, buildOutput? } | null
3779
+ * macroBuildNotice(job, prd) → Promise<{ message, notice, buildOutput? } | null>
3528
3780
  * null for any PRD without a `macroId`, or a status other than completed/failed.
3781
+ * A failed job that is the approved 'final' run of a video review points at
3782
+ * that entry's Retry button (pressing the tool again would restart the
3783
+ * review). Async because videoReview.listReviews is; never rejects.
3529
3784
  */
3530
- function macroBuildNotice(job, prd) {
3785
+ async function macroBuildNotice(job, prd) {
3531
3786
  if (!prd || typeof prd.macroId !== 'string' || !prd.macroId) return null;
3532
3787
  if (job.status !== 'completed' && job.status !== 'failed') return null;
3533
3788
  const label = macroLabelFor(prd);
3534
3789
  if (job.status === 'failed') {
3535
3790
  const reason = job.error || job.verifierVerdict || job.status;
3791
+ try {
3792
+ if (job.cwd && job.slug) {
3793
+ const videoReview = require('./lib/project-pages/videoReview.cjs');
3794
+ const reviews = await videoReview.listReviews(job.cwd);
3795
+ const hit = reviews.find((r) => r && r.dispatch && r.dispatch.stage === 'final' && r.dispatch.slug === job.slug);
3796
+ if (hit) {
3797
+ return {
3798
+ 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.`,
3799
+ notice: 'build-failed',
3800
+ };
3801
+ }
3802
+ }
3803
+ } catch {
3804
+ // fall through to the generic failed message
3805
+ }
3536
3806
  return {
3537
3807
  message: `FAILED — ${label}: the background build failed (${reason}). Press it again in Project Home to retry.`,
3538
3808
  notice: 'build-failed',
3539
3809
  };
3540
3810
  }
3811
+ if (isMacroReviewStage(prd)) {
3812
+ return {
3813
+ message: `WAITING — ${label}: the review material is saved. Approve it or ask for changes in Project Home ▸ Video.`,
3814
+ notice: 'build-review',
3815
+ };
3816
+ }
3541
3817
  const out = readMacroBuildOutput(job.cwd, prd);
3542
3818
  if (!out) return { message: `DONE — ${label} finished.`, notice: 'build-done' };
3543
3819
  const buildOutput = { kind: out.kind, id: out.id, title: out.title };
@@ -3593,6 +3869,8 @@ async function notifyOriginatingTab(job, {
3593
3869
  appendResponseEvent = appendResponseEventIfKnown,
3594
3870
  appendTranscriptTurn = promptSessionTranscript.appendTurn,
3595
3871
  readResultFromLog = extractResultTextFromLog,
3872
+ readStructuredFromLog = extractStructuredOutputFromLog,
3873
+ writeVerdictsFile = writeJsonAtomic,
3596
3874
  scheduleSettle = defaultScheduleSettle,
3597
3875
  } = {}) {
3598
3876
  try {
@@ -3613,7 +3891,7 @@ async function notifyOriginatingTab(job, {
3613
3891
  message = `PRD ${job.slug} was skipped: its PRD source could not be found on disk. Blocked dependents: ${shown}${more}.`
3614
3892
  + ' If the PRD file exists, run scheduler_reset_job with force:true; if it was intentionally removed, archive it with scheduler_archive_prd.';
3615
3893
  }
3616
- const macroNotice = macroBuildNotice(job, prd);
3894
+ const macroNotice = await macroBuildNotice(job, prd);
3617
3895
  if (macroNotice) message = macroNotice.message;
3618
3896
 
3619
3897
  // The EPIC this check-in belongs to. Deliberately does NOT consider
@@ -3651,9 +3929,9 @@ async function notifyOriginatingTab(job, {
3651
3929
  const needsResultText = (epicIdForTranscript && job.cwd)
3652
3930
  || (job.agentType === 'validator' && job.status === 'completed');
3653
3931
  let resultText = null;
3932
+ const logPath = job.runId ? path.join(schedulerPaths.runsDir(), job.runId, `${job.slug}.log`) : null;
3654
3933
  if (needsResultText) {
3655
3934
  try {
3656
- const logPath = job.runId ? path.join(schedulerPaths.runsDir(), job.runId, `${job.slug}.log`) : null;
3657
3935
  resultText = readResultFromLog(logPath);
3658
3936
  } catch (e) {
3659
3937
  console.error('[scheduler] notifyOriginatingTab readResultFromLog error', job?.slug, e);
@@ -3671,13 +3949,31 @@ async function notifyOriginatingTab(job, {
3671
3949
  }
3672
3950
  }
3673
3951
 
3674
- // PRD 1407: a plan-level validator job ends its run with one
3675
- // `VALIDATION: <slug> VERIFIED`/`REFUTED` line per PRD it checked.
3676
- // Parsed only for a completed validator job; every ordinary work-item
3677
- // job gets an empty array here and behaves exactly as before.
3678
- const verdicts = (job.agentType === 'validator' && job.status === 'completed')
3679
- ? parseValidationSentinels(resultText)
3680
- : [];
3952
+ // PRD 1407: a plan-level validator job reports one verdict per PRD it
3953
+ // checked. Since `--json-schema` (PRD 3614) the verdicts come from the
3954
+ // result event's structured_output, checked by parseValidatorVerdict —
3955
+ // the CLI replaces the result text with the JSON string, so VALIDATION:
3956
+ // lines are no longer there. Missing/invalid output → no verdict events.
3957
+ // Every ordinary work-item job gets an empty array and behaves as before.
3958
+ /** @type {{ slug: string, verdict: string, reason: string, missKinds: string[] }[]} */
3959
+ let verdicts = [];
3960
+ /** @type {any} */
3961
+ let checkedVerdict = null;
3962
+ if (job.agentType === 'validator' && job.status === 'completed') {
3963
+ let structured = null;
3964
+ try {
3965
+ structured = readStructuredFromLog(logPath);
3966
+ } catch (e) {
3967
+ console.error('[scheduler] notifyOriginatingTab readStructuredFromLog error', job?.slug, e);
3968
+ }
3969
+ const checked = parseValidatorVerdict(structured);
3970
+ if (checked.ok) {
3971
+ checkedVerdict = checked.value;
3972
+ verdicts = verdictRowsFromStructured(checked.value);
3973
+ } else {
3974
+ console.error(`[scheduler] notifyOriginatingTab: validator ${job.slug} structured output rejected — ${checked.error}`);
3975
+ }
3976
+ }
3681
3977
 
3682
3978
  if (!epicId && verdicts.length > 0) {
3683
3979
  // No Epic to attach these to (unresolved sourcePromptId/epicId, same
@@ -3702,12 +3998,41 @@ async function notifyOriginatingTab(job, {
3702
3998
  job.cwd || null,
3703
3999
  epicId,
3704
4000
  `Validation ${v.verdict.toUpperCase()}: ${v.slug}${v.reason ? ` — ${v.reason}` : ''}`,
3705
- { prdSlug: v.slug, outcome: 'completed', validation: v.verdict },
4001
+ {
4002
+ prdSlug: v.slug,
4003
+ outcome: 'completed',
4004
+ validation: v.verdict,
4005
+ reason: typeof v.reason === 'string' ? v.reason : '',
4006
+ missKinds: Array.isArray(v.missKinds) ? v.missKinds : [],
4007
+ validator: job.slug,
4008
+ },
3706
4009
  );
3707
4010
  } catch (e) {
3708
4011
  console.error('[scheduler] notifyOriginatingTab verdict appendResponseEvent error', job?.slug, v.slug, e);
3709
4012
  }
3710
4013
  }
4014
+ }
4015
+ if (epicId && checkedVerdict && job.cwd && !isSafeEpicId(epicId)) {
4016
+ // PRD 3688: mirror epicOutsideRead.readVerdictFiles — an unsafe id
4017
+ // ('../x', 'a/b') must never be concatenated into a write path.
4018
+ console.error('[scheduler] notifyOriginatingTab verdicts file skipped: unsafe epicId', job?.slug, JSON.stringify(epicId));
4019
+ } else if (epicId && checkedVerdict && job.cwd) {
4020
+ // PRD 3614: keep the checked object beside the Markdown plan record.
4021
+ try {
4022
+ const file = opsPath(job.cwd, 'plan-records', epicId, `${bareSlug(job.slug)}.verdicts.json`);
4023
+ assertOpsWrite(file, 'scheduler');
4024
+ await writeVerdictsFile(file, {
4025
+ validator: job.slug,
4026
+ runId: job.runId || null,
4027
+ at: new Date().toISOString(),
4028
+ schedulerVerdict: checkedVerdict.schedulerVerdict,
4029
+ verdicts: checkedVerdict.verdicts,
4030
+ });
4031
+ } catch (e) {
4032
+ console.error('[scheduler] notifyOriginatingTab verdicts file write error', job?.slug, e);
4033
+ }
4034
+ }
4035
+ if (epicId) {
3711
4036
  // PRD 986: the check-in event is born validation:'unvalidated' — never
3712
4037
  // 'verified' — regardless of the job's self-reported outcome. The
3713
4038
  // check-in is a request to validate, not an assertion of done.
@@ -4688,6 +5013,12 @@ const HEADLESS_DISALLOWED_TOOLS = Object.freeze([
4688
5013
  * `--disallowedTools` takes a variadic list, so another flag must always
4689
5014
  * follow it to end that list — `--output-format` does, right after. Never
4690
5015
  * put `--disallowedTools` last.
5016
+ * `jsonSchema` (object; validator jobs only) adds `--json-schema <json>` right
5017
+ * before `--dangerously-skip-permissions`; the caller must also grant
5018
+ * StructuredOutput in the tool scope — probe 2026-11-22 (CLI 2.1.325): a scoped
5019
+ * run without it silently ignores the schema. null/absent = today's argv.
5020
+ * `sandboxArgs` (buildJobSandboxSettings(...).argv) replaces the single
5021
+ * `--dangerously-skip-permissions` element at the same position; null/empty = today's argv.
4691
5022
  * The prompt is NOT in argv: callers send it on the child's stdin
4692
5023
  * (withChildAndLog's `stdinText`). Linux caps a single argv element at 128 KB,
4693
5024
  * and a large prompt failed with spawn E2BIG before the job started (the
@@ -4700,7 +5031,64 @@ function knownMcpServers() {
4700
5031
  return { [seed.SERVER_NAME]: seed.schedulerServerEntry() };
4701
5032
  }
4702
5033
 
4703
- function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope, pluginDirArgs = [] }) {
5034
+ /**
5035
+ * The CLI keeps only the LAST --settings value, and the job sandbox argv
5036
+ * already carries one inline JSON --settings. When it does, fold the
5037
+ * tool-risk guard file's PreToolUse hooks into that JSON instead of adding a
5038
+ * second --settings that would silently drop one of the two. Returns null
5039
+ * when there is nothing to merge into (or the guard file cannot be read).
5040
+ * @param {string[]} sandboxArgs
5041
+ * @param {string} riskGuardSettingsPath
5042
+ * @returns {string[]|null}
5043
+ */
5044
+ function mergeRiskGuardIntoSandboxArgs(sandboxArgs, riskGuardSettingsPath) {
5045
+ const i = sandboxArgs.indexOf('--settings');
5046
+ if (i === -1 || typeof sandboxArgs[i + 1] !== 'string') return null;
5047
+ let inline;
5048
+ try { inline = JSON.parse(sandboxArgs[i + 1]); } catch { return null; }
5049
+ if (!inline || typeof inline !== 'object' || Array.isArray(inline)) return null;
5050
+ const guard = readJsonOrSync(riskGuardSettingsPath, null);
5051
+ const guardHooks = guard && guard.hooks && Array.isArray(guard.hooks.PreToolUse) ? guard.hooks.PreToolUse : null;
5052
+ if (!guardHooks) return null;
5053
+ const hooks = inline.hooks && typeof inline.hooks === 'object' ? inline.hooks : {};
5054
+ const pre = Array.isArray(hooks.PreToolUse) ? hooks.PreToolUse : [];
5055
+ const merged = { ...inline, hooks: { ...hooks, PreToolUse: [...pre, ...guardHooks] } };
5056
+ const out = sandboxArgs.slice();
5057
+ out[i + 1] = JSON.stringify(merged);
5058
+ return out;
5059
+ }
5060
+
5061
+ /**
5062
+ * A job's tool-risk clearance list (env SM_SCHEDULER_JOB_RISK_TOOLS): the
5063
+ * PRD's riskTools plus the persona's tools, keeping only entries
5064
+ * toolRiskMarks.parseRule accepts (MCP names, Bash(...) rules). Deduped,
5065
+ * order-preserving. Never throws.
5066
+ * @param {unknown} prdRiskTools
5067
+ * @param {unknown} personaTools
5068
+ * @returns {string[]}
5069
+ */
5070
+ function jobRiskToolsClearance(prdRiskTools, personaTools) {
5071
+ const out = [];
5072
+ const seen = new Set();
5073
+ for (const list of [prdRiskTools, personaTools]) {
5074
+ if (!Array.isArray(list)) continue;
5075
+ for (const t of list) {
5076
+ if (typeof t !== 'string' || seen.has(t) || !toolRiskMarks.parseRule(t)) continue;
5077
+ seen.add(t);
5078
+ out.push(t);
5079
+ }
5080
+ }
5081
+ return out;
5082
+ }
5083
+
5084
+ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope, pluginDirArgs = [], jsonSchema = null, sandboxArgs = null, riskGuardSettingsPath = null }) {
5085
+ let permissionArgs = Array.isArray(sandboxArgs) && sandboxArgs.length ? sandboxArgs : ['--dangerously-skip-permissions'];
5086
+ let riskArgs = [];
5087
+ if (typeof riskGuardSettingsPath === 'string' && riskGuardSettingsPath) {
5088
+ const merged = mergeRiskGuardIntoSandboxArgs(permissionArgs, riskGuardSettingsPath);
5089
+ if (merged) permissionArgs = merged;
5090
+ else riskArgs = ['--settings', riskGuardSettingsPath];
5091
+ }
4704
5092
  return [
4705
5093
  '-p',
4706
5094
  '--model', model,
@@ -4708,7 +5096,9 @@ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt,
4708
5096
  ...(systemPrompt ? ['--append-system-prompt', systemPrompt] : []),
4709
5097
  ...personaToolScopeArgs(toolScope, { mcpServers: knownMcpServers() }),
4710
5098
  ...(Array.isArray(pluginDirArgs) ? pluginDirArgs : []),
4711
- '--dangerously-skip-permissions',
5099
+ ...(jsonSchema && typeof jsonSchema === 'object' ? ['--json-schema', JSON.stringify(jsonSchema)] : []),
5100
+ ...riskArgs,
5101
+ ...permissionArgs,
4712
5102
  ...headlessPermissionArgs(),
4713
5103
  '--disallowedTools', HEADLESS_DISALLOWED_TOOLS.join(','),
4714
5104
  '--output-format', 'stream-json',
@@ -4717,6 +5107,41 @@ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt,
4717
5107
  ];
4718
5108
  }
4719
5109
 
5110
+ // ---------- job sandbox dependencies ----------
5111
+
5112
+ // Computed once per process: which OS-sandbox binaries exist, and (linux)
5113
+ // whether bwrap can actually create namespaces here. Never throws — any
5114
+ // failure degrades to the tool-rules level with the reason recorded.
5115
+ /** @type {{ available: boolean, missing: string[] }|null} */
5116
+ let jobSandboxDeps = null;
5117
+
5118
+ function whichOnPath(name) {
5119
+ const dirs = String(process.env.PATH || '').split(path.delimiter).filter(Boolean);
5120
+ for (const dir of dirs) {
5121
+ const candidate = path.join(dir, name);
5122
+ try { fs.accessSync(candidate, fs.constants.X_OK); return candidate; } catch { /* next */ }
5123
+ }
5124
+ return null;
5125
+ }
5126
+
5127
+ function resolveJobSandboxDeps() {
5128
+ if (process.env.SM_JOB_SANDBOX === '0') return { available: false, missing: ['disabled by SM_JOB_SANDBOX=0'] };
5129
+ if (jobSandboxDeps) return jobSandboxDeps;
5130
+ try {
5131
+ let deps = sandboxDependencies({ platform: process.platform, which: whichOnPath });
5132
+ if (deps.available && process.platform === 'linux') {
5133
+ const r = spawnSync(whichOnPath('bwrap') || 'bwrap',
5134
+ ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--unshare-net', '--unshare-pid', '--', 'true'],
5135
+ { timeout: 5000, stdio: 'ignore' });
5136
+ if (r.error || r.status !== 0) deps = { available: false, missing: ['bwrap self-test failed'] };
5137
+ }
5138
+ jobSandboxDeps = deps;
5139
+ } catch (e) {
5140
+ jobSandboxDeps = { available: false, missing: [`sandbox dependency probe failed: ${(e && e.message) || e}`] };
5141
+ }
5142
+ return jobSandboxDeps;
5143
+ }
5144
+
4720
5145
  // ---------- execution ----------
4721
5146
 
4722
5147
  // Allocates the runId/dir pair at dispatch time WITHOUT creating the
@@ -4837,6 +5262,10 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4837
5262
  // the scheduler's own short status chip (that's notifyOriginatingTab's job
4838
5263
  // for the assistant side).
4839
5264
  let parsedPrdMeta = null;
5265
+ // The PRD file's own riskTools frontmatter (tool-risk clearance). Fresh
5266
+ // spawns fill it from the isArtifactOnly read; resume spawns re-resolve the
5267
+ // PRD file below so a resumed session keeps the same clearance.
5268
+ let prdRiskTools = [];
4840
5269
  if (resumeTarget) {
4841
5270
  // Resume mode (PRD 1111): a short deterministic preamble naming the
4842
5271
  // recorded dirty paths, NEVER the original PRD body — the resumed
@@ -5003,11 +5432,13 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5003
5432
  try {
5004
5433
  const fm = parsePrdFile(await fsp.readFile(prdPath, 'utf8')).frontmatter;
5005
5434
  isArtifactOnly = isArtifactOnlyDeclaration(fm);
5435
+ // Tool-risk clearance (PRD scheduler-tool-risk-wiring): same read.
5436
+ prdRiskTools = Array.isArray(fm && fm.riskTools) ? fm.riskTools : [];
5006
5437
  } catch {
5007
5438
  isArtifactOnly = false;
5008
5439
  }
5009
5440
  }
5010
- prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun, isFixPlan: resolveIsFixPlan(job.slug, job.isFixPlan), isArtifactOnly }) });
5441
+ prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun, isFixPlan: resolveIsFixPlan(job.slug, job.isFixPlan), isArtifactOnly, isValidator: job.agentType === 'validator' }) });
5011
5442
 
5012
5443
  // Foreign-WIP manifest (starry-night-ships PRD 148 postmortem): the
5013
5444
  // scheduler already knows, at spawn time, which dirty paths this job did
@@ -5037,9 +5468,31 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5037
5468
  // a dangling/absent agentType falls back to no persona + FALLBACK_MODEL
5038
5469
  // and is logged once by resolvePrdPersonaForSpawn itself.
5039
5470
  const personaResolution = await agentModelResolve.resolvePrdPersonaForSpawn({ cwd, agentType: job.agentType });
5471
+ if (resumeTarget) {
5472
+ try {
5473
+ const dir = await prdPaths.findPrdDirForJob(job);
5474
+ const file = dir ? path.join(dir, `${job.slug}.md`) : prdPaths.prdPathForJob(job);
5475
+ const fm = parsePrdFile(await fsp.readFile(file, 'utf8')).frontmatter;
5476
+ prdRiskTools = Array.isArray(fm && fm.riskTools) ? fm.riskTools : [];
5477
+ } catch {
5478
+ prdRiskTools = [];
5479
+ }
5480
+ }
5481
+ // Tool-risk guard (PRD scheduler-tool-risk-wiring): a job worktree never
5482
+ // sees the project's untracked .claude/settings.json, so guard-tool-risk
5483
+ // loads via --settings <file>. Resolved once per job; null never blocks
5484
+ // the spawn.
5485
+ const jobRiskTools = jobRiskToolsClearance(prdRiskTools, personaResolution.tools);
5486
+ const riskGuardSettingsPath = await writeToolRiskGuardSettingsFile({ homeDir: os.homedir() });
5487
+ if (!riskGuardSettingsPath) {
5488
+ safeLog(`[scheduler] tool-risk guard settings unavailable for ${job.slug}; spawning without guard-tool-risk\n`);
5489
+ }
5040
5490
  const effortResolution = resolveEpicEffort({ cwd, agentType: job.agentType, prdEffort: job.effort });
5041
5491
  const personaEffort = effortResolution.effort;
5042
- const personaToolScope = buildPersonaToolScope(personaResolution.tools, { disallowed: HEADLESS_DISALLOWED_TOOLS });
5492
+ // Validator jobs (fresh and resume) return a schema-checked verdict:
5493
+ // --json-schema + StructuredOutput in scope (PRD 3613).
5494
+ const isValidator = job.agentType === 'validator';
5495
+ const personaToolScope = buildPersonaToolScope(personaResolution.tools, { disallowed: HEADLESS_DISALLOWED_TOOLS, structuredOutput: isValidator });
5043
5496
  // Epic context packs (PRD 3154): the job's Epic's selected packs load as
5044
5497
  // --plugin-dir per pack, and their laws are appended AFTER the (already
5045
5498
  // capped) persona body — the persona cap never applies to laws. Fresh and
@@ -5097,6 +5550,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5097
5550
  SM_SCHEDULER_JOB_SLUG: job.slug,
5098
5551
  SM_SCHEDULER_JOB_MAY_QUEUE: job.agentType === 'architect' ? '1' : '0',
5099
5552
  ...personaToolScopeEnv(personaToolScope),
5553
+ SM_SCHEDULER_JOB_RISK_TOOLS: JSON.stringify(jobRiskTools),
5100
5554
  BASH_DEFAULT_TIMEOUT_MS: String(BASH_DEFAULT_TIMEOUT_MS),
5101
5555
  BASH_MAX_TIMEOUT_MS: String(BASH_MAX_TIMEOUT_MS),
5102
5556
  ...(launchEnv && typeof launchEnv === 'object' ? launchEnv : {}),
@@ -5267,7 +5721,43 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5267
5721
 
5268
5722
  // Distinct comm (`sm-claude-job`) + slug-labelled argv0 for System Monitor.
5269
5723
  // Both keep the word `claude`, which the /\bclaude\b/ reaper gates need.
5724
+ // An os-sandbox job gets its own private temp dir as its only tmp write
5725
+ // root (TMPDIR/TMP/TEMP point at it), so its Bash cannot write into other
5726
+ // /tmp dirs. Kept short and directly under os.tmpdir(): the CLI puts its
5727
+ // proxy unix sockets under $TMPDIR and socket paths cap at 108 bytes —
5728
+ // never move it under the run directory.
5729
+ const sandboxDeps = resolveJobSandboxDeps();
5730
+ const sandboxAgentType = job.agentType || 'dev-lead';
5731
+ /** @type {string|null} */
5732
+ let sandboxTmpDir = null;
5733
+ if (sandboxDeps.available && Object.prototype.hasOwnProperty.call(SANDBOX_PROFILES, sandboxAgentType)) {
5734
+ try {
5735
+ sandboxTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'smj-'));
5736
+ } catch (e) {
5737
+ sandboxTmpDir = null;
5738
+ safeLog(`[scheduler] sandbox: private tmp dir not created (${(e && e.message) || e}); using ${os.tmpdir()}\n`);
5739
+ }
5740
+ }
5741
+ const removeSandboxTmp = () => {
5742
+ if (!sandboxTmpDir) return;
5743
+ try { fs.rmSync(sandboxTmpDir, { recursive: true, force: true }); } catch { /* never throws */ }
5744
+ };
5745
+ const sandboxPolicy = buildJobSandboxSettings({
5746
+ agentType: sandboxAgentType,
5747
+ worktreeDir: spawnCwd,
5748
+ projectRoot: cwd,
5749
+ homeDir: os.homedir(),
5750
+ tmpDir: sandboxTmpDir || os.tmpdir(),
5751
+ deps: sandboxDeps,
5752
+ });
5753
+ // childEnv was built (and cleanChildEnv already ran) above.
5754
+ Object.assign(childEnv, sandboxChildEnv(sandboxPolicy, sandboxTmpDir || os.tmpdir()));
5755
+ const sandboxMeta = { ...sandboxPolicy.summary, tmpDir: sandboxTmpDir };
5756
+ safeLog(`[scheduler] sandbox: level=${sandboxMeta.level} profile=${sandboxMeta.profile ?? 'none'} ` +
5757
+ `network=${sandboxMeta.network ? (sandboxMeta.network.join(',') || 'none') : 'unrestricted'} reason=${sandboxMeta.reason ?? 'none'} ` +
5758
+ `tmp=${sandboxTmpDir ?? 'none'}\n`);
5270
5759
  const jobArgs = buildClaudeSpawnArgs({
5760
+ sandboxArgs: sandboxPolicy.argv,
5271
5761
  model: personaResolution.model,
5272
5762
  effort: personaEffort,
5273
5763
  sessionId,
@@ -5275,6 +5765,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5275
5765
  systemPrompt: jobSystemPrompt,
5276
5766
  toolScope: personaToolScope,
5277
5767
  pluginDirArgs: packArgs.pluginDirArgs,
5768
+ jsonSchema: isValidator ? VALIDATOR_VERDICT_SCHEMA : null,
5769
+ riskGuardSettingsPath,
5278
5770
  });
5279
5771
  const jobSpawn = claudeSpawnTarget('job', job.slug, claudeBin, jobArgs);
5280
5772
 
@@ -5284,7 +5776,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5284
5776
  const errMsg = `argv too large: ${oversized.flag} is ${oversized.bytes} bytes, over the ${launchFailure.MAX_ARG_BYTES}-byte per-argument limit; not spawned`;
5285
5777
  safeLog(`[scheduler] ${errMsg}\n`);
5286
5778
  closeFd();
5287
- config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: errMsg, startedAt, finishedAt: Date.now(), durationMs: 0, ...SCHEDULER_META_IDENTITY, ...setupMeta });
5779
+ config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: errMsg, startedAt, finishedAt: Date.now(), durationMs: 0, sandbox: sandboxMeta, ...SCHEDULER_META_IDENTITY, ...setupMeta });
5780
+ removeSandboxTmp();
5288
5781
  resolve({ exitCode: -1, durationMs: 0, error: errMsg, launchError: 'argv_too_large', sessionId });
5289
5782
  return;
5290
5783
  }
@@ -5336,7 +5829,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5336
5829
  sl(`\n[scheduler] ${errMsg}\n`);
5337
5830
  // Sync write: inside a Promise executor callback; must flush meta
5338
5831
  // before resolve() so the spawnJob mutate() that follows sees it.
5339
- 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 });
5832
+ config.writeJsonSync(metaPath, { slug: job.slug, cwd, sessionId, exitCode: -1, error: errMsg, startedAt, finishedAt: Date.now(), durationMs, leakedDescendants: leaked, sandbox: sandboxMeta, ...SCHEDULER_META_IDENTITY, ...setupMeta, originSessionId, contextDigestApplied });
5833
+ removeSandboxTmp();
5340
5834
  resolve({ exitCode: -1, durationMs, error: errMsg, leakedDescendants: leaked, sessionId,
5341
5835
  ...(launchFailure.isArgvTooLargeSpawnError(error?.message) ? { launchError: 'argv_too_large' } : {}) });
5342
5836
  return;
@@ -5399,9 +5893,11 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5399
5893
  startedAt, finishedAt: Date.now(), durationMs, leakedDescendants: leaked,
5400
5894
  agentResultSubtype, mappedFromSignal: mappedToSuccess ? signal || `code=${exitCode}` : null,
5401
5895
  killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
5896
+ sandbox: sandboxMeta,
5402
5897
  ...SCHEDULER_META_IDENTITY, ...setupMeta,
5403
5898
  originSessionId, contextDigestApplied,
5404
5899
  });
5900
+ removeSandboxTmp();
5405
5901
  resolve({
5406
5902
  exitCode: effectiveCode, durationMs, rateLimited, networkError, launchFailure: launchFailed, resultStats,
5407
5903
  leakedDescendants: leaked, sessionId, killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
@@ -5945,7 +6441,10 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
5945
6441
  args: [
5946
6442
  '-p',
5947
6443
  '--model', 'opus',
5948
- '--dangerously-skip-permissions',
6444
+ ...buildJobSandboxSettings({
6445
+ agentType: 'investigation', worktreeDir: cwd, projectRoot: cwd,
6446
+ homeDir: os.homedir(), tmpDir: os.tmpdir(), deps: resolveJobSandboxDeps(),
6447
+ }).argv,
5949
6448
  ...headlessPermissionArgs(),
5950
6449
  '--disallowedTools', HEADLESS_DISALLOWED_TOOLS.join(','),
5951
6450
  '--output-format', 'stream-json',
@@ -6404,7 +6903,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6404
6903
  // Session-Manager owns the machine-wide `claude -p` pool (sessionSlots.cjs)
6405
6904
  // — the scheduler REQUESTS capacity, it doesn't own a private cap. A miss
6406
6905
  // leaves the job pending; the next tick retries when a slot frees up.
6407
- const slotToken = sessionSlots.acquire(`scheduler:${job.slug}`, { claimedAt: Date.now() });
6906
+ const slotToken = sessionSlots.acquire(`scheduler:${job.slug}`, { claimedAt: Date.now(), lane: 'job' });
6408
6907
  if (!slotToken) {
6409
6908
  console.log(`[scheduler] no session slot free for ${job.slug} — deferring (${JSON.stringify(sessionSlots.snapshot().holders.map((h) => h.owner))})`);
6410
6909
  return;
@@ -6835,6 +7334,10 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6835
7334
  }, reviewInRun, worktree.ok ? worktree.setup : { ran: false, ok: false, reason: 'in-place', waitedMs: 0, ms: 0, commands: [] });
6836
7335
  } finally {
6837
7336
  if (worktree.ok) {
7337
+ // Plan records are written in the worktree and never committed; copy
7338
+ // them to the main checkout before verify and before the checkout is
7339
+ // removed. Never throws (planRecordHarvest.cjs).
7340
+ harvestJobPlanRecords(job, worktree.dir, job.cwd || defaultCwd);
6838
7341
  ({ worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha, worktreeHead, uncommittedSnapshot } =
6839
7342
  await finalizeJobWorktree({ job, runId, runDir, worktree, guardCwd, carriedPaths }));
6840
7343
  } else {
@@ -8184,6 +8687,12 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8184
8687
  reclaimTerminalJobOrphansThrottled(state).catch((e) => {
8185
8688
  console.warn('[scheduler] terminal job-worktree orphan reclaim failed', e?.message);
8186
8689
  });
8690
+ // Emit epic_state_changed audit rows for Epics whose outside-facing state
8691
+ // moved since the last tick. Best-effort and fire-and-forget: never awaited,
8692
+ // must never hold up dispatch.
8693
+ runEpicStateWatchForTick(state).catch((e) => {
8694
+ console.warn('[scheduler] epic state watch failed', e?.message);
8695
+ });
8187
8696
  // Session-Manager's machine-wide slot pool is the ONLY concurrency limit
8188
8697
  // the picker answers to (plus the memory gate below). The scheduler used
8189
8698
  // to also carry a private `concurrencyCap` of 3 — the exact per-consumer
@@ -8196,11 +8705,12 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8196
8705
  // degraded cap minus what's already running.
8197
8706
  runReservationExpiryPass(state.jobs, tickStartedAt);
8198
8707
  const freeSlots = degradedConcurrencyCapValue != null
8199
- ? Math.max(0, Math.min(sessionSlots.available(), degradedConcurrencyCapValue - runningSet.size))
8200
- : sessionSlots.available();
8708
+ ? Math.max(0, Math.min(sessionSlots.availableFor('job'), degradedConcurrencyCapValue - runningSet.size))
8709
+ : sessionSlots.availableFor('job');
8201
8710
  const heldSlugs = await computeLaunchHolds(state);
8202
8711
  if (stale()) return STALE_TICK;
8203
8712
  const satisfiedSlugsByCwd = await budget.computeDepHistorySatisfaction(state);
8713
+ lastSatisfiedSlugsByCwd = satisfiedSlugsByCwd;
8204
8714
  if (stale()) return STALE_TICK;
8205
8715
  const { batch, reason: holdReason, holds } = pickNextBatch(state.jobs, runningSet, freeSlots, {
8206
8716
  leaseHeld: quietMachineLease.isHeld(),
@@ -8363,7 +8873,7 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8363
8873
  const mins = Math.round(load.heldMs / 60_000);
8364
8874
  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'}`);
8365
8875
  } else if (load.standDown) {
8366
- 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`);
8876
+ 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`);
8367
8877
  if (load.shouldAuditStandDown) {
8368
8878
  appendAuditEvent('load_gate_stood_down', loadGateAuditFields(load));
8369
8879
  }
@@ -8720,29 +9230,63 @@ function runQueueHealthSweep(jobs) {
8720
9230
  }
8721
9231
 
8722
9232
  // Cross-cycle "already attempted" memory for the branch sweep (PRD 1135) —
8723
- // in-memory only, keyed `"<cwd>::<branch>"`. Resets on restart, same as
8724
- // consecutiveRapidRateLimitsBySlug above; the goal is "don't retry a
8725
- // permanently-conflicting branch every cycle forever" while the process
8726
- // stays up, not durability across a restart.
9233
+ // in-memory only, keyed `"<cwd>::<branch>"`: at most one attempt per branch
9234
+ // per process lifetime. Durability across restarts is the persisted backoff
9235
+ // state below (PRD 3494), not this set.
8727
9236
  const branchSweepAttempted = new Set();
9237
+ // Fallback backoff state for a project whose ops root cannot be written
9238
+ // (ephemeral/unprovable cwd) — keyed by cwd, lives for the process only.
9239
+ const branchSweepBackoffFallback = new Map();
9240
+ const BRANCH_SWEEP_NEEDS_YOU_APP = 'session-manager';
9241
+ const BRANCH_SWEEP_BACKOFF_FILE = 'branch-sweep-backoff.json';
9242
+
9243
+ /** Persisted backoff file for `cwd` (scheduler namespace), or null when unwritable. */
9244
+ function branchSweepBackoffFile(cwd) {
9245
+ try {
9246
+ const file = opsPath(cwd, 'scheduler', BRANCH_SWEEP_BACKOFF_FILE);
9247
+ assertOpsWrite(file, 'scheduler');
9248
+ return file;
9249
+ } catch {
9250
+ return null;
9251
+ }
9252
+ }
8728
9253
 
8729
9254
  /**
8730
9255
  * Recover any `sm-job/*` branch left stranded (unmerged, owning row terminal
8731
9256
  * or gone) across every known project — the other half of PRD 1135's
8732
9257
  * invariant alongside the reaper's liveness check above: that check stops
8733
9258
  * NEW stranding, this sweep recovers anything stranded before it (or by a
8734
- * crash the liveness check can't cover). Read-only reporting plus AT MOST one
8735
- * bounded integrateBranch attempt per branch per process lifetime (see
8736
- * branchSweepAttempted) — never forces anything, never deletes a branch.
8737
- * Hangs off the same cadence as runQueueHealthSweep. Never throws.
9259
+ * crash the liveness check can't cover). At most one bounded integrateBranch
9260
+ * attempt per branch per process lifetime (branchSweepAttempted), gated by a
9261
+ * persisted per-(cwd, branch) failure count with exponential backoff
9262
+ * (PRD 3494): after BRANCH_SWEEP_MAX_FAILURES failures, or once the owning
9263
+ * PRD is skipped/superseded, the branch is given up on — one
9264
+ * branch_sweep_gave_up audit row per branch, then one cleanup summary (audit
9265
+ * row + Needs-you notice) for the pass that stopped any, never one per boot.
9266
+ * Never forces anything, never deletes a branch. Never throws.
8738
9267
  */
8739
- async function runBranchSweep(jobs) {
9268
+ async function runBranchSweep(jobs, deps = {}) {
8740
9269
  if (process.env.SM_BRANCH_SWEEP_DISABLE === '1') return;
9270
+ const audit = deps.audit ?? appendAuditEvent;
9271
+ const store = deps.store ?? needsYouStore;
9272
+ const now = deps.now ?? Date.now();
9273
+ const stopped = [];
8741
9274
  try {
8742
- for (const cwd of allProjectCwds()) {
9275
+ for (const cwd of (deps.cwds ?? allProjectCwds())) {
9276
+ const file = branchSweepBackoffFile(cwd);
9277
+ let state;
9278
+ try {
9279
+ state = file
9280
+ ? await loadBranchSweepBackoff(file)
9281
+ : (branchSweepBackoffFallback.get(cwd) ?? emptyBranchSweepBackoffState());
9282
+ } catch {
9283
+ state = emptyBranchSweepBackoffState();
9284
+ }
8743
9285
  let sweep;
8744
9286
  try {
8745
- sweep = await sweepStrandedJobBranches({ cwd, jobs, attemptedBranches: branchSweepAttempted });
9287
+ sweep = await sweepStrandedJobBranches({
9288
+ cwd, jobs, attemptedBranches: branchSweepAttempted, backoff: { state, now },
9289
+ });
8746
9290
  } catch (e) {
8747
9291
  console.warn(`[scheduler] branch sweep error for ${cwd}`, e?.message);
8748
9292
  continue;
@@ -8750,10 +9294,12 @@ async function runBranchSweep(jobs) {
8750
9294
  for (const r of sweep.results) {
8751
9295
  if (r.action === 'integrated') {
8752
9296
  console.log(`[scheduler] branch-sweep: merged stranded branch ${r.branch} into ${cwd} HEAD`);
8753
- appendAuditEvent('branch_sweep_integrated', { cwd, branch: r.branch, slug: r.slug });
9297
+ audit('branch_sweep_integrated', { cwd, branch: r.branch, slug: r.slug });
8754
9298
  } else if (r.action === 'conflict') {
8755
- console.warn(`[scheduler] branch-sweep: ${r.branch} could not be integrated: ${r.integration?.reason}`);
8756
- appendAuditEvent('branch_sweep_conflict', { cwd, branch: r.branch, slug: r.slug, reason: r.integration?.reason });
9299
+ console.warn(`[scheduler] branch-sweep: ${r.branch} could not be integrated (failure ${r.failures}): ${r.integration?.reason}`);
9300
+ audit('branch_sweep_conflict', {
9301
+ cwd, branch: r.branch, slug: r.slug, reason: r.integration?.reason, failures: r.failures,
9302
+ });
8757
9303
  if (r.slug) {
8758
9304
  await mutate((s) => {
8759
9305
  const j = s.jobs.find((x) => x.slug === r.slug);
@@ -8762,12 +9308,59 @@ async function runBranchSweep(jobs) {
8762
9308
  }
8763
9309
  }
8764
9310
  }
9311
+ const gaveUp = takeUnreportedGiveUps(state);
9312
+ for (const g of gaveUp) {
9313
+ console.warn(`[scheduler] branch-sweep: gave up on ${g.branch} in ${cwd} (${g.reason}); branch left in place`);
9314
+ audit('branch_sweep_gave_up', { cwd, branch: g.branch, slug: g.slug, reason: g.reason, failures: g.failures });
9315
+ stopped.push({ cwd, ...g });
9316
+ }
9317
+ if (sweep.changed || gaveUp.length) {
9318
+ if (file) {
9319
+ try {
9320
+ await saveBranchSweepBackoff(file, state);
9321
+ } catch (e) {
9322
+ console.warn(`[scheduler] branch sweep backoff save failed for ${cwd}`, e?.message);
9323
+ }
9324
+ } else {
9325
+ branchSweepBackoffFallback.set(cwd, state);
9326
+ }
9327
+ }
8765
9328
  }
9329
+ if (stopped.length) await reportBranchSweepGaveUp(stopped, { audit, store, now });
8766
9330
  } catch (e) {
8767
9331
  console.warn('[scheduler] branch sweep error', e?.message);
8768
9332
  }
8769
9333
  }
8770
9334
 
9335
+ /**
9336
+ * One cleanup summary for the branches a sweep pass stopped retrying: a
9337
+ * branch_sweep_cleanup_summary audit row plus one Needs-you notice. Only
9338
+ * called for a pass that newly gave up on something, so a reboot with nothing
9339
+ * new reports nothing.
9340
+ */
9341
+ async function reportBranchSweepGaveUp(stopped, { audit, store, now }) {
9342
+ const lines = stopped.map((s) => `${s.cwd}: ${s.branch} (${s.reason})`);
9343
+ audit('branch_sweep_cleanup_summary', {
9344
+ count: stopped.length,
9345
+ branches: stopped.map((s) => ({ cwd: s.cwd, branch: s.branch, slug: s.slug, reason: s.reason })),
9346
+ });
9347
+ const head = 'Stopped retrying these sm-job branches (conflicted 3 times or their PRD was skipped/superseded). '
9348
+ + 'Nothing was deleted — merge or delete each by hand:\n';
9349
+ let why = head + lines.join('\n');
9350
+ if (why.length > 1000) why = `${why.slice(0, 980)}\n… (${stopped.length} total)`;
9351
+ try {
9352
+ const result = await store.postNeedsYou({
9353
+ app: BRANCH_SWEEP_NEEDS_YOU_APP,
9354
+ id: `branch-sweep-gave-up-${now}`,
9355
+ title: `Branch sweep gave up on ${stopped.length} stranded branch${stopped.length === 1 ? '' : 'es'}`,
9356
+ why,
9357
+ });
9358
+ if (result?.changed && mainWindow) sendIfAlive(mainWindow, 'needsYou:changed', {});
9359
+ } catch (e) {
9360
+ console.error('[scheduler] branch-sweep cleanup Needs-you post failed', e?.message ?? e);
9361
+ }
9362
+ }
9363
+
8771
9364
  /**
8772
9365
  * Scan running jobs, identify those whose claude process is provably dead OR
8773
9366
  * whose spawn never got far enough to record a runtime.pid in the first
@@ -10310,6 +10903,15 @@ let gateShadowPending = null;
10310
10903
  let gateShadowSlug = null;
10311
10904
 
10312
10905
 
10906
+ // Boot-reverify park errors, keyed by the verifierVerdict they pair with.
10907
+ // They state only what happened: the self-heal ladder may still reopen the
10908
+ // job, so they must not claim a human has to act.
10909
+ const PARK_ERRORS = Object.freeze({
10910
+ no_run_artifacts: 'no run artifacts — parked',
10911
+ autofix_no_plan: 'auto-fix investigation produced no fix plan after retry — parked',
10912
+ autofix_plan_unqueued: 'auto-fix investigation produced a fix plan that never reached the queue — parked',
10913
+ });
10914
+
10313
10915
  async function reverifyNeedsReview() {
10314
10916
  const snap = await readQueue();
10315
10917
  // isGuardParkedWithoutAutoFix rows are NOT isRescanCandidate (their
@@ -10601,25 +11203,25 @@ async function reverifyNeedsReview() {
10601
11203
  for (const j of s.jobs) {
10602
11204
  if (unresolvableSet.has(j.slug)) {
10603
11205
  j.verifierVerdict = 'no_run_artifacts';
10604
- j.error = 'no run artifacts — manual review';
11206
+ j.error = PARK_ERRORS.no_run_artifacts;
10605
11207
  } else if (exhaustedSet.has(j.slug)) {
10606
11208
  j.verifierVerdict = 'autofix_no_plan';
10607
- j.error = 'auto-fix investigation produced no fix plan after retry — manual review';
11209
+ j.error = PARK_ERRORS.autofix_no_plan;
10608
11210
  } else if (planUnqueuedSet.has(j.slug)) {
10609
11211
  j.verifierVerdict = 'autofix_plan_unqueued';
10610
- j.error = 'auto-fix investigation produced a fix plan that never reached the queue — manual review';
11212
+ j.error = PARK_ERRORS.autofix_plan_unqueued;
10611
11213
  }
10612
11214
  }
10613
11215
  });
10614
11216
  if (unresolvable.length) {
10615
- console.log(`[scheduler] boot reverify: no run artifacts for ${unresolvable.map((j) => j.slug).join(', ')} — flagged for manual review`);
11217
+ console.log(`[scheduler] boot reverify: no run artifacts for ${unresolvable.map((j) => j.slug).join(', ')} — parked`);
10616
11218
  }
10617
11219
  if (exhaustedAutoFix.length) {
10618
- console.log(`[scheduler] boot reverify: auto-fix retry exhausted for ${exhaustedAutoFix.map((j) => j.slug).join(', ')} — flagged for manual review`);
11220
+ console.log(`[scheduler] boot reverify: auto-fix retry exhausted for ${exhaustedAutoFix.map((j) => j.slug).join(', ')} — parked`);
10619
11221
  }
10620
11222
  if (planUnqueued.length) {
10621
11223
  for (const j of planUnqueued) {
10622
- console.log(`[scheduler] boot reverify: auto-fix plan never queued for ${j.slug} — flagged for manual review`);
11224
+ console.log(`[scheduler] boot reverify: auto-fix plan never queued for ${j.slug} — parked`);
10623
11225
  }
10624
11226
  }
10625
11227
  await broadcast();
@@ -10861,7 +11463,7 @@ function registerScheduleHandlers() {
10861
11463
  }
10862
11464
  const now = Date.now();
10863
11465
  const slotSnapshot = sessionSlots.snapshot();
10864
- const freeSlots = Math.max(0, slotSnapshot.total - slotSnapshot.inUse);
11466
+ const freeSlots = jobFreeSlots(slotSnapshot);
10865
11467
  const verdict = starvation.classifyQueueHealth({
10866
11468
  jobs: state.jobs,
10867
11469
  paused: upgradeDrain.effectivePaused(state),
@@ -12019,7 +12621,17 @@ const remote = {
12019
12621
 
12020
12622
  async listJobs() {
12021
12623
  const state = await readQueue();
12022
- return state.jobs.map((j) => ({ slug: j.slug, title: j.title, status: j.status, cwd: j.cwd, agentType: j.agentType ?? null }));
12624
+ // epicId + sourcePromptId are what epicOutsideState.buildKnownPrds joins
12625
+ // rows to an Epic on — dropping them made GET /admin/epic count no rows.
12626
+ return state.jobs.map((j) => ({
12627
+ slug: j.slug,
12628
+ title: j.title,
12629
+ status: j.status,
12630
+ cwd: j.cwd,
12631
+ agentType: j.agentType ?? null,
12632
+ epicId: j.epicId ?? null,
12633
+ sourcePromptId: j.sourcePromptId ?? null,
12634
+ }));
12023
12635
  },
12024
12636
 
12025
12637
  // Single queue row lookup, used by cancelJob/updatePrd's status guards and
@@ -12212,8 +12824,23 @@ const remote = {
12212
12824
 
12213
12825
  const { frontmatter: fm, body: origBody } = parsePrdFile(raw);
12214
12826
  if (frontmatter) {
12827
+ // riskTools: same validator createPrd uses (prdCreate.normalizeRiskTools),
12828
+ // so update and create can never disagree. Refused before any write; an
12829
+ // explicit [] removes the key.
12830
+ const clearRiskTools = Array.isArray(frontmatter.riskTools) && frontmatter.riskTools.length === 0;
12831
+ let riskTools;
12832
+ if (frontmatter.riskTools !== undefined && !clearRiskTools) {
12833
+ const rt = prdCreate.normalizeRiskTools(frontmatter.riskTools);
12834
+ if (!rt.ok) return { ok: false, error: rt.error };
12835
+ riskTools = rt.value;
12836
+ }
12215
12837
  for (const key of Object.keys(frontmatter)) {
12216
12838
  if (frontmatter[key] === undefined) continue;
12839
+ if (key === 'riskTools') {
12840
+ if (clearRiskTools) delete fm.riskTools;
12841
+ else fm.riskTools = riskTools;
12842
+ continue;
12843
+ }
12217
12844
  fm[key] = frontmatter[key];
12218
12845
  }
12219
12846
  }
@@ -12294,6 +12921,49 @@ const remote = {
12294
12921
  if (job.status === 'completed' || job.status === 'failed' || job.status === 'needs_review' || job.status === 'skipped') {
12295
12922
  return { ok: false, error: `job already terminal (status: "${job.status}") — nothing to cancel` };
12296
12923
  }
12924
+ // Dependents choice (PRD 3499): cancelling a row that pending PRDs depend
12925
+ // on would strand them behind a dead row (Self stall, 2026-11-22). Refuse
12926
+ // unless the caller says what happens to them; apply that choice BEFORE
12927
+ // the target is cancelled, aborting on any failure.
12928
+ const depCwd = job.cwd ?? null;
12929
+ const pendingDependents = cancelDependents.findPendingDependents(state.jobs, slug, depCwd);
12930
+ let depPlan = null;
12931
+ if (pendingDependents.length > 0) {
12932
+ const names = pendingDependents.map((d) => d.slug);
12933
+ if (!opts.dependents) {
12934
+ return {
12935
+ ok: false,
12936
+ error: `job "${slug}" has ${names.length} pending dependent(s): ${names.join(', ')}. `
12937
+ + 'Pass dependents: { action: "cascade" } to cancel them too, '
12938
+ + '{ action: "repoint", to: "<slug>" } to make them depend on another PRD instead, '
12939
+ + 'or { action: "clear" } to drop the dependency.',
12940
+ dependents: names,
12941
+ choices: [...cancelDependents.DEPENDENTS_ACTIONS],
12942
+ };
12943
+ }
12944
+ depPlan = cancelDependents.planDependentsUpdate(state.jobs, slug, opts.dependents, depCwd);
12945
+ if (!depPlan.ok) return { ok: false, error: depPlan.error, dependents: names };
12946
+ const applied = [];
12947
+ for (const edit of depPlan.edits) {
12948
+ if (edit.action !== 'setDependsOn') continue;
12949
+ const res = await this.updatePrd({ slug: edit.slug, cwd: depCwd ?? undefined, frontmatter: { dependsOn: edit.dependsOn } });
12950
+ if (!res?.ok) {
12951
+ // Best-effort rollback of edits already written, so an aborted
12952
+ // cancel leaves the dependents as they were.
12953
+ for (const done of applied.reverse()) {
12954
+ await this.updatePrd({ slug: done.slug, cwd: depCwd ?? undefined, frontmatter: { dependsOn: done.previous } }).catch(() => null);
12955
+ }
12956
+ return {
12957
+ ok: false,
12958
+ error: `could not update dependent ${edit.slug}: ${res?.error ?? 'unknown error'} — "${slug}" was not cancelled`,
12959
+ dependents: names,
12960
+ };
12961
+ }
12962
+ applied.push(edit);
12963
+ }
12964
+ }
12965
+ const cascadeEdits = depPlan?.action === 'cascade' ? depPlan.edits : [];
12966
+ const dependsOnEdits = depPlan && depPlan.action !== 'cascade' ? depPlan.edits : [];
12297
12967
  const wasRunning = job.status === 'running';
12298
12968
  const pid = job.runtime?.pid;
12299
12969
  // Evidence-before-failure guard, scoped to an actually-running job being
@@ -12317,6 +12987,24 @@ const remote = {
12317
12987
  : 'cancelled via admin API';
12318
12988
  const cancelledAt = new Date().toISOString();
12319
12989
  await mutate((s) => {
12990
+ // Dependents first (same mutate, so the target never lands cancelled
12991
+ // while its dependents still point at it).
12992
+ for (const edit of cascadeEdits) {
12993
+ const d = s.jobs.find((x) => x.slug === edit.slug && x.cwd === job.cwd);
12994
+ if (!d || d.status !== 'pending') continue;
12995
+ if (!transitionJob(d, 'failed', { reason: edit.reason, source: 'remote:cancelJob' })) continue;
12996
+ d.error = edit.reason;
12997
+ d.cancelledAt = cancelledAt;
12998
+ d.finishedAt = new Date().toISOString();
12999
+ d.exitCode = d.exitCode ?? null;
13000
+ delete d.runtime;
13001
+ }
13002
+ // Mirror the rewritten dependsOn onto the rows now; reconcile() would
13003
+ // refresh it from the PRD file on its next pass anyway.
13004
+ for (const edit of dependsOnEdits) {
13005
+ const d = s.jobs.find((x) => x.slug === edit.slug && x.cwd === job.cwd);
13006
+ if (d) d.dependsOn = edit.dependsOn;
13007
+ }
12320
13008
  const idx = s.jobs.findIndex((j) => j.slug === slug);
12321
13009
  if (idx < 0) return;
12322
13010
  const j = s.jobs[idx];
@@ -12333,6 +13021,12 @@ const remote = {
12333
13021
  if (wasRunning && pid) killOrphanClaudePid(pid);
12334
13022
  await broadcast({ flush: true });
12335
13023
  const result = { ok: true, slug, status: targetStatus, wasRunning, cwd: job.cwd ?? null, cancelledAt };
13024
+ if (depPlan) {
13025
+ appendAuditEvent('job_cancel_dependents', {
13026
+ slug, cwd: job.cwd ?? null, action: depPlan.action, to: depPlan.to ?? null, dependents: depPlan.dependents,
13027
+ });
13028
+ result.dependents = { action: depPlan.action, to: depPlan.to ?? null, slugs: depPlan.dependents };
13029
+ }
12336
13030
  if (wasRunning) {
12337
13031
  // Whatever the executor committed before SIGTERM stays on its job
12338
13032
  // branch (never integrated); tell the caller where. Known residual: a
@@ -12422,7 +13116,20 @@ function registerAdminRoutes(adminHttp, remoteObj = remote) {
12422
13116
  });
12423
13117
  }
12424
13118
 
13119
+ // queueOps.dismissCancelled needs the serialized queue writer; queueOps
13120
+ // cannot require this module (circular), so it is bound here (PRD 3492).
13121
+ queueOps.bindQueueAccess({
13122
+ readQueue,
13123
+ mutate,
13124
+ broadcast: (opts) => broadcast(opts),
13125
+ updatePrd: (args) => remote.updatePrd(args),
13126
+ transitionJob,
13127
+ });
13128
+
12425
13129
  module.exports = {
13130
+ PARK_ERRORS,
13131
+ applyDepHoldNotices,
13132
+ _resetDepHoldNoticesForTests,
12426
13133
  readValidatorGateMs,
12427
13134
  resolveValidatorEstimate,
12428
13135
  planJobScope,
@@ -12469,6 +13176,7 @@ module.exports = {
12469
13176
  pickForProject,
12470
13177
  reapDeadRunningJobs,
12471
13178
  runBranchSweep,
13179
+ runEpicStateWatchForTick,
12472
13180
  pollRecoveryClearSource,
12473
13181
  memoryLimitedBatchSize,
12474
13182
  availableForJobs,
@@ -12523,6 +13231,7 @@ module.exports = {
12523
13231
  isNotifiableTerminalStatus,
12524
13232
  armSettleAfterValidatorBudgetKill,
12525
13233
  extractResultTextFromLog,
13234
+ extractStructuredOutputFromLog,
12526
13235
  resolveVerifyPrdPath,
12527
13236
  resolveFixPlanPath,
12528
13237
  resolveNotifyPrd,
@@ -12547,6 +13256,7 @@ module.exports = {
12547
13256
  INVESTIGATION_MAX_MS,
12548
13257
  buildResumeRecoveryPreamble,
12549
13258
  buildClaudeSpawnArgs,
13259
+ jobRiskToolsClearance,
12550
13260
  HEADLESS_DISALLOWED_TOOLS,
12551
13261
  spawnResumeRecovery,
12552
13262
  resolveHeadShasForPass,