claude-code-session-manager 0.143.0 → 0.145.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 (128) hide show
  1. package/README.md +3 -1
  2. package/dist/assets/AppSettings-BR5b6oof.js +2 -0
  3. package/dist/assets/{History-DTttbvPb.js → History-B4U0mCdK.js} +2 -2
  4. package/dist/assets/HomeClaudeConfig-DQqG7lFE.js +5 -0
  5. package/dist/assets/{Panel-B_D4Bg7L.js → Panel-CwsOJ0nI.js} +1 -1
  6. package/dist/assets/ProjectClaudeConfig-BzRowu8x.js +26 -0
  7. package/dist/assets/Scheduler-dr7CNOcL.js +16 -0
  8. package/dist/assets/{SkillReferenceGraph-D1b2aiol.js → SkillReferenceGraph-CroBPY4C.js} +1 -1
  9. package/dist/assets/{Skills-cfV7sgk6.js → Skills-BiW2lCnD.js} +23 -23
  10. package/dist/assets/{TiptapBody-DVXtEIVy.js → TiptapBody-CYTkQiva.js} +27 -27
  11. package/dist/assets/{Toggle-CYajnSdx.js → Toggle-WFBYo8JI.js} +1 -1
  12. package/dist/assets/{VoiceButton-DJ4gGRuE.js → VoiceButton-DZu8dTpO.js} +1 -1
  13. package/dist/assets/{historyTotals-D3MoHY2U.js → historyTotals-B7KeXLSE.js} +1 -1
  14. package/dist/assets/{index-DVHIHoJf.css → index-BJ5TJvmz.css} +1 -1
  15. package/dist/assets/{index-CdTppjKR.js → index-hXRNm0UJ.js} +698 -697
  16. package/dist/index.html +2 -2
  17. package/dist-web/app.css +1 -1
  18. package/dist-web/app.js +442 -439
  19. package/package.json +4 -2
  20. package/plugins/session-manager-dev/skills/develop/SKILL.md +25 -19
  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 +91 -0
  23. package/plugins/session-manager-dev/skills/send-feedback/SKILL.md +9 -6
  24. package/scripts/README.md +1 -1
  25. package/scripts/scheduler-mcp-server.cjs +77 -0
  26. package/src/main/adminRouteRegistry.cjs +6 -0
  27. package/src/main/agentLibrary.cjs +60 -11
  28. package/src/main/agentsIpc.cjs +19 -0
  29. package/src/main/build-info.json +4 -4
  30. package/src/main/chatRunner.cjs +139 -0
  31. package/src/main/config.cjs +12 -0
  32. package/src/main/health.cjs +59 -17
  33. package/src/main/index.cjs +6 -2
  34. package/src/main/ipcSchemas.cjs +55 -1
  35. package/src/main/lib/claude/agentArmory.cjs +128 -0
  36. package/src/main/lib/claude/agentModelResolve.cjs +3 -2
  37. package/src/main/lib/claude/agentSnapshot.cjs +24 -3
  38. package/src/main/lib/claude/builtinTools.cjs +110 -0
  39. package/src/main/lib/claude/environmentProfiles.cjs +1 -1
  40. package/src/main/lib/claude/headlessMcpServers.cjs +138 -0
  41. package/src/main/lib/claude/jobSandboxPolicy.cjs +8 -2
  42. package/src/main/lib/claude/personaToolScope.cjs +100 -14
  43. package/src/main/lib/demo-video-kit/resumableRun.cjs +21 -14
  44. package/src/main/lib/demo-video-kit/seedKit.cjs +2 -2
  45. package/src/main/lib/epic/epicDepsSync.cjs +66 -0
  46. package/src/main/lib/epic/epicOutsideRead.cjs +74 -2
  47. package/src/main/lib/epic/epicSettle.cjs +48 -4
  48. package/src/main/lib/epic/epicSpawnPlan.cjs +3 -1
  49. package/src/main/lib/epic/epicValidationHook.cjs +9 -1
  50. package/src/main/lib/epic/planReviewInput.cjs +125 -0
  51. package/src/main/lib/epic/restorableSessions.cjs +1 -0
  52. package/src/main/lib/epic/scriptStartedBy.cjs +86 -0
  53. package/src/main/lib/externalContract.cjs +12 -0
  54. package/src/main/lib/feedback-remote/createdProjects.cjs +291 -0
  55. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +108 -14
  56. package/src/main/lib/feedback-remote/localAdminHttp.cjs +5 -1
  57. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +24 -3
  58. package/src/main/lib/feedback-remote/pendingReplies.cjs +8 -4
  59. package/src/main/lib/feedback-remote/projectCreate.cjs +415 -0
  60. package/src/main/lib/feedback-remote/replyClaims.cjs +15 -6
  61. package/src/main/lib/feedback-remote/serviceMcpSession.cjs +35 -4
  62. package/src/main/lib/feedback-remote/serviceMcpTools.cjs +43 -2
  63. package/src/main/lib/feedback-remote/servicePairLocalRoutes.cjs +91 -0
  64. package/src/main/lib/feedback-remote/servicePairings.cjs +95 -7
  65. package/src/main/lib/feedback-remote/serviceStdioBridge.cjs +104 -1
  66. package/src/main/lib/git/gitWorktree.cjs +1 -1
  67. package/src/main/lib/git/worktreeDeps.cjs +9 -3
  68. package/src/main/lib/mcpToolCatalog.cjs +47 -7
  69. package/src/main/lib/mcpToolsProbe.cjs +19 -2
  70. package/src/main/lib/opsOwnership.cjs +2 -0
  71. package/src/main/lib/packs/packCatalog.cjs +98 -5
  72. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +6 -0
  73. package/src/main/lib/persona-macro/builtinMacros.cjs +6 -4
  74. package/src/main/lib/persona-macro/personaFrontmatterSchema.cjs +9 -0
  75. package/src/main/lib/persona-macro/personaLoadout.cjs +58 -0
  76. package/src/main/lib/persona-macro/personaMerge.cjs +11 -3
  77. package/src/main/lib/persona-macro/personaUpgrade.cjs +96 -0
  78. package/src/main/lib/persona-macro/projectVideoToolCheck.cjs +1 -1
  79. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +94 -0
  80. package/src/main/lib/prd/prdCreate.cjs +49 -5
  81. package/src/main/lib/prd/prdFrontmatter.cjs +5 -2
  82. package/src/main/lib/prd/prdMcpReachWarnings.cjs +46 -0
  83. package/src/main/lib/prd/prdSandboxWarnings.cjs +49 -0
  84. package/src/main/lib/process/peerChatSession.cjs +165 -0
  85. package/src/main/lib/project-pages/videoScriptPress.cjs +6 -0
  86. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +24 -4
  87. package/src/main/lib/promptSessionSchema.cjs +2 -0
  88. package/src/main/lib/scheduler/baselineGate.cjs +31 -2
  89. package/src/main/lib/scheduler/planRecordHarvest.cjs +104 -12
  90. package/src/main/lib/scheduler/planReleaseRoute.cjs +110 -0
  91. package/src/main/lib/scheduler/planReviewSchema.cjs +182 -0
  92. package/src/main/lib/scheduler/planReviewStats.cjs +63 -0
  93. package/src/main/lib/scheduler/planReviewStore.cjs +150 -0
  94. package/src/main/lib/scheduler/reviewNotice.cjs +3 -1
  95. package/src/main/lib/scheduler/sandboxEnvironmentLimit.cjs +141 -0
  96. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  97. package/src/main/lib/scheduler/upgradeDrain.cjs +32 -5
  98. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +12 -2
  99. package/src/main/lib/tasks/memoryConsolidation.cjs +118 -37
  100. package/src/main/lib/tasks/taskAdminRoutes.cjs +26 -14
  101. package/src/main/lib/tasks/taskRun.cjs +3 -1
  102. package/src/main/lib/tasks/weeklyConsolidationInputs.cjs +298 -0
  103. package/src/main/projectPages.cjs +22 -14
  104. package/src/main/pty.cjs +3 -0
  105. package/src/main/runVerify.cjs +80 -5
  106. package/src/main/scheduler/gitTreeGuard.cjs +6 -0
  107. package/src/main/scheduler/planReviewHold.cjs +146 -0
  108. package/src/main/scheduler/prdParser.cjs +1 -0
  109. package/src/main/scheduler/prdPaths.cjs +10 -1
  110. package/src/main/scheduler/reviewLadder.cjs +2 -0
  111. package/src/main/scheduler/utilizationHold.cjs +7 -2
  112. package/src/main/scheduler.cjs +692 -86
  113. package/src/main/seedAgentPersonas.cjs +11 -6
  114. package/src/main/seedStatus.cjs +1 -1
  115. package/src/main/templates/PRD_AUTHORING.md +17 -2
  116. package/src/main/webRemote.cjs +69 -7
  117. package/src/preload/api.d.ts +79 -1
  118. package/src/preload/apiSurface.json +39 -0
  119. package/src/preload/index.cjs +11 -0
  120. package/src/seed/agents/architect.md +28 -43
  121. package/src/seed/agents/dev-lead.md +3 -1
  122. package/src/seed/agents/md-network-curator.md +27 -0
  123. package/src/seed/agents/plan-reviewer.md +47 -0
  124. package/src/seed/agents/validator.md +2 -1
  125. package/dist/assets/AppSettings-BO4jDVGO.js +0 -2
  126. package/dist/assets/HomeClaudeConfig-DADP5bfn.js +0 -3
  127. package/dist/assets/ProjectClaudeConfig-DPnDJKcr.js +0 -26
  128. package/dist/assets/Scheduler-CNLjn90m.js +0 -16
@@ -69,6 +69,8 @@ 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 { isProtectedClaudePath, sandboxWarnings } = require('./lib/prd/prdSandboxWarnings.cjs');
73
+ const { sandboxLimitFromStreamJson, environmentLimitStamp, ENVIRONMENT_LIMIT_MESSAGE } = require('./lib/scheduler/sandboxEnvironmentLimit.cjs');
72
74
  const { decideVerifyDowngrade } = require('./lib/scheduler/refireCap.cjs');
73
75
  const { finalizeReasonFor } = require('./lib/scheduler/finalizeReason.cjs');
74
76
  const { shouldRunFlatSweep, FLAT_SWEEP_INTERVAL_MS } = require('./lib/scheduler/flatSweepThrottle.cjs');
@@ -130,6 +132,7 @@ const { buildReviewNotice, selectDueReviewNotices, formatReviewNotice, holdMsFro
130
132
  const { phaseOfJob } = require('./lib/phaseProjection.cjs');
131
133
  const epicValidationHook = require('./lib/epic/epicValidationHook.cjs');
132
134
  const prdCreate = require('./lib/prd/prdCreate.cjs');
135
+ const { mcpReachWarnings } = require('./lib/prd/prdMcpReachWarnings.cjs');
133
136
  const { resolveProjectContext } = require('./lib/projectRootResolve.cjs');
134
137
  const { expandHome } = require('./lib/util/expandHome.cjs');
135
138
  const { hasDownstreamValidator } = require('./lib/prd/planValidator.cjs');
@@ -138,9 +141,13 @@ const { verifyRun, captureArtifactEvidence, parseLog, scanSentinel, scanForeignW
138
141
  const { latestTerminalOutcomeForSlug, COMPLETED_EQUIVALENT_VERDICTS } = require('./lib/scheduler/terminalRunOutcome.cjs');
139
142
  const { isFixPlanSlug, classifyDiscoveredFixPlan, resolveIsFixPlan, fixPlanRecordPath } = require('./lib/scheduler/fixPlanSlug.cjs');
140
143
  const { landedSinceRun, landedOnMainSince } = require('./lib/scheduler/landedSinceRun.cjs');
141
- const { declaredPathsForPrd, issuedAtForPrd } = require('./lib/prd/prdDeclaredPaths.cjs');
144
+ const { declaredPathsForPrd, issuedAtForPrd, extractDeclaredPaths } = require('./lib/prd/prdDeclaredPaths.cjs');
145
+ const { extractSection: extractPrdSection } = require('./lib/scheduler/definitionOfDone.cjs');
142
146
  const { identity: procIdentityOf, isDifferentProcess } = require('./lib/process/procIdentity.cjs');
143
147
  const jobLeftovers = require('./lib/scheduler/jobLeftovers.cjs');
148
+ const planReviewHold = require('./scheduler/planReviewHold.cjs');
149
+ const planReviewStore = require('./lib/scheduler/planReviewStore.cjs');
150
+ const { buildPlanReviewInput } = require('./lib/epic/planReviewInput.cjs');
144
151
  const { harvestPlanRecords, saveValidatorVerdicts } = require('./lib/scheduler/planRecordHarvest.cjs');
145
152
  const artifactStore = require('./lib/epic/artifactStore.cjs');
146
153
  const prdOutcomeRecord = require('./lib/scheduler/prdOutcomeRecord.cjs');
@@ -181,13 +188,17 @@ const { ensureEpic, appendPrdCreatedEvent, readActiveIndex } = require('./lib/ep
181
188
  const agentModelResolve = require('./lib/claude/agentModelResolve.cjs');
182
189
  const agentSnapshot = require('./lib/claude/agentSnapshot.cjs');
183
190
  const packSpawnArgs = require('./lib/packs/packSpawnArgs.cjs');
184
- const { buildPersonaToolScope, personaToolScopeArgs, personaToolScopeEnv, resolvedMcpServerNames } = require('./lib/claude/personaToolScope.cjs');
191
+ const { resolveHeadlessMcpServers } = require('./lib/claude/headlessMcpServers.cjs');
192
+ const { buildPersonaToolScope, personaToolScopeArgs, personaToolScopeEnv, resolvedMcpServerNames, resolveSkillDeny } = require('./lib/claude/personaToolScope.cjs');
193
+ const { PLAN_REVIEW_SCHEMA, parsePlanReview, isAllOk: isAllOkPlanReview } = require('./lib/scheduler/planReviewSchema.cjs');
194
+ const { readSettingsModel } = require('./lib/claude/modelCatalog.cjs');
185
195
  const { VALIDATOR_VERDICT_SCHEMA, parseValidatorVerdict, verdictRowsFromStructured, expectedFromCriteria, formatCriteriaChecksSection } = require('./lib/scheduler/validatorVerdictSchema.cjs');
186
196
  const { resolveEpicEffort, effortArgs } = require('./lib/claude/agentEffortResolve.cjs');
187
197
  const { transitionJob, emitJobEvent, STATUS_HISTORY_CAP, LEGAL_TRANSITIONS } = require('./lib/scheduler/scheduleJobTransitions.cjs');
188
198
  const { buildContextDigest, composeExecutorPrompt } = require('./lib/epic/epicContextDigest.cjs');
189
199
  const { JOB_STATUSES } = require('./lib/scheduler/scheduleJobSchema.cjs');
190
- const { appendAuditEvent } = require('./lib/telemetry/auditLog.cjs');
200
+ const auditLogModule = require('./lib/telemetry/auditLog.cjs');
201
+ const { appendAuditEvent } = auditLogModule;
191
202
  const heldSchedulerTurns = require('./lib/scheduler/heldSchedulerTurns.cjs');
192
203
  const autoStartedSession = require('./lib/feedback-remote/autoStartedSession.cjs');
193
204
  const preflightCheck = require('./lib/scheduler/preflightCheck.cjs');
@@ -547,7 +558,12 @@ async function harvestJobArtifacts(job, worktreeDir, projectRoot, { runId = job
547
558
  const FINISH_VALIDATOR_VERDICT_LINE = `
548
559
  - Your structured output's schedulerVerdict (and failReason) is what the scheduler reads as this verdict.`;
549
560
 
550
- function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum, isFixPlan = false, isArtifactOnly = false, isValidator = false }) {
561
+ // Plan-reviewer jobs (`--json-schema` PLAN_REVIEW_SCHEMA): the structured
562
+ // object is the whole deliverable; there is nothing to commit.
563
+ const FINISH_PLAN_REVIEWER_LINE = `
564
+ - 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.`;
565
+
566
+ function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum, isFixPlan = false, isArtifactOnly = false, isValidator = false, isPlanReviewer = false }) {
551
567
  return `${verifyStepNum}. VERIFY — run every command in the PRD's \`# Gate\` section, in order, in the
552
568
  foreground. Each must exit 0. If the PRD has no \`# Gate\` section, run the
553
569
  project's own typecheck, lint and test commands instead. The project's
@@ -579,7 +595,7 @@ ${verdictStepNum}. VERDICT LINE — end your final report with exactly one of th
579
595
  SCHEDULER_VERDICT: PASS
580
596
  SCHEDULER_VERDICT: FAIL <one-line reason>
581
597
  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 : ''}
598
+ - 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
599
  - Print FAIL when the gate is red or the commit could not land. Also print
584
600
  FAIL when a step needs something this run cannot reach (live runtime
585
601
  state, credentials, an account or dashboard action, a host install): do
@@ -629,13 +645,13 @@ in your final report.`;
629
645
  * tree, never FAIL for the missing commit. Self job 826 printed exactly that
630
646
  * false FAIL. Omitted/false leaves the text unchanged.
631
647
  */
632
- function buildFinishProtocol({ reviewInRun = true, isFixPlan = false, isArtifactOnly = false, isValidator = false } = {}) {
648
+ function buildFinishProtocol({ reviewInRun = true, isFixPlan = false, isArtifactOnly = false, isValidator = false, isPlanReviewer = false } = {}) {
633
649
  if (reviewInRun) {
634
650
  return buildFinishHead(3) + FINISH_REVIEW_STEPS_IN_RUN
635
- + buildFinishTail({ verifyStepNum: 3, commitStepNum: 4, verdictStepNum: 5, isFixPlan, isArtifactOnly, isValidator });
651
+ + buildFinishTail({ verifyStepNum: 3, commitStepNum: 4, verdictStepNum: 5, isFixPlan, isArtifactOnly, isValidator, isPlanReviewer });
636
652
  }
637
653
  return buildFinishHead(2) + FINISH_REVIEW_STEP_DEFERRED
638
- + buildFinishTail({ verifyStepNum: 2, commitStepNum: 3, verdictStepNum: 4, isFixPlan, isArtifactOnly, isValidator });
654
+ + buildFinishTail({ verifyStepNum: 2, commitStepNum: 3, verdictStepNum: 4, isFixPlan, isArtifactOnly, isValidator, isPlanReviewer });
639
655
  }
640
656
 
641
657
  const FINISH_PROTOCOL = buildFinishProtocol({ reviewInRun: true });
@@ -1108,6 +1124,7 @@ function restoreOpenAutoDispatchHold(v) {
1108
1124
  window: typeof v.window === 'string' ? v.window : null,
1109
1125
  threshold: Number.isFinite(v.threshold) ? v.threshold : null,
1110
1126
  resetsAt: typeof v.resetsAt === 'string' ? v.resetsAt : null,
1127
+ lastResetsAt: typeof v.lastResetsAt === 'string' ? v.lastResetsAt : (typeof v.resetsAt === 'string' ? v.resetsAt : null),
1111
1128
  startedAt: v.startedAt,
1112
1129
  maxPercent: Number.isFinite(v.maxPercent) ? v.maxPercent : null,
1113
1130
  heldTicks: Number.isFinite(v.heldTicks) ? v.heldTicks : 0,
@@ -1118,6 +1135,30 @@ function restoreOpenAutoDispatchHold(v) {
1118
1135
  /** Test-only seam: the open audit hold, and a reset that drops it from memory (a simulated process exit). */
1119
1136
  function _getOpenAutoDispatchHoldForTests() { return openAutoDispatchHold; }
1120
1137
  function _forgetOpenAutoDispatchHoldForTests() { openAutoDispatchHold = null; }
1138
+ /** Test-only seam: a fresh process — no previous tick. */
1139
+ function _resetPreviousTickUnheldForTests() { previousTickUnheld = false; }
1140
+
1141
+ const HOLD_RESET_CONTINUITY_MS = 60_000;
1142
+
1143
+ /**
1144
+ * Whether `hold` continues the open audit hold: same reason and window, and
1145
+ * resetsAt within 60 s (equal strings when either is unparseable). Not
1146
+ * holdIdentityKey equality — its nearest-minute rounding flips when a reset
1147
+ * near hh:mm:30 jitters by under a second.
1148
+ * @param {{ reason?: string | null, window?: string | null, resetsAt?: string | null } | null} open
1149
+ * @param {{ reason?: string | null, window?: string | null, resetsAt?: string | number | null } | null} hold
1150
+ */
1151
+ function continuesOpenHold(open, hold) {
1152
+ if (!open || !hold) return false;
1153
+ if ((open.reason ?? null) !== (hold.reason ?? null)) return false;
1154
+ if ((open.window ?? null) !== (hold.window ?? null)) return false;
1155
+ const a = open.lastResetsAt ?? open.resetsAt ?? null;
1156
+ const b = hold.resetsAt ?? null;
1157
+ const ta = a == null ? NaN : Date.parse(String(a));
1158
+ const tb = b == null ? NaN : Date.parse(String(b));
1159
+ if (Number.isFinite(ta) && Number.isFinite(tb)) return Math.abs(ta - tb) <= HOLD_RESET_CONTINUITY_MS;
1160
+ return (a == null ? null : String(a)) === (b == null ? null : String(b));
1161
+ }
1121
1162
 
1122
1163
  /**
1123
1164
  * Track the auto-dispatch hold in audit-log.jsonl: one started event when a
@@ -1126,13 +1167,15 @@ function _forgetOpenAutoDispatchHoldForTests() { openAutoDispatchHold = null; }
1126
1167
  * @param {object | null} hold currentAutoDispatchHold() result
1127
1168
  * @param {number} pending pending-row count for the started event
1128
1169
  */
1129
- function trackAutoDispatchHoldAudit(hold, pending) {
1170
+ function trackAutoDispatchHoldAudit(hold, pending, startObserved = false) {
1130
1171
  try {
1131
1172
  const identity = hold ? autoDispatchHold.holdIdentityKey(hold) : null;
1132
1173
  const open = openAutoDispatchHold;
1133
- if (open && open.holdKey === identity) {
1174
+ if (open && continuesOpenHold(open, hold)) {
1134
1175
  if (Number.isFinite(hold.percent) && (open.maxPercent == null || hold.percent > open.maxPercent)) open.maxPercent = hold.percent;
1135
1176
  open.heldTicks += 1;
1177
+ open.lastResetsAt = hold.resetsAt ?? open.lastResetsAt;
1178
+ persistSchedulerState();
1136
1179
  return;
1137
1180
  }
1138
1181
  if (open) {
@@ -1141,6 +1184,7 @@ function trackAutoDispatchHoldAudit(hold, pending) {
1141
1184
  window: open.window,
1142
1185
  threshold: open.threshold,
1143
1186
  resetsAt: open.resetsAt,
1187
+ lastResetsAt: open.lastResetsAt ?? open.resetsAt,
1144
1188
  holdKey: open.holdKey,
1145
1189
  startedAt: open.startedAt,
1146
1190
  endedAt: new Date().toISOString(),
@@ -1160,6 +1204,7 @@ function trackAutoDispatchHoldAudit(hold, pending) {
1160
1204
  resetsAt: hold.resetsAt ?? null,
1161
1205
  holdKey: identity,
1162
1206
  pending,
1207
+ startObserved,
1163
1208
  version: SCHEDULER_BUILD_IDENTITY.version,
1164
1209
  });
1165
1210
  openAutoDispatchHold = {
@@ -1169,6 +1214,7 @@ function trackAutoDispatchHoldAudit(hold, pending) {
1169
1214
  threshold: hold.threshold ?? null,
1170
1215
  baseThreshold: hold.baseThreshold ?? null,
1171
1216
  resetsAt: hold.resetsAt ?? null,
1217
+ lastResetsAt: hold.resetsAt ?? null,
1172
1218
  startedAt: new Date().toISOString(),
1173
1219
  maxPercent: Number.isFinite(hold.percent) ? hold.percent : null,
1174
1220
  heldTicks: 1,
@@ -1234,6 +1280,7 @@ function persistSchedulerState() {
1234
1280
  window: openAutoDispatchHold.window,
1235
1281
  threshold: openAutoDispatchHold.threshold,
1236
1282
  resetsAt: openAutoDispatchHold.resetsAt,
1283
+ lastResetsAt: openAutoDispatchHold.lastResetsAt,
1237
1284
  startedAt: openAutoDispatchHold.startedAt,
1238
1285
  maxPercent: openAutoDispatchHold.maxPercent,
1239
1286
  heldTicks: openAutoDispatchHold.heldTicks,
@@ -1326,6 +1373,8 @@ async function driveUpgradeDrain(state) {
1326
1373
  queueSnapshot: drainSnapshot(state.jobs),
1327
1374
  drainState: state.drain,
1328
1375
  now: Date.now(),
1376
+ // A request older than this process asked for a restart that already happened.
1377
+ bootedAt: SCHEDULER_BOOTED_AT,
1329
1378
  });
1330
1379
  if (action === 'none' || action === 'wait') { drainActive = Boolean(state.drain?.active); return; }
1331
1380
  if (action === 'pause') {
@@ -1382,9 +1431,9 @@ async function driveUpgradeDrain(state) {
1382
1431
  /** Boot: clear a leftover drain whose request is complete (the restart happened) or gone. */
1383
1432
  async function clearStaleDrainAtBoot(boot) {
1384
1433
  const request = upgradeDrain.readRestartRequest();
1385
- const action = upgradeDrain.bootDrainAction({ drainState: boot.drain, request });
1434
+ const action = upgradeDrain.bootDrainAction({ drainState: boot.drain, request, bootedAt: SCHEDULER_BOOTED_AT });
1386
1435
  upgradeDrain.clearRestartingMarker();
1387
- if (request?.drainCompletedAt) upgradeDrain.retireRestartRequest();
1436
+ if (request && (request.drainCompletedAt || (action === 'clear' && upgradeDrain.requestPredatesBoot(request, SCHEDULER_BOOTED_AT)))) upgradeDrain.retireRestartRequest();
1388
1437
  if (action === 'clear') await mutate((s) => { s.drain = null; });
1389
1438
  drainActive = action === 'keep';
1390
1439
  }
@@ -1716,6 +1765,7 @@ function normalizeConfig(cfg) {
1716
1765
  // currentAutoDispatchHold (state.config). The held-turns store's hold provider
1717
1766
  // reads it synchronously; undefined before the first read (DEFAULT_CONFIG applies).
1718
1767
  let lastSeenConfig;
1768
+ function _forgetLastSeenConfigForTests() { lastSeenConfig = undefined; }
1719
1769
 
1720
1770
  function readQueueSync() {
1721
1771
  const s = queueStore.readMergedSync();
@@ -2288,6 +2338,7 @@ async function reconcilePass(state) {
2288
2338
  effort: p.effort ?? job.effort ?? null,
2289
2339
  voiceId: p.voiceId ?? job.voiceId ?? null,
2290
2340
  preflight: p.preflight ?? null,
2341
+ planReview: p.planReview ?? null,
2291
2342
  };
2292
2343
  // Adopt path: a row parked 'quarantined' (no createdVia provenance when
2293
2344
  // discovered) whose PRD file now carries a stamp — written via the
@@ -2417,6 +2468,7 @@ async function reconcilePass(state) {
2417
2468
  effort: p.effort ?? inv.row?.effort ?? null,
2418
2469
  voiceId: p.voiceId ?? inv.row?.voiceId ?? null,
2419
2470
  preflight: p.preflight ?? null,
2471
+ planReview: p.planReview ?? null,
2420
2472
  };
2421
2473
  const reason = `reconcile: repaired invalid status ${JSON.stringify(oldStatus)}`;
2422
2474
  // A repair is not a lifecycle transition — the corrupted `status` was
@@ -2574,6 +2626,7 @@ async function reconcilePass(state) {
2574
2626
  effort: p.effort ?? null,
2575
2627
  voiceId: p.voiceId ?? null,
2576
2628
  preflight: p.preflight ?? null,
2629
+ planReview: p.planReview ?? null,
2577
2630
  status: 'pending',
2578
2631
  // Enqueue time (PRD 1086/1087): the cross-project fairness tiebreak and
2579
2632
  // the starvation escalation both need a provable age for a pending row;
@@ -2612,6 +2665,29 @@ async function reconcilePass(state) {
2612
2665
  const parent = healTargetForFix(slug, state.jobs);
2613
2666
  entry.investigationDepth = parent ? (parent.investigationDepth ?? 1) + 1 : 2;
2614
2667
  }
2668
+ // A scheduler-authored fix plan whose # Files names a protected .claude path can never pass: the job
2669
+ // sandbox refuses every write there. Minted parked (born directly, like quarantine — not a transition)
2670
+ // with an environment limit so reviewLadder never auto-fixes it.
2671
+ if (entry.isFixPlan && Array.isArray(p.files)) {
2672
+ const protectedFiles = p.files.filter(isProtectedClaudePath);
2673
+ if (protectedFiles.length > 0) {
2674
+ const joined = protectedFiles.join(', ');
2675
+ const bornAt = new Date().toISOString();
2676
+ entry.status = 'needs_review';
2677
+ entry.environmentLimit = { kind: 'claude-dir-write', evidence: `${joined} in # Files` };
2678
+ entry.error = ENVIRONMENT_LIMIT_MESSAGE;
2679
+ entry.statusHistory = [{
2680
+ from: null,
2681
+ to: 'needs_review',
2682
+ reason: `fix plan lists protected path ${joined}; the job sandbox refuses writes there — architect-inline work`,
2683
+ source: 'reconcile',
2684
+ at: bornAt,
2685
+ }];
2686
+ entry.reviewNotice = buildReviewNotice({ job: entry, report: null, epicId: entry.sourcePromptId ?? null, now: bornAt });
2687
+ console.warn(`[scheduler] reconcile: parking fix plan ${slug} — # Files lists protected .claude path(s) ${joined}`);
2688
+ appendAuditEvent('fix_plan_sandbox_refused', { slug, cwd: p.cwd, path: p.path, files: protectedFiles });
2689
+ }
2690
+ }
2615
2691
  // Provenance gate (PRD-authoring lockdown): a PRD discovered with no
2616
2692
  // `createdVia` stamp was never written through scheduler_create_prd/
2617
2693
  // chat:create-prd (prdCreate.cjs always stamps 'scheduler-api') or the
@@ -2762,11 +2838,16 @@ let utilizationHold = null;
2762
2838
  let lastAutoDispatchHoldKey = null;
2763
2839
  // The auto-dispatch hold currently open in audit-log.jsonl (one
2764
2840
  // 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).
2841
+ // window, threshold, resetsAt, lastResetsAt, startedAt, maxPercent, heldTicks, restored? },
2842
+ // continued under continuesOpenHold (same reason + window, resetsAt within
2843
+ // 60 s of the last-seen resetsAt, not the opening one) so percent changes and
2844
+ // reset jitter write nothing. Persisted in scheduler-state.json so a restart
2845
+ // neither re-opens nor loses it (the heartbeat log keeps only ~15-37 h).
2769
2846
  let openAutoDispatchHold = null;
2847
+ // True when this process's immediately preceding tick found no auto-dispatch
2848
+ // hold: a hold opening now was seen to start (startObserved: true); one that
2849
+ // replaces another hold, or is in force on the first tick after boot, was not.
2850
+ let previousTickUnheld = false;
2770
2851
  // ms timestamp of the last FRESH reset observation (see recordObservedReset)
2771
2852
  // — distinct from Date.now(), so persistSchedulerState never re-stamps a
2772
2853
  // stale cachedNextReset as "just observed" on every poll cycle.
@@ -4270,6 +4351,13 @@ async function readStoredCriteriaChecks(cwd, epicId, slug) {
4270
4351
  * only bodyPath/bodyBytes/truncated. Fresh rows replace stored ones by id;
4271
4352
  * the exact-slug outcome record (when one exists) is updated in place.
4272
4353
  * Falls back to `stored` on any error. Never rejects.
4354
+ * @param {string} cwd
4355
+ * @param {string} epicId
4356
+ * @param {string} slug
4357
+ * @param {Record<string, unknown>[]} criteria
4358
+ * @param {Record<string, unknown>[]} stored
4359
+ * @param {{ httpRetry?: import('./lib/scheduler/criteriaChecks.cjs').HttpRetry }} [opts]
4360
+ * @returns {Promise<Record<string, unknown>[]>}
4273
4361
  */
4274
4362
  async function runDispatchCriteriaChecks(cwd, epicId, slug, criteria, stored, { httpRetry } = {}) {
4275
4363
  try {
@@ -4317,7 +4405,7 @@ async function runDispatchCriteriaChecks(cwd, epicId, slug, criteria, stored, {
4317
4405
  * checks only: no http request, no outcome record or body file write.
4318
4406
  * `httpRetry` overrides the dispatch retry defaults (tests only).
4319
4407
  * @param {any} job
4320
- * @param {{ runChecks?: boolean, httpRetry?: { attempts?: number, delayMs?: number } }} [opts]
4408
+ * @param {{ runChecks?: boolean, httpRetry?: import('./lib/scheduler/criteriaChecks.cjs').HttpRetry }} [opts]
4321
4409
  * @returns {Promise<{ expected: Record<string, { ids: string[], failedIds: string[] }>, section: string }>}
4322
4410
  */
4323
4411
  async function loadValidatorCriteriaContext(job, { runChecks = true, httpRetry } = {}) {
@@ -4549,6 +4637,8 @@ async function notifyOriginatingTab(job, {
4549
4637
  writeVerdictsFile = writeJsonAtomic,
4550
4638
  scheduleSettle = defaultScheduleSettle,
4551
4639
  loadValidatorCriteria = loadValidatorCriteriaContext,
4640
+ planReviewRows = undefined,
4641
+ planReviewStoreImpl = undefined,
4552
4642
  } = {}) {
4553
4643
  try {
4554
4644
  const prd = await resolveNotifyPrd(job, parsePrdRaw);
@@ -4729,6 +4819,9 @@ async function notifyOriginatingTab(job, {
4729
4819
  console.error('[scheduler] notifyOriginatingTab verdicts file write error', job?.slug, e);
4730
4820
  }
4731
4821
  }
4822
+ if (job.agentType === 'plan-reviewer' && (job.status === 'completed' || job.status === 'failed')) {
4823
+ await harvestPlanReview(job, epicId, logPath, { readStructured: readStructuredFromLog, sendPrompt, rows: planReviewRows, store: planReviewStoreImpl });
4824
+ }
4732
4825
  if (epicId) {
4733
4826
  // PRD 986: the check-in event is born validation:'unvalidated' — never
4734
4827
  // 'verified' — regardless of the job's self-reported outcome. The
@@ -4786,6 +4879,102 @@ async function notifyOriginatingTab(job, {
4786
4879
  }
4787
4880
  }
4788
4881
 
4882
+ /** Digest text for one harvested plan review (pure). */
4883
+ function buildPlanReviewDigest({ validateSlug, round, outcome, review, error }) {
4884
+ const head = `PLAN REVIEWED: ${validateSlug} (round ${round})`;
4885
+ if (outcome === 'failed') {
4886
+ return `${head}\nThe independent review failed (${error || 'no structured output'}) — the plan was released without review (review-failed). Its PRDs are free to dispatch.`;
4887
+ }
4888
+ if (outcome === 'ok') {
4889
+ return `${head}\nEvery PRD is ok and there are no plan findings — the plan was released automatically. Its PRDs are free to dispatch.`;
4890
+ }
4891
+ const lines = [head, 'The reviewer asks for changes before the PRDs dispatch.'];
4892
+ for (const p of review.prds) {
4893
+ lines.push('', `${p.prd}: ${p.decision}`);
4894
+ for (const f of p.findings) {
4895
+ lines.push(` - [${f.severity}] ${f.check}: ${f.text}`);
4896
+ if (f.suggestedEdit) lines.push(` suggested edit: ${f.suggestedEdit}`);
4897
+ }
4898
+ }
4899
+ if (review.planFindings.length) {
4900
+ lines.push('', 'Plan findings:');
4901
+ for (const f of review.planFindings) lines.push(` - [${f.severity}] ${f.check}: ${f.text}`);
4902
+ }
4903
+ 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.');
4904
+ return lines.join('\n');
4905
+ }
4906
+
4907
+ /**
4908
+ * harvestPlanReview — a finished plan-reviewer job: parse its structured output,
4909
+ * save the round, auto-release an all-ok plan (an unusable review releases as
4910
+ * 'review-failed'), and send the planner's Epic ONE digest per (validateSlug,
4911
+ * round). The sent round is persisted in the record (`digestSent`) so a restart
4912
+ * does not resend. Never throws.
4913
+ */
4914
+ async function harvestPlanReview(job, epicId, logPath, deps = {}) {
4915
+ const store = deps.store || planReviewStore;
4916
+ try {
4917
+ if (!epicId || !job.cwd || !isSafeEpicId(epicId)) return;
4918
+ const m = /^plan-review-(.+?)(?:-r(\d+))?$/.exec(bareSlug(job.slug));
4919
+ if (!m) return;
4920
+ const round = m[2] ? Number(m[2]) : 1;
4921
+ const rows = (deps.rows || (await readQueue()).jobs || []);
4922
+ const validator = rows.find((r) => r && r.agentType === 'validator' && r.planReview === 'required'
4923
+ && bareSlug(r.slug) === m[1] && (!r.cwd || r.cwd === job.cwd));
4924
+ if (!validator) {
4925
+ console.error('[scheduler] harvestPlanReview: no validate row for', job.slug);
4926
+ return;
4927
+ }
4928
+ const validateSlug = validator.slug;
4929
+ const prior = store.readPlanReview(job.cwd, epicId, validateSlug);
4930
+ const sentBefore = prior && Array.isArray(prior.digestSent) ? prior.digestSent.slice() : [];
4931
+ if (sentBefore.includes(round)) return;
4932
+
4933
+ const members = planReviewHold.planMembers(validator, rows).map((r) => r.slug);
4934
+ let structured = null;
4935
+ try { structured = (deps.readStructured || extractStructuredOutputFromLog)(logPath); } catch { structured = null; }
4936
+ const checked = job.status === 'completed' && structured
4937
+ ? parsePlanReview(structured, { expected: members })
4938
+ : { ok: false, error: job.status === 'completed' ? 'no structured output' : `reviewer ${job.status}` };
4939
+
4940
+ let outcome;
4941
+ if (checked.ok) {
4942
+ await store.savePlanReviewResult({
4943
+ cwd: job.cwd, epicId, validateSlug, round, reviewer: job.slug,
4944
+ runId: job.runId || null, model: job.model || null, review: checked.value,
4945
+ });
4946
+ if (isAllOkPlanReview(checked.value)) {
4947
+ outcome = 'ok';
4948
+ await store.recordPlanRelease({ cwd: job.cwd, epicId, validateSlug, by: 'auto', accepted: 0 });
4949
+ } else {
4950
+ outcome = 'amend';
4951
+ }
4952
+ } else {
4953
+ outcome = 'failed';
4954
+ console.error(`[scheduler] harvestPlanReview: ${job.slug} review rejected — ${checked.error}`);
4955
+ await store.recordPlanRelease({
4956
+ cwd: job.cwd, epicId, validateSlug, by: 'timeout',
4957
+ rejected: [{ finding: 'plan-review', reason: 'review-failed' }],
4958
+ });
4959
+ }
4960
+
4961
+ // Persist the dedupe key (the store's own writes rebuild the record without it).
4962
+ const rec = store.readPlanReview(job.cwd, epicId, validateSlug);
4963
+ if (rec) {
4964
+ const file = store.planReviewPath(job.cwd, epicId, validateSlug);
4965
+ assertOpsWrite(file, 'scheduler');
4966
+ await writeJsonAtomic(file, { ...rec, digestSent: [...new Set([...sentBefore, round])] });
4967
+ }
4968
+ const text = buildPlanReviewDigest({
4969
+ validateSlug, round, outcome,
4970
+ review: checked.ok ? checked.value : null, error: checked.ok ? null : checked.error,
4971
+ });
4972
+ (deps.sendPrompt || enqueueExternalPrompt)(epicId, text, { origin: 'scheduler', heldKind: 'scheduler-notice' });
4973
+ } catch (e) {
4974
+ console.error('[scheduler] harvestPlanReview error', job?.slug, e);
4975
+ }
4976
+ }
4977
+
4789
4978
  // Single-flight guard for flushDueReviewNotices — same shape as
4790
4979
  // gateShadowPending above: a module-level flag rather than a class, so two
4791
4980
  // triggers landing close together (an auto-resolve skip right next to the
@@ -4955,9 +5144,11 @@ const TRANSIENT_RETRY_CAP = 2;
4955
5144
  * transient (PRD 543/545 incident) — same bounded-retry treatment, not a
4956
5145
  * second parallel classifier.
4957
5146
  */
4958
- function classifyFailureOutcome({ exitCode, networkError, durationMs, transientRetries, newlyDirtyCount, launchError }) {
5147
+ function classifyFailureOutcome({ exitCode, networkError, durationMs, transientRetries, newlyDirtyCount, launchError, environmentLimit }) {
4959
5148
  // The run never started (argv too large): not transient, not investigable.
4960
5149
  if (launchError) return { action: 'fail-launch', launchError };
5150
+ // The job sandbox refused the run: not a code bug, and an investigation would hit the same wall.
5151
+ if (environmentLimit) return { action: 'fail-environment', environmentLimit };
4961
5152
  const signalTransient = (exitCode === 143 || exitCode === 137) && durationMs < IDLE_OUTPUT_KILL_MS;
4962
5153
  const networkTransient = networkError === true;
4963
5154
  const transient = signalTransient || networkTransient;
@@ -5755,13 +5946,6 @@ const HEADLESS_DISALLOWED_TOOLS = Object.freeze([
5755
5946
  * and a large prompt failed with spawn E2BIG before the job started (the
5756
5947
  * 2026-10-26 incident). `claude -p` with no positional prompt reads stdin.
5757
5948
  */
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
5949
  /**
5766
5950
  * The CLI keeps only the LAST --settings value, and the job sandbox argv
5767
5951
  * already carries one inline JSON --settings. When it does, fold the
@@ -5812,7 +5996,7 @@ function jobRiskToolsClearance(prdRiskTools, personaTools) {
5812
5996
  return out;
5813
5997
  }
5814
5998
 
5815
- function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope, mcpServerNames = [], pluginDirArgs = [], jsonSchema = null, sandboxArgs = null, riskGuardSettingsPath = null }) {
5999
+ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope, mcpServerNames = [], pluginDirArgs = [], jsonSchema = null, sandboxArgs = null, riskGuardSettingsPath = null, skillDeny = [], knownServers }) {
5816
6000
  let permissionArgs = Array.isArray(sandboxArgs) && sandboxArgs.length ? sandboxArgs : ['--dangerously-skip-permissions'];
5817
6001
  let riskArgs = [];
5818
6002
  if (typeof riskGuardSettingsPath === 'string' && riskGuardSettingsPath) {
@@ -5827,13 +6011,14 @@ function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt,
5827
6011
  ...(systemPrompt ? ['--append-system-prompt', systemPrompt] : []),
5828
6012
  // Always strict: exactly the persona's resolved servers (dispatch already
5829
6013
  // parked any job whose set names an unknown server — capability_unknown).
5830
- ...personaToolScopeArgs(toolScope, { mcpServers: knownMcpServers(), declaredServers: mcpServerNames }).args,
6014
+ ...personaToolScopeArgs(toolScope, { mcpServers: knownServers, declaredServers: mcpServerNames }).args,
5831
6015
  ...(Array.isArray(pluginDirArgs) ? pluginDirArgs : []),
5832
6016
  ...(jsonSchema && typeof jsonSchema === 'object' ? ['--json-schema', JSON.stringify(jsonSchema)] : []),
5833
6017
  ...riskArgs,
5834
6018
  ...permissionArgs,
5835
6019
  ...headlessPermissionArgs(),
5836
6020
  '--disallowedTools', HEADLESS_DISALLOWED_TOOLS.join(','),
6021
+ ...(Array.isArray(skillDeny) ? skillDeny : []),
5837
6022
  '--output-format', 'stream-json',
5838
6023
  '--verbose',
5839
6024
  ...(resume ? ['--resume', sessionId] : ['--session-id', sessionId]),
@@ -5938,11 +6123,20 @@ function ensureTimeoutShimOnce() {
5938
6123
  * @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
6124
  */
5940
6125
  async function resolveJobAgentSnapshot(job, cwd, packs) {
6126
+ let repinFrom = null;
6127
+ let pinnedSnap = null;
5941
6128
  if (typeof job.agentSnapshotId === 'string' && job.agentSnapshotId) {
5942
- const snap = await agentSnapshot.readAgentSnapshot(cwd, job.agentSnapshotId);
5943
- if (!snap) {
6129
+ pinnedSnap = await agentSnapshot.readAgentSnapshot(cwd, job.agentSnapshotId);
6130
+ if (!pinnedSnap) {
5944
6131
  return { refusal: { code: 'agent_snapshot_missing', detail: `pinned agent snapshot ${job.agentSnapshotId} is missing or does not match its id` } };
5945
6132
  }
6133
+ // An explicit persona change (the PRD's agentType moved) is an audited re-pin.
6134
+ if (pinnedSnap.name && pinnedSnap.name !== (job.agentType || DEFAULT_PRD_AGENT_TYPE)) {
6135
+ repinFrom = job.agentSnapshotId;
6136
+ }
6137
+ }
6138
+ if (pinnedSnap && !repinFrom) {
6139
+ const snap = pinnedSnap;
5946
6140
  return {
5947
6141
  refusal: null,
5948
6142
  systemPrompt: snap.body || null,
@@ -5950,6 +6144,7 @@ async function resolveJobAgentSnapshot(job, cwd, packs) {
5950
6144
  tools: Array.isArray(snap.tools) ? snap.tools : null,
5951
6145
  mcpServers: Array.isArray(snap.mcpServers) ? snap.mcpServers.map(String) : [],
5952
6146
  packs: Array.isArray(snap.packs) ? snap.packs.map(String) : [],
6147
+ loadout: typeof snap.loadout === 'string' ? snap.loadout : null,
5953
6148
  personaPath: null,
5954
6149
  agentSnapshotId: job.agentSnapshotId,
5955
6150
  pinned: true,
@@ -5978,6 +6173,7 @@ async function resolveJobAgentSnapshot(job, cwd, packs) {
5978
6173
  id = (await agentSnapshot.writeAgentSnapshot(cwd, snap)).id;
5979
6174
  job.agentSnapshotId = id;
5980
6175
  } catch (err) {
6176
+ if (repinFrom) job.agentSnapshotId = null;
5981
6177
  console.error(`[scheduler] agent snapshot write failed for ${job.slug} (spawning unpinned): ${err?.message ?? err}`);
5982
6178
  }
5983
6179
  return {
@@ -5987,9 +6183,11 @@ async function resolveJobAgentSnapshot(job, cwd, packs) {
5987
6183
  tools: snap.tools,
5988
6184
  mcpServers: snap.mcpServers,
5989
6185
  packs: snap.packs,
6186
+ loadout: typeof snap.loadout === 'string' ? snap.loadout : null,
5990
6187
  personaPath: null,
5991
6188
  agentSnapshotId: id,
5992
6189
  pinned: false,
6190
+ ...(repinFrom && id ? { repinned: { from: repinFrom, to: id, reason: 'agentType_changed' } } : {}),
5993
6191
  };
5994
6192
  }
5995
6193
 
@@ -6341,7 +6539,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6341
6539
  job.validatorCriteriaExpected = expected;
6342
6540
  if (section) prompt = `${prompt}\n\n${section}`;
6343
6541
  }
6344
- prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun, isFixPlan: resolveIsFixPlan(job.slug, job.isFixPlan), isArtifactOnly, isValidator: job.agentType === 'validator' }) });
6542
+ 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
6543
 
6346
6544
  // Foreign-WIP manifest (starry-night-ships PRD 148 postmortem): the
6347
6545
  // scheduler already knows, at spawn time, which dirty paths this job did
@@ -6416,7 +6614,17 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6416
6614
  // Validator jobs (fresh and resume) return a schema-checked verdict:
6417
6615
  // --json-schema + StructuredOutput in scope (PRD 3613).
6418
6616
  const isValidator = job.agentType === 'validator';
6419
- const personaToolScope = buildPersonaToolScope(personaResolution.tools, { disallowed: HEADLESS_DISALLOWED_TOOLS, structuredOutput: isValidator });
6617
+ // Plan-reviewer jobs return a schema-checked review (PLAN_REVIEW_SCHEMA) on a
6618
+ // model that differs from the planner Epic's.
6619
+ const isPlanReviewer = job.agentType === 'plan-reviewer';
6620
+ let spawnModel = personaResolution.model;
6621
+ if (isPlanReviewer) {
6622
+ const plannerModel = (packEpic && typeof packEpic.model === 'string' && packEpic.model.trim())
6623
+ || readSettingsModel(cwd) || 'opus';
6624
+ spawnModel = planReviewHold.reviewerModelFor(personaResolution.model, plannerModel);
6625
+ job.model = spawnModel;
6626
+ }
6627
+ const personaToolScope = buildPersonaToolScope(personaResolution.tools, { loadout: personaResolution.loadout, disallowed: HEADLESS_DISALLOWED_TOOLS, structuredOutput: isValidator || isPlanReviewer });
6420
6628
  // Epic context packs (PRD 3154): the job's Epic's selected packs load as
6421
6629
  // --plugin-dir per pack, and their laws are appended AFTER the (already
6422
6630
  // capped) persona body — the persona cap never applies to laws. Fresh and
@@ -6439,19 +6647,37 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6439
6647
  } catch (err) {
6440
6648
  safeLog(`[scheduler] context packs skipped for ${job.slug}: ${err && err.message ? err.message : String(err)}\n`);
6441
6649
  }
6650
+ // Skills ride only inside packs: refuse every installed skill the persona's
6651
+ // packs (snapshot-pinned when pinned) do not carry.
6652
+ const skillDeny = await resolveSkillDeny({ packs: personaResolution.packs || [], loadout: personaResolution.loadout });
6653
+ safeLog(`[scheduler] skills=${skillDeny.denied} denied for ${job.slug}\n`);
6442
6654
  // 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;
6655
+ // missing from the resolved known map, or an unknown persona-declared pack,
6656
+ // parks the job needs_review 'capability_unknown: <name>'; a credential-bearing
6657
+ // one parks 'capability_credentialed'. Never spawned with a widened config.
6658
+ const mcpResolution = resolveHeadlessMcpServers({ cwd, projectRoot: job.cwd || defaultCwd });
6659
+ let capRefusal = null;
6660
+ for (const name of resolvedMcpServerNames(personaToolScope?.tools, personaResolution.mcpServers || [])) {
6661
+ if (Object.prototype.hasOwnProperty.call(mcpResolution.credentialed, name)) {
6662
+ capRefusal = { code: 'capability_credentialed', detail: mcpResolution.credentialed[name] };
6663
+ break;
6664
+ }
6665
+ }
6666
+ if (!capRefusal) {
6667
+ const capabilityCheck = personaToolScopeArgs(personaToolScope, {
6668
+ mcpServers: mcpResolution.known,
6669
+ declaredServers: personaResolution.mcpServers || [],
6670
+ packs: unknownPacks ? personaPackIds : [],
6671
+ knownPacks: unknownPacks ? personaPackIds.filter((p) => !unknownPacks.includes(p)) : [],
6672
+ });
6673
+ if (capabilityCheck.refusal) {
6674
+ const { code, name } = capabilityCheck.refusal;
6675
+ const isPack = Array.isArray(unknownPacks) && unknownPacks.includes(String(name));
6676
+ 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 };
6677
+ }
6678
+ }
6679
+ if (capRefusal) {
6680
+ const { code, detail } = capRefusal;
6455
6681
  const refusalError = `${code}: ${detail}`;
6456
6682
  safeLog(`[scheduler] capability refused for ${job.slug} — not spawned: ${refusalError}\n`);
6457
6683
  closeFd();
@@ -6461,7 +6687,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6461
6687
  const jobSystemPrompt = packArgs.laws
6462
6688
  ? (personaResolution.systemPrompt ? `${personaResolution.systemPrompt}\n\n${packArgs.laws}` : packArgs.laws)
6463
6689
  : 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`);
6690
+ 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
6691
 
6466
6692
  // Authoritative guarantee that buildClaudeSpawnArgs (a pure sync helper,
6467
6693
  // called below via withChildAndLog) sees a resolved --permission-prompts
@@ -6765,7 +6991,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6765
6991
  `tmp=${sandboxTmpDir ?? 'none'}\n`);
6766
6992
  const jobArgs = buildClaudeSpawnArgs({
6767
6993
  sandboxArgs: sandboxPolicy.argv,
6768
- model: personaResolution.model,
6994
+ model: spawnModel,
6769
6995
  effort: personaEffort,
6770
6996
  sessionId,
6771
6997
  resume: !!resumeTarget,
@@ -6773,8 +6999,10 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6773
6999
  toolScope: personaToolScope,
6774
7000
  mcpServerNames: personaResolution.mcpServers || [],
6775
7001
  pluginDirArgs: packArgs.pluginDirArgs,
6776
- jsonSchema: isValidator ? VALIDATOR_VERDICT_SCHEMA : null,
7002
+ jsonSchema: isValidator ? VALIDATOR_VERDICT_SCHEMA : (isPlanReviewer ? PLAN_REVIEW_SCHEMA : null),
6777
7003
  riskGuardSettingsPath,
7004
+ skillDeny: skillDeny.args,
7005
+ knownServers: mcpResolution.known,
6778
7006
  });
6779
7007
  const jobSpawn = claudeSpawnTarget('job', job.slug, claudeBin, jobArgs);
6780
7008
 
@@ -6942,10 +7170,15 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6942
7170
  ...SCHEDULER_META_IDENTITY, ...setupMeta,
6943
7171
  originSessionId, contextDigestApplied,
6944
7172
  agentSnapshotId: personaResolution.agentSnapshotId || null,
7173
+ ...(personaResolution.repinned ? { agentSnapshotRepinned: personaResolution.repinned } : {}),
7174
+ ...(isPlanReviewer ? { agentType: 'plan-reviewer', model: spawnModel } : {}),
6945
7175
  });
6946
7176
  removeSandboxTmp();
7177
+ // Only the OS-sandboxed run can hit a sandbox refusal; stamped at finalize if the row ends failed/needs_review.
7178
+ const sandboxLimit = sandboxMeta.level === 'os-sandbox'
7179
+ ? sandboxLimitFromStreamJson(readTail(logPath, 16384)) : null;
6947
7180
  resolve({
6948
- exitCode: effectiveCode, durationMs, rateLimited, networkError, launchFailure: launchFailed, resultStats,
7181
+ exitCode: effectiveCode, durationMs, rateLimited, networkError, sandboxLimit, launchFailure: launchFailed, resultStats,
6949
7182
  leakedDescendants: leaked, sessionId, killedByWatchdog: effectiveKilledByWatchdog, budgetKillReason,
6950
7183
  ...(memoryCapReason ? { error: memoryCapReason, memoryCapReason } : {}),
6951
7184
  });
@@ -7046,6 +7279,36 @@ function healTargetForFix(fixSlug, jobs) {
7046
7279
  return jobs.find((x) => x.slug === originalSlug && isPromotableOriginal(x.status) && !isCancelledRow(x)) || null;
7047
7280
  }
7048
7281
 
7282
+ /**
7283
+ * A fix plan succeeded for `orig`. An artifact-only parent (PRD declares
7284
+ * deliverable: artifact) is re-queued to pending for a fresh run, because
7285
+ * promoting it would mark it done without its record (4418: live probe never
7286
+ * re-run, artifactEvidence stayed ok:false). Any other parent is promoted to
7287
+ * completed as before. Returns 'requeued' | 'completed' | 'skipped'
7288
+ * ('skipped' = already re-queued once for this fix plan; a repeat boot pass
7289
+ * must not loop the parent back to pending after it failed again).
7290
+ */
7291
+ function applyFixSuccessToOriginal(orig, fixSlug, { promoteReason, promoteSource, requeueSource }) {
7292
+ if (orig.deliverable === 'artifact') {
7293
+ if (orig.requeuedByFix === fixSlug) return 'skipped';
7294
+ const ok = resetJobFields(orig, `requeued: fix plan ${fixSlug} succeeded`, { source: requeueSource });
7295
+ if (ok) {
7296
+ orig.error = null; // the reason lives on the transition, not as a row error
7297
+ orig.requeuedByFix = fixSlug;
7298
+ delete orig.completedBy;
7299
+ delete orig.looksDone;
7300
+ return 'requeued';
7301
+ }
7302
+ return 'skipped';
7303
+ }
7304
+ transitionJob(orig, 'completed', { reason: promoteReason, source: promoteSource });
7305
+ orig.exitCode = 0;
7306
+ orig.error = null;
7307
+ orig.completedBy = fixSlug;
7308
+ delete orig.looksDone;
7309
+ return 'completed';
7310
+ }
7311
+
7049
7312
  /**
7050
7313
  * Build the Opus investigation prompt. Pure/hermetic so its content can be
7051
7314
  * unit-tested (no spawn, no fs). Inputs are the already-resolved values that
@@ -7180,6 +7443,7 @@ ${logTail}
7180
7443
  the scheduler's commit guard and post-run verifier read git state from this path, and a
7181
7444
  non-repo cwd parks even a fully green, committed run in \`needs_review\`.
7182
7445
  List each file under \`# Files\` as \`- <repo-relative path>\` with nothing else on the line; put any note about a file in the Implementation notes, never on its path line.
7446
+ The job sandbox refuses every write under \`.claude/agents\`, \`.claude/commands\`, \`.claude/skills\`, \`.claude/hooks\` and \`.claude/settings*.json\` (Edit and Write too), so the fix plan must NEVER list such a path in \`# Files\`. If the only fix is there, write no fix plan and report that the edit is architect-inline work in the Epic chat (see PRD_AUTHORING.md #job-sandbox-limits).
7183
7447
  6. The PRD body MUST be self-contained — \`claude -p\` runs it on a fresh Sonnet session with NO conversation context. Include:
7184
7448
  - Root-cause analysis (what went wrong and why)
7185
7449
  - Concrete fix steps (specific files / commands / edits)
@@ -7254,7 +7518,9 @@ function readRunOutcomeSidecars(runDir, slug) {
7254
7518
  */
7255
7519
  const INVESTIGATION_LAUNCH_KEY = 'investigation';
7256
7520
 
7257
- async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {}) {
7521
+ function spawnInvestigation(failedJob, runDir, opts) { return trackInFlight(spawnInvestigationUntracked(failedJob, runDir, opts)); }
7522
+
7523
+ async function spawnInvestigationUntracked(failedJob, runDir, { deadChild = null } = {}) {
7258
7524
  // Auto-dispatch hold first — before anything below can spawn a process
7259
7525
  // (probeClaudeVersion included). A held needs_review row stays eligible for
7260
7526
  // the periodic auto-fix pass; a plain 'failed' row (never a
@@ -8008,6 +8274,193 @@ async function recordInterruptLeftovers(slug, runId, { dirtyPaths, salvagePatch
8008
8274
  }
8009
8275
  }
8010
8276
 
8277
+ const PLAN_REVIEW_HELD_PREFIX = 'held: plan-review';
8278
+ const planReviewTimeoutNoticesSent = new Set();
8279
+
8280
+ /** Parse one member PRD's text into the shape buildPlanReviewInput expects. */
8281
+ function planReviewMemberFromPrd(row, text, prdPath) {
8282
+ let fm = {};
8283
+ let body = String(text || '');
8284
+ try { const p = parsePrdFile(body); fm = p.frontmatter || {}; body = p.body || ''; } catch { /* keep raw */ }
8285
+ const section = (name) => {
8286
+ const m = body.match(new RegExp(`^#{1,3}\\s*${name}[^\\n]*\\n([\\s\\S]*?)(?=^#{1,3}\\s|(?![\\s\\S]))`, 'im'));
8287
+ return m ? m[1] : '';
8288
+ };
8289
+ const bullets = (txt) => txt.split('\n').map((l) => l.match(/^\s*(?:[-*]|\d+\.)\s+(?:\[[ xX]\]\s+)?(.*\S)\s*$/)?.[1]).filter(Boolean);
8290
+ const gateTxt = section('Gate');
8291
+ const gate = (gateTxt.match(/```[^\n]*\n([\s\S]*?)```/)?.[1] || '').split('\n').map((l) => l.trim()).filter(Boolean);
8292
+ return {
8293
+ slug: row.slug,
8294
+ title: fm.title || row.title || '',
8295
+ prdPath: prdPath || `${row.slug}.md`,
8296
+ goal: section('Goal').trim().split('\n')[0] || '',
8297
+ acceptanceCriteria: bullets(section('Acceptance criteria')),
8298
+ files: bullets(section('Files')).map((f) => f.replace(/^`|`$/g, '')),
8299
+ gate,
8300
+ dependsOn: Array.isArray(row.dependsOn) ? row.dependsOn : [],
8301
+ };
8302
+ }
8303
+
8304
+ /**
8305
+ * Per-tick plan-review orchestration. Merges computePlanReviewHolds into the
8306
+ * returned held Map, creates each missing plan-review PRD once (idempotent by
8307
+ * slug), and releases + notifies on timeout. Pending member rows carry
8308
+ * `heldReason` ('held: plan-review …') so epic settle and starvation see a known
8309
+ * wait; the field is cleared when the hold ends. Never throws.
8310
+ * deps: { now, holdMs, readReview, createPrd, recordRelease, notify, gitHead, readPrdTexts, audit, mutateRows }
8311
+ */
8312
+ async function applyPlanReviewHolds(state, deps = {}) {
8313
+ const held = new Map();
8314
+ try {
8315
+ const rows = state.jobs || [];
8316
+ const now = deps.now ?? Date.now();
8317
+ const holdMs = deps.holdMs ?? planReviewHold.holdMsFromEnv();
8318
+ const readReview = deps.readReview || ((cwd, epicId, slug) => planReviewStore.readPlanReview(cwd, epicId, slug));
8319
+ const createPrd = deps.createPrd || ((input) => prdCreate.createPrd(input, remote, { internalMint: true }));
8320
+ const recordRelease = deps.recordRelease || ((a) => planReviewStore.recordPlanRelease(a));
8321
+ const notify = deps.notify || ((cwd, epicId, text, extra) => appendResponseEventIfKnown(cwd, epicId, text, extra));
8322
+ const gitHead = deps.gitHead || (async (cwd) => { try { return String(await execGitAt(cwd, ['rev-parse', 'HEAD'])).trim() || null; } catch { return null; } });
8323
+ const readPrdFiles = deps.readPrdFiles || ((cwd, epicId, slugs) => prdPaths.readEpicPrdFiles(cwd, epicId, slugs));
8324
+ const readPrdTexts = deps.readPrdTexts || (async (cwd, epicId, slugs) => {
8325
+ const files = await readPrdFiles(cwd, epicId, slugs);
8326
+ return new Map([...files].map(([k, v]) => [k, v.text]));
8327
+ });
8328
+ const audit = deps.audit || ((k, d) => { try { auditLogModule.appendAuditEvent(k, d); } catch { /* audit never breaks dispatch */ } });
8329
+ const readEpicGoal = deps.readEpicGoal || ((cwd, epicId) => {
8330
+ try {
8331
+ const sessions = readActiveIndex(cwd).sessions;
8332
+ const sess = sessions && Object.prototype.hasOwnProperty.call(sessions, epicId) ? sessions[epicId] : null;
8333
+ if (!sess) return '';
8334
+ const title = typeof sess.title === 'string' && sess.title.trim() ? sess.title.trim()
8335
+ : (typeof sess.goalText === 'string' ? sess.goalText.trim().split(/\n\s*\n/)[0].trim() : '');
8336
+ const objective = typeof sess.openingPrompt === 'string' ? sess.openingPrompt.trim().slice(0, 2000) : '';
8337
+ return [title, objective].filter(Boolean).join('\n\n');
8338
+ } catch { return ''; }
8339
+ });
8340
+ const resolvePrdPath = deps.resolvePrdPath || (async (m, cwd, epicId) => {
8341
+ try {
8342
+ const files = await readPrdFiles(m.cwd || cwd, m.epicId || epicId, [m.slug]);
8343
+ const hit = files.get(m.slug);
8344
+ if (hit && hit.path) return path.resolve(hit.path);
8345
+ } catch { /* fall through */ }
8346
+ return opsPath(cwd, 'scheduler', 'epics', epicId, 'prds', `${m.slug}.md`);
8347
+ });
8348
+ const markCreateRefused = deps.markCreateRefused || ((cwd, epicId, slug, round) => planReviewStore.markCreateRefused(cwd, epicId, slug, round));
8349
+ const heldReasons = new Map();
8350
+ const notifyCreateFailed = async (v, epicId, vslug, err) => {
8351
+ try {
8352
+ await notify(v.cwd, epicId, `PLAN REVIEW NOT STARTED — the independent review job for plan ${bareSlug(vslug)} could not be created: ${err}. Its PRDs stay held until the review lands, you release it with scheduler_release_plan, or the hold times out.`, { prdSlug: v.slug, notice: 'plan-review-create-failed', allowInactive: true });
8353
+ } catch { /* notice never breaks the tick */ }
8354
+ };
8355
+
8356
+ const reviews = {};
8357
+ const validators = rows.filter((r) => r && r.status === 'pending' && r.agentType === 'validator' && r.planReview === 'required');
8358
+ for (const v of validators) {
8359
+ const epicId = v.sourcePromptId || v.epicId;
8360
+ if (!epicId || !v.cwd) continue;
8361
+ const rec = readReview(v.cwd, epicId, v.slug);
8362
+ if (rec) reviews[bareSlug(v.slug)] = rec;
8363
+ }
8364
+ const { held: holds, needsReview, expired } = planReviewHold.computePlanReviewHolds(rows, reviews, { now, holdMs });
8365
+ const expiredSet = new Set(expired);
8366
+ const byVSlug = new Map(validators.map((v) => [v.slug, v]));
8367
+
8368
+ // Expired plans release by timeout; their members are not held this tick.
8369
+ const releasedMembers = new Set();
8370
+ for (const vslug of expired) {
8371
+ const v = byVSlug.get(vslug);
8372
+ if (!v) continue;
8373
+ const epicId = v.sourcePromptId || v.epicId;
8374
+ const members = planReviewHold.planMembers(v, rows);
8375
+ try {
8376
+ const out = await recordRelease({ cwd: v.cwd, epicId, validateSlug: v.slug, by: 'timeout' });
8377
+ for (const m of members) releasedMembers.add(m.slug);
8378
+ if (!out || !out.alreadyReleased) {
8379
+ audit('plan_review_timeout', { validateSlug: v.slug, epicId, holdMs });
8380
+ const key = `${epicId}:${v.slug}`;
8381
+ if (!planReviewTimeoutNoticesSent.has(key)) {
8382
+ planReviewTimeoutNoticesSent.add(key);
8383
+ 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 });
8384
+ }
8385
+ }
8386
+ } catch (e) {
8387
+ console.error('[scheduler] plan review timeout release failed', vslug, e?.message || e);
8388
+ }
8389
+ }
8390
+ for (const [slug, why] of holds) {
8391
+ if (releasedMembers.has(slug)) continue;
8392
+ held.set(slug, why);
8393
+ heldReasons.set(slug, why);
8394
+ }
8395
+
8396
+ // Create the review PRD for plans that have none yet (round 1), and r2 on request.
8397
+ const wanted = [];
8398
+ for (const vslug of needsReview) if (!expiredSet.has(vslug)) wanted.push({ vslug, round: 1 });
8399
+ for (const v of validators) {
8400
+ const rec = reviews[bareSlug(v.slug)];
8401
+ if (rec && rec.rereviewRequested === true && !rec.release && !expiredSet.has(v.slug)) wanted.push({ vslug: v.slug, round: 2 });
8402
+ }
8403
+ for (const { vslug, round } of wanted) {
8404
+ const v = byVSlug.get(vslug);
8405
+ if (!v) continue;
8406
+ const epicId = v.sourcePromptId || v.epicId;
8407
+ const reviewSlug = `plan-review-${bareSlug(vslug)}${round >= 2 ? `-r${round}` : ''}`;
8408
+ if (rows.some((r) => r && bareSlug(r.slug) === reviewSlug)) continue;
8409
+ try {
8410
+ const memberRows = planReviewHold.planMembers(v, rows);
8411
+ const texts = await readPrdTexts(v.cwd, epicId, memberRows.map((m) => m.slug));
8412
+ const members = [];
8413
+ for (const m of memberRows) members.push(planReviewMemberFromPrd(m, texts.get(m.slug), await resolvePrdPath(m, v.cwd, epicId)));
8414
+ const epicGoal = String((await readEpicGoal(v.cwd, epicId)) || '');
8415
+ const baseSha = await gitHead(v.cwd);
8416
+ const input = buildPlanReviewInput({ epicId, cwd: v.cwd, epicGoal, validateSlug: v.slug, members, baseSha, round });
8417
+ const res = await createPrd(input);
8418
+ if (res && res.ok === false) {
8419
+ const err = String(res.error || res.reason || '');
8420
+ console.warn('[scheduler] plan review PRD not created', reviewSlug, err);
8421
+ if (await markCreateRefused(v.cwd, epicId, v.slug, round)) {
8422
+ audit('plan_review_create_refused', { validateSlug: vslug, round, error: err });
8423
+ await notifyCreateFailed(v, epicId, vslug, err);
8424
+ }
8425
+ }
8426
+ } catch (e) {
8427
+ console.error('[scheduler] plan review PRD create failed', reviewSlug, e?.message || e);
8428
+ try {
8429
+ const err = String(e?.message || e);
8430
+ if (await markCreateRefused(v.cwd, epicId, v.slug, round)) {
8431
+ audit('plan_review_create_refused', { validateSlug: vslug, round, error: err });
8432
+ await notifyCreateFailed(v, epicId, vslug, err);
8433
+ }
8434
+ } catch { /* never breaks the tick */ }
8435
+ }
8436
+ }
8437
+
8438
+ // Stamp / clear heldReason on pending rows so settle + starvation see a known wait.
8439
+ const mutateRows = deps.mutateRows || ((fn) => mutate((s) => fn(s.jobs)));
8440
+ const stampSlugs = new Set();
8441
+ for (const v of validators) {
8442
+ if (expiredSet.has(v.slug) || v.queuedAt || v.createdAt || v.planReviewHeldAt) continue;
8443
+ if (needsReview.includes(v.slug) || planReviewHold.planMembers(v, rows).some((m) => held.has(m.slug))) stampSlugs.add(v.slug);
8444
+ }
8445
+ const dirty = stampSlugs.size > 0 || rows.some((r) => r && r.status === 'pending' && (
8446
+ (heldReasons.has(r.slug) && !r.preflightHold && r.heldReason !== heldReasons.get(r.slug))
8447
+ || (!heldReasons.has(r.slug) && typeof r.heldReason === 'string' && r.heldReason.startsWith(PLAN_REVIEW_HELD_PREFIX))));
8448
+ if (dirty) {
8449
+ await mutateRows((list) => {
8450
+ for (const r of list) {
8451
+ if (!r || r.status !== 'pending') continue;
8452
+ if (stampSlugs.has(r.slug) && !r.queuedAt && !r.createdAt && !r.planReviewHeldAt) r.planReviewHeldAt = new Date(now).toISOString();
8453
+ if (heldReasons.has(r.slug) && !r.preflightHold) r.heldReason = heldReasons.get(r.slug);
8454
+ else if (typeof r.heldReason === 'string' && r.heldReason.startsWith(PLAN_REVIEW_HELD_PREFIX)) delete r.heldReason;
8455
+ }
8456
+ });
8457
+ }
8458
+ } catch (e) {
8459
+ console.error('[scheduler] applyPlanReviewHolds error', e?.message || e);
8460
+ }
8461
+ return held;
8462
+ }
8463
+
8011
8464
  function computePreflightHolds(jobs, now = Date.now()) {
8012
8465
  const held = new Map();
8013
8466
  for (const j of jobs || []) {
@@ -8147,7 +8600,28 @@ function auditPreflightHold(slug, command, result, hold, extra = {}) {
8147
8600
  } catch { /* audit must not break dispatch */ }
8148
8601
  }
8149
8602
 
8150
- async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, siblingJobs = null) {
8603
+ // In-flight launch tracker: every spawnJob / spawnResumeRecovery / spawnInvestigation
8604
+ // run is registered here until it settles, so whenIdle() is a deterministic
8605
+ // "nothing this module launched is still running" signal (no polling, no clock).
8606
+ const inFlightLaunches = new Set();
8607
+ function trackInFlight(promise) {
8608
+ inFlightLaunches.add(promise);
8609
+ const done = () => { inFlightLaunches.delete(promise); };
8610
+ promise.then(done, done);
8611
+ return promise;
8612
+ }
8613
+
8614
+ /** Resolves once every tracked launch has settled, including launches that a
8615
+ * settling launch's own finally-tick started. Never rejects. */
8616
+ async function whenIdle() {
8617
+ while (inFlightLaunches.size > 0) {
8618
+ await Promise.allSettled([...inFlightLaunches]);
8619
+ }
8620
+ }
8621
+
8622
+ function spawnJob(...args) { return trackInFlight(spawnJobUntracked(...args)); }
8623
+
8624
+ async function spawnJobUntracked(job, runId, runDir, defaultCwd, resumeTarget = null, siblingJobs = null) {
8151
8625
  // PRD 1408: the queue rows in scope at dispatch (tickQueue's own
8152
8626
  // state.jobs, threaded straight down — never re-read here or inside
8153
8627
  // executeJob) decide whether this job's own finish protocol still needs to
@@ -8831,7 +9305,13 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8831
9305
  let siblingOverlap = false;
8832
9306
  if (!worktree.ok) {
8833
9307
  rangeCommits = await gitTreeGuard.gitRangeCommits(guardCwd, guardHeadBefore, headAtExit);
8834
- transcriptCommitShas = parseLog(path.join(runDir, `${job.slug}.log`)).transcriptCommitShas || [];
9308
+ // One parseLog call: harness-reported shas plus shas git printed for the run's own
9309
+ // `git commit` Bash call. Both are claims; resolveRunCommitAttribution only credits one inside rangeCommits.
9310
+ const parsedRunLog = parseLog(path.join(runDir, `${job.slug}.log`));
9311
+ transcriptCommitShas = [...new Set([
9312
+ ...(parsedRunLog.transcriptCommitShas || []),
9313
+ ...(parsedRunLog.transcriptCommitOutputShas || []),
9314
+ ])];
8835
9315
  const overlapState = await readQueue().catch(() => ({ jobs: [] }));
8836
9316
  const myStart = Date.parse(dispatchStartedAt) || 0;
8837
9317
  const myEnd = Date.now();
@@ -9494,6 +9974,13 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9494
9974
  // attribute" via its Array.isArray guard, same as an empty array.
9495
9975
  applyLeftoverFields(s.jobs[i2], newlyDirtyAll);
9496
9976
 
9977
+ const envStamp = environmentLimitStamp(res.sandboxLimit, effectiveStatus);
9978
+ if (envStamp.environmentLimit) {
9979
+ s.jobs[i2].environmentLimit = envStamp.environmentLimit;
9980
+ s.jobs[i2].error = envStamp.error;
9981
+ } else {
9982
+ delete s.jobs[i2].environmentLimit;
9983
+ }
9497
9984
  if (effectiveStatus === 'completed' || effectiveStatus === 'failed' || effectiveStatus === 'needs_review') {
9498
9985
  outcomeRecordSnapshot = { ...s.jobs[i2] };
9499
9986
  }
@@ -9597,16 +10084,18 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9597
10084
  const orig = healTargetForFix(job.slug, s.jobs);
9598
10085
  if (orig) {
9599
10086
  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;
10087
+ const outcome = applyFixSuccessToOriginal(orig, job.slug, {
10088
+ promoteReason: `auto-promoted: fix plan ${job.slug} succeeded`,
10089
+ promoteSource: 'spawnJob:auto-promote',
10090
+ requeueSource: 'spawnJob:auto-promote',
10091
+ });
10092
+ console.log(`[scheduler] auto-promote: ${orig.slug} (${priorStatus}) → ${outcome} because ${job.slug} succeeded`);
10093
+ if (outcome === 'completed') {
10094
+ if (priorStatus === 'needs_review') {
10095
+ delete orig.verifierVerdict;
10096
+ }
10097
+ newlyCompletedPrds.push({ slug: orig.slug, cwd: orig.cwd });
9608
10098
  }
9609
- newlyCompletedPrds.push({ slug: orig.slug, cwd: orig.cwd });
9610
10099
  }
9611
10100
  }
9612
10101
  }
@@ -9756,6 +10245,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9756
10245
  transientRetries: retries,
9757
10246
  newlyDirtyCount,
9758
10247
  launchError: res.launchError,
10248
+ environmentLimit: failedJobSnapshot.environmentLimit,
9759
10249
  });
9760
10250
 
9761
10251
  if (decision.action === 'fail-launch') {
@@ -9767,6 +10257,13 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9767
10257
  }
9768
10258
  });
9769
10259
  await broadcast({ flush: true });
10260
+ } else if (decision.action === 'fail-environment') {
10261
+ console.log(`[scheduler] environment limit (${decision.environmentLimit.kind}) for ${job.slug} — no investigation`);
10262
+ await mutate((s) => {
10263
+ const i = s.jobs.findIndex((x) => x.slug === job.slug);
10264
+ if (i >= 0) s.jobs[i].error = ENVIRONMENT_LIMIT_MESSAGE;
10265
+ });
10266
+ await broadcast({ flush: true });
9770
10267
  } else if (decision.action === 'retry') {
9771
10268
  console.log(`[scheduler] transient failure (${decision.transientKind} dur=${res.durationMs}ms) — auto-retry ${decision.retries + 1}/${TRANSIENT_RETRY_CAP} for ${job.slug}`);
9772
10269
  await mutate((s) => {
@@ -9913,7 +10410,9 @@ async function reclaimTerminalJobOrphansThrottled(state) {
9913
10410
  * own dispatch mutate is what stamps resumeRecoveryAttempted, atomically
9914
10411
  * with the 'running' transition).
9915
10412
  */
9916
- async function spawnResumeRecovery(job, resumeTarget) {
10413
+ function spawnResumeRecovery(job, resumeTarget) { return trackInFlight(spawnResumeRecoveryUntracked(job, resumeTarget)); }
10414
+
10415
+ async function spawnResumeRecoveryUntracked(job, resumeTarget) {
9917
10416
  // No queue rows in scope here (unlike tickQueue's own dispatch loop) — read
9918
10417
  // once, before delegating to spawnJob, so hasDownstreamValidator still
9919
10418
  // never runs inside executeJob itself. Its config also feeds the hold below.
@@ -9972,7 +10471,9 @@ function holdAuditFields(hold) {
9972
10471
  threshold: hold.threshold ?? null,
9973
10472
  baseThreshold: hold.baseThreshold ?? null,
9974
10473
  resetsAt: hold.resetsAt ?? null,
9975
- holdKey: autoDispatchHold.holdIdentityKey(hold),
10474
+ holdKey: openAutoDispatchHold && continuesOpenHold(openAutoDispatchHold, hold)
10475
+ ? openAutoDispatchHold.holdKey
10476
+ : autoDispatchHold.holdIdentityKey(hold),
9976
10477
  };
9977
10478
  }
9978
10479
 
@@ -9984,8 +10485,12 @@ function holdAuditFields(hold) {
9984
10485
  */
9985
10486
  async function auditHumanPress(press) {
9986
10487
  try {
10488
+ // lastSeenConfig is refreshed by every queue read/write; only a press before
10489
+ // the first read pays for a queue read just to audit itself.
9987
10490
  let config = lastSeenConfig;
9988
- try { config = (await readQueue()).config; } catch { /* last seen config */ }
10491
+ if (config == null) {
10492
+ try { config = (await readQueue()).config; } catch { /* DEFAULT_CONFIG applies */ }
10493
+ }
9989
10494
  appendAuditEvent('scheduler_human_press', { press, hold: holdAuditFields(currentAutoDispatchHold(config)) });
9990
10495
  } catch (e) {
9991
10496
  console.error('[scheduler] human press audit failed', e?.message ?? String(e));
@@ -10352,7 +10857,9 @@ async function tickBody(gen, { bypassLoadGate, lastResort, human = false }) {
10352
10857
  const pendingCount = hold || openAutoDispatchHold
10353
10858
  ? state.jobs.filter((j) => j.status === 'pending' && !runningSet.has(j.slug)).length
10354
10859
  : 0;
10355
- if (hold || openAutoDispatchHold) trackAutoDispatchHoldAudit(hold, pendingCount);
10860
+ const startObserved = previousTickUnheld;
10861
+ previousTickUnheld = hold == null;
10862
+ if (hold || openAutoDispatchHold) trackAutoDispatchHoldAudit(hold, pendingCount, startObserved);
10356
10863
  if (hold) {
10357
10864
  if (human) {
10358
10865
  bypassedHold = hold;
@@ -10377,6 +10884,10 @@ async function tickBody(gen, { bypassLoadGate, lastResort, human = false }) {
10377
10884
  const heldSlugs = await computeLaunchHolds(state);
10378
10885
  for (const [slug, why] of computePreflightHolds(state.jobs)) if (!heldSlugs.has(slug)) heldSlugs.set(slug, why);
10379
10886
  for (const [slug, why] of computeInterruptHolds(state.jobs)) if (!heldSlugs.has(slug)) heldSlugs.set(slug, why);
10887
+ if (planReviewHold.planReviewEnabled()) {
10888
+ const prHeld = await applyPlanReviewHolds(state, {});
10889
+ for (const [slug, why] of prHeld) if (!heldSlugs.has(slug)) heldSlugs.set(slug, why);
10890
+ }
10380
10891
  if (stale()) return STALE_TICK;
10381
10892
  const satisfiedSlugsByCwd = await budget.computeDepHistorySatisfaction(state);
10382
10893
  lastSatisfiedSlugsByCwd = satisfiedSlugsByCwd;
@@ -10825,6 +11336,10 @@ function projectRowsFor(jobs, cwd) {
10825
11336
  * root — the scheduler re-checks those on its own backoff, so the project is
10826
11337
  * waiting on a precondition, not starved.
10827
11338
  */
11339
+ function isPlanReviewHeldRow(j) {
11340
+ return !!j && j.status === 'pending' && typeof j.heldReason === 'string' && j.heldReason.startsWith(PLAN_REVIEW_HELD_PREFIX);
11341
+ }
11342
+
10828
11343
  function starveRootFor(projectRows, oldestPendingSlug = null) {
10829
11344
  const roots = starvation.rootBlockersForProject(projectRows);
10830
11345
  const root = roots.find((r) => r.heldSlugs.includes(oldestPendingSlug)) ?? roots[0] ?? null;
@@ -10832,7 +11347,16 @@ function starveRootFor(projectRows, oldestPendingSlug = null) {
10832
11347
  if (roots.length > 0 && roots.every((r) => r.preflightHeld)) {
10833
11348
  const waiting = new Set(roots.flatMap((r) => r.heldSlugs));
10834
11349
  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'));
11350
+ knownWait = projectRows.every((j) => j.status !== 'pending' || waiting.has(j.slug) || (j.preflightHold && typeof j.preflightHold === 'object') || isPlanReviewHeldRow(j));
11351
+ }
11352
+ // Every pending row is waiting on an independent plan review (or behind one that is).
11353
+ if (!knownWait) {
11354
+ const pending = projectRows.filter((j) => j.status === 'pending');
11355
+ if (pending.some(isPlanReviewHeldRow)) {
11356
+ const waiting = new Set(roots.flatMap((r) => [r.slug, ...r.heldSlugs]));
11357
+ knownWait = roots.every((r) => r.preflightHeld || isPlanReviewHeldRow(projectRows.find((j) => j.slug === r.slug)))
11358
+ && pending.every((j) => isPlanReviewHeldRow(j) || waiting.has(j.slug) || (j.preflightHold && typeof j.preflightHold === 'object'));
11359
+ }
10836
11360
  }
10837
11361
  return { root, knownWait };
10838
11362
  }
@@ -12246,6 +12770,42 @@ async function attributeLandedCommits(job, pathCommits, cwd) {
12246
12770
  return null;
12247
12771
  }
12248
12772
 
12773
+ /**
12774
+ * Resolve a commit this job's own transcript names that actually landed on HEAD
12775
+ * during its run. Rule: the transcript SHA resolves to a commit, is an ancestor
12776
+ * of HEAD, and its committer date is within [startedAt, finishedAt + 60s].
12777
+ * Fails closed per candidate and never throws.
12778
+ *
12779
+ * @param {{cwd?: string, logPath?: string, startedAt?: string, finishedAt?: string}} [opts]
12780
+ * @returns {Promise<string|null>}
12781
+ */
12782
+ async function ownTranscriptCommitOnHead({ cwd, logPath, startedAt, finishedAt } = {}) {
12783
+ try {
12784
+ if (!cwd || !logPath) return null;
12785
+ const start = Date.parse(startedAt);
12786
+ const end = Date.parse(finishedAt);
12787
+ if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
12788
+ const parsed = parseLog(logPath);
12789
+ const candidates = [...new Set([
12790
+ ...(parsed.transcriptCommitShas || []),
12791
+ ...(parsed.transcriptCommitOutputShas || []),
12792
+ ])];
12793
+ for (const cand of candidates) {
12794
+ try {
12795
+ if (typeof cand !== 'string' || !/^[0-9a-f]{4,64}$/i.test(cand)) continue;
12796
+ const full = String(await execGitAt(cwd, ['rev-parse', '--verify', `${cand}^{commit}`])).trim();
12797
+ if (!/^[0-9a-f]{40,64}$/i.test(full)) continue;
12798
+ await execGitAt(cwd, ['merge-base', '--is-ancestor', full, 'HEAD']);
12799
+ const cIso = String(await execGitAt(cwd, ['show', '-s', '--format=%cI', full])).trim();
12800
+ const ct = Date.parse(cIso);
12801
+ if (!Number.isFinite(ct) || ct < start || ct > end + 60_000) continue;
12802
+ return full;
12803
+ } catch { /* this candidate fails closed */ }
12804
+ }
12805
+ } catch { /* never throws */ }
12806
+ return null;
12807
+ }
12808
+
12249
12809
  /**
12250
12810
  * Widened evidence check (PRD 1102, narrowed to per-job attribution by a
12251
12811
  * later PRD): does at least one commit ATTRIBUTABLE TO THIS JOB land AFTER
@@ -12435,6 +12995,8 @@ async function runGateShadow(job) {
12435
12995
  // still complete when every HEAD failure already failed at the job's base
12436
12996
  // commit. The base run is memoized per HEAD on gateShadow.baseline.
12437
12997
  let baselineDecision = null;
12998
+ const runId = job.runId || reviewLadder.resolveRunId(job);
12999
+ const verdictsPath = runId ? path.join(schedulerPaths.runsDir(), runId, `${job.slug}.verdicts.json`) : null;
12438
13000
  if (
12439
13001
  job.verifierVerdict === 'sentinel_fail'
12440
13002
  && outcome.status === 'red' && definitive
@@ -12481,21 +13043,19 @@ async function runGateShadow(job) {
12481
13043
  try { await execGitAt(job.cwd, ['worktree', 'prune'], { timeout: 30_000 }); } catch { /* best-effort */ }
12482
13044
  }
12483
13045
  }
12484
- baselineDecision = decideBaselineAuthority({ job, headOutcome: outcome, baseOutcome, evidenceOk, ancestorOk, cleanOk, headStable });
13046
+ // The run's recorded FAIL reason (read-only; runVerify owns the sidecar).
13047
+ const sidecar = verdictsPath ? readJsonOrSync(verdictsPath, null) : null;
13048
+ const failReason = sidecar && typeof sidecar.reason === 'string' ? sidecar.reason : '';
13049
+ baselineDecision = decideBaselineAuthority({ job, headOutcome: outcome, baseOutcome, evidenceOk, ancestorOk, cleanOk, headStable, failReason });
12485
13050
  gateShadow.baseline = { head: headBefore, base: job.guardHeadBefore, outcome: baseOutcome, setup: baseSetup, ...baselineDecision };
12486
13051
  }
12487
13052
 
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
- }
13053
+ // Read-merge (single-writer law: runVerify owns the sidecar's other keys).
13054
+ // Only merge into an existing run dir — never conjure one.
13055
+ if (verdictsPath && fs.existsSync(path.dirname(verdictsPath))) {
13056
+ const existing = readJsonOrSync(verdictsPath, {}) || {}; // absent/unparseable → fresh
13057
+ const criteriaRecord = gateShadow.criteriaChecks ? { criteriaChecks: { head: headBefore, ranAt: gateShadow.ranAt, results: gateShadow.criteriaChecks } } : {};
13058
+ try { config.writeJsonSync(verdictsPath, { ...existing, gateShadow, ...criteriaRecord }); } catch { /* best-effort */ }
12499
13059
  }
12500
13060
 
12501
13061
  const headShort = headBefore ? headBefore.slice(0, 7) : 'unknown';
@@ -12722,6 +13282,7 @@ async function reverifyNeedsReview() {
12722
13282
  // rescan) rather than through the isRescanCandidate machinery.
12723
13283
  const candidates = snap.jobs.filter((j) => reviewLadder.isRescanCandidate(j) || reviewLadder.isGuardParkedWithoutAutoFix(j) || reviewLadder.isStaleSharedTreeRevertedPark(j));
12724
13284
  const healed = [];
13285
+ const transcriptHealed = new Map();
12725
13286
  const leftForReview = [];
12726
13287
  const looksDoneUpdates = [];
12727
13288
  // Shared across every computeLooksDone call in this one pass — dedupes
@@ -12791,6 +13352,9 @@ async function reverifyNeedsReview() {
12791
13352
  const hist = await queueHistory.historyTerminalBySlug().catch(() => null);
12792
13353
  priorLandedCommit = hist?.get(job.slug)?.landedCommit ?? null;
12793
13354
  }
13355
+ const transcriptOwn = !job.landedCommit && reviewLadder.NO_ATTRIBUTABLE_COMMIT_VERDICTS.has(job.verifierVerdict)
13356
+ ? await ownTranscriptCommitOnHead({ cwd: job.cwd, logPath: path.join(runDir, `${job.slug}.log`), startedAt: job.startedAt, finishedAt: job.finishedAt })
13357
+ : null;
12794
13358
  let v = null;
12795
13359
  try {
12796
13360
  v = await verifyRun({
@@ -12809,16 +13373,17 @@ async function reverifyNeedsReview() {
12809
13373
  // ground-truth-outranks-heuristics evidence spawnJob passes live,
12810
13374
  // just read back post-hoc since there is no in-flight guardHeadBefore/
12811
13375
  // headAtExit pair to recompute for an already-terminal row.
12812
- jobLandedCommitThisRun: job.landedCommit ?? null,
13376
+ jobLandedCommitThisRun: job.landedCommit ?? transcriptOwn,
12813
13377
  exitCode: job.exitCode ?? null,
12814
13378
  });
12815
13379
  } catch { leftForReview.push({ slug: job.slug, reason: 'verifyRun threw' }); continue; }
12816
- const refusal = reviewLadder.healRefusalReason(job, v, committedDuringRun);
13380
+ const refusal = reviewLadder.healRefusalReason(transcriptOwn ? { ...job, landedCommit: transcriptOwn } : job, v, committedDuringRun);
12817
13381
  let stillOpen = true;
12818
13382
  if (refusal) {
12819
13383
  leftForReview.push({ slug: job.slug, reason: refusal });
12820
13384
  } else if (v && COMPLETED_EQUIVALENT_VERDICTS.has(v.verdict)) {
12821
13385
  healed.push(job.slug);
13386
+ if (transcriptOwn) transcriptHealed.set(job.slug, transcriptOwn);
12822
13387
  stillOpen = false;
12823
13388
  } else {
12824
13389
  leftForReview.push({ slug: job.slug, reason: v ? `${v.verdict}: ${v.reason}` : 'null verdict' });
@@ -12924,6 +13489,10 @@ async function reverifyNeedsReview() {
12924
13489
  j.error = null;
12925
13490
  delete j.verifierVerdict;
12926
13491
  delete j.looksDone;
13492
+ if (transcriptHealed.has(j.slug) && !j.landedCommit) {
13493
+ j.landedCommit = transcriptHealed.get(j.slug);
13494
+ j.landedCommitSource = 'transcript-output';
13495
+ }
12927
13496
  healedPrds.push({ slug: j.slug, cwd: j.cwd });
12928
13497
  }
12929
13498
  }
@@ -12959,14 +13528,17 @@ async function reverifyNeedsReview() {
12959
13528
  const orig = healTargetForFix(job.slug, s.jobs);
12960
13529
  if (!orig) continue;
12961
13530
  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 });
13531
+ const outcome = applyFixSuccessToOriginal(orig, job.slug, {
13532
+ promoteReason: `auto-promoted: fix plan ${job.slug} already completed`,
13533
+ promoteSource: 'reverifyNeedsReview:auto-promote',
13534
+ requeueSource: 'reverifyNeedsReview:auto-promote',
13535
+ });
13536
+ if (outcome === 'skipped') continue;
13537
+ if (outcome === 'completed') {
13538
+ if (priorStatus === 'needs_review') delete orig.verifierVerdict;
13539
+ promotedPrds.push({ slug: orig.slug, cwd: orig.cwd });
13540
+ }
13541
+ promoted.push(`${orig.slug} (was ${priorStatus}, ${outcome} via ${job.slug})`);
12970
13542
  }
12971
13543
  });
12972
13544
  for (const { slug, cwd } of promotedPrds) {
@@ -14729,6 +15301,24 @@ const remote = {
14729
15301
  try {
14730
15302
  await config.writeTextAtomic(filePath, newRaw, { writer: 'scheduler' });
14731
15303
  const stat = await fsp.stat(filePath);
15304
+ try {
15305
+ patchWarnings = patchWarnings.concat(mcpReachWarnings(
15306
+ { agentType: fm.agentType, riskTools: fm.riskTools, cwd: fm.cwd || cwd },
15307
+ prdCreate.mcpReachDeps,
15308
+ ));
15309
+ } catch { /* advisory only — never fails the update */ }
15310
+ try {
15311
+ const effFiles = Array.isArray(files) ? files : extractDeclaredPaths(newBody);
15312
+ const crit = Array.isArray(fm.criteria) && fm.criteria.length
15313
+ ? fm.criteria.map((c) => (typeof c === 'string' ? c : c?.statement))
15314
+ : [extractPrdSection(newBody, 'Acceptance criteria')];
15315
+ patchWarnings = patchWarnings.concat(sandboxWarnings({
15316
+ files: effFiles,
15317
+ goal: extractPrdSection(newBody, 'Goal'),
15318
+ implementationNotes: extractPrdSection(newBody, 'Implementation notes'),
15319
+ acceptanceCriteria: crit.filter((c) => typeof c === 'string'),
15320
+ }));
15321
+ } catch { /* advisory only — never fails the update */ }
14732
15322
  return patchWarnings.length
14733
15323
  ? { ok: true, slug, bytesWritten: stat.size, warnings: patchWarnings }
14734
15324
  : { ok: true, slug, bytesWritten: stat.size };
@@ -15128,7 +15718,10 @@ queueOps.bindQueueAccess({
15128
15718
  });
15129
15719
 
15130
15720
  module.exports = {
15721
+ readQueue,
15131
15722
  PARK_ERRORS,
15723
+ applyPlanReviewHolds,
15724
+ starveRootFor,
15132
15725
  rescanArtifactEvidence,
15133
15726
  harvestJobArtifacts,
15134
15727
  jobArtifactRunId,
@@ -15171,7 +15764,9 @@ module.exports = {
15171
15764
  getSchedulerStateSnapshot,
15172
15765
  _getOpenAutoDispatchHoldForTests,
15173
15766
  _auditHumanPressForTests: auditHumanPress,
15767
+ _forgetLastSeenConfigForTests,
15174
15768
  _forgetOpenAutoDispatchHoldForTests,
15769
+ _resetPreviousTickUnheldForTests,
15175
15770
  computeDegradedBudget,
15176
15771
  utilizationReading,
15177
15772
  usageHoldThreshold,
@@ -15214,10 +15809,12 @@ module.exports = {
15214
15809
  applyNeedsReviewAutoResolve,
15215
15810
  applyStuckFailedAutoSkip,
15216
15811
  computeLooksDone,
15812
+ ownTranscriptCommitOnHead,
15217
15813
  attributeLandedCommits,
15218
15814
  isPromotableOriginal,
15219
15815
  applyRcaClassification,
15220
15816
  healTargetForFix,
15817
+ applyFixSuccessToOriginal,
15221
15818
  buildInvestigationPrompt,
15222
15819
  readRunOutcomeSidecars,
15223
15820
  isFixPlanSlug,
@@ -15302,6 +15899,7 @@ module.exports = {
15302
15899
  driveUpgradeDrain,
15303
15900
  clearStaleDrainAtBoot,
15304
15901
  stop,
15902
+ whenIdle,
15305
15903
  runDueJobs,
15306
15904
  pollLoop,
15307
15905
  maybeLaunchWhenAvailable,
@@ -15320,6 +15918,14 @@ module.exports = {
15320
15918
  validateForeignWipBlockClaim,
15321
15919
  requeueForeignWipBlockedJobs,
15322
15920
  __test: { bindingWindowPauseThreshold },
15921
+ // Test-only seams (schedulerPlanRecordHarvest.test.cjs).
15922
+ __jobDeclaredArtifactPaths: jobDeclaredArtifactPaths,
15923
+ __harvestJobPlanRecords: harvestJobPlanRecords,
15924
+ __driveUpgradeDrain: driveUpgradeDrain,
15925
+ __clearStaleDrainAtBoot: clearStaleDrainAtBoot,
15926
+ __getDrainActive: () => drainActive,
15927
+ __setDrainActiveForTests: (v) => { drainActive = Boolean(v); },
15928
+ __setRestartHandlerForTests: setRestartHandler,
15323
15929
  };
15324
15930
 
15325
15931
  // Lazy path getters: resolved from SM_SCHEDULER_HOME at each read, never frozen