claude-code-session-manager 0.142.0 → 0.143.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 (95) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +20 -107
  3. package/dist/assets/{AppSettings-BcZgIvvY.js → AppSettings-BO4jDVGO.js} +1 -1
  4. package/dist/assets/{History-DpZuJXi1.js → History-DTttbvPb.js} +1 -1
  5. package/dist/assets/{HomeClaudeConfig-D32ZJtU-.js → HomeClaudeConfig-DADP5bfn.js} +2 -2
  6. package/dist/assets/{Panel-BjdJjhqt.js → Panel-B_D4Bg7L.js} +1 -1
  7. package/dist/assets/{ProjectClaudeConfig-BTClYV6i.js → ProjectClaudeConfig-DPnDJKcr.js} +1 -1
  8. package/dist/assets/{Scheduler-DPobKx1Z.js → Scheduler-CNLjn90m.js} +8 -8
  9. package/dist/assets/{SkillReferenceGraph-Cqyu4mef.js → SkillReferenceGraph-D1b2aiol.js} +1 -1
  10. package/dist/assets/{Skills-vv0noNVI.js → Skills-cfV7sgk6.js} +1 -1
  11. package/dist/assets/{TiptapBody-CXi8Pvut.js → TiptapBody-DVXtEIVy.js} +1 -1
  12. package/dist/assets/{Toggle-CiYCWLjh.js → Toggle-CYajnSdx.js} +1 -1
  13. package/dist/assets/{VoiceButton-4NKKd1sC.js → VoiceButton-DJ4gGRuE.js} +1 -1
  14. package/dist/assets/{historyTotals-DDunb8Ch.js → historyTotals-D3MoHY2U.js} +1 -1
  15. package/dist/assets/{index-Cn5E9958.js → index-CdTppjKR.js} +436 -436
  16. package/dist/index.html +1 -1
  17. package/dist-web/app.js +356 -356
  18. package/package.json +3 -3
  19. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  20. package/plugins/session-manager-dev/skills/builder/SKILL.md +5 -0
  21. package/plugins/session-manager-dev/skills/develop/SKILL.md +9 -3
  22. package/scripts/README.md +1 -0
  23. package/scripts/scheduler-mcp-server.cjs +304 -6
  24. package/src/main/adminRouteRegistry.cjs +10 -0
  25. package/src/main/build-info.json +4 -4
  26. package/src/main/chatRunner.cjs +105 -7
  27. package/src/main/config.cjs +5 -1
  28. package/src/main/health.cjs +38 -2
  29. package/src/main/index.cjs +12 -4
  30. package/src/main/ipcSchemas.cjs +11 -0
  31. package/src/main/lib/demo-video-kit/cast.md +10 -1
  32. package/src/main/lib/demo-video-kit/character.cjs +77 -21
  33. package/src/main/lib/demo-video-kit/kind-tiktok.md +5 -1
  34. package/src/main/lib/demo-video-kit/projectSounds.cjs +191 -0
  35. package/src/main/lib/demo-video-kit/seedKit.cjs +3 -3
  36. package/src/main/lib/demo-video-kit/sound.cjs +166 -9
  37. package/src/main/lib/demo-video-kit/standalone.cjs +231 -0
  38. package/src/main/lib/epic/activeIndexMerge.cjs +5 -0
  39. package/src/main/lib/epic/artifactRetention.cjs +55 -9
  40. package/src/main/lib/epic/artifactStore.cjs +78 -35
  41. package/src/main/lib/epic/delegationReadiness.cjs +10 -3
  42. package/src/main/lib/epic/epicEventLog.cjs +45 -1
  43. package/src/main/lib/epic/epicStateEmitter.cjs +248 -0
  44. package/src/main/lib/epic/epicValidationHook.cjs +13 -2
  45. package/src/main/lib/externalContract.cjs +12 -1
  46. package/src/main/lib/feedback-remote/autoStartedSession.cjs +1 -1
  47. package/src/main/lib/feedback-remote/crossProjectReply.cjs +96 -8
  48. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +30 -0
  49. package/src/main/lib/feedback-remote/pendingReplies.cjs +18 -0
  50. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +94 -4
  51. package/src/main/lib/feedback-remote/replyClaims.cjs +159 -0
  52. package/src/main/lib/git/gitWorktree.cjs +8 -0
  53. package/src/main/lib/git/runtimeStateUntrack.cjs +15 -1
  54. package/src/main/lib/git/worktreeDeps.cjs +113 -10
  55. package/src/main/lib/mcpToolCatalog.cjs +102 -8
  56. package/src/main/lib/opsOwnership.cjs +113 -28
  57. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +46 -0
  58. package/src/main/lib/prd/prdCreate.cjs +350 -227
  59. package/src/main/lib/prd/prdCriteria.cjs +7 -4
  60. package/src/main/lib/project-pages/videoPressLines.cjs +145 -0
  61. package/src/main/lib/project-pages/videoScriptPress.cjs +260 -0
  62. package/src/main/lib/project-pages/videoScriptRunRoute.cjs +351 -0
  63. package/src/main/lib/project-pages/videoScriptSwitchIpc.cjs +49 -0
  64. package/src/main/lib/project-pages/videoScriptSwitchRoute.cjs +173 -0
  65. package/src/main/lib/scheduler/criteriaChecks.cjs +164 -20
  66. package/src/main/lib/scheduler/heldSchedulerTurns.cjs +238 -0
  67. package/src/main/lib/scheduler/jobMemoryStats.cjs +13 -2
  68. package/src/main/lib/scheduler/planRecordHarvest.cjs +120 -52
  69. package/src/main/lib/scheduler/prdOutcomeRecord.cjs +60 -2
  70. package/src/main/lib/scheduler/queueStore.cjs +16 -0
  71. package/src/main/lib/scheduler/rcaReport.cjs +79 -15
  72. package/src/main/lib/scheduler/scheduleJobSchema.cjs +13 -0
  73. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  74. package/src/main/lib/scheduler/slotsRoute.cjs +101 -87
  75. package/src/main/lib/scheduler/usageHoldRoute.cjs +97 -0
  76. package/src/main/lib/scheduler/validatorVerdictSchema.cjs +16 -5
  77. package/src/main/lib/tasks/memoryConsolidation.cjs +14 -2
  78. package/src/main/lib/tasks/mitigationReview.cjs +21 -1
  79. package/src/main/lib/tasks/taskAdminRoutes.cjs +78 -3
  80. package/src/main/lib/tasks/taskLedger.cjs +2 -2
  81. package/src/main/lib/telemetry/auditEvents.cjs +21 -24
  82. package/src/main/lib/telemetry/auditLog.cjs +6 -2
  83. package/src/main/lib/util/atomicFs.cjs +2 -2
  84. package/src/main/promptSessionEvents.cjs +16 -1
  85. package/src/main/pty.cjs +11 -2
  86. package/src/main/queueOps.cjs +1 -1
  87. package/src/main/runVerify.cjs +1 -1
  88. package/src/main/scheduler/utilizationHold.cjs +96 -6
  89. package/src/main/scheduler.cjs +533 -39
  90. package/src/main/templates/PRD_AUTHORING.md +7 -2
  91. package/src/preload/api.d.ts +47 -1
  92. package/src/preload/apiSurface.json +14 -0
  93. package/src/preload/index.cjs +2 -0
  94. package/src/seed/agents/demo-video-builder.md +15 -8
  95. package/src/seed/agents/validator.md +20 -19
@@ -169,7 +169,7 @@ const { runDefinitionOfDoneOnDrain } = require('./lib/scheduler/dodDrainHook.cjs
169
169
  const { writeRcaReport, extractRcaBlock } = require('./lib/scheduler/rcaReport.cjs');
170
170
  const queueHistory = require('./lib/scheduler/queueHistory.cjs');
171
171
  const { resolveGate, runGateSequence, gateTimeoutMs } = require('./lib/scheduler/definitionOfDone.cjs');
172
- const { runCriteriaChecks } = require('./lib/scheduler/criteriaChecks.cjs');
172
+ const { runCriteriaChecks, HTTP_RETRY_ATTEMPTS, HTTP_RETRY_DELAY_MS } = require('./lib/scheduler/criteriaChecks.cjs');
173
173
  const queueOps = require('./queueOps.cjs');
174
174
  // Feedback-auto-PRD sweep — formerly only run by the external scheduler-watchdog
175
175
  // while the app was down (PRD 686 moved it in-app so it also runs while alive).
@@ -188,6 +188,8 @@ const { transitionJob, emitJobEvent, STATUS_HISTORY_CAP, LEGAL_TRANSITIONS } = r
188
188
  const { buildContextDigest, composeExecutorPrompt } = require('./lib/epic/epicContextDigest.cjs');
189
189
  const { JOB_STATUSES } = require('./lib/scheduler/scheduleJobSchema.cjs');
190
190
  const { appendAuditEvent } = require('./lib/telemetry/auditLog.cjs');
191
+ const heldSchedulerTurns = require('./lib/scheduler/heldSchedulerTurns.cjs');
192
+ const autoStartedSession = require('./lib/feedback-remote/autoStartedSession.cjs');
191
193
  const preflightCheck = require('./lib/scheduler/preflightCheck.cjs');
192
194
  const needsYouStore = require('./lib/feedback-remote/needsYouStore.cjs');
193
195
  const { withTimeout } = require('./lib/util/withTimeout.cjs');
@@ -424,15 +426,39 @@ const FINISH_ARTIFACT_ONLY_VERDICT_LINE = `
424
426
  const FINISH_ARTIFACT_ONLY_COMMIT_LINE = `
425
427
  This job is artifact-only: its output is git-excluded, so there is nothing to stage. Skip the commit and go to the next step.`;
426
428
 
429
+ /**
430
+ * jobDeclaredArtifactPaths(job) → Promise<string[]> — the job PRD's
431
+ * frontmatter artifactPaths (live PRD, else its archived copy). [] on any
432
+ * read/parse error; never throws.
433
+ */
434
+ async function jobDeclaredArtifactPaths(job) {
435
+ try {
436
+ const prdPath = (await resolveVerifyPrdPath(job)) ?? prdPaths.archivedPrdPathForJob(job);
437
+ if (!prdPath) return [];
438
+ const fm = parsePrdFile(fs.readFileSync(prdPath, 'utf8')).frontmatter;
439
+ if (!fm || !Array.isArray(fm.artifactPaths)) return [];
440
+ // Only plan-records entries are this harvest's; every other declared
441
+ // artifact belongs to harvestJobArtifacts and must not log a refusal here.
442
+ return fm.artifactPaths.filter((p) => typeof p === 'string'
443
+ && path.posix.normalize(p.replace(/\\/g, '/')).startsWith(ARTIFACT_PLAN_RECORDS_PREFIX));
444
+ } catch {
445
+ return [];
446
+ }
447
+ }
448
+
427
449
  /**
428
450
  * harvestJobPlanRecords(job, worktreeDir, projectRoot) — copy this run's
429
- * plan records from its worktree into the main checkout. Logs, never throws.
451
+ * plan records from its worktree into the main checkout: the job's own
452
+ * plan-records/<epicId>/ folder plus every plan record its PRD declares in
453
+ * frontmatter artifactPaths (which may sit in another Epic's folder).
454
+ * Logs, never throws.
430
455
  */
431
- function harvestJobPlanRecords(job, worktreeDir, projectRoot) {
456
+ async function harvestJobPlanRecords(job, worktreeDir, projectRoot) {
432
457
  try {
433
458
  const epicId = job.epicId || job.sourcePromptId;
434
459
  if (!epicId || !worktreeDir || !projectRoot || path.resolve(worktreeDir) === path.resolve(projectRoot)) return;
435
- const { copied, skipped } = harvestPlanRecords({ worktreeDir, projectRoot, epicId });
460
+ const declaredPaths = await jobDeclaredArtifactPaths(job);
461
+ const { copied, skipped } = harvestPlanRecords({ worktreeDir, projectRoot, epicId, declaredPaths });
436
462
  if (copied.length) console.log(`[scheduler] ${job.slug}: harvested ${copied.length} plan record(s) into ${projectRoot}`);
437
463
  for (const sk of skipped) console.warn(`[scheduler] ${job.slug}: plan record not harvested: ${sk.path} — ${sk.reason}`);
438
464
  } catch (e) {
@@ -1063,6 +1089,7 @@ function loadSchedulerState() {
1063
1089
  ? s.cachedUtilizationKnown
1064
1090
  : typeof cachedUtilization === 'number';
1065
1091
  restoredUsageWindows = isValidUsageWindowList(s.usageWindows) ? s.usageWindows : null;
1092
+ openAutoDispatchHold = restoreOpenAutoDispatchHold(s.openAutoDispatchHold);
1066
1093
  } catch { /* first boot or corrupt — start fresh */ }
1067
1094
  }
1068
1095
 
@@ -1071,6 +1098,88 @@ function getSchedulerStateSnapshot() {
1071
1098
  return { lastPollOk, lastFailureKind, backoffNextAt, cachedUtilization, cachedBindingWindowName };
1072
1099
  }
1073
1100
 
1101
+ /** A persisted open hold is trusted only with a string holdKey and a parseable startedAt; restored ones are marked. */
1102
+ function restoreOpenAutoDispatchHold(v) {
1103
+ if (!v || typeof v !== 'object' || typeof v.holdKey !== 'string') return null;
1104
+ if (typeof v.startedAt !== 'string' || !Number.isFinite(Date.parse(v.startedAt))) return null;
1105
+ return {
1106
+ holdKey: v.holdKey,
1107
+ reason: typeof v.reason === 'string' ? v.reason : null,
1108
+ window: typeof v.window === 'string' ? v.window : null,
1109
+ threshold: Number.isFinite(v.threshold) ? v.threshold : null,
1110
+ resetsAt: typeof v.resetsAt === 'string' ? v.resetsAt : null,
1111
+ startedAt: v.startedAt,
1112
+ maxPercent: Number.isFinite(v.maxPercent) ? v.maxPercent : null,
1113
+ heldTicks: Number.isFinite(v.heldTicks) ? v.heldTicks : 0,
1114
+ restored: true,
1115
+ };
1116
+ }
1117
+
1118
+ /** Test-only seam: the open audit hold, and a reset that drops it from memory (a simulated process exit). */
1119
+ function _getOpenAutoDispatchHoldForTests() { return openAutoDispatchHold; }
1120
+ function _forgetOpenAutoDispatchHoldForTests() { openAutoDispatchHold = null; }
1121
+
1122
+ /**
1123
+ * Track the auto-dispatch hold in audit-log.jsonl: one started event when a
1124
+ * hold opens, one ended event when it lifts or its identity changes. Never
1125
+ * throws (an audit failure must not break the tick).
1126
+ * @param {object | null} hold currentAutoDispatchHold() result
1127
+ * @param {number} pending pending-row count for the started event
1128
+ */
1129
+ function trackAutoDispatchHoldAudit(hold, pending) {
1130
+ try {
1131
+ const identity = hold ? autoDispatchHold.holdIdentityKey(hold) : null;
1132
+ const open = openAutoDispatchHold;
1133
+ if (open && open.holdKey === identity) {
1134
+ if (Number.isFinite(hold.percent) && (open.maxPercent == null || hold.percent > open.maxPercent)) open.maxPercent = hold.percent;
1135
+ open.heldTicks += 1;
1136
+ return;
1137
+ }
1138
+ if (open) {
1139
+ appendAuditEvent('auto_dispatch_hold_ended', {
1140
+ reason: open.reason,
1141
+ window: open.window,
1142
+ threshold: open.threshold,
1143
+ resetsAt: open.resetsAt,
1144
+ holdKey: open.holdKey,
1145
+ startedAt: open.startedAt,
1146
+ endedAt: new Date().toISOString(),
1147
+ maxPercent: open.maxPercent,
1148
+ heldTicks: open.heldTicks,
1149
+ ...(open.restored ? { endedAcrossRestart: true } : {}),
1150
+ });
1151
+ openAutoDispatchHold = null;
1152
+ }
1153
+ if (hold) {
1154
+ appendAuditEvent('auto_dispatch_hold_started', {
1155
+ reason: hold.reason,
1156
+ window: hold.window ?? null,
1157
+ percent: hold.percent ?? null,
1158
+ threshold: hold.threshold ?? null,
1159
+ baseThreshold: hold.baseThreshold ?? null,
1160
+ resetsAt: hold.resetsAt ?? null,
1161
+ holdKey: identity,
1162
+ pending,
1163
+ version: SCHEDULER_BUILD_IDENTITY.version,
1164
+ });
1165
+ openAutoDispatchHold = {
1166
+ holdKey: identity,
1167
+ reason: hold.reason,
1168
+ window: hold.window ?? null,
1169
+ threshold: hold.threshold ?? null,
1170
+ baseThreshold: hold.baseThreshold ?? null,
1171
+ resetsAt: hold.resetsAt ?? null,
1172
+ startedAt: new Date().toISOString(),
1173
+ maxPercent: Number.isFinite(hold.percent) ? hold.percent : null,
1174
+ heldTicks: 1,
1175
+ };
1176
+ }
1177
+ persistSchedulerState();
1178
+ } catch (e) {
1179
+ console.warn('[scheduler] auto-dispatch hold audit failed', e?.message);
1180
+ }
1181
+ }
1182
+
1074
1183
  /** A persisted usageWindows list is trusted only if every entry names a window with a finite percent. */
1075
1184
  function isValidUsageWindowList(v) {
1076
1185
  return Array.isArray(v) && v.every((w) => w && typeof w.window === 'string' && Number.isFinite(w.percent));
@@ -1118,6 +1227,18 @@ function persistSchedulerState() {
1118
1227
  // the binding session window.
1119
1228
  cachedUtilizationKnown,
1120
1229
  usageWindows: utilizationReading().windows,
1230
+ openAutoDispatchHold: openAutoDispatchHold
1231
+ ? {
1232
+ holdKey: openAutoDispatchHold.holdKey,
1233
+ reason: openAutoDispatchHold.reason,
1234
+ window: openAutoDispatchHold.window,
1235
+ threshold: openAutoDispatchHold.threshold,
1236
+ resetsAt: openAutoDispatchHold.resetsAt,
1237
+ startedAt: openAutoDispatchHold.startedAt,
1238
+ maxPercent: openAutoDispatchHold.maxPercent,
1239
+ heldTicks: openAutoDispatchHold.heldTicks,
1240
+ }
1241
+ : null,
1121
1242
  });
1122
1243
  } catch (e) {
1123
1244
  console.warn('[scheduler] failed to persist scheduler state', e?.message);
@@ -1431,6 +1552,14 @@ function heartbeatTick(deps = {}) {
1431
1552
  // this log can't otherwise tell a 5h hold from a weekly one.
1432
1553
  utilizationWindow: cachedBindingWindowName,
1433
1554
  utilizationHold,
1555
+ // Scheduler chat turns the usage hold is keeping (heldSchedulerTurns.cjs).
1556
+ heldSchedulerTurns: (() => {
1557
+ const sum = heldSchedulerTurns.summary() || {};
1558
+ return {
1559
+ count: Number(sum.count) || 0,
1560
+ tabs: Array.isArray(sum.tabs) ? sum.tabs : [],
1561
+ };
1562
+ })(),
1434
1563
  consecutiveFailures,
1435
1564
  // Why a memory-held tick held (PRD 4019): the new job's reservation, the
1436
1565
  // shared spike buffer and the running jobs' growth term. null = not gated.
@@ -1455,6 +1584,11 @@ function heartbeatTick(deps = {}) {
1455
1584
  entry = { ts: Date.now(), pid: process.pid, build: heartbeatBuild(), degraded: true, errors };
1456
1585
  }
1457
1586
  appendHeartbeat(entry);
1587
+ // Deliver held scheduler turns once the hold has cleared (no-op while held).
1588
+ guard('held-scheduler-turns-drain', () => {
1589
+ const run = deps.drainHeldSchedulerTurns ?? drainHeldSchedulerTurns;
1590
+ Promise.resolve(run()).catch(() => {});
1591
+ });
1458
1592
  return entry;
1459
1593
  }
1460
1594
 
@@ -1578,9 +1712,15 @@ function normalizeConfig(cfg) {
1578
1712
  return cfg;
1579
1713
  }
1580
1714
 
1715
+ // Last config object a queue read produced — the same object tickBody hands
1716
+ // currentAutoDispatchHold (state.config). The held-turns store's hold provider
1717
+ // reads it synchronously; undefined before the first read (DEFAULT_CONFIG applies).
1718
+ let lastSeenConfig;
1719
+
1581
1720
  function readQueueSync() {
1582
1721
  const s = queueStore.readMergedSync();
1583
1722
  s.config = normalizeConfig({ ...DEFAULT_CONFIG, ...(s.config || {}) });
1723
+ lastSeenConfig = s.config;
1584
1724
  return flagUnreadable(s);
1585
1725
  }
1586
1726
 
@@ -1590,6 +1730,7 @@ function readQueueSync() {
1590
1730
  async function readQueue() {
1591
1731
  const s = await queueStore.readMerged();
1592
1732
  s.config = normalizeConfig({ ...DEFAULT_CONFIG, ...(s.config || {}) });
1733
+ lastSeenConfig = s.config;
1593
1734
  return flagUnreadable(s);
1594
1735
  }
1595
1736
 
@@ -1991,7 +2132,7 @@ async function reconcilePass(state) {
1991
2132
  try { roots.add(resolveProjectRoot(c)); } catch { /* ephemeral/invalid cwd */ }
1992
2133
  }
1993
2134
  for (const r of roots) {
1994
- try { ensureRuntimeIgnores(r); } catch { /* best-effort */ }
2135
+ try { ensureRuntimeIgnores(r); } catch (e) { console.warn('[scheduler] runtime self-ignore failed for', r, e && e.message); }
1995
2136
  }
1996
2137
  } catch { /* best-effort */ }
1997
2138
  phaseMs.flatPrdSweep = Date.now() - phaseStartMs;
@@ -2619,6 +2760,13 @@ let utilizationHold = null;
2619
2760
  // `${reason}|${window}|${percent}` of the hold last logged — the hold line is
2620
2761
  // written when the hold starts or changes, not on every 30 s tick.
2621
2762
  let lastAutoDispatchHoldKey = null;
2763
+ // The auto-dispatch hold currently open in audit-log.jsonl (one
2764
+ // 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).
2769
+ let openAutoDispatchHold = null;
2622
2770
  // ms timestamp of the last FRESH reset observation (see recordObservedReset)
2623
2771
  // — distinct from Date.now(), so persistSchedulerState never re-stamps a
2624
2772
  // stale cachedNextReset as "just observed" on every poll cycle.
@@ -2712,6 +2860,38 @@ function currentAutoDispatchHold(config) {
2712
2860
  });
2713
2861
  }
2714
2862
 
2863
+ /**
2864
+ * The saved 'pause above' threshold (config.utilizationThreshold), read from
2865
+ * the machine-runtime scheduler state file only — never every project's queue
2866
+ * shard — so timers and routes can call it cheaply. DEFAULT_CONFIG's value
2867
+ * when unset, non-finite or unreadable.
2868
+ */
2869
+ function usageHoldThreshold() {
2870
+ try {
2871
+ const t = queueStore.readMachineConfigSync().utilizationThreshold;
2872
+ return typeof t === 'number' && Number.isFinite(t) ? t : DEFAULT_CONFIG.utilizationThreshold;
2873
+ } catch {
2874
+ return DEFAULT_CONFIG.utilizationThreshold;
2875
+ }
2876
+ }
2877
+
2878
+ /**
2879
+ * The usage hold in force right now for claude -p runs started OUTSIDE the PRD
2880
+ * queue: Tasks (POST /admin/tasks), their timers, and outside readers. Applies
2881
+ * the same utilization rule as currentAutoDispatchHold over the last real
2882
+ * reading at usageHoldThreshold(), but never firePolicy — firePolicy is the PRD
2883
+ * queue's own setting. null, or { reason: 'utilization-held', window, percent,
2884
+ * threshold, resetsAt, detail }; never 'manual-fire-policy'.
2885
+ */
2886
+ function currentUsageHold() {
2887
+ return autoDispatchHold.evaluateAutoDispatchHold({
2888
+ firePolicy: null,
2889
+ threshold: usageHoldThreshold(),
2890
+ reading: utilizationReading(),
2891
+ now: Date.now(),
2892
+ });
2893
+ }
2894
+
2715
2895
  /**
2716
2896
  * The auto-fix investigation probe is an automatic `claude -p` too, but it is
2717
2897
  * launched from spawnJob's failure path and the periodic auto-fix pass, never
@@ -2747,8 +2927,12 @@ function utilizationReading() {
2747
2927
  };
2748
2928
  }
2749
2929
 
2750
- /** Fetches latest usage from billing API. Throws on any error — callers handle it. */
2751
- async function refreshNextReset() {
2930
+ /**
2931
+ * Fetches latest usage from billing API and returns its binding window as one
2932
+ * paired reading ({ window, resetsAt }). Throws on any error — callers handle it.
2933
+ * @returns {Promise<{ window: string | null, resetsAt: string | null }>}
2934
+ */
2935
+ async function refreshBindingReading() {
2752
2936
  const r = await billing.fetchUsage();
2753
2937
  if (r.kind !== 'ok') throw new Error(`usage fetch failed (${r.kind}): ${r.message ?? ''}`);
2754
2938
  const window = bindingWindow(r.data?.usage);
@@ -2762,7 +2946,12 @@ async function refreshNextReset() {
2762
2946
  cachedBindingWindowName = window.name;
2763
2947
  cachedUtilizationKnown = true;
2764
2948
  lastGoodUsagePayload = r.data?.usage ?? lastGoodUsagePayload;
2765
- return cachedNextReset;
2949
+ return { window: window.name ?? null, resetsAt: cachedNextReset };
2950
+ }
2951
+
2952
+ /** Fetches latest usage from billing API. Throws on any error — callers handle it. */
2953
+ async function refreshNextReset() {
2954
+ return (await refreshBindingReading()).resetsAt;
2766
2955
  }
2767
2956
 
2768
2957
  /**
@@ -2797,6 +2986,41 @@ function resolveRateLimitPauseReset(logPath, billingResetIso, nowMs = Date.now()
2797
2986
  return null;
2798
2987
  }
2799
2988
 
2989
+ /**
2990
+ * The 'pause above' a rate_limit pause compares the billing binding window
2991
+ * with: the same pro-rated threshold the auto-dispatch hold uses
2992
+ * (utilizationHold.proRatedThreshold) for THAT window and its reset, so a
2993
+ * weekly window in its last days is not read as over a flat cap the hold
2994
+ * itself has already raised. Window name and reset come from the SAME
2995
+ * reading (the caller's refreshed billing reading) — pairing a cached name
2996
+ * with a fresh reset pro-rates against the wrong window length. The cached
2997
+ * pair is used only when no reading is passed. Non-numeric base passes
2998
+ * through unchanged.
2999
+ * @param {unknown} base
3000
+ * @param {{ window?: string | null, resetsAt?: string | null } | null | undefined} reading
3001
+ * @param {number} nowMs
3002
+ */
3003
+ function bindingWindowPauseThreshold(base, reading, nowMs) {
3004
+ if (typeof base !== 'number' || !Number.isFinite(base)) return base;
3005
+ const pair = reading ?? { window: cachedBindingWindowName, resetsAt: cachedNextReset };
3006
+ return autoDispatchHold.proRatedThreshold({ base, window: pair.window ?? null, resetsAt: pair.resetsAt ?? null, now: nowMs });
3007
+ }
3008
+
3009
+ /**
3010
+ * Effective 'pause above' for the binding window of the last known reading
3011
+ * (renderer snapshot field effectiveUtilizationThreshold); null with no known
3012
+ * reading or no numeric base.
3013
+ * @param {unknown} base
3014
+ * @param {number} [nowMs]
3015
+ * @returns {number | null}
3016
+ */
3017
+ function effectiveUtilizationThreshold(base, nowMs = Date.now()) {
3018
+ if (typeof base !== 'number' || !Number.isFinite(base)) return null;
3019
+ const reading = utilizationReading();
3020
+ if (reading.known !== true || typeof reading.percent !== 'number' || !Number.isFinite(reading.percent)) return null;
3021
+ return autoDispatchHold.proRatedThreshold({ base, window: reading.window, resetsAt: reading.resetsAt, now: nowMs });
3022
+ }
3023
+
2800
3024
  /** Logs when a fresh billing reset was discarded because its reading is under threshold. */
2801
3025
  function logBillingResetRejected(billingResetIso, billingUtilization, threshold) {
2802
3026
  if (!billingResetIso || !Number.isFinite(threshold)) return;
@@ -2814,8 +3038,19 @@ function logBillingResetRejected(billingResetIso, billingUtilization, threshold)
2814
3038
  * itself still rejects that cached value if it has since gone stale).
2815
3039
  */
2816
3040
  async function billingResetForPause() {
2817
- if (billing.usageCircuit.state() === 'open') return cachedNextReset;
2818
- return refreshNextReset().catch(() => cachedNextReset);
3041
+ return (await billingReadingForPause()).resetsAt;
3042
+ }
3043
+
3044
+ /**
3045
+ * billingResetForPause's reading with its binding window name kept beside the
3046
+ * reset ({ window, resetsAt }), so both come from one reading — the refreshed
3047
+ * one, or the cached pair when the circuit is open or the refresh fails.
3048
+ * @returns {Promise<{ window: string | null, resetsAt: string | null }>}
3049
+ */
3050
+ async function billingReadingForPause() {
3051
+ const cached = () => ({ window: cachedBindingWindowName ?? null, resetsAt: cachedNextReset });
3052
+ if (billing.usageCircuit.state() === 'open') return cached();
3053
+ return refreshBindingReading().catch(cached);
2819
3054
  }
2820
3055
 
2821
3056
  // ---------- health / poll state ----------
@@ -3028,6 +3263,40 @@ function drainDeferredInvestigation() {
3028
3263
  return;
3029
3264
  }
3030
3265
  }
3266
+
3267
+ /**
3268
+ * drainHeldSchedulerTurns(deps?) → Promise<Array<{ tabId, delivered, dropped }>>
3269
+ *
3270
+ * Deliver the scheduler chat turns the usage hold kept (heldSchedulerTurns.cjs)
3271
+ * once no hold is in force — each tab's held messages as one turn. An
3272
+ * auto-start follow-up is dropped when its session no longer needs a plan.
3273
+ * Every tab the drain touched is audited. Single-flight lives in the store.
3274
+ * Never rejects. Deps are injectable for tests.
3275
+ */
3276
+ async function drainHeldSchedulerTurns(deps = {}) {
3277
+ const hold = deps.hold ?? (() => currentAutoDispatchHold(lastSeenConfig));
3278
+ const send = deps.send ?? enqueueExternalPrompt;
3279
+ const needsPlan = deps.needsPlan ?? autoStartedSession.autoStartNeedsPlan;
3280
+ const audit = deps.audit ?? appendAuditEvent;
3281
+ try {
3282
+ if (hold()) return [];
3283
+ if (heldSchedulerTurns.summary().count <= 0) return [];
3284
+ const isStillNeeded = (entry) => (entry && entry.kind === 'auto-start-follow-up'
3285
+ ? needsPlan(entry.cwd, entry.sessionId)
3286
+ : true);
3287
+ const results = await heldSchedulerTurns.drain({ send, isStillNeeded });
3288
+ for (const r of results || []) {
3289
+ try {
3290
+ audit('scheduler_turns_delivered', { tabId: r.tabId, delivered: r.delivered, dropped: r.dropped });
3291
+ } catch { /* audit must not break the drain */ }
3292
+ }
3293
+ return results || [];
3294
+ } catch (e) {
3295
+ console.error('[scheduler] drainHeldSchedulerTurns error', e?.message ?? e);
3296
+ return [];
3297
+ }
3298
+ }
3299
+
3031
3300
  let cancelToken = { cancelled: false };
3032
3301
  // Last memory-gate observation; included in snapshot for renderer visibility.
3033
3302
  let lastMemGate = null;
@@ -3148,6 +3417,8 @@ function buildScheduleStatePayload(state) {
3148
3417
  utilization: cachedUtilization,
3149
3418
  utilizationWindow: cachedBindingWindowName,
3150
3419
  utilizationHold,
3420
+ // Pro-rated 'pause above' for the binding window (utilizationHold.proRatedThreshold).
3421
+ effectiveUtilizationThreshold: effectiveUtilizationThreshold(state.config?.utilizationThreshold),
3151
3422
  pollHealth: {
3152
3423
  lastPollAt,
3153
3424
  lastPollOk,
@@ -3988,16 +4259,68 @@ async function readStoredCriteriaChecks(cwd, epicId, slug) {
3988
4259
  return [];
3989
4260
  }
3990
4261
 
4262
+ /**
4263
+ * runDispatchCriteriaChecks(cwd, epicId, slug, criteria, stored, { httpRetry }?) → merged checks.
4264
+ * Runs the PRD's http + file criteria fresh in `cwd` (outside the job
4265
+ * sandbox, whose Bash cannot reach host loopback), never command or manual
4266
+ * ones. A failed http check is retried (default HTTP_RETRY_ATTEMPTS,
4267
+ * HTTP_RETRY_DELAY_MS apart; `httpRetry` overrides, tests only) because a
4268
+ * local dev server may be mid-reload just after a landing; each http row
4269
+ * keeps its `attempts`. http bodies go to a sidecar file (writeCheckBody); the row keeps
4270
+ * only bodyPath/bodyBytes/truncated. Fresh rows replace stored ones by id;
4271
+ * the exact-slug outcome record (when one exists) is updated in place.
4272
+ * Falls back to `stored` on any error. Never rejects.
4273
+ */
4274
+ async function runDispatchCriteriaChecks(cwd, epicId, slug, criteria, stored, { httpRetry } = {}) {
4275
+ try {
4276
+ const subset = criteria.filter((c) => c && c.check && (c.check.kind === 'http' || c.check.kind === 'file'));
4277
+ if (!subset.length) return stored;
4278
+ const ranAt = new Date().toISOString();
4279
+ const rows = await runCriteriaChecks({
4280
+ criteria: subset,
4281
+ cwd,
4282
+ keepBody: true,
4283
+ httpRetry: httpRetry || { attempts: HTTP_RETRY_ATTEMPTS, delayMs: HTTP_RETRY_DELAY_MS },
4284
+ });
4285
+ const fresh = [];
4286
+ for (const r of rows) {
4287
+ const { body, ...rest } = r;
4288
+ /** @type {Record<string, unknown>} */
4289
+ const row = { ...rest, ranAt, stage: 'validator-dispatch' };
4290
+ if (typeof body === 'string') {
4291
+ const bodyPath = await prdOutcomeRecord.writeCheckBody({ cwd, epicId, slug, id: r.id, body });
4292
+ if (bodyPath) row.bodyPath = bodyPath;
4293
+ }
4294
+ fresh.push(row);
4295
+ }
4296
+ const freshIds = new Set(fresh.map((c) => c.id));
4297
+ const merged = [...(Array.isArray(stored) ? stored : []).filter((c) => !(c && freshIds.has(c.id))), ...fresh];
4298
+ let exactExists = false;
4299
+ try { exactExists = !!(await readJsonOr(prdOutcomeRecord.outcomeRecordPath(cwd, epicId, slug), null)); } catch { exactExists = false; }
4300
+ if (exactExists) await prdOutcomeRecord.mergeOutcomeChecks({ cwd, epicId, slug, checks: fresh });
4301
+ return merged;
4302
+ } catch (e) {
4303
+ console.error('[scheduler] runDispatchCriteriaChecks error', slug, e && e.message ? e.message : e);
4304
+ return stored;
4305
+ }
4306
+ }
4307
+
3991
4308
  /**
3992
4309
  * loadValidatorCriteriaContext(job) → { expected, section } for a validator
3993
4310
  * job: per judged PRD (job.dependsOn) with frontmatter `criteria`, the
3994
4311
  * { ids, failedIds } parseValidatorVerdict cross-checks against, and the
3995
- * prompt section listing each criterion's stored check result. Empty when
3996
- * nothing is structured. Never rejects.
4312
+ * prompt section listing each criterion's check result — http + file checks
4313
+ * run fresh here at dispatch (runDispatchCriteriaChecks), command results as
4314
+ * stored. Empty when
4315
+ * nothing is structured. Never rejects. With `runChecks: false` (the notify
4316
+ * fallback for a row without a dispatch-time stamp) it reads the stored
4317
+ * checks only: no http request, no outcome record or body file write.
4318
+ * `httpRetry` overrides the dispatch retry defaults (tests only).
3997
4319
  * @param {any} job
4320
+ * @param {{ runChecks?: boolean, httpRetry?: { attempts?: number, delayMs?: number } }} [opts]
3998
4321
  * @returns {Promise<{ expected: Record<string, { ids: string[], failedIds: string[] }>, section: string }>}
3999
4322
  */
4000
- async function loadValidatorCriteriaContext(job) {
4323
+ async function loadValidatorCriteriaContext(job, { runChecks = true, httpRetry } = {}) {
4001
4324
  /** @type {Record<string, { ids: string[], failedIds: string[] }>} */
4002
4325
  const expected = {};
4003
4326
  try {
@@ -4012,7 +4335,8 @@ async function loadValidatorCriteriaContext(job) {
4012
4335
  let criteria = null;
4013
4336
  try { criteria = parsePrdFile(text).frontmatter.criteria; } catch { criteria = null; }
4014
4337
  if (!Array.isArray(criteria) || !criteria.length) continue;
4015
- const checks = await readStoredCriteriaChecks(job.cwd, epicId, slug);
4338
+ const stored = await readStoredCriteriaChecks(job.cwd, epicId, slug);
4339
+ const checks = runChecks ? await runDispatchCriteriaChecks(job.cwd, epicId, slug, criteria, stored, { httpRetry }) : stored;
4016
4340
  const exp = expectedFromCriteria(criteria, checks);
4017
4341
  if (exp) expected[slug] = exp;
4018
4342
  prds.push({ slug, criteria, checks });
@@ -4040,7 +4364,7 @@ function defaultScheduleSettle({ cwd, epicId }) {
4040
4364
  },
4041
4365
  readGateMs: readValidatorGateMs,
4042
4366
  jobBudget: { factor: budget.JOB_BUDGET_FACTOR, ceilingMs: budget.JOB_BUDGET_CEILING_MS },
4043
- sendPrompt: (tabId, prompt) => enqueueExternalPrompt(tabId, prompt, { origin: 'scheduler' }),
4367
+ sendPrompt: (tabId, prompt, extra) => enqueueExternalPrompt(tabId, prompt, { ...(extra || {}), origin: 'scheduler' }),
4044
4368
  appendResponseEvent: appendResponseEventIfKnown,
4045
4369
  };
4046
4370
  epicValidationHook.scheduleEpicSettle({ cwd, epicId }, (args) => epicValidationHook.runEpicSettle(args, deps));
@@ -4322,9 +4646,14 @@ async function notifyOriginatingTab(job, {
4322
4646
  // Cross-check per-criterion entries against the judged PRDs' frontmatter
4323
4647
  // criteria + stored check results: a missing id or met-on-failed-check
4324
4648
  // refuses the whole verdict.
4649
+ // The dispatch-time stamp (job.validatorCriteriaExpected) is what the
4650
+ // validator was shown; re-running the http/file checks here would judge
4651
+ // it against results it never saw and overwrite the outcome record.
4325
4652
  let expected = null;
4326
4653
  try {
4327
- const ctx = await loadValidatorCriteria(job);
4654
+ const stamp = job && job.validatorCriteriaExpected;
4655
+ const isPlain = !!stamp && typeof stamp === 'object' && !Array.isArray(stamp);
4656
+ const ctx = isPlain ? { expected: stamp } : await loadValidatorCriteria(job, { runChecks: false });
4328
4657
  if (ctx && ctx.expected && Object.keys(ctx.expected).length) expected = ctx.expected;
4329
4658
  } catch (e) {
4330
4659
  console.error('[scheduler] notifyOriginatingTab loadValidatorCriteria error', job?.slug, e);
@@ -4451,7 +4780,7 @@ async function notifyOriginatingTab(job, {
4451
4780
  return;
4452
4781
  }
4453
4782
 
4454
- sendPrompt(targetTabId, message, { origin: 'scheduler' });
4783
+ sendPrompt(targetTabId, message, { origin: 'scheduler', heldKind: 'job-notice' });
4455
4784
  } catch (e) {
4456
4785
  console.error('[scheduler] notifyOriginatingTab error', job?.slug, e);
4457
4786
  }
@@ -6002,11 +6331,14 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
6002
6331
  isArtifactOnly = false;
6003
6332
  }
6004
6333
  }
6005
- // Validator: list each judged PRD's structured criteria with their stored
6006
- // mechanical check results, so its per-criterion verdict entries use the
6334
+ // Validator: list each judged PRD's structured criteria with their
6335
+ // mechanical check results (http + file run fresh here, outside the sandbox), so its per-criterion verdict entries use the
6007
6336
  // same ids and never mark a failed check met (parseValidatorVerdict refuses that).
6008
6337
  if (job.agentType === 'validator') {
6009
- const { section } = await loadValidatorCriteriaContext({ ...job, cwd: job.cwd || cwd });
6338
+ const { section, expected } = await loadValidatorCriteriaContext({ ...job, cwd: job.cwd || cwd });
6339
+ // Stamped onto the queue row (spawnJob onPid) so notifyOriginatingTab
6340
+ // cross-checks the verdict against exactly these results.
6341
+ job.validatorCriteriaExpected = expected;
6010
6342
  if (section) prompt = `${prompt}\n\n${section}`;
6011
6343
  }
6012
6344
  prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun, isFixPlan: resolveIsFixPlan(job.slug, job.isFixPlan), isArtifactOnly, isValidator: job.agentType === 'validator' }) });
@@ -8034,14 +8366,16 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8034
8366
  source: 'spawnJob:dispatch',
8035
8367
  });
8036
8368
  delete s.jobs[idx].heldReason;
8037
- // A fresh dispatch means any gateShadow, looksDone, or
8038
- // evidenceScannedAt on this row was computed for an earlier
8039
- // runId/startedAt — never let any of them linger and read as this
8040
- // run's result (looksDone stale here would let rung 6 complete this
8041
- // run on the PREVIOUS run's evidence).
8369
+ // A fresh dispatch means any gateShadow, looksDone,
8370
+ // evidenceScannedAt, or artifactEvidence on this row was computed for
8371
+ // an earlier runId/startedAt — never let any of them linger and read
8372
+ // as this run's result (looksDone stale here would let rung 6
8373
+ // complete this run on the PREVIOUS run's evidence; a running row
8374
+ // must never carry another run's artifactEvidence).
8042
8375
  delete s.jobs[idx].gateShadow;
8043
8376
  delete s.jobs[idx].looksDone;
8044
8377
  delete s.jobs[idx].evidenceScannedAt;
8378
+ delete s.jobs[idx].artifactEvidence;
8045
8379
  s.jobs[idx].runId = runId;
8046
8380
  s.jobs[idx].startedAt = new Date().toISOString();
8047
8381
  // Dispatch-phase breadcrumb (PRD: dispatch-region diagnostic
@@ -8257,6 +8591,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8257
8591
  if (idx >= 0) {
8258
8592
  s.jobs[idx].sessionId = sessionId;
8259
8593
  if (job.agentSnapshotId) s.jobs[idx].agentSnapshotId = job.agentSnapshotId;
8594
+ if (job.validatorCriteriaExpected) s.jobs[idx].validatorCriteriaExpected = job.validatorCriteriaExpected;
8260
8595
  s.jobs[idx].runtime = { pid, runId, startedAt: s.jobs[idx].startedAt, sessionId, cwd };
8261
8596
  s.jobs[idx].dispatchPhase = 'spawned';
8262
8597
  s.jobs[idx].dispatchPhaseAt = new Date().toISOString();
@@ -8277,7 +8612,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8277
8612
  // Plan records are written in the worktree and never committed; copy
8278
8613
  // them to the main checkout before verify and before the checkout is
8279
8614
  // removed. Never throws (planRecordHarvest.cjs).
8280
- harvestJobPlanRecords(job, worktree.dir, job.cwd || defaultCwd);
8615
+ await harvestJobPlanRecords(job, worktree.dir, job.cwd || defaultCwd);
8281
8616
  // Capture artifact evidence before the worktree is removed: a
8282
8617
  // git-ignored artifact may live only here. Never breaks teardown.
8283
8618
  try {
@@ -8401,9 +8736,10 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
8401
8736
  // poller's own reads).
8402
8737
  billing.usageCircuit.recordFailure('executor_429');
8403
8738
  const logPath = path.join(runDir, `${job.slug}.log`);
8404
- const billingResetIso = await billingResetForPause();
8739
+ const billingReading = await billingReadingForPause();
8740
+ const billingResetIso = billingReading.resetsAt;
8405
8741
  const pauseState = await readQueue().catch(() => null);
8406
- const pauseThreshold = pauseState?.config?.utilizationThreshold;
8742
+ const pauseThreshold = bindingWindowPauseThreshold(pauseState?.config?.utilizationThreshold, billingReading, Date.now());
8407
8743
  const resetIso = resolveRateLimitPauseReset(logPath, billingResetIso, Date.now(), { billingUtilization: cachedUtilization, threshold: pauseThreshold });
8408
8744
  if (resetIso == null) logBillingResetRejected(billingResetIso, cachedUtilization, pauseThreshold);
8409
8745
  const observedAt = dispatchStartedAtMs;
@@ -9066,6 +9402,21 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
9066
9402
  } else {
9067
9403
  delete s.jobs[i2].uncommittedSnapshot;
9068
9404
  }
9405
+ // Persist this run's artifact evidence, bound to its runId, so the
9406
+ // stale needs_review rescan (reverifyNeedsReview) can verify a
9407
+ // worktree-only artifact after the worktree is gone. Cleared when
9408
+ // this run captured none so an older run's evidence never leaks.
9409
+ if (artifactEvidence) {
9410
+ s.jobs[i2].artifactEvidence = {
9411
+ runId,
9412
+ ok: artifactEvidence.ok,
9413
+ verified: artifactEvidence.verified,
9414
+ paths: artifactEvidence.paths,
9415
+ capturedAt: artifactEvidence.capturedAt,
9416
+ };
9417
+ } else {
9418
+ delete s.jobs[i2].artifactEvidence;
9419
+ }
9069
9420
  // Closed-set outcome taxonomy (issue #11 list A2) so a queue row
9070
9421
  // says WHY it ended without anyone opening the transcript.
9071
9422
  s.jobs[i2].terminalReason = launchFailure.deriveTerminalReason({
@@ -9597,13 +9948,85 @@ const toolConfirmationHeldKeys = new Map();
9597
9948
  // slug -> hold key under which its 'investigation_held' / 'resume_recovery_held'
9598
9949
  // audit event was already appended (one event per row per hold). A row's key
9599
9950
  // is removed when no hold is in force for it (it launches), so a later hold
9600
- // audits it once again.
9951
+ // audits it once again; every tick also clears both Maps when no hold is in
9952
+ // force and drops slugs no longer in the queue (pruneRowHeldKeys).
9601
9953
  const investigationHeldKeys = new Map();
9602
9954
  const resumeRecoveryHeldKeys = new Map();
9603
9955
 
9604
- /** Identity of one auto-dispatch hold: reason + window + resetsAt. */
9956
+ /**
9957
+ * Identity of one auto-dispatch hold: reason + window + reset rounded to the
9958
+ * minute (utilizationHold.holdIdentityKey — the usage API jitters resets_at
9959
+ * by about ±0.5 s from fetch to fetch).
9960
+ */
9605
9961
  function autoDispatchHoldKey(hold) {
9606
- return `${hold.reason}|${hold.window ?? ''}|${hold.resetsAt ?? ''}`;
9962
+ return autoDispatchHold.holdIdentityKey(hold);
9963
+ }
9964
+
9965
+ /** The audited fields of one auto-dispatch hold (null when none is in force). */
9966
+ function holdAuditFields(hold) {
9967
+ if (!hold) return null;
9968
+ return {
9969
+ reason: hold.reason,
9970
+ window: hold.window ?? null,
9971
+ percent: hold.percent ?? null,
9972
+ threshold: hold.threshold ?? null,
9973
+ baseThreshold: hold.baseThreshold ?? null,
9974
+ resetsAt: hold.resetsAt ?? null,
9975
+ holdKey: autoDispatchHold.holdIdentityKey(hold),
9976
+ };
9977
+ }
9978
+
9979
+ /**
9980
+ * One 'scheduler_human_press' audit event for a Run now / Fire next batch now
9981
+ * press, naming the auto-dispatch hold in force at press time (null = none),
9982
+ * so a human launch under a usage hold is told apart from a leak. Never throws.
9983
+ * @param {'run-now' | 'force-tick'} press
9984
+ */
9985
+ async function auditHumanPress(press) {
9986
+ try {
9987
+ let config = lastSeenConfig;
9988
+ try { config = (await readQueue()).config; } catch { /* last seen config */ }
9989
+ appendAuditEvent('scheduler_human_press', { press, hold: holdAuditFields(currentAutoDispatchHold(config)) });
9990
+ } catch (e) {
9991
+ console.error('[scheduler] human press audit failed', e?.message ?? String(e));
9992
+ }
9993
+ }
9994
+
9995
+ /**
9996
+ * One 'auto_dispatch_hold_bypassed' audit event for a human tick that passed
9997
+ * through `hold`, naming the slugs of the batch it launches. Never throws.
9998
+ */
9999
+ function auditHoldBypassed(hold, batch) {
10000
+ try {
10001
+ appendAuditEvent('auto_dispatch_hold_bypassed', {
10002
+ ...holdAuditFields(hold),
10003
+ dispatched: (batch || []).map((j) => j.slug),
10004
+ });
10005
+ } catch (e) {
10006
+ console.error('[scheduler] hold bypass audit failed', e?.message ?? String(e));
10007
+ }
10008
+ }
10009
+
10010
+ /**
10011
+ * Tick-level bound on the per-row held-key Maps. No hold in force → clear
10012
+ * both (a later hold audits every row once again); a hold in force → drop
10013
+ * slugs that are no longer a queue row (cancelled or archived while held).
10014
+ * `rawHold` is the tick's own hold decision, before any human bypass.
10015
+ * @param {any[] | undefined} jobs
10016
+ * @param {any} rawHold
10017
+ */
10018
+ function pruneRowHeldKeys(jobs, rawHold) {
10019
+ if (!rawHold) {
10020
+ investigationHeldKeys.clear();
10021
+ resumeRecoveryHeldKeys.clear();
10022
+ return;
10023
+ }
10024
+ const liveSlugs = new Set((jobs || []).map((j) => j.slug));
10025
+ for (const keys of [investigationHeldKeys, resumeRecoveryHeldKeys]) {
10026
+ for (const slug of keys.keys()) {
10027
+ if (!liveSlugs.has(slug)) keys.delete(slug);
10028
+ }
10029
+ }
9607
10030
  }
9608
10031
 
9609
10032
  /**
@@ -9646,6 +10069,8 @@ async function processToolConfirmationAnswers(state, { human = false } = {}) {
9646
10069
  // tick that bypasses a hold in force does not count as the hold clearing.
9647
10070
  const rawHold = currentAutoDispatchHold(state.config);
9648
10071
  if (!rawHold) toolConfirmationHeldKeys.clear();
10072
+ // Same bound for the per-row investigation / resume-recovery held keys.
10073
+ pruneRowHeldKeys(state.jobs, rawHold);
9649
10074
  if (!pending.length) return;
9650
10075
  // Same hold decision as the tick running this pass: an approval starts a
9651
10076
  // `claude -p --resume`, so an automatic tick under the hold leaves it
@@ -9913,18 +10338,24 @@ async function tickBody(gen, { bypassLoadGate, lastResort, human = false }) {
9913
10338
  // watchdog, boot/resume runDueJobs — holds at or above the threshold on
9914
10339
  // ANY live window of the last real reading, and under firePolicy
9915
10340
  // 'manual'. Only a human Run now / Fire next batch now passes through.
10341
+ // bypassedHold = the hold a human tick passed through (audited after the picker).
10342
+ let bypassedHold = null;
9916
10343
  {
9917
10344
  const hold = currentAutoDispatchHold(state.config);
9918
10345
  const nextHold = hold && hold.reason === 'utilization-held'
9919
- ? { window: hold.window, percent: hold.percent, threshold: hold.threshold, resetsAt: hold.resetsAt }
10346
+ ? { window: hold.window, percent: hold.percent, threshold: hold.threshold, baseThreshold: hold.baseThreshold ?? null, resetsAt: hold.resetsAt }
9920
10347
  : null;
9921
10348
  const holdKey = hold ? `${hold.reason}|${hold.window ?? ''}|${String(hold.percent)}` : null;
9922
10349
  const holdChanged = holdKey !== lastAutoDispatchHoldKey;
9923
10350
  utilizationHold = nextHold;
9924
10351
  lastAutoDispatchHoldKey = holdKey;
10352
+ const pendingCount = hold || openAutoDispatchHold
10353
+ ? state.jobs.filter((j) => j.status === 'pending' && !runningSet.has(j.slug)).length
10354
+ : 0;
10355
+ if (hold || openAutoDispatchHold) trackAutoDispatchHoldAudit(hold, pendingCount);
9925
10356
  if (hold) {
9926
- const pendingCount = state.jobs.filter((j) => j.status === 'pending' && !runningSet.has(j.slug)).length;
9927
10357
  if (human) {
10358
+ bypassedHold = hold;
9928
10359
  console.log(`[scheduler] ${hold.reason}: ${hold.detail} — human run bypassed the hold`);
9929
10360
  } else {
9930
10361
  if (holdChanged) {
@@ -9957,6 +10388,7 @@ async function tickBody(gen, { bypassLoadGate, lastResort, human = false }) {
9957
10388
  heldSlugs,
9958
10389
  satisfiedSlugsByCwd,
9959
10390
  });
10391
+ if (bypassedHold) auditHoldBypassed(bypassedHold, batch);
9960
10392
  if (batch.length === 0 && freeSlots === 0) {
9961
10393
  const snap = sessionSlots.snapshot();
9962
10394
  const pendingCount = state.jobs.filter((j) => j.status === 'pending').length;
@@ -10862,8 +11294,9 @@ async function reapDeadRunningJobs() {
10862
11294
  // observed 429 as a live one, and must open the same shared circuit.
10863
11295
  billing.usageCircuit.recordFailure('executor_429');
10864
11296
  const triggering = dead.find((d) => d.outcome === 'rate_limited');
10865
- const billingResetIso = await billingResetForPause();
10866
- const pauseThreshold = state.config?.utilizationThreshold;
11297
+ const billingReading = await billingReadingForPause();
11298
+ const billingResetIso = billingReading.resetsAt;
11299
+ const pauseThreshold = bindingWindowPauseThreshold(state.config?.utilizationThreshold, billingReading, Date.now());
10867
11300
  const resetIso = resolveRateLimitPauseReset(triggering.logPath, billingResetIso, Date.now(), { billingUtilization: cachedUtilization, threshold: pauseThreshold });
10868
11301
  if (resetIso == null) logBillingResetRejected(billingResetIso, cachedUtilization, pauseThreshold);
10869
11302
  const triggeringRow = triggering ? state.jobs.find((x) => x.slug === triggering.slug) : null;
@@ -11632,7 +12065,8 @@ function applyNeedsReviewAutoResolve(j, jobsInProject = []) {
11632
12065
  if ((j.exhaustedResolveAttempts ?? 0) > reviewLadder.NEEDS_REVIEW_RESOLVE_CAP) return null;
11633
12066
  const originIsGuardParked = !reviewLadder.isExhaustedAutoFix(j) && reviewLadder.isGuardParkedWithoutAutoFix(j);
11634
12067
 
11635
- if (j.looksDone) {
12068
+ // A looksDone stamped before PRD 4500 must never complete a FAIL row.
12069
+ if (j.looksDone && j.verifierVerdict !== 'sentinel_fail') {
11636
12070
  const attempt = j.exhaustedResolveAttempts ?? 0;
11637
12071
  const reason = originIsGuardParked
11638
12072
  ? `needs_review auto-resolve: guard verdict '${j.verifierVerdict}' with landed commit and looksDone evidence (${j.looksDone.rule}) — `
@@ -11843,6 +12277,10 @@ async function attributeLandedCommits(job, pathCommits, cwd) {
11843
12277
  * @returns {Promise<{commits: string[], paths: string[], detectedAt: string, rule: string} | null>}
11844
12278
  */
11845
12279
  async function computeLooksDone(job, fetchedCwds) {
12280
+ // An explicit executor FAIL is authoritative: the run said the work is not
12281
+ // done, so its own commits (often just a record of the blocker) are never
12282
+ // evidence that it is (PRD 4500; starry-night-2 863-fix, eac6e7e).
12283
+ if (job?.verifierVerdict === 'sentinel_fail') return null;
11846
12284
  const prdPath = (await resolveVerifyPrdPath(job)) ?? prdPaths.archivedPrdPathForJob(job);
11847
12285
  const paths = declaredPathsForPrd(prdPath);
11848
12286
  if (!paths.length) return null;
@@ -12255,6 +12693,24 @@ const PARK_ERRORS = Object.freeze({
12255
12693
  autofix_plan_unqueued: 'auto-fix investigation produced a fix plan that never reached the queue — parked',
12256
12694
  });
12257
12695
 
12696
+ /**
12697
+ * The artifact evidence persisted on a job row by spawnJob's finalize, but only
12698
+ * when it was captured for `runId` — the run the rescan is re-verifying.
12699
+ * Never throws.
12700
+ * @param {object} job
12701
+ * @param {string} runId
12702
+ * @returns {object|null}
12703
+ */
12704
+ function rescanArtifactEvidence(job, runId) {
12705
+ try {
12706
+ const ev = job?.artifactEvidence;
12707
+ if (!ev || typeof ev !== 'object' || Array.isArray(ev)) return null;
12708
+ return ev.runId === runId ? ev : null;
12709
+ } catch {
12710
+ return null;
12711
+ }
12712
+ }
12713
+
12258
12714
  async function reverifyNeedsReview() {
12259
12715
  const snap = await readQueue();
12260
12716
  // isGuardParkedWithoutAutoFix rows are NOT isRescanCandidate (their
@@ -12321,7 +12777,8 @@ async function reverifyNeedsReview() {
12321
12777
  }
12322
12778
  continue;
12323
12779
  }
12324
- const runDir = path.join(schedulerPaths.runsDir(), job.runId || reviewLadder.resolveRunId(job));
12780
+ const rescanRunId = job.runId || reviewLadder.resolveRunId(job);
12781
+ const runDir = path.join(schedulerPaths.runsDir(), rescanRunId);
12325
12782
  const prdPath = (await resolveVerifyPrdPath(job)) ?? prdPaths.archivedPrdPathForJob(job);
12326
12783
  // Derive committedDuringRun from the recorded run window. The live
12327
12784
  // commit-guard uses gitTreeGuard.gitHead() (before/after HEAD diff); here the run is
@@ -12344,6 +12801,9 @@ async function reverifyNeedsReview() {
12344
12801
  committedDuringRun,
12345
12802
  allowPreSentinelHeal: true,
12346
12803
  priorLandedCommit,
12804
+ // Evidence captured before this run's worktree was removed — only
12805
+ // when it belongs to the run being re-verified.
12806
+ artifactEvidence: rescanArtifactEvidence(job, rescanRunId),
12347
12807
  // job.landedCommit is THIS row's own last-run attribution (stamped by
12348
12808
  // spawnJob's finalize, survives resetJobFields) — the same
12349
12809
  // ground-truth-outranks-heuristics evidence spawnJob passes live,
@@ -12854,6 +13314,7 @@ function registerScheduleHandlers() {
12854
13314
  });
12855
13315
 
12856
13316
  ipcMain.handle('schedule:force-tick', async () => {
13317
+ await auditHumanPress('force-tick');
12857
13318
  // Bypass the billing-poll gate entirely — fire pending jobs immediately regardless of meter state.
12858
13319
  // Clears any existing pause first (same semantics as run-now).
12859
13320
  await clearPause('run-now');
@@ -12950,6 +13411,7 @@ function registerScheduleHandlers() {
12950
13411
  }));
12951
13412
 
12952
13413
  ipcMain.handle('schedule:run-now', async () => {
13414
+ await auditHumanPress('run-now');
12953
13415
  // Manual run-now overrides any auto-pause. Clear it first.
12954
13416
  await clearPause('run-now');
12955
13417
  runDueJobs({ bypassLoadGate: true, human: true }).catch((e) => logs.writeLine({ level: 'error', scope: 'scheduler', message: 'runDueJobs error (run-now)', meta: { error: e?.message } }));
@@ -13345,6 +13807,9 @@ function _setPeriodicReverifyEnabledForTests(enabled) {
13345
13807
 
13346
13808
  async function init() {
13347
13809
  ensureDirs();
13810
+ // Held scheduler turns (heldSchedulerTurns.cjs) consult the same auto-dispatch
13811
+ // hold tickBody applies — registered before boot reconcile can finish a job.
13812
+ heldSchedulerTurns.setHoldProvider(() => currentAutoDispatchHold(lastSeenConfig));
13348
13813
  // Boot phase — reconciliation, migrations, self-heal, first reset probe.
13349
13814
  // Guarded as a unit: everything below installs the timers that ARE the
13350
13815
  // running scheduler (poll loop, heartbeat, supervisor). A throw in here
@@ -13540,6 +14005,10 @@ async function init() {
13540
14005
  });
13541
14006
 
13542
14007
  await rescheduleTimer();
14008
+
14009
+ // Once after boot reconciliation: deliver any turns held across a restart
14010
+ // whose hold has since cleared (never rejects).
14011
+ drainHeldSchedulerTurns();
13543
14012
  } catch (e) {
13544
14013
  console.error('[scheduler] boot phase failed — starting timers anyway:', e?.message);
13545
14014
  try {
@@ -14019,6 +14488,14 @@ const remote = {
14019
14488
  return JSON.parse(JSON.stringify(Array.isArray(state?.jobs) ? state.jobs : []));
14020
14489
  },
14021
14490
 
14491
+ // listJobRows after any in-flight mutate() has written queue.json. A mutate
14492
+ // body appends job.status_changed BEFORE writeQueue, so the epic-state
14493
+ // emitter's recompute must wait for the write. Never calls mutate().
14494
+ async listJobRowsSettled() {
14495
+ try { await mutateTail; } catch { /* chain errors are not ours */ }
14496
+ return remote.listJobRows();
14497
+ },
14498
+
14022
14499
  // Single queue row lookup, used by cancelJob/updatePrd's status guards and
14023
14500
  // the admin GET /admin/scheduler/prds?slug= route (PRD 1024).
14024
14501
  async getJob(slug) {
@@ -14036,7 +14513,15 @@ const remote = {
14036
14513
  // long as the underlying PRD set doesn't change mid-page.
14037
14514
  async listPrds(filter = {}) {
14038
14515
  const filterCwd = normalizeListCwd(filter.cwd);
14039
- const all = await listPrdsShared({ cwd: filterCwd });
14516
+ // fresh: true (strictly the boolean) skips the single-flight and scans
14517
+ // now. It exists for the PRD-create cross-Epic guard, which reads under a
14518
+ // per-project lock and must never reuse a scan that began before another
14519
+ // create's write (2026-11-24: Bilko PRD 2005 duplicated 2001). In-process
14520
+ // callers only — the admin route never forwards it, since outside callers
14521
+ // piling up full scans is the 2026-11-08 heap incident the single-flight fixed.
14522
+ const all = filter.fresh === true
14523
+ ? await listPrdsInternal({ cwd: filterCwd })
14524
+ : await listPrdsShared({ cwd: filterCwd });
14040
14525
  const filtered = all.filter((entry) => {
14041
14526
  if (filterCwd && entry.cwd !== filterCwd) return false;
14042
14527
  if (filter.epicId && entry.epicId !== filter.epicId) return false;
@@ -14521,7 +15006,7 @@ const remote = {
14521
15006
  return {
14522
15007
  ok: false,
14523
15008
  error: `usage hold in force: ${hold.detail} - continue again once it clears`,
14524
- hold: { reason: hold.reason, window: hold.window, percent: hold.percent, threshold: hold.threshold, resetsAt: hold.resetsAt },
15009
+ hold: { reason: hold.reason, window: hold.window, percent: hold.percent, threshold: hold.threshold, baseThreshold: hold.baseThreshold ?? null, resetsAt: hold.resetsAt },
14525
15010
  };
14526
15011
  }
14527
15012
  const target = {
@@ -14644,6 +15129,7 @@ queueOps.bindQueueAccess({
14644
15129
 
14645
15130
  module.exports = {
14646
15131
  PARK_ERRORS,
15132
+ rescanArtifactEvidence,
14647
15133
  harvestJobArtifacts,
14648
15134
  jobArtifactRunId,
14649
15135
  applyDepHoldNotices,
@@ -14683,8 +15169,13 @@ module.exports = {
14683
15169
  loadSchedulerState,
14684
15170
  persistSchedulerState,
14685
15171
  getSchedulerStateSnapshot,
15172
+ _getOpenAutoDispatchHoldForTests,
15173
+ _auditHumanPressForTests: auditHumanPress,
15174
+ _forgetOpenAutoDispatchHoldForTests,
14686
15175
  computeDegradedBudget,
14687
15176
  utilizationReading,
15177
+ usageHoldThreshold,
15178
+ currentUsageHold,
14688
15179
  writeQueue,
14689
15180
  _setPeriodicReverifyEnabledForTests,
14690
15181
  _setLoadGateForTests,
@@ -14757,6 +15248,7 @@ module.exports = {
14757
15248
  applyOrphanOutcome,
14758
15249
  registerAdminRoutes,
14759
15250
  notifyOriginatingTab,
15251
+ drainHeldSchedulerTurns,
14760
15252
  flushDueReviewNotices,
14761
15253
  isNotifiableTerminalStatus,
14762
15254
  armSettleAfterValidatorBudgetKill,
@@ -14821,11 +15313,13 @@ module.exports = {
14821
15313
  pickRunDir,
14822
15314
  resolveRateLimitPauseReset,
14823
15315
  billingResetForPause,
15316
+ billingReadingForPause,
14824
15317
  computeEffectiveResumeAt,
14825
15318
  computeResumeDelay,
14826
15319
  FOREIGN_WIP_BLOCK_STREAK_LIMIT,
14827
15320
  validateForeignWipBlockClaim,
14828
15321
  requeueForeignWipBlockedJobs,
15322
+ __test: { bindingWindowPauseThreshold },
14829
15323
  };
14830
15324
 
14831
15325
  // Lazy path getters: resolved from SM_SCHEDULER_HOME at each read, never frozen