claude-code-session-manager 0.139.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 (150) hide show
  1. package/README.md +20 -4
  2. package/dist/assets/AppSettings-CMFEM68R.js +2 -0
  3. package/dist/assets/History--JwsFnbn.js +2 -0
  4. package/dist/assets/{HomeClaudeConfig-CGD2Onjv.js → HomeClaudeConfig-ijEXs--3.js} +2 -2
  5. package/dist/assets/{Panel-Csyd9HbD.js → Panel-CALyU0pe.js} +1 -1
  6. package/dist/assets/{ProjectClaudeConfig-C-jlYpC_.js → ProjectClaudeConfig-sdlA-fUb.js} +1 -1
  7. package/dist/assets/Scheduler-YT3j8SUa.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-DcscPXAG.js → SkillReferenceGraph-CxAuwhNN.js} +1 -1
  9. package/dist/assets/{Skills-BpGRKOcY.js → Skills-DtRzghn5.js} +26 -26
  10. package/dist/assets/{TiptapBody-DSU3769X.js → TiptapBody-DApeu7x8.js} +1 -1
  11. package/dist/assets/{ViewTabs-C0PRZx4_.js → ViewTabs-B7qLXRAH.js} +1 -1
  12. package/dist/assets/{VoiceButton-D2rMurNg.js → VoiceButton-DtStfv1H.js} +1 -1
  13. package/dist/assets/{historyTotals-TcIQs2sh.js → historyTotals-ydfnwepc.js} +1 -1
  14. package/dist/assets/index-CtxruO1L.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/develop/SKILL.md +26 -19
  23. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +5 -4
  24. package/plugins/session-manager-dev/skills/maintaining-md-network/audit.md +4 -2
  25. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +16 -12
  26. package/plugins/session-manager-dev/skills/maintaining-md-network/migrate-to-agents-md.md +15 -0
  27. package/plugins/session-manager-dev/skills/maintaining-md-network/placement.md +50 -2
  28. package/plugins/session-manager-dev/skills/maintaining-md-network/plan.md +10 -10
  29. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +117 -112
  30. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdDuplicates.cjs +182 -0
  31. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/mdLinks.cjs +340 -0
  32. package/scripts/README.md +1 -0
  33. package/scripts/hooks/guard-tool-risk.cjs +91 -0
  34. package/scripts/hooks/lib/guard-tool-risk-policy.cjs +217 -0
  35. package/scripts/ops-sweep.cjs +53 -23
  36. package/scripts/scheduler-mcp-server.cjs +200 -18
  37. package/src/main/build-info.json +4 -4
  38. package/src/main/config.cjs +112 -8
  39. package/src/main/docEdit.cjs +6 -1
  40. package/src/main/files.cjs +7 -27
  41. package/src/main/health.cjs +48 -15
  42. package/src/main/historyAggregator.cjs +88 -5
  43. package/src/main/historyDashboard.cjs +69 -4
  44. package/src/main/index.cjs +56 -2
  45. package/src/main/ipcSchemas.cjs +112 -16
  46. package/src/main/lib/AGENTS.md +54 -0
  47. package/src/main/lib/CLAUDE.md +1 -54
  48. package/src/main/lib/agent-cli/adapters/codex.cjs +5 -2
  49. package/src/main/lib/agent-cli/agentCliIpc.cjs +18 -2
  50. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +1 -0
  51. package/src/main/lib/agent-cli/agentCliTurn.cjs +20 -2
  52. package/src/main/lib/agent-cli/geminiContextDefaults.cjs +94 -0
  53. package/src/main/lib/claude/effectiveModelInfo.cjs +90 -20
  54. package/src/main/lib/claude/jobSandboxPolicy.cjs +202 -0
  55. package/src/main/lib/claude/personaToolScope.cjs +12 -6
  56. package/src/main/lib/claude/rateLimitDetect.cjs +13 -2
  57. package/src/main/lib/claude/runClaudeP.cjs +6 -1
  58. package/src/main/lib/claude/toolRiskIpc.cjs +177 -0
  59. package/src/main/lib/claude/toolRiskMarks.cjs +373 -0
  60. package/src/main/lib/demo-video-kit/seedKit.cjs +27 -6
  61. package/src/main/lib/ephemeralCwd.cjs +37 -2
  62. package/src/main/lib/epic/delegationReadiness.cjs +42 -9
  63. package/src/main/lib/epic/epicAdminRoutes.cjs +25 -5
  64. package/src/main/lib/epic/epicOutsideRead.cjs +118 -1
  65. package/src/main/lib/epic/epicOutsideState.cjs +2 -2
  66. package/src/main/lib/epic/epicSweepValidator.cjs +7 -2
  67. package/src/main/lib/epic/epicValidationHook.cjs +24 -4
  68. package/src/main/lib/epic/guardSpawnSettings.cjs +57 -1
  69. package/src/main/lib/externalContract.cjs +31 -5
  70. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +55 -1
  71. package/src/main/lib/feedback-remote/crossProjectReply.cjs +106 -11
  72. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +47 -19
  73. package/src/main/lib/feedback-remote/needsYouStore.cjs +6 -2
  74. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +98 -1
  75. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +5 -0
  76. package/src/main/lib/git/branchSweep.cjs +209 -4
  77. package/src/main/lib/git/gitWorktree.cjs +41 -5
  78. package/src/main/lib/guardShims.cjs +1 -1
  79. package/src/main/lib/historyRollup.cjs +26 -0
  80. package/src/main/lib/insideHome.cjs +27 -1
  81. package/src/main/lib/mcpToolCatalog.cjs +122 -12
  82. package/src/main/lib/mdDocCensus.cjs +59 -78
  83. package/src/main/lib/mdDocRefs.cjs +71 -93
  84. package/src/main/lib/mdNetworkScan.cjs +245 -250
  85. package/src/main/lib/mdReviewRecord.cjs +22 -9
  86. package/src/main/lib/memoryMdNetwork.cjs +5 -12
  87. package/src/main/lib/opsOwnership.cjs +18 -2
  88. package/src/main/lib/opsRetentionSettings.cjs +28 -4
  89. package/src/main/lib/persona-macro/macroJobDispatch.cjs +90 -20
  90. package/src/main/lib/persona-macro/macroJobIpc.cjs +144 -46
  91. package/src/main/lib/persona-macro/macroJobStatus.cjs +87 -9
  92. package/src/main/lib/persona-macro/macroLibrary.cjs +95 -5
  93. package/src/main/lib/persona-macro/personaImportHealth.cjs +78 -17
  94. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +96 -0
  95. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  96. package/src/main/lib/prd/depSlugResolve.cjs +104 -4
  97. package/src/main/lib/prd/prdAdminRoutes.cjs +35 -2
  98. package/src/main/lib/prd/prdCreate.cjs +351 -23
  99. package/src/main/lib/prd/prdDisposition.cjs +11 -2
  100. package/src/main/lib/prd/prdFrontmatter.cjs +96 -3
  101. package/src/main/lib/process/loginItem.cjs +171 -0
  102. package/src/main/lib/process/loginItemPlan.cjs +193 -0
  103. package/src/main/lib/project-pages/playerBridge.cjs +4 -0
  104. package/src/main/lib/project-pages/videoReview.cjs +268 -0
  105. package/src/main/lib/project-pages/videoReviewIpc.cjs +229 -0
  106. package/src/main/lib/scheduler/cpuSample.cjs +131 -4
  107. package/src/main/lib/scheduler/fixPlanSlug.cjs +4 -3
  108. package/src/main/lib/scheduler/loadGate.cjs +24 -6
  109. package/src/main/lib/scheduler/planRecordHarvest.cjs +108 -0
  110. package/src/main/lib/scheduler/planRecordRetention.cjs +144 -0
  111. package/src/main/lib/scheduler/queueStore.cjs +7 -0
  112. package/src/main/lib/scheduler/rcaReport.cjs +21 -1
  113. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -5
  114. package/src/main/lib/scheduler/runLogRetention.cjs +104 -3
  115. package/src/main/lib/scheduler/scheduleJobSchema.cjs +3 -0
  116. package/src/main/lib/scheduler/schedulerBatch.cjs +25 -48
  117. package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
  118. package/src/main/lib/scheduler/sessionSlots.cjs +176 -21
  119. package/src/main/lib/scheduler/validationQuality.cjs +282 -0
  120. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +254 -0
  121. package/src/main/lib/tasks/taskAdminRoutes.cjs +641 -0
  122. package/src/main/lib/tasks/taskIpc.cjs +80 -0
  123. package/src/main/lib/tasks/taskLedger.cjs +502 -0
  124. package/src/main/lib/tasks/taskRun.cjs +313 -0
  125. package/src/main/lib/tasks/taskSwitch.cjs +120 -0
  126. package/src/main/loginItemIpc.cjs +35 -0
  127. package/src/main/loopEfficiencyHandlers.cjs +10 -1
  128. package/src/main/projectPages.cjs +6 -15
  129. package/src/main/promptSessionEvents.cjs +9 -1
  130. package/src/main/queueOps.cjs +260 -3
  131. package/src/main/runVerify.cjs +53 -25
  132. package/src/main/scheduler/AGENTS.md +26 -0
  133. package/src/main/scheduler/CLAUDE.md +1 -26
  134. package/src/main/scheduler/budget.cjs +239 -9
  135. package/src/main/scheduler/cancelDependents.cjs +154 -0
  136. package/src/main/scheduler/prdParser.cjs +4 -1
  137. package/src/main/scheduler/starvation.cjs +20 -18
  138. package/src/main/scheduler.cjs +745 -64
  139. package/src/main/supervisor.cjs +5 -1
  140. package/src/main/templates/PRD_AUTHORING.md +6 -1
  141. package/src/main/validationQualityHandlers.cjs +199 -0
  142. package/src/main/webRemote.cjs +10 -2
  143. package/src/preload/api.d.ts +364 -21
  144. package/src/preload/apiSurface.json +89 -10
  145. package/src/preload/index.cjs +23 -2
  146. package/src/seed/agents/validator.md +19 -8
  147. package/dist/assets/AppSettings-CUfWY9vN.js +0 -2
  148. package/dist/assets/History-DDnqaLyw.js +0 -2
  149. package/dist/assets/Scheduler-NLs08fx7.js +0 -16
  150. 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');
@@ -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
  }
@@ -2210,6 +2275,12 @@ async function reconcilePass(state) {
2210
2275
  // (commitGuardVerdict, isFixPlanBeyondDepthCap, the fix-plan-completion
2211
2276
  // checks) reads this stamp instead of re-deriving it from the name.
2212
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
+ }
2213
2284
  // Stamp investigationDepth relative to the original job it heals, so
2214
2285
  // selectAutoFixTargets/spawnInvestigation can bound the fix-of-a-fix
2215
2286
  // recursion (see MAX_INVESTIGATION_DEPTH). Non-fix-plan jobs get no
@@ -2321,6 +2392,16 @@ async function reconcilePass(state) {
2321
2392
  } catch (e) {
2322
2393
  console.warn('[scheduler] autoArchiveCompleted failed', e?.message);
2323
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
+ }
2324
2405
  phaseMs.queueWrite = Date.now() - phaseStartMs;
2325
2406
 
2326
2407
  const totalMs = Date.now() - reconcileStartMs;
@@ -2571,6 +2652,90 @@ let dispatchLoopHandle = null;
2571
2652
  // stalled) rather than every 60s heartbeat tick.
2572
2653
  let stallSince = new Map();
2573
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
+ }
2574
2739
  // (The 5-minute feedback sweep that used to piggyback on this heartbeat is
2575
2740
  // gone: it scanned each active project's session-manager-operations/feedback/
2576
2741
  // and auto-queued a /process-feedback PRD. Both the folder and that skill are
@@ -2683,7 +2848,9 @@ function formatLoadGateDetail(load) {
2683
2848
  function loadGateAuditFields(load) {
2684
2849
  return {
2685
2850
  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,
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,
2687
2854
  };
2688
2855
  }
2689
2856
 
@@ -2735,9 +2902,11 @@ function buildScheduleStatePayload(state) {
2735
2902
  // UI can disable its own control when the env has taken over.
2736
2903
  effectiveConcurrency: (() => {
2737
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.
2738
2907
  return {
2739
2908
  cap: snap.total,
2740
- free: Math.max(0, snap.total - snap.inUse),
2909
+ free: jobFreeSlots(snap),
2741
2910
  source: snap.envOverride ? 'env' : 'pool',
2742
2911
  };
2743
2912
  })(),
@@ -2745,6 +2914,17 @@ function buildScheduleStatePayload(state) {
2745
2914
  return payload;
2746
2915
  }
2747
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
+
2748
2928
  // Trailing-edge debounce for the `schedule:state` IPC push: a burst of
2749
2929
  // broadcast() calls (boot reverify healing several rows, poll-loop refreshes,
2750
2930
  // queue-linter fixups) arms one BROADCAST_COALESCE_MS timer and sends a
@@ -3347,6 +3527,35 @@ function extractResultTextFromLog(logPath) {
3347
3527
  }
3348
3528
  }
3349
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
+
3350
3559
  /**
3351
3560
  * resolveNotifyPrd(job, parsePrdRaw) → Promise<parsed PRD | null>
3352
3561
  *
@@ -3467,7 +3676,9 @@ function defaultScheduleSettle({ cwd, epicId }) {
3467
3676
  const deps = {
3468
3677
  loadJobs: async () => (await readQueue()).jobs || [],
3469
3678
  loadHistory: () => queueHistory.readHistory({ limit: 500 }),
3470
- 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 }),
3471
3682
  resolveBaseSha: async (c, commit) => {
3472
3683
  try {
3473
3684
  return String(await execGitAt(c, ['rev-parse', `${commit}^`])).trim() || null;
@@ -3513,10 +3724,28 @@ function armSettleAfterValidatorBudgetKill(job, { scheduleSettle = defaultSchedu
3513
3724
  const MACRO_ARTIFACT_RE = /^session-manager-operations\/project-pages\/(videos|knowledge)\/([a-z0-9-]+)\/index\.html$/;
3514
3725
  const MACRO_META_MAX_BYTES = 256 * 1024;
3515
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
+
3516
3745
  function macroLabelFor(prd) {
3517
3746
  const builtin = BUILTIN_MACROS.find((m) => m && m.id === prd.macroId);
3518
3747
  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() : '';
3748
+ const title = typeof prd.title === 'string' ? prd.title.replace(/:\s*(?:background build|review material)\s*$/i, '').trim() : '';
3520
3749
  return title || prd.macroId;
3521
3750
  }
3522
3751
 
@@ -3530,6 +3759,7 @@ function readMacroBuildOutput(cwd, prd) {
3530
3759
  if (!cwd) return null;
3531
3760
  const first = Array.isArray(prd.artifactPaths) ? prd.artifactPaths[0] : null;
3532
3761
  if (typeof first !== 'string') return null;
3762
+ if (MACRO_REVIEW_MATERIAL_RE.test(first.trim())) return null;
3533
3763
  const m = MACRO_ARTIFACT_RE.exec(first.trim());
3534
3764
  if (!m) return null;
3535
3765
  const dir = m[1];
@@ -3546,20 +3776,44 @@ function readMacroBuildOutput(cwd, prd) {
3546
3776
  }
3547
3777
 
3548
3778
  /**
3549
- * macroBuildNotice(job, prd) → { message, notice, buildOutput? } | null
3779
+ * macroBuildNotice(job, prd) → Promise<{ message, notice, buildOutput? } | null>
3550
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.
3551
3784
  */
3552
- function macroBuildNotice(job, prd) {
3785
+ async function macroBuildNotice(job, prd) {
3553
3786
  if (!prd || typeof prd.macroId !== 'string' || !prd.macroId) return null;
3554
3787
  if (job.status !== 'completed' && job.status !== 'failed') return null;
3555
3788
  const label = macroLabelFor(prd);
3556
3789
  if (job.status === 'failed') {
3557
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
+ }
3558
3806
  return {
3559
3807
  message: `FAILED — ${label}: the background build failed (${reason}). Press it again in Project Home to retry.`,
3560
3808
  notice: 'build-failed',
3561
3809
  };
3562
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
+ }
3563
3817
  const out = readMacroBuildOutput(job.cwd, prd);
3564
3818
  if (!out) return { message: `DONE — ${label} finished.`, notice: 'build-done' };
3565
3819
  const buildOutput = { kind: out.kind, id: out.id, title: out.title };
@@ -3615,6 +3869,8 @@ async function notifyOriginatingTab(job, {
3615
3869
  appendResponseEvent = appendResponseEventIfKnown,
3616
3870
  appendTranscriptTurn = promptSessionTranscript.appendTurn,
3617
3871
  readResultFromLog = extractResultTextFromLog,
3872
+ readStructuredFromLog = extractStructuredOutputFromLog,
3873
+ writeVerdictsFile = writeJsonAtomic,
3618
3874
  scheduleSettle = defaultScheduleSettle,
3619
3875
  } = {}) {
3620
3876
  try {
@@ -3635,7 +3891,7 @@ async function notifyOriginatingTab(job, {
3635
3891
  message = `PRD ${job.slug} was skipped: its PRD source could not be found on disk. Blocked dependents: ${shown}${more}.`
3636
3892
  + ' If the PRD file exists, run scheduler_reset_job with force:true; if it was intentionally removed, archive it with scheduler_archive_prd.';
3637
3893
  }
3638
- const macroNotice = macroBuildNotice(job, prd);
3894
+ const macroNotice = await macroBuildNotice(job, prd);
3639
3895
  if (macroNotice) message = macroNotice.message;
3640
3896
 
3641
3897
  // The EPIC this check-in belongs to. Deliberately does NOT consider
@@ -3673,9 +3929,9 @@ async function notifyOriginatingTab(job, {
3673
3929
  const needsResultText = (epicIdForTranscript && job.cwd)
3674
3930
  || (job.agentType === 'validator' && job.status === 'completed');
3675
3931
  let resultText = null;
3932
+ const logPath = job.runId ? path.join(schedulerPaths.runsDir(), job.runId, `${job.slug}.log`) : null;
3676
3933
  if (needsResultText) {
3677
3934
  try {
3678
- const logPath = job.runId ? path.join(schedulerPaths.runsDir(), job.runId, `${job.slug}.log`) : null;
3679
3935
  resultText = readResultFromLog(logPath);
3680
3936
  } catch (e) {
3681
3937
  console.error('[scheduler] notifyOriginatingTab readResultFromLog error', job?.slug, e);
@@ -3693,13 +3949,31 @@ async function notifyOriginatingTab(job, {
3693
3949
  }
3694
3950
  }
3695
3951
 
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
- : [];
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
+ }
3703
3977
 
3704
3978
  if (!epicId && verdicts.length > 0) {
3705
3979
  // No Epic to attach these to (unresolved sourcePromptId/epicId, same
@@ -3724,12 +3998,41 @@ async function notifyOriginatingTab(job, {
3724
3998
  job.cwd || null,
3725
3999
  epicId,
3726
4000
  `Validation ${v.verdict.toUpperCase()}: ${v.slug}${v.reason ? ` — ${v.reason}` : ''}`,
3727
- { 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
+ },
3728
4009
  );
3729
4010
  } catch (e) {
3730
4011
  console.error('[scheduler] notifyOriginatingTab verdict appendResponseEvent error', job?.slug, v.slug, e);
3731
4012
  }
3732
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) {
3733
4036
  // PRD 986: the check-in event is born validation:'unvalidated' — never
3734
4037
  // 'verified' — regardless of the job's self-reported outcome. The
3735
4038
  // check-in is a request to validate, not an assertion of done.
@@ -4710,6 +5013,12 @@ const HEADLESS_DISALLOWED_TOOLS = Object.freeze([
4710
5013
  * `--disallowedTools` takes a variadic list, so another flag must always
4711
5014
  * follow it to end that list — `--output-format` does, right after. Never
4712
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.
4713
5022
  * The prompt is NOT in argv: callers send it on the child's stdin
4714
5023
  * (withChildAndLog's `stdinText`). Linux caps a single argv element at 128 KB,
4715
5024
  * and a large prompt failed with spawn E2BIG before the job started (the
@@ -4722,7 +5031,64 @@ function knownMcpServers() {
4722
5031
  return { [seed.SERVER_NAME]: seed.schedulerServerEntry() };
4723
5032
  }
4724
5033
 
4725
- 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
+ }
4726
5092
  return [
4727
5093
  '-p',
4728
5094
  '--model', model,
@@ -4730,7 +5096,9 @@ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt,
4730
5096
  ...(systemPrompt ? ['--append-system-prompt', systemPrompt] : []),
4731
5097
  ...personaToolScopeArgs(toolScope, { mcpServers: knownMcpServers() }),
4732
5098
  ...(Array.isArray(pluginDirArgs) ? pluginDirArgs : []),
4733
- '--dangerously-skip-permissions',
5099
+ ...(jsonSchema && typeof jsonSchema === 'object' ? ['--json-schema', JSON.stringify(jsonSchema)] : []),
5100
+ ...riskArgs,
5101
+ ...permissionArgs,
4734
5102
  ...headlessPermissionArgs(),
4735
5103
  '--disallowedTools', HEADLESS_DISALLOWED_TOOLS.join(','),
4736
5104
  '--output-format', 'stream-json',
@@ -4739,6 +5107,41 @@ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt,
4739
5107
  ];
4740
5108
  }
4741
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
+
4742
5145
  // ---------- execution ----------
4743
5146
 
4744
5147
  // Allocates the runId/dir pair at dispatch time WITHOUT creating the
@@ -4859,6 +5262,10 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4859
5262
  // the scheduler's own short status chip (that's notifyOriginatingTab's job
4860
5263
  // for the assistant side).
4861
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 = [];
4862
5269
  if (resumeTarget) {
4863
5270
  // Resume mode (PRD 1111): a short deterministic preamble naming the
4864
5271
  // recorded dirty paths, NEVER the original PRD body — the resumed
@@ -5025,11 +5432,13 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5025
5432
  try {
5026
5433
  const fm = parsePrdFile(await fsp.readFile(prdPath, 'utf8')).frontmatter;
5027
5434
  isArtifactOnly = isArtifactOnlyDeclaration(fm);
5435
+ // Tool-risk clearance (PRD scheduler-tool-risk-wiring): same read.
5436
+ prdRiskTools = Array.isArray(fm && fm.riskTools) ? fm.riskTools : [];
5028
5437
  } catch {
5029
5438
  isArtifactOnly = false;
5030
5439
  }
5031
5440
  }
5032
- 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' }) });
5033
5442
 
5034
5443
  // Foreign-WIP manifest (starry-night-ships PRD 148 postmortem): the
5035
5444
  // scheduler already knows, at spawn time, which dirty paths this job did
@@ -5059,9 +5468,31 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5059
5468
  // a dangling/absent agentType falls back to no persona + FALLBACK_MODEL
5060
5469
  // and is logged once by resolvePrdPersonaForSpawn itself.
5061
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
+ }
5062
5490
  const effortResolution = resolveEpicEffort({ cwd, agentType: job.agentType, prdEffort: job.effort });
5063
5491
  const personaEffort = effortResolution.effort;
5064
- 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 });
5065
5496
  // Epic context packs (PRD 3154): the job's Epic's selected packs load as
5066
5497
  // --plugin-dir per pack, and their laws are appended AFTER the (already
5067
5498
  // capped) persona body — the persona cap never applies to laws. Fresh and
@@ -5119,6 +5550,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5119
5550
  SM_SCHEDULER_JOB_SLUG: job.slug,
5120
5551
  SM_SCHEDULER_JOB_MAY_QUEUE: job.agentType === 'architect' ? '1' : '0',
5121
5552
  ...personaToolScopeEnv(personaToolScope),
5553
+ SM_SCHEDULER_JOB_RISK_TOOLS: JSON.stringify(jobRiskTools),
5122
5554
  BASH_DEFAULT_TIMEOUT_MS: String(BASH_DEFAULT_TIMEOUT_MS),
5123
5555
  BASH_MAX_TIMEOUT_MS: String(BASH_MAX_TIMEOUT_MS),
5124
5556
  ...(launchEnv && typeof launchEnv === 'object' ? launchEnv : {}),
@@ -5289,7 +5721,43 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5289
5721
 
5290
5722
  // Distinct comm (`sm-claude-job`) + slug-labelled argv0 for System Monitor.
5291
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`);
5292
5759
  const jobArgs = buildClaudeSpawnArgs({
5760
+ sandboxArgs: sandboxPolicy.argv,
5293
5761
  model: personaResolution.model,
5294
5762
  effort: personaEffort,
5295
5763
  sessionId,
@@ -5297,6 +5765,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5297
5765
  systemPrompt: jobSystemPrompt,
5298
5766
  toolScope: personaToolScope,
5299
5767
  pluginDirArgs: packArgs.pluginDirArgs,
5768
+ jsonSchema: isValidator ? VALIDATOR_VERDICT_SCHEMA : null,
5769
+ riskGuardSettingsPath,
5300
5770
  });
5301
5771
  const jobSpawn = claudeSpawnTarget('job', job.slug, claudeBin, jobArgs);
5302
5772
 
@@ -5306,7 +5776,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5306
5776
  const errMsg = `argv too large: ${oversized.flag} is ${oversized.bytes} bytes, over the ${launchFailure.MAX_ARG_BYTES}-byte per-argument limit; not spawned`;
5307
5777
  safeLog(`[scheduler] ${errMsg}\n`);
5308
5778
  closeFd();
5309
- 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();
5310
5781
  resolve({ exitCode: -1, durationMs: 0, error: errMsg, launchError: 'argv_too_large', sessionId });
5311
5782
  return;
5312
5783
  }
@@ -5358,7 +5829,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5358
5829
  sl(`\n[scheduler] ${errMsg}\n`);
5359
5830
  // Sync write: inside a Promise executor callback; must flush meta
5360
5831
  // 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 });
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();
5362
5834
  resolve({ exitCode: -1, durationMs, error: errMsg, leakedDescendants: leaked, sessionId,
5363
5835
  ...(launchFailure.isArgvTooLargeSpawnError(error?.message) ? { launchError: 'argv_too_large' } : {}) });
5364
5836
  return;
@@ -5421,9 +5893,11 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
5421
5893
  startedAt, finishedAt: Date.now(), durationMs, leakedDescendants: leaked,
5422
5894
  agentResultSubtype, mappedFromSignal: mappedToSuccess ? signal || `code=${exitCode}` : null,
5423
5895
  killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
5896
+ sandbox: sandboxMeta,
5424
5897
  ...SCHEDULER_META_IDENTITY, ...setupMeta,
5425
5898
  originSessionId, contextDigestApplied,
5426
5899
  });
5900
+ removeSandboxTmp();
5427
5901
  resolve({
5428
5902
  exitCode: effectiveCode, durationMs, rateLimited, networkError, launchFailure: launchFailed, resultStats,
5429
5903
  leakedDescendants: leaked, sessionId, killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
@@ -5967,7 +6441,10 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
5967
6441
  args: [
5968
6442
  '-p',
5969
6443
  '--model', 'opus',
5970
- '--dangerously-skip-permissions',
6444
+ ...buildJobSandboxSettings({
6445
+ agentType: 'investigation', worktreeDir: cwd, projectRoot: cwd,
6446
+ homeDir: os.homedir(), tmpDir: os.tmpdir(), deps: resolveJobSandboxDeps(),
6447
+ }).argv,
5971
6448
  ...headlessPermissionArgs(),
5972
6449
  '--disallowedTools', HEADLESS_DISALLOWED_TOOLS.join(','),
5973
6450
  '--output-format', 'stream-json',
@@ -6426,7 +6903,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6426
6903
  // Session-Manager owns the machine-wide `claude -p` pool (sessionSlots.cjs)
6427
6904
  // — the scheduler REQUESTS capacity, it doesn't own a private cap. A miss
6428
6905
  // leaves the job pending; the next tick retries when a slot frees up.
6429
- const slotToken = sessionSlots.acquire(`scheduler:${job.slug}`, { claimedAt: Date.now() });
6906
+ const slotToken = sessionSlots.acquire(`scheduler:${job.slug}`, { claimedAt: Date.now(), lane: 'job' });
6430
6907
  if (!slotToken) {
6431
6908
  console.log(`[scheduler] no session slot free for ${job.slug} — deferring (${JSON.stringify(sessionSlots.snapshot().holders.map((h) => h.owner))})`);
6432
6909
  return;
@@ -6857,6 +7334,10 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6857
7334
  }, reviewInRun, worktree.ok ? worktree.setup : { ran: false, ok: false, reason: 'in-place', waitedMs: 0, ms: 0, commands: [] });
6858
7335
  } finally {
6859
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);
6860
7341
  ({ worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha, worktreeHead, uncommittedSnapshot } =
6861
7342
  await finalizeJobWorktree({ job, runId, runDir, worktree, guardCwd, carriedPaths }));
6862
7343
  } else {
@@ -8224,11 +8705,12 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8224
8705
  // degraded cap minus what's already running.
8225
8706
  runReservationExpiryPass(state.jobs, tickStartedAt);
8226
8707
  const freeSlots = degradedConcurrencyCapValue != null
8227
- ? Math.max(0, Math.min(sessionSlots.available(), degradedConcurrencyCapValue - runningSet.size))
8228
- : sessionSlots.available();
8708
+ ? Math.max(0, Math.min(sessionSlots.availableFor('job'), degradedConcurrencyCapValue - runningSet.size))
8709
+ : sessionSlots.availableFor('job');
8229
8710
  const heldSlugs = await computeLaunchHolds(state);
8230
8711
  if (stale()) return STALE_TICK;
8231
8712
  const satisfiedSlugsByCwd = await budget.computeDepHistorySatisfaction(state);
8713
+ lastSatisfiedSlugsByCwd = satisfiedSlugsByCwd;
8232
8714
  if (stale()) return STALE_TICK;
8233
8715
  const { batch, reason: holdReason, holds } = pickNextBatch(state.jobs, runningSet, freeSlots, {
8234
8716
  leaseHeld: quietMachineLease.isHeld(),
@@ -8391,7 +8873,7 @@ async function tickBody(gen, { bypassLoadGate, lastResort }) {
8391
8873
  const mins = Math.round(load.heldMs / 60_000);
8392
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'}`);
8393
8875
  } 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`);
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`);
8395
8877
  if (load.shouldAuditStandDown) {
8396
8878
  appendAuditEvent('load_gate_stood_down', loadGateAuditFields(load));
8397
8879
  }
@@ -8748,29 +9230,63 @@ function runQueueHealthSweep(jobs) {
8748
9230
  }
8749
9231
 
8750
9232
  // 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.
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.
8755
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
+ }
8756
9253
 
8757
9254
  /**
8758
9255
  * Recover any `sm-job/*` branch left stranded (unmerged, owning row terminal
8759
9256
  * or gone) across every known project — the other half of PRD 1135's
8760
9257
  * invariant alongside the reaper's liveness check above: that check stops
8761
9258
  * 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.
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.
8766
9267
  */
8767
- async function runBranchSweep(jobs) {
9268
+ async function runBranchSweep(jobs, deps = {}) {
8768
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 = [];
8769
9274
  try {
8770
- 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
+ }
8771
9285
  let sweep;
8772
9286
  try {
8773
- sweep = await sweepStrandedJobBranches({ cwd, jobs, attemptedBranches: branchSweepAttempted });
9287
+ sweep = await sweepStrandedJobBranches({
9288
+ cwd, jobs, attemptedBranches: branchSweepAttempted, backoff: { state, now },
9289
+ });
8774
9290
  } catch (e) {
8775
9291
  console.warn(`[scheduler] branch sweep error for ${cwd}`, e?.message);
8776
9292
  continue;
@@ -8778,10 +9294,12 @@ async function runBranchSweep(jobs) {
8778
9294
  for (const r of sweep.results) {
8779
9295
  if (r.action === 'integrated') {
8780
9296
  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 });
9297
+ audit('branch_sweep_integrated', { cwd, branch: r.branch, slug: r.slug });
8782
9298
  } 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 });
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
+ });
8785
9303
  if (r.slug) {
8786
9304
  await mutate((s) => {
8787
9305
  const j = s.jobs.find((x) => x.slug === r.slug);
@@ -8790,12 +9308,59 @@ async function runBranchSweep(jobs) {
8790
9308
  }
8791
9309
  }
8792
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
+ }
8793
9328
  }
9329
+ if (stopped.length) await reportBranchSweepGaveUp(stopped, { audit, store, now });
8794
9330
  } catch (e) {
8795
9331
  console.warn('[scheduler] branch sweep error', e?.message);
8796
9332
  }
8797
9333
  }
8798
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
+
8799
9364
  /**
8800
9365
  * Scan running jobs, identify those whose claude process is provably dead OR
8801
9366
  * whose spawn never got far enough to record a runtime.pid in the first
@@ -10338,6 +10903,15 @@ let gateShadowPending = null;
10338
10903
  let gateShadowSlug = null;
10339
10904
 
10340
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
+
10341
10915
  async function reverifyNeedsReview() {
10342
10916
  const snap = await readQueue();
10343
10917
  // isGuardParkedWithoutAutoFix rows are NOT isRescanCandidate (their
@@ -10629,25 +11203,25 @@ async function reverifyNeedsReview() {
10629
11203
  for (const j of s.jobs) {
10630
11204
  if (unresolvableSet.has(j.slug)) {
10631
11205
  j.verifierVerdict = 'no_run_artifacts';
10632
- j.error = 'no run artifacts — manual review';
11206
+ j.error = PARK_ERRORS.no_run_artifacts;
10633
11207
  } else if (exhaustedSet.has(j.slug)) {
10634
11208
  j.verifierVerdict = 'autofix_no_plan';
10635
- j.error = 'auto-fix investigation produced no fix plan after retry — manual review';
11209
+ j.error = PARK_ERRORS.autofix_no_plan;
10636
11210
  } else if (planUnqueuedSet.has(j.slug)) {
10637
11211
  j.verifierVerdict = 'autofix_plan_unqueued';
10638
- j.error = 'auto-fix investigation produced a fix plan that never reached the queue — manual review';
11212
+ j.error = PARK_ERRORS.autofix_plan_unqueued;
10639
11213
  }
10640
11214
  }
10641
11215
  });
10642
11216
  if (unresolvable.length) {
10643
- 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`);
10644
11218
  }
10645
11219
  if (exhaustedAutoFix.length) {
10646
- 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`);
10647
11221
  }
10648
11222
  if (planUnqueued.length) {
10649
11223
  for (const j of planUnqueued) {
10650
- 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`);
10651
11225
  }
10652
11226
  }
10653
11227
  await broadcast();
@@ -10889,7 +11463,7 @@ function registerScheduleHandlers() {
10889
11463
  }
10890
11464
  const now = Date.now();
10891
11465
  const slotSnapshot = sessionSlots.snapshot();
10892
- const freeSlots = Math.max(0, slotSnapshot.total - slotSnapshot.inUse);
11466
+ const freeSlots = jobFreeSlots(slotSnapshot);
10893
11467
  const verdict = starvation.classifyQueueHealth({
10894
11468
  jobs: state.jobs,
10895
11469
  paused: upgradeDrain.effectivePaused(state),
@@ -12047,7 +12621,17 @@ const remote = {
12047
12621
 
12048
12622
  async listJobs() {
12049
12623
  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 }));
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
+ }));
12051
12635
  },
12052
12636
 
12053
12637
  // Single queue row lookup, used by cancelJob/updatePrd's status guards and
@@ -12240,8 +12824,23 @@ const remote = {
12240
12824
 
12241
12825
  const { frontmatter: fm, body: origBody } = parsePrdFile(raw);
12242
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
+ }
12243
12837
  for (const key of Object.keys(frontmatter)) {
12244
12838
  if (frontmatter[key] === undefined) continue;
12839
+ if (key === 'riskTools') {
12840
+ if (clearRiskTools) delete fm.riskTools;
12841
+ else fm.riskTools = riskTools;
12842
+ continue;
12843
+ }
12245
12844
  fm[key] = frontmatter[key];
12246
12845
  }
12247
12846
  }
@@ -12322,6 +12921,49 @@ const remote = {
12322
12921
  if (job.status === 'completed' || job.status === 'failed' || job.status === 'needs_review' || job.status === 'skipped') {
12323
12922
  return { ok: false, error: `job already terminal (status: "${job.status}") — nothing to cancel` };
12324
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 : [];
12325
12967
  const wasRunning = job.status === 'running';
12326
12968
  const pid = job.runtime?.pid;
12327
12969
  // Evidence-before-failure guard, scoped to an actually-running job being
@@ -12345,6 +12987,24 @@ const remote = {
12345
12987
  : 'cancelled via admin API';
12346
12988
  const cancelledAt = new Date().toISOString();
12347
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
+ }
12348
13008
  const idx = s.jobs.findIndex((j) => j.slug === slug);
12349
13009
  if (idx < 0) return;
12350
13010
  const j = s.jobs[idx];
@@ -12361,6 +13021,12 @@ const remote = {
12361
13021
  if (wasRunning && pid) killOrphanClaudePid(pid);
12362
13022
  await broadcast({ flush: true });
12363
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
+ }
12364
13030
  if (wasRunning) {
12365
13031
  // Whatever the executor committed before SIGTERM stays on its job
12366
13032
  // branch (never integrated); tell the caller where. Known residual: a
@@ -12450,7 +13116,20 @@ function registerAdminRoutes(adminHttp, remoteObj = remote) {
12450
13116
  });
12451
13117
  }
12452
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
+
12453
13129
  module.exports = {
13130
+ PARK_ERRORS,
13131
+ applyDepHoldNotices,
13132
+ _resetDepHoldNoticesForTests,
12454
13133
  readValidatorGateMs,
12455
13134
  resolveValidatorEstimate,
12456
13135
  planJobScope,
@@ -12552,6 +13231,7 @@ module.exports = {
12552
13231
  isNotifiableTerminalStatus,
12553
13232
  armSettleAfterValidatorBudgetKill,
12554
13233
  extractResultTextFromLog,
13234
+ extractStructuredOutputFromLog,
12555
13235
  resolveVerifyPrdPath,
12556
13236
  resolveFixPlanPath,
12557
13237
  resolveNotifyPrd,
@@ -12576,6 +13256,7 @@ module.exports = {
12576
13256
  INVESTIGATION_MAX_MS,
12577
13257
  buildResumeRecoveryPreamble,
12578
13258
  buildClaudeSpawnArgs,
13259
+ jobRiskToolsClearance,
12579
13260
  HEADLESS_DISALLOWED_TOOLS,
12580
13261
  spawnResumeRecovery,
12581
13262
  resolveHeadShasForPass,