claude-code-session-manager 0.143.0 → 0.144.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +3 -1
  2. package/dist/assets/AppSettings-Z68gQiVE.js +2 -0
  3. package/dist/assets/{History-DTttbvPb.js → History-C3E6y_7t.js} +2 -2
  4. package/dist/assets/HomeClaudeConfig-Yd1vXzBn.js +5 -0
  5. package/dist/assets/{Panel-B_D4Bg7L.js → Panel-CnfWs46Z.js} +1 -1
  6. package/dist/assets/ProjectClaudeConfig-CP0Wsg-H.js +26 -0
  7. package/dist/assets/Scheduler-D8un7N3B.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-D1b2aiol.js → SkillReferenceGraph-DRtZV1Al.js} +1 -1
  9. package/dist/assets/{Skills-cfV7sgk6.js → Skills-Bg5O2Hyn.js} +23 -23
  10. package/dist/assets/{TiptapBody-DVXtEIVy.js → TiptapBody-BdzoBmqu.js} +27 -27
  11. package/dist/assets/{Toggle-CYajnSdx.js → Toggle-Dt5K1OXt.js} +1 -1
  12. package/dist/assets/{VoiceButton-DJ4gGRuE.js → VoiceButton-CTLyRgdF.js} +1 -1
  13. package/dist/assets/{historyTotals-D3MoHY2U.js → historyTotals-B2_KWBga.js} +1 -1
  14. package/dist/assets/{index-CdTppjKR.js → index-446b69rr.js} +698 -697
  15. package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
  16. package/dist/index.html +2 -2
  17. package/dist-web/app.css +1 -1
  18. package/dist-web/app.js +439 -436
  19. package/package.json +4 -2
  20. package/plugins/session-manager-dev/skills/develop/SKILL.md +14 -13
  21. package/plugins/session-manager-dev/skills/maintaining-md-network/SKILL.md +16 -2
  22. package/plugins/session-manager-dev/skills/maintaining-md-network/weekly-consolidation.md +87 -0
  23. package/scripts/README.md +1 -1
  24. package/scripts/scheduler-mcp-server.cjs +77 -0
  25. package/src/main/adminRouteRegistry.cjs +6 -0
  26. package/src/main/agentLibrary.cjs +60 -11
  27. package/src/main/agentsIpc.cjs +19 -0
  28. package/src/main/build-info.json +4 -4
  29. package/src/main/chatRunner.cjs +109 -0
  30. package/src/main/health.cjs +59 -17
  31. package/src/main/index.cjs +4 -0
  32. package/src/main/ipcSchemas.cjs +50 -1
  33. package/src/main/lib/claude/agentArmory.cjs +128 -0
  34. package/src/main/lib/claude/agentModelResolve.cjs +3 -2
  35. package/src/main/lib/claude/agentSnapshot.cjs +24 -3
  36. package/src/main/lib/claude/builtinTools.cjs +110 -0
  37. package/src/main/lib/claude/environmentProfiles.cjs +1 -1
  38. package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
  39. package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
  40. package/src/main/lib/claude/personaToolScope.cjs +77 -6
  41. package/src/main/lib/epic/epicDepsSync.cjs +66 -0
  42. package/src/main/lib/epic/epicOutsideRead.cjs +38 -1
  43. package/src/main/lib/epic/epicSettle.cjs +48 -4
  44. package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
  45. package/src/main/lib/epic/epicValidationHook.cjs +9 -1
  46. package/src/main/lib/epic/planReviewInput.cjs +123 -0
  47. package/src/main/lib/epic/restorableSessions.cjs +1 -0
  48. package/src/main/lib/epic/scriptStartedBy.cjs +71 -0
  49. package/src/main/lib/externalContract.cjs +12 -0
  50. package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
  51. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +24 -2
  52. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +24 -3
  53. package/src/main/lib/feedback-remote/pendingReplies.cjs +8 -4
  54. package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
  55. package/src/main/lib/feedback-remote/replyClaims.cjs +15 -6
  56. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +29 -1
  57. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
  58. package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
  59. package/src/main/lib/feedback-remote/servicePairings.cjs +47 -7
  60. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +99 -1
  61. package/src/main/lib/git/gitWorktree.cjs +1 -1
  62. package/src/main/lib/git/worktreeDeps.cjs +9 -3
  63. package/src/main/lib/mcpToolCatalog.cjs +43 -5
  64. package/src/main/lib/mcpToolsProbe.cjs +19 -2
  65. package/src/main/lib/packs/packCatalog.cjs +98 -5
  66. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
  67. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  68. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
  69. package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
  70. package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
  71. package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
  72. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
  73. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +94 -0
  74. package/src/main/lib/prd/prdCreate.cjs +48 -5
  75. package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
  76. package/src/main/lib/prd/prdMcpReachWarnings.cjs +44 -0
  77. package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
  78. package/src/main/lib/process/peerChatSession.cjs +165 -0
  79. package/src/main/lib/project-pages/videoScriptPress.cjs +6 -0
  80. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +24 -4
  81. package/src/main/lib/promptSessionSchema.cjs +2 -0
  82. package/src/main/lib/scheduler/baselineGate.cjs +31 -2
  83. package/src/main/lib/scheduler/planRecordHarvest.cjs +104 -12
  84. package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
  85. package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
  86. package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
  87. package/src/main/lib/scheduler/planReviewStore.cjs +128 -0
  88. package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
  89. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  90. package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
  91. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +12 -2
  92. package/src/main/lib/tasks/memoryConsolidation.cjs +109 -37
  93. package/src/main/lib/tasks/taskAdminRoutes.cjs +26 -14
  94. package/src/main/lib/tasks/taskRun.cjs +3 -1
  95. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +178 -0
  96. package/src/main/projectPages.cjs +22 -14
  97. package/src/main/pty.cjs +3 -0
  98. package/src/main/runVerify.cjs +3 -2
  99. package/src/main/scheduler/planReviewHold.cjs +140 -0
  100. package/src/main/scheduler/prdParser.cjs +1 -0
  101. package/src/main/scheduler/reviewLadder.cjs +2 -0
  102. package/src/main/scheduler/utilizationHold.cjs +7 -2
  103. package/src/main/scheduler.cjs +532 -78
  104. package/src/main/seedAgentPersonas.cjs +11 -6
  105. package/src/main/seedStatus.cjs +1 -1
  106. package/src/main/templates/PRD_AUTHORING.md +16 -1
  107. package/src/main/webRemote.cjs +47 -7
  108. package/src/preload/api.d.ts +71 -1
  109. package/src/preload/apiSurface.json +28 -0
  110. package/src/preload/index.cjs +9 -0
  111. package/src/seed/agents/architect.md +28 -43
  112. package/src/seed/agents/dev-lead.md +3 -1
  113. package/src/seed/agents/md-network-curator.md +27 -0
  114. package/src/seed/agents/plan-reviewer.md +47 -0
  115. package/src/seed/agents/validator.md +2 -1
  116. package/dist/assets/AppSettings-BO4jDVGO.js +0 -2
  117. package/dist/assets/HomeClaudeConfig-DADP5bfn.js +0 -3
  118. package/dist/assets/ProjectClaudeConfig-DPnDJKcr.js +0 -26
  119. package/dist/assets/Scheduler-CNLjn90m.js +0 -16
@@ -69,6 +69,7 @@ const { headlessPermissionArgs, ensureCliCapsProbed } = require('./lib/claude/cl
69
69
  // as the authoritative guarantee.
70
70
  ensureCliCapsProbed().catch(() => {});
71
71
  const launchFailure = require('./lib/scheduler/launchFailure.cjs');
72
+ const { sandboxLimitFromStreamJson, environmentLimitStamp, ENVIRONMENT_LIMIT_MESSAGE } = require('./lib/scheduler/sandboxEnvironmentLimit.cjs');
72
73
  const { decideVerifyDowngrade } = require('./lib/scheduler/refireCap.cjs');
73
74
  const { finalizeReasonFor } = require('./lib/scheduler/finalizeReason.cjs');
74
75
  const { shouldRunFlatSweep, FLAT_SWEEP_INTERVAL_MS } = require('./lib/scheduler/flatSweepThrottle.cjs');
@@ -130,6 +131,7 @@ const { buildReviewNotice, selectDueReviewNotices, formatReviewNotice, holdMsFro
130
131
  const { phaseOfJob } = require('./lib/phaseProjection.cjs');
131
132
  const epicValidationHook = require('./lib/epic/epicValidationHook.cjs');
132
133
  const prdCreate = require('./lib/prd/prdCreate.cjs');
134
+ const { mcpReachWarnings } = require('./lib/prd/prdMcpReachWarnings.cjs');
133
135
  const { resolveProjectContext } = require('./lib/projectRootResolve.cjs');
134
136
  const { expandHome } = require('./lib/util/expandHome.cjs');
135
137
  const { hasDownstreamValidator } = require('./lib/prd/planValidator.cjs');
@@ -141,6 +143,9 @@ const { landedSinceRun, landedOnMainSince } = require('./lib/scheduler/landedSin
141
143
  const { declaredPathsForPrd, issuedAtForPrd } = require('./lib/prd/prdDeclaredPaths.cjs');
142
144
  const { identity: procIdentityOf, isDifferentProcess } = require('./lib/process/procIdentity.cjs');
143
145
  const jobLeftovers = require('./lib/scheduler/jobLeftovers.cjs');
146
+ const planReviewHold = require('./scheduler/planReviewHold.cjs');
147
+ const planReviewStore = require('./lib/scheduler/planReviewStore.cjs');
148
+ const { buildPlanReviewInput } = require('./lib/epic/planReviewInput.cjs');
144
149
  const { harvestPlanRecords, saveValidatorVerdicts } = require('./lib/scheduler/planRecordHarvest.cjs');
145
150
  const artifactStore = require('./lib/epic/artifactStore.cjs');
146
151
  const prdOutcomeRecord = require('./lib/scheduler/prdOutcomeRecord.cjs');
@@ -181,7 +186,10 @@ const { ensureEpic, appendPrdCreatedEvent, readActiveIndex } = require('./lib/ep
181
186
  const agentModelResolve = require('./lib/claude/agentModelResolve.cjs');
182
187
  const agentSnapshot = require('./lib/claude/agentSnapshot.cjs');
183
188
  const packSpawnArgs = require('./lib/packs/packSpawnArgs.cjs');
184
- const { buildPersonaToolScope, personaToolScopeArgs, personaToolScopeEnv, resolvedMcpServerNames } = require('./lib/claude/personaToolScope.cjs');
189
+ const { resolveHeadlessMcpServers } = require('./lib/claude/headlessMcpServers.cjs');
190
+ const { buildPersonaToolScope, personaToolScopeArgs, personaToolScopeEnv, resolvedMcpServerNames, resolveSkillDeny } = require('./lib/claude/personaToolScope.cjs');
191
+ const { PLAN_REVIEW_SCHEMA, parsePlanReview, isAllOk: isAllOkPlanReview } = require('./lib/scheduler/planReviewSchema.cjs');
192
+ const { readSettingsModel } = require('./lib/claude/modelCatalog.cjs');
185
193
  const { VALIDATOR_VERDICT_SCHEMA, parseValidatorVerdict, verdictRowsFromStructured, expectedFromCriteria, formatCriteriaChecksSection } = require('./lib/scheduler/validatorVerdictSchema.cjs');
186
194
  const { resolveEpicEffort, effortArgs } = require('./lib/claude/agentEffortResolve.cjs');
187
195
  const { transitionJob, emitJobEvent, STATUS_HISTORY_CAP, LEGAL_TRANSITIONS } = require('./lib/scheduler/scheduleJobTransitions.cjs');
@@ -547,7 +555,12 @@ async function harvestJobArtifacts(job, worktreeDir, projectRoot, { runId = job
547
555
  const FINISH_VALIDATOR_VERDICT_LINE = `
548
556
  - Your structured output's schedulerVerdict (and failReason) is what the scheduler reads as this verdict.`;
549
557
 
550
- function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum, isFixPlan = false, isArtifactOnly = false, isValidator = false }) {
558
+ // Plan-reviewer jobs (`--json-schema` PLAN_REVIEW_SCHEMA): the structured
559
+ // object is the whole deliverable; there is nothing to commit.
560
+ const FINISH_PLAN_REVIEWER_LINE = `
561
+ - PLAN REVIEWER: your deliverable is the structured output object (PLAN_REVIEW_SCHEMA) ONLY. Do not commit, do not edit files; the scheduler reads the object, not this verdict line.`;
562
+
563
+ function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum, isFixPlan = false, isArtifactOnly = false, isValidator = false, isPlanReviewer = false }) {
551
564
  return `${verifyStepNum}. VERIFY — run every command in the PRD's \`# Gate\` section, in order, in the
552
565
  foreground. Each must exit 0. If the PRD has no \`# Gate\` section, run the
553
566
  project's own typecheck, lint and test commands instead. The project's
@@ -579,7 +592,7 @@ ${verdictStepNum}. VERDICT LINE — end your final report with exactly one of th
579
592
  SCHEDULER_VERDICT: PASS
580
593
  SCHEDULER_VERDICT: FAIL <one-line reason>
581
594
  SCHEDULER_VERDICT: BLOCKED_BY_FOREIGN_WIP
582
- - Print PASS only when the gate is green AND the commit from step ${commitStepNum} landed.${isFixPlan ? FINISH_FIX_PLAN_VERDICT_LINE : ''}${isArtifactOnly ? FINISH_ARTIFACT_ONLY_VERDICT_LINE : ''}${isValidator ? FINISH_VALIDATOR_VERDICT_LINE : ''}
595
+ - Print PASS only when the gate is green AND the commit from step ${commitStepNum} landed.${isFixPlan ? FINISH_FIX_PLAN_VERDICT_LINE : ''}${isArtifactOnly ? FINISH_ARTIFACT_ONLY_VERDICT_LINE : ''}${isValidator ? FINISH_VALIDATOR_VERDICT_LINE : ''}${isPlanReviewer ? FINISH_PLAN_REVIEWER_LINE : ''}
583
596
  - Print FAIL when the gate is red or the commit could not land. Also print
584
597
  FAIL when a step needs something this run cannot reach (live runtime
585
598
  state, credentials, an account or dashboard action, a host install): do
@@ -629,13 +642,13 @@ in your final report.`;
629
642
  * tree, never FAIL for the missing commit. Self job 826 printed exactly that
630
643
  * false FAIL. Omitted/false leaves the text unchanged.
631
644
  */
632
- function buildFinishProtocol({ reviewInRun = true, isFixPlan = false, isArtifactOnly = false, isValidator = false } = {}) {
645
+ function buildFinishProtocol({ reviewInRun = true, isFixPlan = false, isArtifactOnly = false, isValidator = false, isPlanReviewer = false } = {}) {
633
646
  if (reviewInRun) {
634
647
  return buildFinishHead(3) + FINISH_REVIEW_STEPS_IN_RUN
635
- + buildFinishTail({ verifyStepNum: 3, commitStepNum: 4, verdictStepNum: 5, isFixPlan, isArtifactOnly, isValidator });
648
+ + buildFinishTail({ verifyStepNum: 3, commitStepNum: 4, verdictStepNum: 5, isFixPlan, isArtifactOnly, isValidator, isPlanReviewer });
636
649
  }
637
650
  return buildFinishHead(2) + FINISH_REVIEW_STEP_DEFERRED
638
- + buildFinishTail({ verifyStepNum: 2, commitStepNum: 3, verdictStepNum: 4, isFixPlan, isArtifactOnly, isValidator });
651
+ + buildFinishTail({ verifyStepNum: 2, commitStepNum: 3, verdictStepNum: 4, isFixPlan, isArtifactOnly, isValidator, isPlanReviewer });
639
652
  }
640
653
 
641
654
  const FINISH_PROTOCOL = buildFinishProtocol({ reviewInRun: true });
@@ -1108,6 +1121,7 @@ function restoreOpenAutoDispatchHold(v) {
1108
1121
  window: typeof v.window === 'string' ? v.window : null,
1109
1122
  threshold: Number.isFinite(v.threshold) ? v.threshold : null,
1110
1123
  resetsAt: typeof v.resetsAt === 'string' ? v.resetsAt : null,
1124
+ lastResetsAt: typeof v.lastResetsAt === 'string' ? v.lastResetsAt : (typeof v.resetsAt === 'string' ? v.resetsAt : null),
1111
1125
  startedAt: v.startedAt,
1112
1126
  maxPercent: Number.isFinite(v.maxPercent) ? v.maxPercent : null,
1113
1127
  heldTicks: Number.isFinite(v.heldTicks) ? v.heldTicks : 0,
@@ -1118,6 +1132,30 @@ function restoreOpenAutoDispatchHold(v) {
1118
1132
  /** Test-only seam: the open audit hold, and a reset that drops it from memory (a simulated process exit). */
1119
1133
  function _getOpenAutoDispatchHoldForTests() { return openAutoDispatchHold; }
1120
1134
  function _forgetOpenAutoDispatchHoldForTests() { openAutoDispatchHold = null; }
1135
+ /** Test-only seam: a fresh process — no previous tick. */
1136
+ function _resetPreviousTickUnheldForTests() { previousTickUnheld = false; }
1137
+
1138
+ const HOLD_RESET_CONTINUITY_MS = 60_000;
1139
+
1140
+ /**
1141
+ * Whether `hold` continues the open audit hold: same reason and window, and
1142
+ * resetsAt within 60 s (equal strings when either is unparseable). Not
1143
+ * holdIdentityKey equality — its nearest-minute rounding flips when a reset
1144
+ * near hh:mm:30 jitters by under a second.
1145
+ * @param {{ reason?: string | null, window?: string | null, resetsAt?: string | null } | null} open
1146
+ * @param {{ reason?: string | null, window?: string | null, resetsAt?: string | number | null } | null} hold
1147
+ */
1148
+ function continuesOpenHold(open, hold) {
1149
+ if (!open || !hold) return false;
1150
+ if ((open.reason ?? null) !== (hold.reason ?? null)) return false;
1151
+ if ((open.window ?? null) !== (hold.window ?? null)) return false;
1152
+ const a = open.lastResetsAt ?? open.resetsAt ?? null;
1153
+ const b = hold.resetsAt ?? null;
1154
+ const ta = a == null ? NaN : Date.parse(String(a));
1155
+ const tb = b == null ? NaN : Date.parse(String(b));
1156
+ if (Number.isFinite(ta) && Number.isFinite(tb)) return Math.abs(ta - tb) <= HOLD_RESET_CONTINUITY_MS;
1157
+ return (a == null ? null : String(a)) === (b == null ? null : String(b));
1158
+ }
1121
1159
 
1122
1160
  /**
1123
1161
  * Track the auto-dispatch hold in audit-log.jsonl: one started event when a
@@ -1126,13 +1164,15 @@ function _forgetOpenAutoDispatchHoldForTests() { openAutoDispatchHold = null; }
1126
1164
  * @param {object | null} hold currentAutoDispatchHold() result
1127
1165
  * @param {number} pending pending-row count for the started event
1128
1166
  */
1129
- function trackAutoDispatchHoldAudit(hold, pending) {
1167
+ function trackAutoDispatchHoldAudit(hold, pending, startObserved = false) {
1130
1168
  try {
1131
1169
  const identity = hold ? autoDispatchHold.holdIdentityKey(hold) : null;
1132
1170
  const open = openAutoDispatchHold;
1133
- if (open && open.holdKey === identity) {
1171
+ if (open && continuesOpenHold(open, hold)) {
1134
1172
  if (Number.isFinite(hold.percent) && (open.maxPercent == null || hold.percent > open.maxPercent)) open.maxPercent = hold.percent;
1135
1173
  open.heldTicks += 1;
1174
+ open.lastResetsAt = hold.resetsAt ?? open.lastResetsAt;
1175
+ persistSchedulerState();
1136
1176
  return;
1137
1177
  }
1138
1178
  if (open) {
@@ -1141,6 +1181,7 @@ function trackAutoDispatchHoldAudit(hold, pending) {
1141
1181
  window: open.window,
1142
1182
  threshold: open.threshold,
1143
1183
  resetsAt: open.resetsAt,
1184
+ lastResetsAt: open.lastResetsAt ?? open.resetsAt,
1144
1185
  holdKey: open.holdKey,
1145
1186
  startedAt: open.startedAt,
1146
1187
  endedAt: new Date().toISOString(),
@@ -1160,6 +1201,7 @@ function trackAutoDispatchHoldAudit(hold, pending) {
1160
1201
  resetsAt: hold.resetsAt ?? null,
1161
1202
  holdKey: identity,
1162
1203
  pending,
1204
+ startObserved,
1163
1205
  version: SCHEDULER_BUILD_IDENTITY.version,
1164
1206
  });
1165
1207
  openAutoDispatchHold = {
@@ -1169,6 +1211,7 @@ function trackAutoDispatchHoldAudit(hold, pending) {
1169
1211
  threshold: hold.threshold ?? null,
1170
1212
  baseThreshold: hold.baseThreshold ?? null,
1171
1213
  resetsAt: hold.resetsAt ?? null,
1214
+ lastResetsAt: hold.resetsAt ?? null,
1172
1215
  startedAt: new Date().toISOString(),
1173
1216
  maxPercent: Number.isFinite(hold.percent) ? hold.percent : null,
1174
1217
  heldTicks: 1,
@@ -1234,6 +1277,7 @@ function persistSchedulerState() {
1234
1277
  window: openAutoDispatchHold.window,
1235
1278
  threshold: openAutoDispatchHold.threshold,
1236
1279
  resetsAt: openAutoDispatchHold.resetsAt,
1280
+ lastResetsAt: openAutoDispatchHold.lastResetsAt,
1237
1281
  startedAt: openAutoDispatchHold.startedAt,
1238
1282
  maxPercent: openAutoDispatchHold.maxPercent,
1239
1283
  heldTicks: openAutoDispatchHold.heldTicks,
@@ -1326,6 +1370,8 @@ async function driveUpgradeDrain(state) {
1326
1370
  queueSnapshot: drainSnapshot(state.jobs),
1327
1371
  drainState: state.drain,
1328
1372
  now: Date.now(),
1373
+ // A request older than this process asked for a restart that already happened.
1374
+ bootedAt: SCHEDULER_BOOTED_AT,
1329
1375
  });
1330
1376
  if (action === 'none' || action === 'wait') { drainActive = Boolean(state.drain?.active); return; }
1331
1377
  if (action === 'pause') {
@@ -1382,9 +1428,9 @@ async function driveUpgradeDrain(state) {
1382
1428
  /** Boot: clear a leftover drain whose request is complete (the restart happened) or gone. */
1383
1429
  async function clearStaleDrainAtBoot(boot) {
1384
1430
  const request = upgradeDrain.readRestartRequest();
1385
- const action = upgradeDrain.bootDrainAction({ drainState: boot.drain, request });
1431
+ const action = upgradeDrain.bootDrainAction({ drainState: boot.drain, request, bootedAt: SCHEDULER_BOOTED_AT });
1386
1432
  upgradeDrain.clearRestartingMarker();
1387
- if (request?.drainCompletedAt) upgradeDrain.retireRestartRequest();
1433
+ if (request && (request.drainCompletedAt || (action === 'clear' && upgradeDrain.requestPredatesBoot(request, SCHEDULER_BOOTED_AT)))) upgradeDrain.retireRestartRequest();
1388
1434
  if (action === 'clear') await mutate((s) => { s.drain = null; });
1389
1435
  drainActive = action === 'keep';
1390
1436
  }
@@ -1716,6 +1762,7 @@ function normalizeConfig(cfg) {
1716
1762
  // currentAutoDispatchHold (state.config). The held-turns store's hold provider
1717
1763
  // reads it synchronously; undefined before the first read (DEFAULT_CONFIG applies).
1718
1764
  let lastSeenConfig;
1765
+ function _forgetLastSeenConfigForTests() { lastSeenConfig = undefined; }
1719
1766
 
1720
1767
  function readQueueSync() {
1721
1768
  const s = queueStore.readMergedSync();
@@ -2288,6 +2335,7 @@ async function reconcilePass(state) {
2288
2335
  effort: p.effort ?? job.effort ?? null,
2289
2336
  voiceId: p.voiceId ?? job.voiceId ?? null,
2290
2337
  preflight: p.preflight ?? null,
2338
+ planReview: p.planReview ?? null,
2291
2339
  };
2292
2340
  // Adopt path: a row parked 'quarantined' (no createdVia provenance when
2293
2341
  // discovered) whose PRD file now carries a stamp — written via the
@@ -2417,6 +2465,7 @@ async function reconcilePass(state) {
2417
2465
  effort: p.effort ?? inv.row?.effort ?? null,
2418
2466
  voiceId: p.voiceId ?? inv.row?.voiceId ?? null,
2419
2467
  preflight: p.preflight ?? null,
2468
+ planReview: p.planReview ?? null,
2420
2469
  };
2421
2470
  const reason = `reconcile: repaired invalid status ${JSON.stringify(oldStatus)}`;
2422
2471
  // A repair is not a lifecycle transition — the corrupted `status` was
@@ -2574,6 +2623,7 @@ async function reconcilePass(state) {
2574
2623
  effort: p.effort ?? null,
2575
2624
  voiceId: p.voiceId ?? null,
2576
2625
  preflight: p.preflight ?? null,
2626
+ planReview: p.planReview ?? null,
2577
2627
  status: 'pending',
2578
2628
  // Enqueue time (PRD 1086/1087): the cross-project fairness tiebreak and
2579
2629
  // the starvation escalation both need a provable age for a pending row;
@@ -2762,11 +2812,16 @@ let utilizationHold = null;
2762
2812
  let lastAutoDispatchHoldKey = null;
2763
2813
  // The auto-dispatch hold currently open in audit-log.jsonl (one
2764
2814
  // auto_dispatch_hold_started written, its _ended not yet): { holdKey, reason,
2765
- // window, threshold, resetsAt, startedAt, maxPercent, heldTicks, restored? },
2766
- // keyed by utilizationHold.holdIdentityKey so percent changes and reset jitter
2767
- // write nothing. Persisted in scheduler-state.json so a restart neither
2768
- // re-opens nor loses it (the heartbeat log keeps only ~18-37 h).
2815
+ // window, threshold, resetsAt, lastResetsAt, startedAt, maxPercent, heldTicks, restored? },
2816
+ // continued under continuesOpenHold (same reason + window, resetsAt within
2817
+ // 60 s of the last-seen resetsAt, not the opening one) so percent changes and
2818
+ // reset jitter write nothing. Persisted in scheduler-state.json so a restart
2819
+ // neither re-opens nor loses it (the heartbeat log keeps only ~15-37 h).
2769
2820
  let openAutoDispatchHold = null;
2821
+ // True when this process's immediately preceding tick found no auto-dispatch
2822
+ // hold: a hold opening now was seen to start (startObserved: true); one that
2823
+ // replaces another hold, or is in force on the first tick after boot, was not.
2824
+ let previousTickUnheld = false;
2770
2825
  // ms timestamp of the last FRESH reset observation (see recordObservedReset)
2771
2826
  // — distinct from Date.now(), so persistSchedulerState never re-stamps a
2772
2827
  // stale cachedNextReset as "just observed" on every poll cycle.
@@ -4270,6 +4325,13 @@ async function readStoredCriteriaChecks(cwd, epicId, slug) {
4270
4325
  * only bodyPath/bodyBytes/truncated. Fresh rows replace stored ones by id;
4271
4326
  * the exact-slug outcome record (when one exists) is updated in place.
4272
4327
  * Falls back to `stored` on any error. Never rejects.
4328
+ * @param {string} cwd
4329
+ * @param {string} epicId
4330
+ * @param {string} slug
4331
+ * @param {Record<string, unknown>[]} criteria
4332
+ * @param {Record<string, unknown>[]} stored
4333
+ * @param {{ httpRetry?: import('./lib/scheduler/criteriaChecks.cjs').HttpRetry }} [opts]
4334
+ * @returns {Promise<Record<string, unknown>[]>}
4273
4335
  */
4274
4336
  async function runDispatchCriteriaChecks(cwd, epicId, slug, criteria, stored, { httpRetry } = {}) {
4275
4337
  try {
@@ -4317,7 +4379,7 @@ async function runDispatchCriteriaChecks(cwd, epicId, slug, criteria, stored, {
4317
4379
  * checks only: no http request, no outcome record or body file write.
4318
4380
  * `httpRetry` overrides the dispatch retry defaults (tests only).
4319
4381
  * @param {any} job
4320
- * @param {{ runChecks?: boolean, httpRetry?: { attempts?: number, delayMs?: number } }} [opts]
4382
+ * @param {{ runChecks?: boolean, httpRetry?: import('./lib/scheduler/criteriaChecks.cjs').HttpRetry }} [opts]
4321
4383
  * @returns {Promise<{ expected: Record<string, { ids: string[], failedIds: string[] }>, section: string }>}
4322
4384
  */
4323
4385
  async function loadValidatorCriteriaContext(job, { runChecks = true, httpRetry } = {}) {
@@ -4549,6 +4611,8 @@ async function notifyOriginatingTab(job, {
4549
4611
  writeVerdictsFile = writeJsonAtomic,
4550
4612
  scheduleSettle = defaultScheduleSettle,
4551
4613
  loadValidatorCriteria = loadValidatorCriteriaContext,
4614
+ planReviewRows = undefined,
4615
+ planReviewStoreImpl = undefined,
4552
4616
  } = {}) {
4553
4617
  try {
4554
4618
  const prd = await resolveNotifyPrd(job, parsePrdRaw);
@@ -4729,6 +4793,9 @@ async function notifyOriginatingTab(job, {
4729
4793
  console.error('[scheduler] notifyOriginatingTab verdicts file write error', job?.slug, e);
4730
4794
  }
4731
4795
  }
4796
+ if (job.agentType === 'plan-reviewer' && (job.status === 'completed' || job.status === 'failed')) {
4797
+ await harvestPlanReview(job, epicId, logPath, { readStructured: readStructuredFromLog, sendPrompt, rows: planReviewRows, store: planReviewStoreImpl });
4798
+ }
4732
4799
  if (epicId) {
4733
4800
  // PRD 986: the check-in event is born validation:'unvalidated' — never
4734
4801
  // 'verified' — regardless of the job's self-reported outcome. The
@@ -4786,6 +4853,102 @@ async function notifyOriginatingTab(job, {
4786
4853
  }
4787
4854
  }
4788
4855
 
4856
+ /** Digest text for one harvested plan review (pure). */
4857
+ function buildPlanReviewDigest({ validateSlug, round, outcome, review, error }) {
4858
+ const head = `PLAN REVIEWED: ${validateSlug} (round ${round})`;
4859
+ if (outcome === 'failed') {
4860
+ return `${head}\nThe independent review failed (${error || 'no structured output'}) — the plan was released without review (review-failed). Its PRDs are free to dispatch.`;
4861
+ }
4862
+ if (outcome === 'ok') {
4863
+ return `${head}\nEvery PRD is ok and there are no plan findings — the plan was released automatically. Its PRDs are free to dispatch.`;
4864
+ }
4865
+ const lines = [head, 'The reviewer asks for changes before the PRDs dispatch.'];
4866
+ for (const p of review.prds) {
4867
+ lines.push('', `${p.prd}: ${p.decision}`);
4868
+ for (const f of p.findings) {
4869
+ lines.push(` - [${f.severity}] ${f.check}: ${f.text}`);
4870
+ if (f.suggestedEdit) lines.push(` suggested edit: ${f.suggestedEdit}`);
4871
+ }
4872
+ }
4873
+ if (review.planFindings.length) {
4874
+ lines.push('', 'Plan findings:');
4875
+ for (const f of review.planFindings) lines.push(` - [${f.severity}] ${f.check}: ${f.text}`);
4876
+ }
4877
+ lines.push('', 'Apply the suggested edits with scheduler_update_prd, then call scheduler_release_plan with a one-line reason for each finding you reject.');
4878
+ return lines.join('\n');
4879
+ }
4880
+
4881
+ /**
4882
+ * harvestPlanReview — a finished plan-reviewer job: parse its structured output,
4883
+ * save the round, auto-release an all-ok plan (an unusable review releases as
4884
+ * 'review-failed'), and send the planner's Epic ONE digest per (validateSlug,
4885
+ * round). The sent round is persisted in the record (`digestSent`) so a restart
4886
+ * does not resend. Never throws.
4887
+ */
4888
+ async function harvestPlanReview(job, epicId, logPath, deps = {}) {
4889
+ const store = deps.store || planReviewStore;
4890
+ try {
4891
+ if (!epicId || !job.cwd || !isSafeEpicId(epicId)) return;
4892
+ const m = /^plan-review-(.+?)(?:-r(\d+))?$/.exec(bareSlug(job.slug));
4893
+ if (!m) return;
4894
+ const round = m[2] ? Number(m[2]) : 1;
4895
+ const rows = (deps.rows || (await readQueue()).jobs || []);
4896
+ const validator = rows.find((r) => r && r.agentType === 'validator' && r.planReview === 'required'
4897
+ && bareSlug(r.slug) === m[1] && (!r.cwd || r.cwd === job.cwd));
4898
+ if (!validator) {
4899
+ console.error('[scheduler] harvestPlanReview: no validate row for', job.slug);
4900
+ return;
4901
+ }
4902
+ const validateSlug = validator.slug;
4903
+ const prior = store.readPlanReview(job.cwd, epicId, validateSlug);
4904
+ const sentBefore = prior && Array.isArray(prior.digestSent) ? prior.digestSent.slice() : [];
4905
+ if (sentBefore.includes(round)) return;
4906
+
4907
+ const members = planReviewHold.planMembers(validator, rows).map((r) => r.slug);
4908
+ let structured = null;
4909
+ try { structured = (deps.readStructured || extractStructuredOutputFromLog)(logPath); } catch { structured = null; }
4910
+ const checked = job.status === 'completed' && structured
4911
+ ? parsePlanReview(structured, { expected: members })
4912
+ : { ok: false, error: job.status === 'completed' ? 'no structured output' : `reviewer ${job.status}` };
4913
+
4914
+ let outcome;
4915
+ if (checked.ok) {
4916
+ await store.savePlanReviewResult({
4917
+ cwd: job.cwd, epicId, validateSlug, round, reviewer: job.slug,
4918
+ runId: job.runId || null, model: job.model || null, review: checked.value,
4919
+ });
4920
+ if (isAllOkPlanReview(checked.value)) {
4921
+ outcome = 'ok';
4922
+ await store.recordPlanRelease({ cwd: job.cwd, epicId, validateSlug, by: 'auto', accepted: 0 });
4923
+ } else {
4924
+ outcome = 'amend';
4925
+ }
4926
+ } else {
4927
+ outcome = 'failed';
4928
+ console.error(`[scheduler] harvestPlanReview: ${job.slug} review rejected — ${checked.error}`);
4929
+ await store.recordPlanRelease({
4930
+ cwd: job.cwd, epicId, validateSlug, by: 'timeout',
4931
+ rejected: [{ finding: 'plan-review', reason: 'review-failed' }],
4932
+ });
4933
+ }
4934
+
4935
+ // Persist the dedupe key (the store's own writes rebuild the record without it).
4936
+ const rec = store.readPlanReview(job.cwd, epicId, validateSlug);
4937
+ if (rec) {
4938
+ const file = store.planReviewPath(job.cwd, epicId, validateSlug);
4939
+ assertOpsWrite(file, 'scheduler');
4940
+ await writeJsonAtomic(file, { ...rec, digestSent: [...new Set([...sentBefore, round])] });
4941
+ }
4942
+ const text = buildPlanReviewDigest({
4943
+ validateSlug, round, outcome,
4944
+ review: checked.ok ? checked.value : null, error: checked.ok ? null : checked.error,
4945
+ });
4946
+ (deps.sendPrompt || enqueueExternalPrompt)(epicId, text, { origin: 'scheduler', heldKind: 'scheduler-notice' });
4947
+ } catch (e) {
4948
+ console.error('[scheduler] harvestPlanReview error', job?.slug, e);
4949
+ }
4950
+ }
4951
+
4789
4952
  // Single-flight guard for flushDueReviewNotices — same shape as
4790
4953
  // gateShadowPending above: a module-level flag rather than a class, so two
4791
4954
  // triggers landing close together (an auto-resolve skip right next to the
@@ -4955,9 +5118,11 @@ const TRANSIENT_RETRY_CAP = 2;
4955
5118
  * transient (PRD 543/545 incident) — same bounded-retry treatment, not a
4956
5119
  * second parallel classifier.
4957
5120
  */
4958
- function classifyFailureOutcome({ exitCode, networkError, durationMs, transientRetries, newlyDirtyCount, launchError }) {
5121
+ function classifyFailureOutcome({ exitCode, networkError, durationMs, transientRetries, newlyDirtyCount, launchError, environmentLimit }) {
4959
5122
  // The run never started (argv too large): not transient, not investigable.
4960
5123
  if (launchError) return { action: 'fail-launch', launchError };
5124
+ // The job sandbox refused the run: not a code bug, and an investigation would hit the same wall.
5125
+ if (environmentLimit) return { action: 'fail-environment', environmentLimit };
4961
5126
  const signalTransient = (exitCode === 143 || exitCode === 137) && durationMs < IDLE_OUTPUT_KILL_MS;
4962
5127
  const networkTransient = networkError === true;
4963
5128
  const transient = signalTransient || networkTransient;
@@ -5755,13 +5920,6 @@ const HEADLESS_DISALLOWED_TOOLS = Object.freeze([
5755
5920
  * and a large prompt failed with spawn E2BIG before the job started (the
5756
5921
  * 2026-10-26 incident). `claude -p` with no positional prompt reads stdin.
5757
5922
  */
5758
- // MCP servers whose definition the scheduler knows. Lazy require: avoids a
5759
- // load-order cycle with seedSchedulerMcp.cjs.
5760
- function knownMcpServers() {
5761
- const seed = require('./seedSchedulerMcp.cjs');
5762
- return { [seed.SERVER_NAME]: seed.schedulerServerEntry() };
5763
- }
5764
-
5765
5923
  /**
5766
5924
  * The CLI keeps only the LAST --settings value, and the job sandbox argv
5767
5925
  * already carries one inline JSON --settings. When it does, fold the
@@ -5812,7 +5970,7 @@ function jobRiskToolsClearance(prdRiskTools, personaTools) {
5812
5970
  return out;
5813
5971
  }
5814
5972
 
5815
- function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope, mcpServerNames = [], pluginDirArgs = [], jsonSchema = null, sandboxArgs = null, riskGuardSettingsPath = null }) {
5973
+ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope, mcpServerNames = [], pluginDirArgs = [], jsonSchema = null, sandboxArgs = null, riskGuardSettingsPath = null, skillDeny = [], knownServers }) {
5816
5974
  let permissionArgs = Array.isArray(sandboxArgs) && sandboxArgs.length ? sandboxArgs : ['--dangerously-skip-permissions'];
5817
5975
  let riskArgs = [];
5818
5976
  if (typeof riskGuardSettingsPath === 'string' && riskGuardSettingsPath) {
@@ -5827,13 +5985,14 @@ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt,
5827
5985
  ...(systemPrompt ? ['--append-system-prompt', systemPrompt] : []),
5828
5986
  // Always strict: exactly the persona's resolved servers (dispatch already
5829
5987
  // parked any job whose set names an unknown server — capability_unknown).
5830
- ...personaToolScopeArgs(toolScope, { mcpServers: knownMcpServers(), declaredServers: mcpServerNames }).args,
5988
+ ...personaToolScopeArgs(toolScope, { mcpServers: knownServers, declaredServers: mcpServerNames }).args,
5831
5989
  ...(Array.isArray(pluginDirArgs) ? pluginDirArgs : []),
5832
5990
  ...(jsonSchema && typeof jsonSchema === 'object' ? ['--json-schema', JSON.stringify(jsonSchema)] : []),
5833
5991
  ...riskArgs,
5834
5992
  ...permissionArgs,
5835
5993
  ...headlessPermissionArgs(),
5836
5994
  '--disallowedTools', HEADLESS_DISALLOWED_TOOLS.join(','),
5995
+ ...(Array.isArray(skillDeny) ? skillDeny : []),
5837
5996
  '--output-format', 'stream-json',
5838
5997
  '--verbose',
5839
5998
  ...(resume ? ['--resume', sessionId] : ['--session-id', sessionId]),
@@ -5938,11 +6097,20 @@ function ensureTimeoutShimOnce() {
5938
6097
  * @returns {Promise<{ refusal: null|{ code: string, detail: string }, systemPrompt?: string|null, model?: string, tools?: string[]|null, mcpServers?: string[], packs?: string[], personaPath?: string|null, agentSnapshotId?: string|null, pinned?: boolean }>}
5939
6098
  */
5940
6099
  async function resolveJobAgentSnapshot(job, cwd, packs) {
6100
+ let repinFrom = null;
6101
+ let pinnedSnap = null;
5941
6102
  if (typeof job.agentSnapshotId === 'string' && job.agentSnapshotId) {
5942
- const snap = await agentSnapshot.readAgentSnapshot(cwd, job.agentSnapshotId);
5943
- if (!snap) {
6103
+ pinnedSnap = await agentSnapshot.readAgentSnapshot(cwd, job.agentSnapshotId);
6104
+ if (!pinnedSnap) {
5944
6105
  return { refusal: { code: 'agent_snapshot_missing', detail: `pinned agent snapshot ${job.agentSnapshotId} is missing or does not match its id` } };
5945
6106
  }
6107
+ // An explicit persona change (the PRD's agentType moved) is an audited re-pin.
6108
+ if (pinnedSnap.name && pinnedSnap.name !== (job.agentType || DEFAULT_PRD_AGENT_TYPE)) {
6109
+ repinFrom = job.agentSnapshotId;
6110
+ }
6111
+ }
6112
+ if (pinnedSnap && !repinFrom) {
6113
+ const snap = pinnedSnap;
5946
6114
  return {
5947
6115
  refusal: null,
5948
6116
  systemPrompt: snap.body || null,
@@ -5950,6 +6118,7 @@ async function resolveJobAgentSnapshot(job, cwd, packs) {
5950
6118
  tools: Array.isArray(snap.tools) ? snap.tools : null,
5951
6119
  mcpServers: Array.isArray(snap.mcpServers) ? snap.mcpServers.map(String) : [],
5952
6120
  packs: Array.isArray(snap.packs) ? snap.packs.map(String) : [],
6121
+ loadout: typeof snap.loadout === 'string' ? snap.loadout : null,
5953
6122
  personaPath: null,
5954
6123
  agentSnapshotId: job.agentSnapshotId,
5955
6124
  pinned: true,
@@ -5978,6 +6147,7 @@ async function resolveJobAgentSnapshot(job, cwd, packs) {
5978
6147
  id = (await agentSnapshot.writeAgentSnapshot(cwd, snap)).id;
5979
6148
  job.agentSnapshotId = id;
5980
6149
  } catch (err) {
6150
+ if (repinFrom) job.agentSnapshotId = null;
5981
6151
  console.error(`[scheduler] agent snapshot write failed for ${job.slug} (spawning unpinned): ${err?.message ?? err}`);
5982
6152
  }
5983
6153
  return {
@@ -5987,9 +6157,11 @@ async function resolveJobAgentSnapshot(job, cwd, packs) {
5987
6157
  tools: snap.tools,
5988
6158
  mcpServers: snap.mcpServers,
5989
6159
  packs: snap.packs,
6160
+ loadout: typeof snap.loadout === 'string' ? snap.loadout : null,
5990
6161
  personaPath: null,
5991
6162
  agentSnapshotId: id,
5992
6163
  pinned: false,
6164
+ ...(repinFrom && id ? { repinned: { from: repinFrom, to: id, reason: 'agentType_changed' } } : {}),
5993
6165
  };
5994
6166
  }
5995
6167
 
@@ -6341,7 +6513,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6341
6513
  job.validatorCriteriaExpected = expected;
6342
6514
  if (section) prompt = `${prompt}\n\n${section}`;
6343
6515
  }
6344
- prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun, isFixPlan: resolveIsFixPlan(job.slug, job.isFixPlan), isArtifactOnly, isValidator: job.agentType === 'validator' }) });
6516
+ prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun, isFixPlan: resolveIsFixPlan(job.slug, job.isFixPlan), isArtifactOnly: isArtifactOnly || job.agentType === 'plan-reviewer', isValidator: job.agentType === 'validator', isPlanReviewer: job.agentType === 'plan-reviewer' }) });
6345
6517
 
6346
6518
  // Foreign-WIP manifest (starry-night-ships PRD 148 postmortem): the
6347
6519
  // scheduler already knows, at spawn time, which dirty paths this job did
@@ -6416,7 +6588,17 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6416
6588
  // Validator jobs (fresh and resume) return a schema-checked verdict:
6417
6589
  // --json-schema + StructuredOutput in scope (PRD 3613).
6418
6590
  const isValidator = job.agentType === 'validator';
6419
- const personaToolScope = buildPersonaToolScope(personaResolution.tools, { disallowed: HEADLESS_DISALLOWED_TOOLS, structuredOutput: isValidator });
6591
+ // Plan-reviewer jobs return a schema-checked review (PLAN_REVIEW_SCHEMA) on a
6592
+ // model that differs from the planner Epic's.
6593
+ const isPlanReviewer = job.agentType === 'plan-reviewer';
6594
+ let spawnModel = personaResolution.model;
6595
+ if (isPlanReviewer) {
6596
+ const plannerModel = (packEpic && typeof packEpic.model === 'string' && packEpic.model.trim())
6597
+ || readSettingsModel(cwd) || 'opus';
6598
+ spawnModel = planReviewHold.reviewerModelFor(personaResolution.model, plannerModel);
6599
+ job.model = spawnModel;
6600
+ }
6601
+ const personaToolScope = buildPersonaToolScope(personaResolution.tools, { loadout: personaResolution.loadout, disallowed: HEADLESS_DISALLOWED_TOOLS, structuredOutput: isValidator || isPlanReviewer });
6420
6602
  // Epic context packs (PRD 3154): the job's Epic's selected packs load as
6421
6603
  // --plugin-dir per pack, and their laws are appended AFTER the (already
6422
6604
  // capped) persona body — the persona cap never applies to laws. Fresh and
@@ -6439,19 +6621,37 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6439
6621
  } catch (err) {
6440
6622
  safeLog(`[scheduler] context packs skipped for ${job.slug}: ${err && err.message ? err.message : String(err)}\n`);
6441
6623
  }
6624
+ // Skills ride only inside packs: refuse every installed skill the persona's
6625
+ // packs (snapshot-pinned when pinned) do not carry.
6626
+ const skillDeny = await resolveSkillDeny({ packs: personaResolution.packs || [], loadout: personaResolution.loadout });
6627
+ safeLog(`[scheduler] skills=${skillDeny.denied} denied for ${job.slug}\n`);
6442
6628
  // Declared capabilities, fail-closed: an MCP server (declared or tool-named)
6443
- // missing from knownMcpServers(), or an unknown persona-declared pack,
6444
- // parks the job needs_review 'capability_unknown: <name>' — never spawned
6445
- // with a widened (every-server) config.
6446
- const capabilityCheck = personaToolScopeArgs(personaToolScope, {
6447
- mcpServers: knownMcpServers(),
6448
- declaredServers: personaResolution.mcpServers || [],
6449
- packs: unknownPacks ? personaPackIds : [],
6450
- knownPacks: unknownPacks ? personaPackIds.filter((p) => !unknownPacks.includes(p)) : [],
6451
- });
6452
- if (capabilityCheck.refusal) {
6453
- const code = capabilityCheck.refusal.code;
6454
- const detail = capabilityCheck.refusal.name;
6629
+ // missing from the resolved known map, or an unknown persona-declared pack,
6630
+ // parks the job needs_review 'capability_unknown: <name>'; a credential-bearing
6631
+ // one parks 'capability_credentialed'. Never spawned with a widened config.
6632
+ const mcpResolution = resolveHeadlessMcpServers({ cwd, projectRoot: job.cwd || defaultCwd });
6633
+ let capRefusal = null;
6634
+ for (const name of resolvedMcpServerNames(personaToolScope?.tools, personaResolution.mcpServers || [])) {
6635
+ if (Object.prototype.hasOwnProperty.call(mcpResolution.credentialed, name)) {
6636
+ capRefusal = { code: 'capability_credentialed', detail: mcpResolution.credentialed[name] };
6637
+ break;
6638
+ }
6639
+ }
6640
+ if (!capRefusal) {
6641
+ const capabilityCheck = personaToolScopeArgs(personaToolScope, {
6642
+ mcpServers: mcpResolution.known,
6643
+ declaredServers: personaResolution.mcpServers || [],
6644
+ packs: unknownPacks ? personaPackIds : [],
6645
+ knownPacks: unknownPacks ? personaPackIds.filter((p) => !unknownPacks.includes(p)) : [],
6646
+ });
6647
+ if (capabilityCheck.refusal) {
6648
+ const { code, name } = capabilityCheck.refusal;
6649
+ const isPack = Array.isArray(unknownPacks) && unknownPacks.includes(String(name));
6650
+ capRefusal = { code, detail: code === 'capability_unknown' && !isPack ? `${name} (MCP server not defined in ~/.claude.json, <project>/.mcp.json or the project's local scope)` : name };
6651
+ }
6652
+ }
6653
+ if (capRefusal) {
6654
+ const { code, detail } = capRefusal;
6455
6655
  const refusalError = `${code}: ${detail}`;
6456
6656
  safeLog(`[scheduler] capability refused for ${job.slug} — not spawned: ${refusalError}\n`);
6457
6657
  closeFd();
@@ -6461,7 +6661,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6461
6661
  const jobSystemPrompt = packArgs.laws
6462
6662
  ? (personaResolution.systemPrompt ? `${personaResolution.systemPrompt}\n\n${packArgs.laws}` : packArgs.laws)
6463
6663
  : personaResolution.systemPrompt;
6464
- safeLog(`[scheduler] agentType=${job.agentType || '(none)'} agentSnapshot=${personaResolution.agentSnapshotId || '(unpinned)'}${personaResolution.pinned ? ' (pinned)' : ''} persona=${personaResolution.personaPath || '(from snapshot)'} model=${personaResolution.model}${personaEffort ? ` effort=${personaEffort}${effortResolution.source === 'prd' ? ' (prd)' : ''}` : ''} ${personaToolScope ? `tools=${personaToolScope.tools.length} scoped` : 'tools=unscoped'}\n`);
6664
+ safeLog(`[scheduler] agentType=${job.agentType || '(none)'} agentSnapshot=${personaResolution.agentSnapshotId || '(unpinned)'}${personaResolution.pinned ? ' (pinned)' : ''}${personaResolution.repinned ? ` (re-pinned from ${personaResolution.repinned.from.slice(0, 8)}: agentType changed)` : ''} persona=${personaResolution.personaPath || '(from snapshot)'} model=${personaResolution.model}${personaEffort ? ` effort=${personaEffort}${effortResolution.source === 'prd' ? ' (prd)' : ''}` : ''} ${personaToolScope ? `tools=${personaToolScope.tools.length} scoped` : 'tools=unscoped'}\n`);
6465
6665
 
6466
6666
  // Authoritative guarantee that buildClaudeSpawnArgs (a pure sync helper,
6467
6667
  // called below via withChildAndLog) sees a resolved --permission-prompts
@@ -6765,7 +6965,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6765
6965
  `tmp=${sandboxTmpDir ?? 'none'}\n`);
6766
6966
  const jobArgs = buildClaudeSpawnArgs({
6767
6967
  sandboxArgs: sandboxPolicy.argv,
6768
- model: personaResolution.model,
6968
+ model: spawnModel,
6769
6969
  effort: personaEffort,
6770
6970
  sessionId,
6771
6971
  resume: !!resumeTarget,
@@ -6773,8 +6973,10 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6773
6973
  toolScope: personaToolScope,
6774
6974
  mcpServerNames: personaResolution.mcpServers || [],
6775
6975
  pluginDirArgs: packArgs.pluginDirArgs,
6776
- jsonSchema: isValidator ? VALIDATOR_VERDICT_SCHEMA : null,
6976
+ jsonSchema: isValidator ? VALIDATOR_VERDICT_SCHEMA : (isPlanReviewer ? PLAN_REVIEW_SCHEMA : null),
6777
6977
  riskGuardSettingsPath,
6978
+ skillDeny: skillDeny.args,
6979
+ knownServers: mcpResolution.known,
6778
6980
  });
6779
6981
  const jobSpawn = claudeSpawnTarget('job', job.slug, claudeBin, jobArgs);
6780
6982
 
@@ -6942,10 +7144,15 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6942
7144
  ...SCHEDULER_META_IDENTITY, ...setupMeta,
6943
7145
  originSessionId, contextDigestApplied,
6944
7146
  agentSnapshotId: personaResolution.agentSnapshotId || null,
7147
+ ...(personaResolution.repinned ? { agentSnapshotRepinned: personaResolution.repinned } : {}),
7148
+ ...(isPlanReviewer ? { agentType: 'plan-reviewer', model: spawnModel } : {}),
6945
7149
  });
6946
7150
  removeSandboxTmp();
7151
+ // Only the OS-sandboxed run can hit a sandbox refusal; stamped at finalize if the row ends failed/needs_review.
7152
+ const sandboxLimit = sandboxMeta.level === 'os-sandbox'
7153
+ ? sandboxLimitFromStreamJson(readTail(logPath, 16384)) : null;
6947
7154
  resolve({
6948
- exitCode: effectiveCode, durationMs, rateLimited, networkError, launchFailure: launchFailed, resultStats,
7155
+ exitCode: effectiveCode, durationMs, rateLimited, networkError, sandboxLimit, launchFailure: launchFailed, resultStats,
6949
7156
  leakedDescendants: leaked, sessionId, killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
6950
7157
  ...(memoryCapReason ? { error: memoryCapReason, memoryCapReason } : {}),
6951
7158
  });
@@ -7046,6 +7253,36 @@ function healTargetForFix(fixSlug, jobs) {
7046
7253
  return jobs.find((x) => x.slug === originalSlug && isPromotableOriginal(x.status) && !isCancelledRow(x)) || null;
7047
7254
  }
7048
7255
 
7256
+ /**
7257
+ * A fix plan succeeded for `orig`. An artifact-only parent (PRD declares
7258
+ * deliverable: artifact) is re-queued to pending for a fresh run, because
7259
+ * promoting it would mark it done without its record (4418: live probe never
7260
+ * re-run, artifactEvidence stayed ok:false). Any other parent is promoted to
7261
+ * completed as before. Returns 'requeued' | 'completed' | 'skipped'
7262
+ * ('skipped' = already re-queued once for this fix plan; a repeat boot pass
7263
+ * must not loop the parent back to pending after it failed again).
7264
+ */
7265
+ function applyFixSuccessToOriginal(orig, fixSlug, { promoteReason, promoteSource, requeueSource }) {
7266
+ if (orig.deliverable === 'artifact') {
7267
+ if (orig.requeuedByFix === fixSlug) return 'skipped';
7268
+ const ok = resetJobFields(orig, `requeued: fix plan ${fixSlug} succeeded`, { source: requeueSource });
7269
+ if (ok) {
7270
+ orig.error = null; // the reason lives on the transition, not as a row error
7271
+ orig.requeuedByFix = fixSlug;
7272
+ delete orig.completedBy;
7273
+ delete orig.looksDone;
7274
+ return 'requeued';
7275
+ }
7276
+ return 'skipped';
7277
+ }
7278
+ transitionJob(orig, 'completed', { reason: promoteReason, source: promoteSource });
7279
+ orig.exitCode = 0;
7280
+ orig.error = null;
7281
+ orig.completedBy = fixSlug;
7282
+ delete orig.looksDone;
7283
+ return 'completed';
7284
+ }
7285
+
7049
7286
  /**
7050
7287
  * Build the Opus investigation prompt. Pure/hermetic so its content can be
7051
7288
  * unit-tested (no spawn, no fs). Inputs are the already-resolved values that
@@ -8008,6 +8245,159 @@ async function recordInterruptLeftovers(slug, runId, { dirtyPaths, salvagePatch
8008
8245
  }
8009
8246
  }
8010
8247
 
8248
+ const PLAN_REVIEW_HELD_PREFIX = 'held: plan-review';
8249
+ const planReviewTimeoutNoticesSent = new Set();
8250
+
8251
+ /** Parse one member PRD's text into the shape buildPlanReviewInput expects. */
8252
+ function planReviewMemberFromPrd(row, text, prdPath) {
8253
+ let fm = {};
8254
+ let body = String(text || '');
8255
+ try { const p = parsePrdFile(body); fm = p.frontmatter || {}; body = p.body || ''; } catch { /* keep raw */ }
8256
+ const section = (name) => {
8257
+ const m = body.match(new RegExp(`^#{1,3}\\s*${name}[^\\n]*\\n([\\s\\S]*?)(?=^#{1,3}\\s|(?![\\s\\S]))`, 'im'));
8258
+ return m ? m[1] : '';
8259
+ };
8260
+ const bullets = (txt) => txt.split('\n').map((l) => l.match(/^\s*(?:[-*]|\d+\.)\s+(?:\[[ xX]\]\s+)?(.*\S)\s*$/)?.[1]).filter(Boolean);
8261
+ const gateTxt = section('Gate');
8262
+ const gate = (gateTxt.match(/```[^\n]*\n([\s\S]*?)```/)?.[1] || '').split('\n').map((l) => l.trim()).filter(Boolean);
8263
+ return {
8264
+ slug: row.slug,
8265
+ title: fm.title || row.title || '',
8266
+ prdPath: prdPath || `${row.slug}.md`,
8267
+ goal: section('Goal').trim().split('\n')[0] || '',
8268
+ acceptanceCriteria: bullets(section('Acceptance criteria')),
8269
+ files: bullets(section('Files')).map((f) => f.replace(/^`|`$/g, '')),
8270
+ gate,
8271
+ dependsOn: Array.isArray(row.dependsOn) ? row.dependsOn : [],
8272
+ };
8273
+ }
8274
+
8275
+ /**
8276
+ * Per-tick plan-review orchestration. Merges computePlanReviewHolds into the
8277
+ * returned held Map, creates each missing plan-review PRD once (idempotent by
8278
+ * slug), and releases + notifies on timeout. Pending member rows carry
8279
+ * `heldReason` ('held: plan-review …') so epic settle and starvation see a known
8280
+ * wait; the field is cleared when the hold ends. Never throws.
8281
+ * deps: { now, holdMs, readReview, createPrd, recordRelease, notify, gitHead, readPrdTexts, audit, mutateRows }
8282
+ */
8283
+ async function applyPlanReviewHolds(state, deps = {}) {
8284
+ const held = new Map();
8285
+ try {
8286
+ const rows = state.jobs || [];
8287
+ const now = deps.now ?? Date.now();
8288
+ const holdMs = deps.holdMs ?? planReviewHold.holdMsFromEnv();
8289
+ const readReview = deps.readReview || ((cwd, epicId, slug) => planReviewStore.readPlanReview(cwd, epicId, slug));
8290
+ const createPrd = deps.createPrd || ((input) => prdCreate.createPrd(input, remote, { internalMint: true }));
8291
+ const recordRelease = deps.recordRelease || ((a) => planReviewStore.recordPlanRelease(a));
8292
+ const notify = deps.notify || ((cwd, epicId, text, extra) => appendResponseEventIfKnown(cwd, epicId, text, extra));
8293
+ const gitHead = deps.gitHead || (async (cwd) => { try { return String(await execGitAt(cwd, ['rev-parse', 'HEAD'])).trim() || null; } catch { return null; } });
8294
+ const readPrdTexts = deps.readPrdTexts || ((cwd, epicId, slugs) => prdPaths.readEpicPrdTexts(cwd, epicId, slugs));
8295
+ const audit = deps.audit || ((k, d) => { try { appendAuditEvent(k, d); } catch { /* audit never breaks dispatch */ } });
8296
+ const readEpicGoal = deps.readEpicGoal || ((cwd, epicId) => {
8297
+ try {
8298
+ const sessions = readActiveIndex(cwd).sessions;
8299
+ const sess = sessions && Object.prototype.hasOwnProperty.call(sessions, epicId) ? sessions[epicId] : null;
8300
+ const t = sess && typeof sess.goalText === 'string' ? sess.goalText.trim() : '';
8301
+ return t;
8302
+ } catch { return ''; }
8303
+ });
8304
+ const resolvePrdPath = deps.resolvePrdPath || (async (m, cwd, epicId) => {
8305
+ try {
8306
+ const dir = await prdPaths.findPrdDirForJob({ ...m, cwd: m.cwd || cwd, epicId: m.epicId || epicId });
8307
+ if (dir) return path.join(dir, `${m.slug}.md`);
8308
+ } catch { /* fall through to the canonical live path */ }
8309
+ return opsPath(cwd, 'scheduler', 'epics', epicId, 'prds', `${m.slug}.md`);
8310
+ });
8311
+ const heldReasons = new Map();
8312
+
8313
+ const reviews = {};
8314
+ const validators = rows.filter((r) => r && r.status === 'pending' && r.agentType === 'validator' && r.planReview === 'required');
8315
+ for (const v of validators) {
8316
+ const epicId = v.sourcePromptId || v.epicId;
8317
+ if (!epicId || !v.cwd) continue;
8318
+ const rec = readReview(v.cwd, epicId, v.slug);
8319
+ if (rec) reviews[bareSlug(v.slug)] = { ...rec, released: !!rec.release || rec.released === true };
8320
+ }
8321
+ const { held: holds, needsReview, expired } = planReviewHold.computePlanReviewHolds(rows, reviews, { now, holdMs });
8322
+ const expiredSet = new Set(expired);
8323
+ const byVSlug = new Map(validators.map((v) => [v.slug, v]));
8324
+
8325
+ // Expired plans release by timeout; their members are not held this tick.
8326
+ const releasedMembers = new Set();
8327
+ for (const vslug of expired) {
8328
+ const v = byVSlug.get(vslug);
8329
+ if (!v) continue;
8330
+ const epicId = v.sourcePromptId || v.epicId;
8331
+ const members = planReviewHold.planMembers(v, rows);
8332
+ try {
8333
+ const out = await recordRelease({ cwd: v.cwd, epicId, validateSlug: v.slug, by: 'timeout' });
8334
+ for (const m of members) releasedMembers.add(m.slug);
8335
+ if (!out || !out.alreadyReleased) {
8336
+ audit('plan_review_timeout', { validateSlug: v.slug, epicId, holdMs });
8337
+ const key = `${epicId}:${v.slug}`;
8338
+ if (!planReviewTimeoutNoticesSent.has(key)) {
8339
+ planReviewTimeoutNoticesSent.add(key);
8340
+ await notify(v.cwd, epicId, `PLAN REVIEW TIMED OUT — released without review. Plan ${bareSlug(v.slug)} waited ${Math.round(holdMs / 60000)} minutes for its independent review; its PRDs are now free to dispatch.`, { prdSlug: v.slug, validation: 'unvalidated', notice: 'plan-review-timeout', allowInactive: true });
8341
+ }
8342
+ }
8343
+ } catch (e) {
8344
+ console.error('[scheduler] plan review timeout release failed', vslug, e?.message || e);
8345
+ }
8346
+ }
8347
+ for (const [slug, why] of holds) {
8348
+ if (releasedMembers.has(slug)) continue;
8349
+ held.set(slug, why);
8350
+ heldReasons.set(slug, why);
8351
+ }
8352
+
8353
+ // Create the review PRD for plans that have none yet (round 1), and r2 on request.
8354
+ const wanted = [];
8355
+ for (const vslug of needsReview) if (!expiredSet.has(vslug)) wanted.push({ vslug, round: 1 });
8356
+ for (const v of validators) {
8357
+ const rec = reviews[bareSlug(v.slug)];
8358
+ if (rec && rec.rereviewRequested === true && !rec.release && !expiredSet.has(v.slug)) wanted.push({ vslug: v.slug, round: 2 });
8359
+ }
8360
+ for (const { vslug, round } of wanted) {
8361
+ const v = byVSlug.get(vslug);
8362
+ if (!v) continue;
8363
+ const epicId = v.sourcePromptId || v.epicId;
8364
+ const reviewSlug = `plan-review-${bareSlug(vslug)}${round >= 2 ? `-r${round}` : ''}`;
8365
+ if (rows.some((r) => r && bareSlug(r.slug) === reviewSlug)) continue;
8366
+ try {
8367
+ const memberRows = planReviewHold.planMembers(v, rows);
8368
+ const texts = await readPrdTexts(v.cwd, epicId, memberRows.map((m) => m.slug));
8369
+ const members = [];
8370
+ for (const m of memberRows) members.push(planReviewMemberFromPrd(m, texts.get(m.slug), await resolvePrdPath(m, v.cwd, epicId)));
8371
+ const epicGoal = String((await readEpicGoal(v.cwd, epicId)) || '');
8372
+ const baseSha = await gitHead(v.cwd);
8373
+ const input = buildPlanReviewInput({ epicId, cwd: v.cwd, epicGoal, validateSlug: v.slug, members, baseSha, round });
8374
+ const res = await createPrd(input);
8375
+ if (res && res.ok === false) console.warn('[scheduler] plan review PRD not created', reviewSlug, res.error || res.reason || '');
8376
+ } catch (e) {
8377
+ console.error('[scheduler] plan review PRD create failed', reviewSlug, e?.message || e);
8378
+ }
8379
+ }
8380
+
8381
+ // Stamp / clear heldReason on pending rows so settle + starvation see a known wait.
8382
+ const mutateRows = deps.mutateRows || ((fn) => mutate((s) => fn(s.jobs)));
8383
+ const dirty = rows.some((r) => r && r.status === 'pending' && (
8384
+ (heldReasons.has(r.slug) && !r.preflightHold && r.heldReason !== heldReasons.get(r.slug))
8385
+ || (!heldReasons.has(r.slug) && typeof r.heldReason === 'string' && r.heldReason.startsWith(PLAN_REVIEW_HELD_PREFIX))));
8386
+ if (dirty) {
8387
+ await mutateRows((list) => {
8388
+ for (const r of list) {
8389
+ if (!r || r.status !== 'pending') continue;
8390
+ if (heldReasons.has(r.slug) && !r.preflightHold) r.heldReason = heldReasons.get(r.slug);
8391
+ else if (typeof r.heldReason === 'string' && r.heldReason.startsWith(PLAN_REVIEW_HELD_PREFIX)) delete r.heldReason;
8392
+ }
8393
+ });
8394
+ }
8395
+ } catch (e) {
8396
+ console.error('[scheduler] applyPlanReviewHolds error', e?.message || e);
8397
+ }
8398
+ return held;
8399
+ }
8400
+
8011
8401
  function computePreflightHolds(jobs, now = Date.now()) {
8012
8402
  const held = new Map();
8013
8403
  for (const j of jobs || []) {
@@ -9494,6 +9884,13 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9494
9884
  // attribute" via its Array.isArray guard, same as an empty array.
9495
9885
  applyLeftoverFields(s.jobs[i2], newlyDirtyAll);
9496
9886
 
9887
+ const envStamp = environmentLimitStamp(res.sandboxLimit, effectiveStatus);
9888
+ if (envStamp.environmentLimit) {
9889
+ s.jobs[i2].environmentLimit = envStamp.environmentLimit;
9890
+ s.jobs[i2].error = envStamp.error;
9891
+ } else {
9892
+ delete s.jobs[i2].environmentLimit;
9893
+ }
9497
9894
  if (effectiveStatus === 'completed' || effectiveStatus === 'failed' || effectiveStatus === 'needs_review') {
9498
9895
  outcomeRecordSnapshot = { ...s.jobs[i2] };
9499
9896
  }
@@ -9597,16 +9994,18 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9597
9994
  const orig = healTargetForFix(job.slug, s.jobs);
9598
9995
  if (orig) {
9599
9996
  const priorStatus = orig.status;
9600
- console.log(`[scheduler] auto-promote: ${orig.slug} (${priorStatus}) → completed because ${job.slug} succeeded`);
9601
- transitionJob(orig, 'completed', { reason: `auto-promoted: fix plan ${job.slug} succeeded`, source: 'spawnJob:auto-promote' });
9602
- orig.exitCode = 0;
9603
- orig.error = null;
9604
- orig.completedBy = job.slug;
9605
- delete orig.looksDone;
9606
- if (priorStatus === 'needs_review') {
9607
- delete orig.verifierVerdict;
9997
+ const outcome = applyFixSuccessToOriginal(orig, job.slug, {
9998
+ promoteReason: `auto-promoted: fix plan ${job.slug} succeeded`,
9999
+ promoteSource: 'spawnJob:auto-promote',
10000
+ requeueSource: 'spawnJob:auto-promote',
10001
+ });
10002
+ console.log(`[scheduler] auto-promote: ${orig.slug} (${priorStatus}) → ${outcome} because ${job.slug} succeeded`);
10003
+ if (outcome === 'completed') {
10004
+ if (priorStatus === 'needs_review') {
10005
+ delete orig.verifierVerdict;
10006
+ }
10007
+ newlyCompletedPrds.push({ slug: orig.slug, cwd: orig.cwd });
9608
10008
  }
9609
- newlyCompletedPrds.push({ slug: orig.slug, cwd: orig.cwd });
9610
10009
  }
9611
10010
  }
9612
10011
  }
@@ -9756,6 +10155,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9756
10155
  transientRetries: retries,
9757
10156
  newlyDirtyCount,
9758
10157
  launchError: res.launchError,
10158
+ environmentLimit: failedJobSnapshot.environmentLimit,
9759
10159
  });
9760
10160
 
9761
10161
  if (decision.action === 'fail-launch') {
@@ -9767,6 +10167,13 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9767
10167
  }
9768
10168
  });
9769
10169
  await broadcast({ flush: true });
10170
+ } else if (decision.action === 'fail-environment') {
10171
+ console.log(`[scheduler] environment limit (${decision.environmentLimit.kind}) for ${job.slug} — no investigation`);
10172
+ await mutate((s) => {
10173
+ const i = s.jobs.findIndex((x) => x.slug === job.slug);
10174
+ if (i >= 0) s.jobs[i].error = ENVIRONMENT_LIMIT_MESSAGE;
10175
+ });
10176
+ await broadcast({ flush: true });
9770
10177
  } else if (decision.action === 'retry') {
9771
10178
  console.log(`[scheduler] transient failure (${decision.transientKind} dur=${res.durationMs}ms) — auto-retry ${decision.retries + 1}/${TRANSIENT_RETRY_CAP} for ${job.slug}`);
9772
10179
  await mutate((s) => {
@@ -9972,7 +10379,9 @@ function holdAuditFields(hold) {
9972
10379
  threshold: hold.threshold ?? null,
9973
10380
  baseThreshold: hold.baseThreshold ?? null,
9974
10381
  resetsAt: hold.resetsAt ?? null,
9975
- holdKey: autoDispatchHold.holdIdentityKey(hold),
10382
+ holdKey: openAutoDispatchHold && continuesOpenHold(openAutoDispatchHold, hold)
10383
+ ? openAutoDispatchHold.holdKey
10384
+ : autoDispatchHold.holdIdentityKey(hold),
9976
10385
  };
9977
10386
  }
9978
10387
 
@@ -9984,8 +10393,12 @@ function holdAuditFields(hold) {
9984
10393
  */
9985
10394
  async function auditHumanPress(press) {
9986
10395
  try {
10396
+ // lastSeenConfig is refreshed by every queue read/write; only a press before
10397
+ // the first read pays for a queue read just to audit itself.
9987
10398
  let config = lastSeenConfig;
9988
- try { config = (await readQueue()).config; } catch { /* last seen config */ }
10399
+ if (config == null) {
10400
+ try { config = (await readQueue()).config; } catch { /* DEFAULT_CONFIG applies */ }
10401
+ }
9989
10402
  appendAuditEvent('scheduler_human_press', { press, hold: holdAuditFields(currentAutoDispatchHold(config)) });
9990
10403
  } catch (e) {
9991
10404
  console.error('[scheduler] human press audit failed', e?.message ?? String(e));
@@ -10352,7 +10765,9 @@ async function tickBody(gen, { bypassLoadGate, lastResort, human = false }) {
10352
10765
  const pendingCount = hold || openAutoDispatchHold
10353
10766
  ? state.jobs.filter((j) => j.status === 'pending' && !runningSet.has(j.slug)).length
10354
10767
  : 0;
10355
- if (hold || openAutoDispatchHold) trackAutoDispatchHoldAudit(hold, pendingCount);
10768
+ const startObserved = previousTickUnheld;
10769
+ previousTickUnheld = hold == null;
10770
+ if (hold || openAutoDispatchHold) trackAutoDispatchHoldAudit(hold, pendingCount, startObserved);
10356
10771
  if (hold) {
10357
10772
  if (human) {
10358
10773
  bypassedHold = hold;
@@ -10377,6 +10792,10 @@ async function tickBody(gen, { bypassLoadGate, lastResort, human = false }) {
10377
10792
  const heldSlugs = await computeLaunchHolds(state);
10378
10793
  for (const [slug, why] of computePreflightHolds(state.jobs)) if (!heldSlugs.has(slug)) heldSlugs.set(slug, why);
10379
10794
  for (const [slug, why] of computeInterruptHolds(state.jobs)) if (!heldSlugs.has(slug)) heldSlugs.set(slug, why);
10795
+ if (planReviewHold.planReviewEnabled()) {
10796
+ const prHeld = await applyPlanReviewHolds(state, {});
10797
+ for (const [slug, why] of prHeld) if (!heldSlugs.has(slug)) heldSlugs.set(slug, why);
10798
+ }
10380
10799
  if (stale()) return STALE_TICK;
10381
10800
  const satisfiedSlugsByCwd = await budget.computeDepHistorySatisfaction(state);
10382
10801
  lastSatisfiedSlugsByCwd = satisfiedSlugsByCwd;
@@ -10825,6 +11244,10 @@ function projectRowsFor(jobs, cwd) {
10825
11244
  * root — the scheduler re-checks those on its own backoff, so the project is
10826
11245
  * waiting on a precondition, not starved.
10827
11246
  */
11247
+ function isPlanReviewHeldRow(j) {
11248
+ return !!j && j.status === 'pending' && typeof j.heldReason === 'string' && j.heldReason.startsWith(PLAN_REVIEW_HELD_PREFIX);
11249
+ }
11250
+
10828
11251
  function starveRootFor(projectRows, oldestPendingSlug = null) {
10829
11252
  const roots = starvation.rootBlockersForProject(projectRows);
10830
11253
  const root = roots.find((r) => r.heldSlugs.includes(oldestPendingSlug)) ?? roots[0] ?? null;
@@ -10832,7 +11255,16 @@ function starveRootFor(projectRows, oldestPendingSlug = null) {
10832
11255
  if (roots.length > 0 && roots.every((r) => r.preflightHeld)) {
10833
11256
  const waiting = new Set(roots.flatMap((r) => r.heldSlugs));
10834
11257
  for (const r of roots) waiting.add(r.slug);
10835
- knownWait = projectRows.every((j) => j.status !== 'pending' || waiting.has(j.slug) || (j.preflightHold && typeof j.preflightHold === 'object'));
11258
+ knownWait = projectRows.every((j) => j.status !== 'pending' || waiting.has(j.slug) || (j.preflightHold && typeof j.preflightHold === 'object') || isPlanReviewHeldRow(j));
11259
+ }
11260
+ // Every pending row is waiting on an independent plan review (or behind one that is).
11261
+ if (!knownWait) {
11262
+ const pending = projectRows.filter((j) => j.status === 'pending');
11263
+ if (pending.some(isPlanReviewHeldRow)) {
11264
+ const waiting = new Set(roots.flatMap((r) => [r.slug, ...r.heldSlugs]));
11265
+ knownWait = roots.every((r) => r.preflightHeld || isPlanReviewHeldRow(projectRows.find((j) => j.slug === r.slug)))
11266
+ && pending.every((j) => isPlanReviewHeldRow(j) || waiting.has(j.slug) || (j.preflightHold && typeof j.preflightHold === 'object'));
11267
+ }
10836
11268
  }
10837
11269
  return { root, knownWait };
10838
11270
  }
@@ -12435,6 +12867,8 @@ async function runGateShadow(job) {
12435
12867
  // still complete when every HEAD failure already failed at the job's base
12436
12868
  // commit. The base run is memoized per HEAD on gateShadow.baseline.
12437
12869
  let baselineDecision = null;
12870
+ const runId = job.runId || reviewLadder.resolveRunId(job);
12871
+ const verdictsPath = runId ? path.join(schedulerPaths.runsDir(), runId, `${job.slug}.verdicts.json`) : null;
12438
12872
  if (
12439
12873
  job.verifierVerdict === 'sentinel_fail'
12440
12874
  && outcome.status === 'red' && definitive
@@ -12481,21 +12915,19 @@ async function runGateShadow(job) {
12481
12915
  try { await execGitAt(job.cwd, ['worktree', 'prune'], { timeout: 30_000 }); } catch { /* best-effort */ }
12482
12916
  }
12483
12917
  }
12484
- baselineDecision = decideBaselineAuthority({ job, headOutcome: outcome, baseOutcome, evidenceOk, ancestorOk, cleanOk, headStable });
12918
+ // The run's recorded FAIL reason (read-only; runVerify owns the sidecar).
12919
+ const sidecar = verdictsPath ? readJsonOrSync(verdictsPath, null) : null;
12920
+ const failReason = sidecar && typeof sidecar.reason === 'string' ? sidecar.reason : '';
12921
+ baselineDecision = decideBaselineAuthority({ job, headOutcome: outcome, baseOutcome, evidenceOk, ancestorOk, cleanOk, headStable, failReason });
12485
12922
  gateShadow.baseline = { head: headBefore, base: job.guardHeadBefore, outcome: baseOutcome, setup: baseSetup, ...baselineDecision };
12486
12923
  }
12487
12924
 
12488
- const runId = job.runId || reviewLadder.resolveRunId(job);
12489
- if (runId) {
12490
- const verdictsPath = path.join(schedulerPaths.runsDir(), runId, `${job.slug}.verdicts.json`);
12491
- // Read-merge (single-writer law: runVerify owns the sidecar's other keys).
12492
- // Only merge into an existing run dir — never conjure one.
12493
- if (fs.existsSync(path.dirname(verdictsPath))) {
12494
- let existing = {};
12495
- try { existing = JSON.parse(fs.readFileSync(verdictsPath, 'utf8')) || {}; } catch { /* absent/unparseable → fresh */ }
12496
- const criteriaRecord = gateShadow.criteriaChecks ? { criteriaChecks: { head: headBefore, ranAt: gateShadow.ranAt, results: gateShadow.criteriaChecks } } : {};
12497
- try { config.writeJsonSync(verdictsPath, { ...existing, gateShadow, ...criteriaRecord }); } catch { /* best-effort */ }
12498
- }
12925
+ // Read-merge (single-writer law: runVerify owns the sidecar's other keys).
12926
+ // Only merge into an existing run dir — never conjure one.
12927
+ if (verdictsPath && fs.existsSync(path.dirname(verdictsPath))) {
12928
+ const existing = readJsonOrSync(verdictsPath, {}) || {}; // absent/unparseable → fresh
12929
+ const criteriaRecord = gateShadow.criteriaChecks ? { criteriaChecks: { head: headBefore, ranAt: gateShadow.ranAt, results: gateShadow.criteriaChecks } } : {};
12930
+ try { config.writeJsonSync(verdictsPath, { ...existing, gateShadow, ...criteriaRecord }); } catch { /* best-effort */ }
12499
12931
  }
12500
12932
 
12501
12933
  const headShort = headBefore ? headBefore.slice(0, 7) : 'unknown';
@@ -12959,14 +13391,17 @@ async function reverifyNeedsReview() {
12959
13391
  const orig = healTargetForFix(job.slug, s.jobs);
12960
13392
  if (!orig) continue;
12961
13393
  const priorStatus = orig.status;
12962
- transitionJob(orig, 'completed', { reason: `auto-promoted: fix plan ${job.slug} already completed`, source: 'reverifyNeedsReview:auto-promote' });
12963
- orig.exitCode = 0;
12964
- orig.error = null;
12965
- orig.completedBy = job.slug;
12966
- delete orig.looksDone;
12967
- if (priorStatus === 'needs_review') delete orig.verifierVerdict;
12968
- promoted.push(`${orig.slug} (was ${priorStatus}, via ${job.slug})`);
12969
- promotedPrds.push({ slug: orig.slug, cwd: orig.cwd });
13394
+ const outcome = applyFixSuccessToOriginal(orig, job.slug, {
13395
+ promoteReason: `auto-promoted: fix plan ${job.slug} already completed`,
13396
+ promoteSource: 'reverifyNeedsReview:auto-promote',
13397
+ requeueSource: 'reverifyNeedsReview:auto-promote',
13398
+ });
13399
+ if (outcome === 'skipped') continue;
13400
+ if (outcome === 'completed') {
13401
+ if (priorStatus === 'needs_review') delete orig.verifierVerdict;
13402
+ promotedPrds.push({ slug: orig.slug, cwd: orig.cwd });
13403
+ }
13404
+ promoted.push(`${orig.slug} (was ${priorStatus}, ${outcome} via ${job.slug})`);
12970
13405
  }
12971
13406
  });
12972
13407
  for (const { slug, cwd } of promotedPrds) {
@@ -14729,6 +15164,12 @@ const remote = {
14729
15164
  try {
14730
15165
  await config.writeTextAtomic(filePath, newRaw, { writer: 'scheduler' });
14731
15166
  const stat = await fsp.stat(filePath);
15167
+ try {
15168
+ patchWarnings = patchWarnings.concat(mcpReachWarnings(
15169
+ { agentType: fm.agentType, riskTools: fm.riskTools, cwd: fm.cwd || cwd },
15170
+ prdCreate.mcpReachDeps,
15171
+ ));
15172
+ } catch { /* advisory only — never fails the update */ }
14732
15173
  return patchWarnings.length
14733
15174
  ? { ok: true, slug, bytesWritten: stat.size, warnings: patchWarnings }
14734
15175
  : { ok: true, slug, bytesWritten: stat.size };
@@ -15129,6 +15570,8 @@ queueOps.bindQueueAccess({
15129
15570
 
15130
15571
  module.exports = {
15131
15572
  PARK_ERRORS,
15573
+ applyPlanReviewHolds,
15574
+ starveRootFor,
15132
15575
  rescanArtifactEvidence,
15133
15576
  harvestJobArtifacts,
15134
15577
  jobArtifactRunId,
@@ -15171,7 +15614,9 @@ module.exports = {
15171
15614
  getSchedulerStateSnapshot,
15172
15615
  _getOpenAutoDispatchHoldForTests,
15173
15616
  _auditHumanPressForTests: auditHumanPress,
15617
+ _forgetLastSeenConfigForTests,
15174
15618
  _forgetOpenAutoDispatchHoldForTests,
15619
+ _resetPreviousTickUnheldForTests,
15175
15620
  computeDegradedBudget,
15176
15621
  utilizationReading,
15177
15622
  usageHoldThreshold,
@@ -15218,6 +15663,7 @@ module.exports = {
15218
15663
  isPromotableOriginal,
15219
15664
  applyRcaClassification,
15220
15665
  healTargetForFix,
15666
+ applyFixSuccessToOriginal,
15221
15667
  buildInvestigationPrompt,
15222
15668
  readRunOutcomeSidecars,
15223
15669
  isFixPlanSlug,
@@ -15320,6 +15766,14 @@ module.exports = {
15320
15766
  validateForeignWipBlockClaim,
15321
15767
  requeueForeignWipBlockedJobs,
15322
15768
  __test: { bindingWindowPauseThreshold },
15769
+ // Test-only seams (schedulerPlanRecordHarvest.test.cjs).
15770
+ __jobDeclaredArtifactPaths: jobDeclaredArtifactPaths,
15771
+ __harvestJobPlanRecords: harvestJobPlanRecords,
15772
+ __driveUpgradeDrain: driveUpgradeDrain,
15773
+ __clearStaleDrainAtBoot: clearStaleDrainAtBoot,
15774
+ __getDrainActive: () => drainActive,
15775
+ __setDrainActiveForTests: (v) => { drainActive = Boolean(v); },
15776
+ __setRestartHandlerForTests: setRestartHandler,
15323
15777
  };
15324
15778
 
15325
15779
  // Lazy path getters: resolved from SM_SCHEDULER_HOME at each read, never frozen