claude-code-session-manager 0.126.0 → 0.128.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 (107) hide show
  1. package/bin/cli.cjs +71 -9
  2. package/bin/supervise.cjs +84 -0
  3. package/dist/assets/{AgentLibrary-bzeuZN4F.js → AgentLibrary-cNQU5YWy.js} +1 -1
  4. package/dist/assets/{Button-8dWfDDuQ.js → Button-9dIPAOBg.js} +1 -1
  5. package/dist/assets/{DataModel-D4ybBPZN.js → DataModel-DrDJ6ysw.js} +1 -1
  6. package/dist/assets/{History-hsztE6yh.js → History-4rrDdWNP.js} +1 -1
  7. package/dist/assets/{Hooks-CRmZMQaW.js → Hooks-Bj_jF5Pa.js} +1 -1
  8. package/dist/assets/{Library-Czt3Bojd.js → Library-D-Wsxrh7.js} +1 -1
  9. package/dist/assets/{ListDetail-Cr6Ct_WX.js → ListDetail-D7Om0H8j.js} +1 -1
  10. package/dist/assets/{McpServers-CeXJ2bng.js → McpServers-CbIbSd5o.js} +1 -1
  11. package/dist/assets/{Memory-caujO8O3.js → Memory-DgQlvQrO.js} +1 -1
  12. package/dist/assets/{Panel-D64i9tGz.js → Panel-DZHiD8Ar.js} +1 -1
  13. package/dist/assets/{Permissions-DpWOIrvr.js → Permissions-CfzduF4B.js} +1 -1
  14. package/dist/assets/{Plugins-Bd1ekP5P.js → Plugins-D-AG5nAo.js} +2 -2
  15. package/dist/assets/{ProvenanceBadge-B96A_uZf.js → ProvenanceBadge-B9JSEjll.js} +1 -1
  16. package/dist/assets/{SaveBar-D0Y2t-Ao.js → SaveBar-mVKig6hL.js} +1 -1
  17. package/dist/assets/{Scheduler-Y5_YbNrC.js → Scheduler-DFTCnh60.js} +1 -1
  18. package/dist/assets/{ScopeSwitcher-BmWA_dP9.js → ScopeSwitcher-s8J-yr7Z.js} +1 -1
  19. package/dist/assets/{Settings-Bcf65bpL.js → Settings-BTmxRMaP.js} +1 -1
  20. package/dist/assets/{SkillReferenceGraph-BeSNXloA.js → SkillReferenceGraph-C5lKqf5y.js} +1 -1
  21. package/dist/assets/{Skills-DwnQKJVc.js → Skills-CxOacq0k.js} +1 -1
  22. package/dist/assets/{SystemPrompt-Dih6SCmL.js → SystemPrompt-BCWg5FAz.js} +1 -1
  23. package/dist/assets/{TagLibrary-BZ-Kp10P.js → TagLibrary-BnF0_PkG.js} +1 -1
  24. package/dist/assets/{TiptapBody-C2nEUmF7.js → TiptapBody-C2Iu6rZd.js} +1 -1
  25. package/dist/assets/{Toggle-Dw8-zNQo.js → Toggle-C-oD66BG.js} +1 -1
  26. package/dist/assets/{ViewTabs-CoYPKGN-.js → ViewTabs-Cs4v7vLY.js} +1 -1
  27. package/dist/assets/{historyTotals-BbKcNpV7.js → historyTotals-CbRSLD8f.js} +1 -1
  28. package/dist/assets/{index-BnKaYERU.css → index-DtdWBGrI.css} +1 -1
  29. package/dist/assets/index-DzY_GXYY.js +3081 -0
  30. package/dist/assets/{settingsSchema-6doG_61l.js → settingsSchema-bSBfHuan.js} +1 -1
  31. package/dist/assets/{skillFrontmatter-BYMYWDfb.js → skillFrontmatter-BEseWm8r.js} +1 -1
  32. package/dist/assets/{useAgentsDirWatch-Cqabjieh.js → useAgentsDirWatch-CdyHxKCI.js} +1 -1
  33. package/dist/index.html +2 -2
  34. package/dist-web/app.css +1 -1
  35. package/dist-web/app.js +343 -341
  36. package/package.json +1 -1
  37. package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -2
  38. package/scripts/scheduler-mcp-server.cjs +209 -7
  39. package/src/main/build-info.json +4 -4
  40. package/src/main/chatRunner.cjs +37 -4
  41. package/src/main/crashDiagnostics.cjs +83 -8
  42. package/src/main/health.cjs +16 -5
  43. package/src/main/index.cjs +46 -0
  44. package/src/main/ipcSchemas.cjs +107 -0
  45. package/src/main/lib/chatBootRecovery.cjs +136 -0
  46. package/src/main/lib/chatInflight.cjs +88 -0
  47. package/src/main/lib/claude/agentModelResolve.cjs +26 -7
  48. package/src/main/lib/claude/personaToolScope.cjs +40 -2
  49. package/src/main/lib/demo-video-kit/capture.cjs +113 -0
  50. package/src/main/lib/demo-video-kit/character.cjs +97 -0
  51. package/src/main/lib/demo-video-kit/checks.cjs +150 -0
  52. package/src/main/lib/demo-video-kit/frames.cjs +200 -0
  53. package/src/main/lib/demo-video-kit/seedKit.cjs +52 -0
  54. package/src/main/lib/demo-video-kit/sound.cjs +312 -0
  55. package/src/main/lib/epic/epicDelegationStats.cjs +1 -0
  56. package/src/main/lib/epic/epicSweepValidator.cjs +60 -6
  57. package/src/main/lib/epic/epicValidationHook.cjs +31 -3
  58. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +71 -15
  59. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +185 -34
  60. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +15 -0
  61. package/src/main/lib/mcpToolCatalog.cjs +93 -14
  62. package/src/main/lib/opsOwnership.cjs +9 -5
  63. package/src/main/lib/persona-macro/builtinMacros.cjs +30 -5
  64. package/src/main/lib/persona-macro/macroJobDispatch.cjs +116 -0
  65. package/src/main/lib/persona-macro/macroJobIpc.cjs +50 -0
  66. package/src/main/lib/persona-macro/macroJobStatus.cjs +112 -0
  67. package/src/main/lib/persona-macro/macroLibrary.cjs +73 -3
  68. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +100 -0
  69. package/src/main/lib/prd/prdCreate.cjs +17 -2
  70. package/src/main/lib/prd/prdFrontmatter.cjs +7 -2
  71. package/src/main/lib/process/childWithLog.cjs +38 -95
  72. package/src/main/lib/process/memoryScope.cjs +140 -0
  73. package/src/main/lib/process/ozonePlatform.cjs +15 -0
  74. package/src/main/lib/process/procIdentity.cjs +10 -3
  75. package/src/main/lib/process/scopeOomPolicy.cjs +69 -0
  76. package/src/main/lib/project-pages/pagesLibrary.cjs +171 -0
  77. package/src/main/lib/project-pages/playerBridge.cjs +129 -0
  78. package/src/main/lib/scheduler/cpuSample.cjs +147 -0
  79. package/src/main/lib/scheduler/definitionOfDone.cjs +40 -0
  80. package/src/main/lib/scheduler/jobLeftovers.cjs +204 -0
  81. package/src/main/lib/scheduler/jobSupervisorRecord.cjs +2 -1
  82. package/src/main/lib/scheduler/loadGate.cjs +116 -45
  83. package/src/main/lib/scheduler/queueStore.cjs +5 -2
  84. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  85. package/src/main/lib/scheduler/schedulerBatch.cjs +10 -3
  86. package/src/main/lib/scheduler/schedulerConfig.cjs +7 -2
  87. package/src/main/lib/smfileHeaders.cjs +11 -3
  88. package/src/main/lib/telemetry/crashTelemetry.cjs +8 -4
  89. package/src/main/projectPages.cjs +107 -30
  90. package/src/main/promptSessionsIpc.cjs +131 -0
  91. package/src/main/scheduler/budget.cjs +31 -0
  92. package/src/main/scheduler/prdParser.cjs +2 -0
  93. package/src/main/scheduler/prdPaths.cjs +54 -0
  94. package/src/main/scheduler/reviewLadder.cjs +17 -0
  95. package/src/main/scheduler/starvation.cjs +22 -0
  96. package/src/main/scheduler.cjs +548 -77
  97. package/src/main/seedSchedulerMcp.cjs +10 -1
  98. package/src/main/templates/PRD_AUTHORING.md +5 -2
  99. package/src/main/transcripts.cjs +8 -0
  100. package/src/main/usage.cjs +4 -2
  101. package/src/main/webRemote.cjs +3 -1
  102. package/src/preload/api.d.ts +113 -7
  103. package/src/preload/apiSurface.json +70 -0
  104. package/src/preload/index.cjs +13 -0
  105. package/src/seed/agents/demo-video-builder.md +141 -43
  106. package/src/seed/agents/project-home-builder.md +26 -13
  107. package/dist/assets/index-DgPUERhe.js +0 -3079
@@ -100,6 +100,7 @@ const prdParser = require('./scheduler/prdParser.cjs');
100
100
  const reviewLadder = require('./scheduler/reviewLadder.cjs');
101
101
  const starvation = require('./scheduler/starvation.cjs');
102
102
  const budget = require('./scheduler/budget.cjs');
103
+ const { validatorEstimateMinutes } = require('./lib/epic/epicSweepValidator.cjs');
103
104
  const gitTreeGuard = require('./scheduler/gitTreeGuard.cjs');
104
105
  const prdPaths = require('./scheduler/prdPaths.cjs');
105
106
  const sessionsStore = require('./sessionsStore.cjs');
@@ -119,6 +120,7 @@ const { isFixPlanSlug, classifyDiscoveredFixPlan, resolveIsFixPlan } = require('
119
120
  const { landedSinceRun, landedOnMainSince } = require('./lib/scheduler/landedSinceRun.cjs');
120
121
  const { declaredPathsForPrd, issuedAtForPrd } = require('./lib/prd/prdDeclaredPaths.cjs');
121
122
  const { identity: procIdentityOf, isDifferentProcess } = require('./lib/process/procIdentity.cjs');
123
+ const jobLeftovers = require('./lib/scheduler/jobLeftovers.cjs');
122
124
  const logs = require('./logs.cjs');
123
125
  const { schemas, validated, SCHEDULE_SLUG_RE } = require('./ipcSchemas.cjs');
124
126
  const { readBody, sendJson } = require('./lib/feedback-remote/localAdminHttp.cjs');
@@ -142,7 +144,7 @@ const { pickForProject, pickNextBatch, findStarvedProjects, DEFAULT_PROJECT_CWD,
142
144
  const { runDefinitionOfDoneOnDrain } = require('./lib/scheduler/dodDrainHook.cjs');
143
145
  const { writeRcaReport, extractRcaBlock } = require('./lib/scheduler/rcaReport.cjs');
144
146
  const queueHistory = require('./lib/scheduler/queueHistory.cjs');
145
- const { resolveGate, runGateSequence } = require('./lib/scheduler/definitionOfDone.cjs');
147
+ const { resolveGate, runGateSequence, gateTimeoutMs } = require('./lib/scheduler/definitionOfDone.cjs');
146
148
  const queueOps = require('./queueOps.cjs');
147
149
  // Feedback-auto-PRD sweep — formerly only run by the external scheduler-watchdog
148
150
  // while the app was down (PRD 686 moved it in-app so it also runs while alive).
@@ -152,7 +154,7 @@ const queueOps = require('./queueOps.cjs');
152
154
  const { listEpicPrdDirs, listArchivedPrdDirs, deriveProjectCwdFromPrdPath } = require('./lib/prd/prdLocations.cjs');
153
155
  const { ensureEpic, appendPrdCreatedEvent, readActiveIndex } = require('./lib/epic/epicMint.cjs');
154
156
  const agentModelResolve = require('./lib/claude/agentModelResolve.cjs');
155
- const { buildPersonaToolScope, personaToolScopeArgs } = require('./lib/claude/personaToolScope.cjs');
157
+ const { buildPersonaToolScope, personaToolScopeArgs, personaToolScopeEnv } = require('./lib/claude/personaToolScope.cjs');
156
158
  const { resolveEpicEffort, effortArgs } = require('./lib/claude/agentEffortResolve.cjs');
157
159
  const { transitionJob, STATUS_HISTORY_CAP, LEGAL_TRANSITIONS } = require('./lib/scheduler/scheduleJobTransitions.cjs');
158
160
  const { buildContextDigest, composeExecutorPrompt } = require('./lib/epic/epicContextDigest.cjs');
@@ -433,13 +435,12 @@ const MIN_FREE_MB_PER_JOB = 2500;
433
435
  // MemAvailable before the per-job gate runs. See availableForJobs().
434
436
  const RESERVED_HOST_MB = 3000;
435
437
 
436
- // oom_score_adj applied to each spawned claude -p job (range -1000..1000;
437
- // Electron inherits the default 0). A positive bias makes the kernel OOM killer
438
- // prefer a disposable, restartable job over Electron — whose death SIGHUPs every
439
- // pty and drops the sleep inhibitor. The job's build subprocesses (tsc/vite)
440
- // inherit it, so the actual memory hogs are the preferred victims. The gate caps
441
- // how many START; this decides who dies if a spike slips through anyway.
442
- const OOM_SCORE_ADJ_JOB = 500;
438
+ // oom_score_adj for each claude -p job (Electron stays 0): jobs die before Electron.
439
+ // Badness = rss + adj/1000 * (RAM+swap): 500 adds ~20 GB here, 200 ~8 GB (Chrome's own 200).
440
+ // 2026-10-31: a 388 MB Blender (+20 GB) outranked an 11.5 GB Chrome (+8 GB) and died in
441
+ // its place while the hog kept growing. 200 lets size decide among job children and
442
+ // still outranks Electron. The gate caps starts; this picks the victim of a slipped spike.
443
+ const OOM_SCORE_ADJ_JOB = 200;
443
444
 
444
445
  const DEFAULT_CONFIG = {
445
446
  offsetMinutes: 15,
@@ -469,18 +470,54 @@ const DEFAULT_CONFIG = {
469
470
  * open (returns Infinity) on darwin or on any parse/read error so the gate
470
471
  * never blocks scheduling on unsupported platforms.
471
472
  */
472
- function getAvailableMemMb() {
473
- if (process.platform !== 'linux') return Infinity;
473
+ function parseMemInfo(raw) {
474
+ const kb = (name) => {
475
+ const m = String(raw).match(new RegExp(`^${name}:\\s+(\\d+)\\s+kB`, 'm'));
476
+ return m ? Math.floor(parseInt(m[1], 10) / 1024) : null;
477
+ };
478
+ const avail = kb('MemAvailable');
479
+ return {
480
+ availableMb: avail === null ? Infinity : avail,
481
+ swapTotalMb: kb('SwapTotal') ?? 0,
482
+ swapFreeMb: kb('SwapFree') ?? 0,
483
+ };
484
+ }
485
+
486
+ /**
487
+ * Reads /proc/meminfo; fails open (Infinity, no swap) off Linux or on any error.
488
+ * SM_MEMINFO_PATH redirects the read to a fixture file. It is for tests only —
489
+ * nothing in production sets it.
490
+ */
491
+ function readMemInfo() {
492
+ const open = { availableMb: Infinity, swapTotalMb: 0, swapFreeMb: 0 };
493
+ if (process.platform !== 'linux') return open;
474
494
  try {
475
- const raw = fs.readFileSync('/proc/meminfo', 'utf8');
476
- const m = raw.match(/^MemAvailable:\s+(\d+)\s+kB/m);
477
- if (!m) return Infinity;
478
- return Math.floor(parseInt(m[1], 10) / 1024);
495
+ return parseMemInfo(fs.readFileSync(process.env.SM_MEMINFO_PATH || '/proc/meminfo', 'utf8'));
479
496
  } catch {
480
- return Infinity;
497
+ return open;
481
498
  }
482
499
  }
483
500
 
501
+ let swapGateLogged = false;
502
+ function getAvailableMemMb() {
503
+ return readMemInfo().availableMb;
504
+ }
505
+
506
+ const SWAP_LOW_FREE_FRACTION = 0.10;
507
+
508
+ /**
509
+ * Pure helper: when swap is configured and under 10% free, allow at most ONE
510
+ * job running in total (so 0 running still lets 1 start — never a hard hold
511
+ * at zero). No swap configured = no clamp. Exported for unit tests.
512
+ */
513
+ function swapLimitedBatchSize(mem, runningCount, batchLen) {
514
+ const total = Number(mem?.swapTotalMb) || 0;
515
+ if (total <= 0) return batchLen;
516
+ const free = Number(mem?.swapFreeMb) || 0;
517
+ if (free >= total * SWAP_LOW_FREE_FRACTION) return batchLen;
518
+ return Math.min(batchLen, Math.max(0, 1 - runningCount));
519
+ }
520
+
484
521
  /**
485
522
  * Pure helper: clamp a batch down so launching `toLaunch` more jobs doesn't
486
523
  * drop available memory below MIN_FREE_MB_PER_JOB per active slot.
@@ -525,6 +562,83 @@ function biasJobOomScore(pid) {
525
562
  }
526
563
  }
527
564
 
565
+ // ---------- job memory scope (systemd cgroup cap) ----------
566
+
567
+ const memoryScope = require('./lib/process/memoryScope.cjs');
568
+
569
+ /**
570
+ * Decide whether a job's spawn target is wrapped in a systemd memory scope.
571
+ * Returns { spawn, unit }: unwrapped → the input target and unit null (today's
572
+ * behaviour untouched); wrapped → systemd-run command/args (argv0 dropped: the
573
+ * scope execs `claude` in place, so the pid and process group stay the job's).
574
+ * Unit = sm-job-<sanitized slug>-<run timestamp>.
575
+ */
576
+ function planJobScope({ jobSpawn, jobArgs, slug, startedAt, deps = {} }) {
577
+ // Limits first: with the cap off, never probe systemd.
578
+ const limits = (deps.memoryLimitsFor || memoryScope.memoryLimitsFor)({ totalRamMb: Math.floor(os.totalmem() / 1048576) });
579
+ const supported = limits ? (deps.scopeSupported || memoryScope.scopeSupported)() : false;
580
+ if (!supported || !limits) return { spawn: jobSpawn, unit: null };
581
+ const unit = `sm-job-${memoryScope.sanitizeUnit(slug)}-${startedAt}`;
582
+ const wrapped = (deps.wrapInMemoryScope || memoryScope.wrapInMemoryScope)({
583
+ command: jobSpawn.command, args: jobSpawn.args || jobArgs, unit, limits,
584
+ });
585
+ return { spawn: { ...jobSpawn, command: wrapped.command, args: wrapped.args, argv0: undefined }, unit };
586
+ }
587
+
588
+ /** Reads the job's cgroup dir from /proc/<pid>/cgroup (cgroup v2). Null when unavailable. */
589
+ function readJobCgroupDir(pid, unit, fsImpl = fs) {
590
+ try {
591
+ const line = String(fsImpl.readFileSync(`/proc/${pid}/cgroup`, 'utf8')).split('\n').find((l) => l.startsWith('0::'));
592
+ const rel = line ? line.slice(3).trim() : '';
593
+ if (!rel || (unit && !rel.includes(unit))) return null;
594
+ return path.join('/sys/fs/cgroup', rel);
595
+ } catch {
596
+ return null;
597
+ }
598
+ }
599
+
600
+ /** Reads memory.peak + oom_kill into state.peak/state.oomKills; keeps the last good values when files are gone. */
601
+ function sampleJobScope(state, fsImpl = fs) {
602
+ if (!state || !state.cgroupDir) return;
603
+ try {
604
+ const peak = Number(String(fsImpl.readFileSync(path.join(state.cgroupDir, 'memory.peak'), 'utf8')).trim());
605
+ if (Number.isFinite(peak)) state.peak = peak;
606
+ } catch { /* gone: keep last */ }
607
+ try {
608
+ const m = /^oom_kill\s+(\d+)/m.exec(String(fsImpl.readFileSync(path.join(state.cgroupDir, 'memory.events'), 'utf8')));
609
+ if (m) state.oomKills = Number(m[1]);
610
+ } catch { /* gone: keep last */ }
611
+ }
612
+
613
+ const JOB_SCOPE_SAMPLE_MS = 30000;
614
+
615
+ /** Starts the unref'd 30 s sampler once cgroupDir is known; finalizeJobScope clears it. */
616
+ function startJobScopeSampling(state, fsImpl = fs) {
617
+ if (!state || !state.cgroupDir || state.finalized || state.sampler) return;
618
+ sampleJobScope(state, fsImpl);
619
+ state.sampler = setInterval(() => sampleJobScope(state, fsImpl), JOB_SCOPE_SAMPLE_MS);
620
+ if (state.sampler.unref) state.sampler.unref();
621
+ }
622
+
623
+ /** Logs the last sampled memory.peak + oom_kill to the run log, then stops the scope exactly once. */
624
+ function finalizeJobScope(state, safeLog, deps = {}) {
625
+ if (!state || !state.unit || state.finalized) return;
626
+ state.finalized = true;
627
+ const fsImpl = deps.fs || fs;
628
+ if (state.sampler) { clearInterval(state.sampler); state.sampler = null; }
629
+ try {
630
+ if (!state.cgroupDir && state.pid) state.cgroupDir = readJobCgroupDir(state.pid, state.unit, fsImpl);
631
+ sampleJobScope(state, fsImpl);
632
+ const hasPeak = Number.isFinite(state.peak);
633
+ const hasOom = state.oomKills !== undefined && state.oomKills !== null;
634
+ if (hasPeak || hasOom) {
635
+ safeLog(`\n[scheduler] memory scope ${state.unit}: peak=${hasPeak ? `${Math.round(state.peak / 1048576)}MB` : 'n/a'} ` +
636
+ `oom_kill=${hasOom ? state.oomKills : 'n/a'}\n`);
637
+ }
638
+ } catch { /* stats are best-effort */ }
639
+ (deps.stopScope || memoryScope.stopScope)(state.unit);
640
+ }
641
+
528
642
  // ---------- fs helpers ----------
529
643
 
530
644
  // ---------- per-project PRD dir resolution (PRD 808) ----------
@@ -1455,7 +1569,61 @@ const warnedUnregisteredEpics = new Set();
1455
1569
  /** @type {number | null} last flat-sweep start (ms); null until first pass. */
1456
1570
  let lastFlatSweepMs = null;
1457
1571
 
1572
+ // Parse cache for reconcile's parse loop, keyed by path and validated against
1573
+ // a FRESH stat (mtimeMs + size) every pass — the cache never decides a file
1574
+ // exists, only that its content is unchanged. Pruned to the live file list
1575
+ // after each loop so deleted PRDs cannot accumulate.
1576
+ /** @type {Map<string, { mtimeMs: number, size: number, parsed: any }>} */
1577
+ const reconcileParseCache = new Map();
1578
+ const RECONCILE_YIELD_EVERY = 10;
1579
+
1580
+ // Single-flight: one pass at a time; requests arriving mid-pass set ONE rerun
1581
+ // flag and resolve when the following pass ends. The rerun uses the most
1582
+ // recent waiter's state object.
1583
+ let reconcileRunning = false;
1584
+ let reconcileRerun = false;
1585
+ /** @type {Array<{ resolve: (s: any) => void, reject: (e: any) => void }>} */
1586
+ let reconcileWaiters = [];
1587
+ let reconcileRerunState = null;
1588
+ let reconcileFirstError = null;
1589
+
1458
1590
  async function reconcile(state) {
1591
+ if (reconcileRunning) {
1592
+ reconcileRerun = true;
1593
+ reconcileRerunState = state;
1594
+ return new Promise((resolve, reject) => { reconcileWaiters.push({ resolve, reject }); });
1595
+ }
1596
+ reconcileRunning = true;
1597
+ try {
1598
+ let result;
1599
+ try {
1600
+ result = await reconcilePass(state);
1601
+ } catch (e) {
1602
+ // Waiters still get their pass; the caller sees its own failure.
1603
+ if (!reconcileRerun) throw e;
1604
+ reconcileFirstError = e;
1605
+ }
1606
+ while (reconcileRerun) {
1607
+ reconcileRerun = false;
1608
+ const waiters = reconcileWaiters;
1609
+ reconcileWaiters = [];
1610
+ const st = reconcileRerunState;
1611
+ reconcileRerunState = null;
1612
+ try {
1613
+ const r = await reconcilePass(st);
1614
+ for (const w of waiters) w.resolve(r);
1615
+ } catch (e) {
1616
+ for (const w of waiters) w.reject(e);
1617
+ }
1618
+ }
1619
+ if (reconcileFirstError) { const e = reconcileFirstError; reconcileFirstError = null; throw e; }
1620
+ return result;
1621
+ } finally {
1622
+ reconcileRunning = false;
1623
+ }
1624
+ }
1625
+
1626
+ async function reconcilePass(state) {
1459
1627
  // Defence in depth — tickQueue already gates on this, but reconcile is the
1460
1628
  // function that would do the damage (every unmatched PRD .md becomes a
1461
1629
  // fresh 'pending' row), so it refuses the poison state itself.
@@ -1508,11 +1676,22 @@ async function reconcile(state) {
1508
1676
  // the bare `onDisk` (unscoped) since a same-slug NEW-PRD collision across
1509
1677
  // two projects is a rarer edge this reconcile pass doesn't yet resolve.
1510
1678
  const onDiskByCwd = new Map();
1679
+ let parsedCount = 0;
1511
1680
  for (const f of files) {
1681
+ if (++parsedCount % RECONCILE_YIELD_EVERY === 0) await new Promise((r) => setImmediate(r));
1512
1682
  try {
1513
- // Per-file await: parsing is mtime-cached so steady-state hits zero
1514
- // disk reads; on cold cache the awaits keep the main thread responsive.
1515
- const p = await parsePrd(f);
1683
+ // Fresh stat every pass; reuse the cached parse only when path, mtimeMs
1684
+ // and size are all unchanged (no content read).
1685
+ let p;
1686
+ let st = null;
1687
+ try { st = await fsp.stat(f); } catch { reconcileParseCache.delete(f); }
1688
+ const hit = st ? reconcileParseCache.get(f) : null;
1689
+ if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) {
1690
+ p = hit.parsed;
1691
+ } else {
1692
+ p = await parsePrd(f);
1693
+ if (st) reconcileParseCache.set(f, { mtimeMs: st.mtimeMs, size: st.size, parsed: p });
1694
+ }
1516
1695
  onDisk.set(p.slug, p);
1517
1696
  if (p.cwd) onDiskByCwd.set(`${p.slug}::${p.cwd}`, p);
1518
1697
  } catch (e) {
@@ -1530,6 +1709,10 @@ async function reconcile(state) {
1530
1709
  }
1531
1710
  return onDisk.get(slug);
1532
1711
  }
1712
+ if (reconcileParseCache.size > 0) {
1713
+ const liveFiles = new Set(files);
1714
+ for (const k of reconcileParseCache.keys()) if (!liveFiles.has(k)) reconcileParseCache.delete(k);
1715
+ }
1533
1716
  phaseMs.parseLoop = Date.now() - phaseStartMs;
1534
1717
 
1535
1718
  const next = [];
@@ -1619,6 +1802,7 @@ async function reconcile(state) {
1619
1802
  ?? resolveOriginSessionId(refreshedCwd, p.epicId ?? reconcileSourcePromptId(job, p.sourcePromptId)),
1620
1803
  bodyPreview: p.body.split('\n').slice(0, 6).join('\n'),
1621
1804
  agentType: p.agentType ?? job.agentType ?? null,
1805
+ macroId: p.macroId ?? job.macroId ?? null,
1622
1806
  };
1623
1807
  // Adopt path: a row parked 'quarantined' (no createdVia provenance when
1624
1808
  // discovered) whose PRD file now carries a stamp — written via the
@@ -1742,6 +1926,7 @@ async function reconcile(state) {
1742
1926
  originSessionId: inv.row?.originSessionId ?? resolveOriginSessionId(repairedCwd, p.epicId ?? p.sourcePromptId),
1743
1927
  bodyPreview: p.body.split('\n').slice(0, 6).join('\n'),
1744
1928
  agentType: p.agentType ?? inv.row?.agentType ?? null,
1929
+ macroId: p.macroId ?? inv.row?.macroId ?? null,
1745
1930
  };
1746
1931
  const reason = `reconcile: repaired invalid status ${JSON.stringify(oldStatus)}`;
1747
1932
  // A repair is not a lifecycle transition — the corrupted `status` was
@@ -1794,8 +1979,23 @@ async function reconcile(state) {
1794
1979
  }
1795
1980
 
1796
1981
  let staleNewDiscoveryCount = 0;
1982
+ // Reads use queueStore's cached project list (up to 120 s old) while PRD
1983
+ // discovery sees every project. A project with a real queue file that this
1984
+ // read never covered looks empty, so minting would write a shard holding
1985
+ // only fresh rows over the real ones (same danger listPrdFiles guards for
1986
+ // quarantined shards). Skip such PRDs and bust the cache for the next read.
1987
+ const covered = Array.isArray(state.sourceCwds) ? new Set(state.sourceCwds) : null;
1988
+ const uncovered = new Map();
1797
1989
  for (const [slug, p] of onDisk) {
1798
1990
  if (seen.has(slug)) continue;
1991
+ if (covered) {
1992
+ const mintCwd = p.cwd ?? deriveProjectCwdFromPrdPath(p.path) ?? null;
1993
+ if (mintCwd && !covered.has(mintCwd) && fs.existsSync(queueStore.projectQueuePath(mintCwd))) {
1994
+ if (!uncovered.has(mintCwd)) uncovered.set(mintCwd, []);
1995
+ uncovered.get(mintCwd).push(slug);
1996
+ continue;
1997
+ }
1998
+ }
1799
1999
  // Security gate: a PRD's file location IS its Epic membership
1800
2000
  // (prdLocations.deriveEpicIdFromPrdPath / p.epicId). Before this check,
1801
2001
  // the scheduler queued ANY .md file it found under an Epic's prds/ dir
@@ -1878,6 +2078,7 @@ async function reconcile(state) {
1878
2078
  originSessionId: resolveOriginSessionId(discoveredCwd, p.epicId ?? p.sourcePromptId),
1879
2079
  bodyPreview: p.body.split('\n').slice(0, 6).join('\n'),
1880
2080
  agentType: p.agentType ?? null,
2081
+ macroId: p.macroId ?? null,
1881
2082
  status: 'pending',
1882
2083
  // Enqueue time (PRD 1086/1087): the cross-project fairness tiebreak and
1883
2084
  // the starvation escalation both need a provable age for a pending row;
@@ -1961,6 +2162,11 @@ async function reconcile(state) {
1961
2162
  } catch { /* stat is best-effort reporting only */ }
1962
2163
  next.push(entry);
1963
2164
  }
2165
+ if (uncovered.size > 0) {
2166
+ queueStore.bustCwdCache();
2167
+ console.warn(`[scheduler] reconcile: skipped minting PRDs for project(s) whose queue file this read did not cover: ${[...uncovered.keys()].join(', ')}`);
2168
+ for (const [cwd, skippedPrds] of uncovered) appendAuditEvent('reconcile_uncovered_project', { cwd, skippedPrds });
2169
+ }
1964
2170
  if (staleNewDiscoveryCount > 0) {
1965
2171
  console.warn(`[scheduler] reconcile: ${staleNewDiscoveryCount} PRD(s) discovered this pass were already older than one poll interval with no prior queue row`);
1966
2172
  }
@@ -2295,7 +2501,8 @@ let cancelToken = { cancelled: false };
2295
2501
  let lastMemGate = null;
2296
2502
  // CPU-load launch gate (PRD 1085, lib/scheduler/loadGate.cjs) — innermost launch
2297
2503
  // predicate after pool → project cap → memory. Withholds launches only.
2298
- const loadGate = createLoadGate();
2504
+ let loadGate = createLoadGate();
2505
+ function _setLoadGateForTests(gate) { loadGate = gate; }
2299
2506
 
2300
2507
  // Last tickQueue outcome, kept for the UI. tickQueue already computes a precise
2301
2508
  // reason for every way a batch can come back empty (dependency holds, slot
@@ -2304,6 +2511,9 @@ const loadGate = createLoadGate();
2304
2511
  // actually pinned at 1 with nothing on screen explaining why. This is that
2305
2512
  // explanation, recorded once per tick and broadcast with the rest of the state.
2306
2513
  let lastTick = null;
2514
+ // Last tick that did NOT fire for a real hold (not already-running/drained); a fired
2515
+ // tick stores no reason, so the starve alert reads this to still name the limiter.
2516
+ let lastHoldTick = null;
2307
2517
  // Strips the leading '[scheduler] <word> [..]: ' prefix from a tick detail.
2308
2518
  // keepWord=true strips only the '[scheduler] ' tag and keeps '<word>: ' (the
2309
2519
  // heartbeat wants the hold kind, e.g. 'quiet-machine: lease held ...').
@@ -2313,6 +2523,7 @@ function stripTickDetailPrefix(detail, { keepWord = false } = {}) {
2313
2523
  }
2314
2524
  function recordTick(outcome, extra = {}) {
2315
2525
  lastTick = { ...outcome, ...extra, at: new Date().toISOString() };
2526
+ if (!outcome.fired && outcome.reason !== 'already-running' && outcome.reason !== 'drained') lastHoldTick = lastTick;
2316
2527
  return outcome;
2317
2528
  }
2318
2529
 
@@ -2350,14 +2561,29 @@ function applyPauseCleared(wasPaused, token) {
2350
2561
  /**
2351
2562
  * Human-readable explanation for a `reason: 'load-deferred'` tick, surfaced
2352
2563
  * to the renderer via lastTick.detail. Names the gate, the measured ratio,
2353
- * the threshold and how long the stretch has been held — the box could sit
2354
- * gated for 80+ minutes with nothing in the UI naming why (PRD: load gate
2355
- * hysteresis). Pure so it's unit-testable without driving tickQueue's full
2564
+ * the threshold and how long this gate itself has held a batch that slots and
2565
+ * memory admitted (heldMs). Pure so it's unit-testable without driving tickQueue's full
2356
2566
  * fs/worktree machinery.
2357
2567
  */
2358
2568
  function formatLoadGateDetail(load) {
2359
- const heldMinutes = Math.round(load.gatedSinceMs / 60_000);
2360
- return `CPU load gate: loadavg1 ${load.loadavg1} / ${load.cores} cores = ${load.ratio} > threshold ${load.threshold}, held for ${heldMinutes}m`;
2569
+ const heldMinutes = Math.round(load.heldMs / 60_000);
2570
+ const cpu = load.cpuBusy == null
2571
+ ? 'no CPU sample yet'
2572
+ : `CPU ${Math.round(load.cpuBusy * 100)}% busy over ${Math.round(load.cpuWindowMs / 1000)}s`;
2573
+ return `CPU load gate: loadavg1 ${load.loadavg1} / ${load.cores} cores = ${load.ratio} > threshold ${load.threshold}, ${cpu}, held ${heldMinutes}m with slots and memory free`;
2574
+ }
2575
+
2576
+ function loadGateAuditFields(load) {
2577
+ return {
2578
+ loadavg1: load.loadavg1, cores: load.cores, ratio: load.ratio, threshold: load.threshold,
2579
+ cpuBusy: load.cpuBusy, cpuIowait: load.cpuIowait, cpuWindowMs: load.cpuWindowMs, heldMs: load.heldMs,
2580
+ };
2581
+ }
2582
+
2583
+ function loadGateStallEvent(load, batch, lead) {
2584
+ const byProject = {};
2585
+ for (const j of batch) byProject[j.cwd] = { held: (byProject[j.cwd]?.held || 0) + 1 };
2586
+ return { message: `${lead} ${formatLoadGateDetail(load)}`, total: batch.length, byProject };
2361
2587
  }
2362
2588
 
2363
2589
  function attachWindow(w) { mainWindow = w; }
@@ -3082,6 +3308,30 @@ async function resolveFixPlanPath(failedJob) {
3082
3308
  * scheduleSettle option: arms the debounced Epic settle runner with live deps.
3083
3309
  * `remote` is defined later in the module but only read at call time.
3084
3310
  */
3311
+ async function readValidatorGateMs(cwd, epicId, slugs) {
3312
+ const texts = await prdPaths.readEpicPrdTexts(cwd, epicId, slugs);
3313
+ const out = new Map();
3314
+ for (const [slug, text] of texts) out.set(slug, gateTimeoutMs(text));
3315
+ return out;
3316
+ }
3317
+
3318
+ /**
3319
+ * resolveValidatorEstimate(job) → number | null — sizes a planner-written
3320
+ * validator (no estimateMinutes) from its dependsOn PRDs' gate timeouts.
3321
+ * Never rejects.
3322
+ */
3323
+ async function resolveValidatorEstimate(job, { readGateMs = readValidatorGateMs } = {}) {
3324
+ try {
3325
+ if (!job || job.agentType !== 'validator' || job.estimateMinutes != null) return null;
3326
+ if (!Array.isArray(job.dependsOn) || job.dependsOn.length === 0) return null;
3327
+ const gateMap = await readGateMs(job.cwd, job.epicId || job.sourcePromptId, job.dependsOn);
3328
+ const values = job.dependsOn.map((slug) => (gateMap && typeof gateMap.get === 'function' ? gateMap.get(slug) : undefined));
3329
+ return validatorEstimateMinutes(values, { factor: budget.JOB_BUDGET_FACTOR });
3330
+ } catch {
3331
+ return null;
3332
+ }
3333
+ }
3334
+
3085
3335
  function defaultScheduleSettle({ cwd, epicId }) {
3086
3336
  const deps = {
3087
3337
  loadJobs: async () => (await readQueue()).jobs || [],
@@ -3094,12 +3344,37 @@ function defaultScheduleSettle({ cwd, epicId }) {
3094
3344
  return null;
3095
3345
  }
3096
3346
  },
3347
+ readGateMs: readValidatorGateMs,
3348
+ jobBudget: { factor: budget.JOB_BUDGET_FACTOR, ceilingMs: budget.JOB_BUDGET_CEILING_MS },
3097
3349
  sendPrompt: (tabId, prompt) => enqueueExternalPrompt(tabId, prompt, { origin: 'scheduler' }),
3098
3350
  appendResponseEvent: appendResponseEventIfKnown,
3099
3351
  };
3100
3352
  epicValidationHook.scheduleEpicSettle({ cwd, epicId }, (args) => epicValidationHook.runEpicSettle(args, deps));
3101
3353
  }
3102
3354
 
3355
+ /**
3356
+ * armSettleAfterValidatorBudgetKill(job, { scheduleSettle }) → boolean
3357
+ *
3358
+ * A park never arms the settle (isNotifiableTerminalStatus excludes
3359
+ * needs_review), budget_exceeded is excluded from the review heal ladder, and
3360
+ * a split's carried PRDs only move on a settle — so a budget-killed validator
3361
+ * would strand them with no digest. Arms the settle for that one case only
3362
+ * (validator + budget_exceeded). Call OUTSIDE mutate with a row snapshot.
3363
+ * Returns whether it armed; never throws.
3364
+ */
3365
+ function armSettleAfterValidatorBudgetKill(job, { scheduleSettle = defaultScheduleSettle } = {}) {
3366
+ try {
3367
+ if (!job || job.agentType !== 'validator' || job.verifierVerdict !== 'budget_exceeded') return false;
3368
+ const epicId = job.epicId || job.sourcePromptId;
3369
+ if (!job.cwd || !epicId) return false;
3370
+ scheduleSettle({ cwd: job.cwd, epicId });
3371
+ return true;
3372
+ } catch (e) {
3373
+ console.error('[scheduler] armSettleAfterValidatorBudgetKill error', job && job.slug, e);
3374
+ return false;
3375
+ }
3376
+ }
3377
+
3103
3378
  /**
3104
3379
  * notifyOriginatingTab(job) → void
3105
3380
  *
@@ -4226,13 +4501,20 @@ const HEADLESS_DISALLOWED_TOOLS = Object.freeze([
4226
4501
  * and a large prompt failed with spawn E2BIG before the job started (the
4227
4502
  * 2026-10-26 incident). `claude -p` with no positional prompt reads stdin.
4228
4503
  */
4504
+ // MCP servers whose definition the scheduler knows. Lazy require: avoids a
4505
+ // load-order cycle with seedSchedulerMcp.cjs.
4506
+ function knownMcpServers() {
4507
+ const seed = require('./seedSchedulerMcp.cjs');
4508
+ return { [seed.SERVER_NAME]: seed.schedulerServerEntry() };
4509
+ }
4510
+
4229
4511
  function buildClaudeSpawnArgs({ model, effort, sessionId, resume, systemPrompt, toolScope }) {
4230
4512
  return [
4231
4513
  '-p',
4232
4514
  '--model', model,
4233
4515
  ...effortArgs(effort),
4234
4516
  ...(systemPrompt ? ['--append-system-prompt', systemPrompt] : []),
4235
- ...personaToolScopeArgs(toolScope),
4517
+ ...personaToolScopeArgs(toolScope, { mcpServers: knownMcpServers() }),
4236
4518
  '--dangerously-skip-permissions',
4237
4519
  ...headlessPermissionArgs(),
4238
4520
  '--disallowedTools', HEADLESS_DISALLOWED_TOOLS.join(','),
@@ -4560,6 +4842,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4560
4842
  await ensureCliCapsProbed();
4561
4843
  await ensureTimeoutShimOnce();
4562
4844
 
4845
+ const validatorEstimate = await resolveValidatorEstimate(job);
4846
+
4563
4847
  return await new Promise((resolve) => {
4564
4848
  const claudeBin = resolveClaudeBin();
4565
4849
  // Strip Claude Code env and secrets that leak in when session-manager is
@@ -4577,6 +4861,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4577
4861
  // scheduler-mcp-server.cjs can refuse scheduler_create_prd from inside a
4578
4862
  // run (issue #11 list C1 — the PRD 460 self-queue incident). Only a
4579
4863
  // persona whose whole job is decomposition may still queue.
4864
+ // SM_SCHEDULER_JOB_MCP_TOOLS tells scheduler-mcp-server.cjs which of its tools this job's
4865
+ // persona admits (see personaToolScope.cjs).
4580
4866
  // `launchEnv` is the launch circuit breaker's degraded-mode env (e.g.
4581
4867
  // MAX_THINKING_TOKENS=0 while an outdated CLI's thinking parameter is
4582
4868
  // being rejected — lib/scheduler/launchFailure.cjs); applied last so it wins.
@@ -4585,6 +4871,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4585
4871
  SM_PROJECT_ROOT: cwd,
4586
4872
  SM_SCHEDULER_JOB_SLUG: job.slug,
4587
4873
  SM_SCHEDULER_JOB_MAY_QUEUE: job.agentType === 'architect' ? '1' : '0',
4874
+ ...personaToolScopeEnv(personaToolScope),
4588
4875
  BASH_DEFAULT_TIMEOUT_MS: String(BASH_DEFAULT_TIMEOUT_MS),
4589
4876
  BASH_MAX_TIMEOUT_MS: String(BASH_MAX_TIMEOUT_MS),
4590
4877
  ...(launchEnv && typeof launchEnv === 'object' ? launchEnv : {}),
@@ -4704,8 +4991,12 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4704
4991
  // is calibrated against). Only a PRD with an
4705
4992
  // explicit `budgetExempt: true` opts out entirely — logged once here so
4706
4993
  // an unbounded job is never silently unbounded.
4707
- const jobBudgetMs = budget.computeJobBudgetMs(
4708
- job.estimateMinutes ?? resolvePersonaDefaultEstimate(job.cwd, job.agentType || DEFAULT_PRD_AGENT_TYPE));
4994
+ const budgetEstimate = budget.resolveBudgetEstimate({
4995
+ estimateMinutes: job.estimateMinutes,
4996
+ validatorEstimate,
4997
+ personaEstimate: job.estimateMinutes != null ? null : resolvePersonaDefaultEstimate(job.cwd, job.agentType || DEFAULT_PRD_AGENT_TYPE),
4998
+ });
4999
+ const jobBudgetMs = budget.computeJobBudgetMs(budgetEstimate);
4709
5000
  const budgetExempt = budget.isJobBudgetExempt(job);
4710
5001
  if (budgetExempt) {
4711
5002
  safeLog(`[scheduler] wall-clock budget watchdog EXEMPT for ${job.slug} ` +
@@ -4735,7 +5026,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4735
5026
  action(ctx) {
4736
5027
  const elapsedMs = Date.now() - ctx.startedAt;
4737
5028
  ctx.safeLog(`\n[scheduler] wall-clock budget watchdog: ran ${Math.round(elapsedMs / 60_000)}m ` +
4738
- `(> ${Math.round(jobBudgetMs / 60_000)}m budget, estimateMinutes=${job.estimateMinutes ?? 0}) — SIGTERM process group\n`);
5029
+ `(> ${Math.round(jobBudgetMs / 60_000)}m budget, estimateMinutes=${budgetEstimate ?? 0}) — SIGTERM process group\n`);
4739
5030
  ctx.killedByWatchdog = 'budget';
4740
5031
  ctx.killTree('SIGTERM');
4741
5032
  const budgetKillTimer = setTimeout(() => {
@@ -4772,22 +5063,26 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4772
5063
  return;
4773
5064
  }
4774
5065
 
5066
+ const scopePlan = planJobScope({ jobSpawn, jobArgs, slug: job.slug, startedAt });
5067
+ const scopeState = { unit: scopePlan.unit, pid: null, cgroupDir: null, finalized: false };
5068
+ const launchSpawn = scopePlan.spawn;
5069
+
4775
5070
  const { child } = withChildAndLog({
4776
5071
  fd,
4777
5072
  logPath,
4778
5073
  safeLog,
4779
5074
  closeFd,
4780
5075
  spawn: {
4781
- command: jobSpawn.command,
5076
+ command: launchSpawn.command,
4782
5077
  stdinText: prompt,
4783
5078
  // Resume mode passes `--resume <sessionId>` (reconnect to the SAME
4784
5079
  // session) INSTEAD of `--session-id <sessionId>` (mint a new one) —
4785
5080
  // never both, see buildClaudeSpawnArgs.
4786
- args: jobSpawn.args || jobArgs,
5081
+ args: launchSpawn.args || jobArgs,
4787
5082
  options: {
4788
5083
  cwd: spawnCwd,
4789
5084
  env: childEnv,
4790
- ...(jobSpawn.argv0 ? { argv0: jobSpawn.argv0 } : {}),
5085
+ ...(launchSpawn.argv0 ? { argv0: launchSpawn.argv0 } : {}),
4791
5086
  ...(jobSpawn.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
4792
5087
  // detached:true puts the child in its own process group so we can kill
4793
5088
  // the entire descendant tree (including any stray background bashes the
@@ -4798,11 +5093,12 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4798
5093
  },
4799
5094
  },
4800
5095
  watchdogs: [resultTailWatchdog, deadmanWatchdog, idleTailWatchdog, budgetWatchdog],
4801
- onExit({ exitCode, signal, killedByWatchdog, error, spawnFailed, leakedDescendants, safeLog: sl }) {
5096
+ onExit({ exitCode, signal, killedByWatchdog, error, spawnFailed, pid, safeLog: sl }) {
5097
+ const leaked = jobLeftovers.listJobSurvivors(job.slug, pid);
4802
5098
  const durationMs = Date.now() - startedAt;
4803
- const leaked = leakedDescendants ?? [];
5099
+ finalizeJobScope(scopeState, sl);
4804
5100
  if (leaked.length > 0) {
4805
- sl(`\n[scheduler] leaked ${leaked.length} descendant(s) swept from job process group: ` +
5101
+ sl(`\n[scheduler] leaked ${leaked.length} descendant(s) left behind after the job exited: ` +
4806
5102
  `${leaked.map((p) => `pid=${p.pid} comm=${p.comm} pcpu=${p.pcpu} etimes=${p.etimes}s`).join(', ')}\n`);
4807
5103
  }
4808
5104
 
@@ -4862,7 +5158,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4862
5158
  // resolveBudgetKillOutcome's own header for why this is gated on
4863
5159
  // killedBySignal, not on killedByWatchdog alone.
4864
5160
  const budgetKillOutcome = budget.resolveBudgetKillOutcome({
4865
- killedByWatchdog, killedBySignal, durationMs, jobBudgetMs, estimateMinutes: job.estimateMinutes,
5161
+ killedByWatchdog, killedBySignal, durationMs, jobBudgetMs, estimateMinutes: budgetEstimate,
4866
5162
  });
4867
5163
  const { budgetKillReason } = budgetKillOutcome;
4868
5164
  const effectiveKilledByWatchdog = budgetKillOutcome.killedByWatchdog;
@@ -4899,6 +5195,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4899
5195
  worktreeDir: execCwd || null, worktreeBranch: execCwd ? `sm-job/${job.slug}` : null,
4900
5196
  sessionId, startedAt, budgetMs: budgetExempt ? null : jobBudgetMs, maxDurationMs: null,
4901
5197
  idleKillMs: IDLE_OUTPUT_KILL_MS, schedulerPid: process.pid, codeSha: SCHEDULER_CODE_SHA,
5198
+ scopeUnit: scopePlan.unit,
4902
5199
  });
4903
5200
  } catch (e) {
4904
5201
  const message = e?.message ?? String(e);
@@ -4907,6 +5204,22 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4907
5204
  }
4908
5205
  // Make this job the OOM killer's preferred victim over Electron.
4909
5206
  biasJobOomScore(child.pid);
5207
+ if (scopeState.unit) {
5208
+ // systemd-run moves itself into the scope just before exec; read the
5209
+ // cgroup now (the process may be gone at finalize), retrying briefly.
5210
+ scopeState.pid = child.pid;
5211
+ scopeState.cgroupDir = readJobCgroupDir(child.pid, scopeState.unit);
5212
+ startJobScopeSampling(scopeState);
5213
+ for (const delay of scopeState.cgroupDir ? [] : [500, 3000]) {
5214
+ const t = setTimeout(() => {
5215
+ if (!scopeState.cgroupDir && !scopeState.finalized) {
5216
+ scopeState.cgroupDir = readJobCgroupDir(child.pid, scopeState.unit);
5217
+ startJobScopeSampling(scopeState);
5218
+ }
5219
+ }, delay);
5220
+ if (t.unref) t.unref();
5221
+ }
5222
+ }
4910
5223
  // Persist runtime.pid with one retry — still fire-and-forget (must
4911
5224
  // never block the spawn), but a final failure is now loud instead of
4912
5225
  // silently swallowed. A silent failure here is exactly what let the
@@ -5957,8 +6270,10 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
5957
6270
  // branch below has this run's OWN start time — the freshness check
5958
6271
  // (isCooldownSuppressed) needs to know whether this specific dispatch
5959
6272
  // started after the manual clear, not whatever startedAt this row
5960
- // carried from a prior run.
6273
+ // carried from a prior run. The same stamped start (ISO form, below)
6274
+ // also feeds verifyRun's queueEntry so artifact-only PRDs get a real window.
5961
6275
  let dispatchStartedAtMs = null;
6276
+ let dispatchStartedAt = null;
5962
6277
  let dispatchSkippedAlreadyCompleted = false;
5963
6278
  await mutate((s) => {
5964
6279
  const idx = s.jobs.findIndex((x) => x.slug === job.slug);
@@ -6041,6 +6356,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6041
6356
  s.jobs[idx].dispatchPhase = 'running-stamped';
6042
6357
  s.jobs[idx].dispatchPhaseAt = s.jobs[idx].startedAt;
6043
6358
  dispatchStartedAtMs = Date.parse(s.jobs[idx].startedAt);
6359
+ dispatchStartedAt = s.jobs[idx].startedAt;
6044
6360
  if (job.quietMachine === true) {
6045
6361
  s.jobs[idx].quietMachine = true;
6046
6362
  s.jobs[idx].quietLeaseDegraded = job.quietLeaseDegraded === true;
@@ -6435,7 +6751,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6435
6751
  guardCwd,
6436
6752
  guardHeadBefore,
6437
6753
  headAtExit,
6438
- job.startedAt,
6754
+ dispatchStartedAt,
6439
6755
  new Date().toISOString(),
6440
6756
  );
6441
6757
  let rangeCommits = [];
@@ -6445,7 +6761,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6445
6761
  rangeCommits = await gitTreeGuard.gitRangeCommits(guardCwd, guardHeadBefore, headAtExit);
6446
6762
  transcriptCommitShas = parseLog(path.join(runDir, `${job.slug}.log`)).transcriptCommitShas || [];
6447
6763
  const overlapState = await readQueue().catch(() => ({ jobs: [] }));
6448
- const myStart = Date.parse(job.startedAt) || 0;
6764
+ const myStart = Date.parse(dispatchStartedAt) || 0;
6449
6765
  const myEnd = Date.now();
6450
6766
  siblingOverlap = (overlapState.jobs || []).some((j) => {
6451
6767
  if (j.slug === job.slug || (j.cwd || defaultCwd) !== guardCwd) return false;
@@ -6489,7 +6805,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6489
6805
  verifyResult = await verifyRun({
6490
6806
  runDir,
6491
6807
  prdPath,
6492
- queueEntry: job,
6808
+ queueEntry: { ...job, startedAt: dispatchStartedAt, finishedAt: null },
6493
6809
  allJobs: stateForDeps.jobs,
6494
6810
  committedDuringRun,
6495
6811
  priorLandedCommit,
@@ -6652,11 +6968,11 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6652
6968
  guardCwd,
6653
6969
  guardHeadBefore,
6654
6970
  guardHeadAtSigterm,
6655
- job.startedAt,
6971
+ dispatchStartedAt,
6656
6972
  new Date().toISOString(),
6657
6973
  );
6658
6974
  if (guardHeadBefore && guardHeadAtSigterm && guardHeadAtSigterm !== guardHeadBefore) {
6659
- const verified = await resolveLandedCommitEvidence(guardCwd, guardHeadAtSigterm, job.startedAt);
6975
+ const verified = await resolveLandedCommitEvidence(guardCwd, guardHeadAtSigterm, dispatchStartedAt);
6660
6976
  if (verified) sigtermLandedCommitEvidence = guardHeadAtSigterm;
6661
6977
  }
6662
6978
  }
@@ -6696,7 +7012,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6696
7012
  if (res.exitCode !== 0 && res.exitCode !== 143 && !res.rateLimited) {
6697
7013
  const headAtPlainExit = await gitTreeGuard.gitHead(guardCwd);
6698
7014
  if (guardHeadBefore && headAtPlainExit && headAtPlainExit !== guardHeadBefore) {
6699
- const verified = await resolveLandedCommitEvidence(guardCwd, headAtPlainExit, job.startedAt);
7015
+ const verified = await resolveLandedCommitEvidence(guardCwd, headAtPlainExit, dispatchStartedAt);
6700
7016
  if (verified) plainExitLandedCommitEvidence = headAtPlainExit;
6701
7017
  }
6702
7018
  }
@@ -7160,6 +7476,8 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7160
7476
  });
7161
7477
  }
7162
7478
 
7479
+ if (needsReviewRcaSnapshot) armSettleAfterValidatorBudgetKill(needsReviewRcaSnapshot);
7480
+
7163
7481
  if (needsReviewRcaSnapshot) {
7164
7482
  // Fire-and-forget, mirroring the DoD drain hook: never blocks the status
7165
7483
  // transition, never throws to this caller.
@@ -7442,9 +7760,10 @@ function tickWatchdogMs() {
7442
7760
  return Number.isFinite(n) && n >= 0 ? n : 120_000;
7443
7761
  }
7444
7762
 
7445
- // `bypassLoadGate` is set only by the explicit human run-now / force-tick
7446
- // paths (via runDueJobs): the human is asking, so the CPU-load gate yields
7447
- // and logs that it did. Every automatic caller leaves it false.
7763
+ // `bypassLoadGate` is set by the human run-now / force-tick paths (via
7764
+ // runDueJobs) and by the starvation watchdog. `lastResort` marks the watchdog:
7765
+ // on a saturated CPU its bypassed tick sends one job; a human run-now keeps
7766
+ // the whole batch. Every other automatic caller leaves both false.
7448
7767
  /**
7449
7768
  * Fail-CLOSED expiry of runtime reservations (slot tokens, quiet-machine
7450
7769
  * lease, investigation set, worktree accounting) whose owner is provably
@@ -7474,11 +7793,11 @@ function runReservationExpiryPass(jobs, now = Date.now()) {
7474
7793
  }
7475
7794
  }
7476
7795
 
7477
- function tickQueue({ bypassLoadGate = false } = {}) {
7796
+ function tickQueue({ bypassLoadGate = false, lastResort = false } = {}) {
7478
7797
  const budgetMs = tickWatchdogMs();
7479
7798
  const next = tickTail.then(() => {
7480
7799
  const gen = tickGeneration;
7481
- return withTimeout(() => tickBody(gen, { bypassLoadGate }), budgetMs, () => {
7800
+ return withTimeout(() => tickBody(gen, { bypassLoadGate, lastResort }), budgetMs, () => {
7482
7801
  tickGeneration++; // fence the abandoned body
7483
7802
  console.warn(`[scheduler] TICK WEDGED: tick body exceeded ${budgetMs}ms — resetting tick chain`);
7484
7803
  if (!tickWedgeLatched) {
@@ -7501,8 +7820,11 @@ function tickQueue({ bypassLoadGate = false } = {}) {
7501
7820
  // The stale sentinel a fenced body returns: never recorded, never acted on.
7502
7821
  const STALE_TICK = Object.freeze({ fired: false, reason: 'stale-generation' });
7503
7822
 
7504
- async function tickBody(gen, { bypassLoadGate }) {
7823
+ async function tickBody(gen, { bypassLoadGate, lastResort }) {
7505
7824
  const tickStartedAt = Date.now();
7825
+ // evaluate() only runs once slots and memory admit a batch, so the CPU sampler
7826
+ // needs every tick to keep a reference reading about a minute old.
7827
+ loadGate.observe();
7506
7828
  {
7507
7829
  const stale = () => gen !== tickGeneration;
7508
7830
  const state = await readQueue();
@@ -7517,7 +7839,10 @@ async function tickBody(gen, { bypassLoadGate }) {
7517
7839
  // even while paused, before any early return below.
7518
7840
  await superviseAdoptedRunsPass(state.jobs);
7519
7841
  if (stale()) return STALE_TICK;
7842
+ // endHold() at the paused, drain and empty-batch returns: nothing is waiting
7843
+ // on the load gate at these points, so a stale hold clock must not carry over.
7520
7844
  if (state.paused) {
7845
+ loadGate.endHold();
7521
7846
  console.log('[scheduler] tickQueue skipped: paused');
7522
7847
  return recordTick({ fired: false, reason: 'paused' }, { detail: 'scheduler paused' });
7523
7848
  }
@@ -7525,6 +7850,7 @@ async function tickBody(gen, { bypassLoadGate }) {
7525
7850
  // rate-limit pause can't overwrite it. Nothing new dispatches; running and
7526
7851
  // investigating rows finish.
7527
7852
  if (state.drain?.active) {
7853
+ loadGate.endHold();
7528
7854
  return recordTick({ fired: false, reason: 'draining' }, { detail: 'draining for restart' });
7529
7855
  }
7530
7856
  if (cancelToken.cancelled) return { fired: false, reason: 'cancelled' };
@@ -7583,13 +7909,22 @@ async function tickBody(gen, { bypassLoadGate }) {
7583
7909
  if (batch.length === 0 && freeSlots === 0) {
7584
7910
  const snap = sessionSlots.snapshot();
7585
7911
  const pendingCount = state.jobs.filter((j) => j.status === 'pending').length;
7586
- console.log(`[scheduler] slot gate: 0 of ${snap.total} session slots free (${snap.holders.map((h) => h.owner).join(', ')}) — deferring ${pendingCount} pending job(s)`);
7912
+ const hold = budget.describeSlotHold({
7913
+ total: snap.total,
7914
+ inUse: snap.inUse,
7915
+ holders: snap.holders,
7916
+ degradedCap: degradedConcurrencyCapValue,
7917
+ running: runningSet.size,
7918
+ deferredCount: pendingCount,
7919
+ });
7920
+ console.log(`[scheduler] slot gate: ${hold.reason} — ${hold.detail} — deferring ${pendingCount} pending job(s)`);
7587
7921
  return recordTick(
7588
- { fired: false, reason: 'slots-exhausted', deferredCount: pendingCount, holders: snap.holders },
7589
- { detail: `${snap.total} of ${snap.total} session slots busy (${snap.holders.map((h) => h.owner).join(', ')})`, holds },
7922
+ { fired: false, reason: hold.reason, deferredCount: pendingCount, holders: snap.holders },
7923
+ { detail: hold.detail, holds },
7590
7924
  );
7591
7925
  }
7592
7926
  if (batch.length === 0) {
7927
+ loadGate.endHold();
7593
7928
  // Queue drained — run the definition-of-done gate fire-and-forget.
7594
7929
  // Non-blocking: does not hold the mutate lock; errors are logged, not thrown.
7595
7930
  // resolvePrdPath mirrors every other verify call site in this file (e.g.
@@ -7619,7 +7954,8 @@ async function tickBody(gen, { bypassLoadGate }) {
7619
7954
  return recordTick({ fired: false, reason: 'drained' }, { holds });
7620
7955
  }
7621
7956
 
7622
- const availableMb = getAvailableMemMb();
7957
+ const memInfo = readMemInfo();
7958
+ const availableMb = memInfo.availableMb;
7623
7959
  // Reserve a fixed slice for the Electron host before the per-job gate, so a
7624
7960
  // job is never started into the host's own headroom (that path OOM-kills
7625
7961
  // Electron and SIGHUPs every pty — 2026-06-16 incident).
@@ -7650,7 +7986,22 @@ async function tickBody(gen, { bypassLoadGate }) {
7650
7986
  { detail: `memory gate: ${availableMb} MB free, need ${threshold} MB (consumed=${consumedMb} MB credited)`, holds },
7651
7987
  );
7652
7988
  }
7653
- const gatedBatch = batch.slice(0, allowed);
7989
+ const swapAllowed = swapLimitedBatchSize(memInfo, runningSet.size, allowed);
7990
+ if (swapAllowed < allowed) {
7991
+ if (!swapGateLogged) {
7992
+ swapGateLogged = true;
7993
+ console.log(`[scheduler] memory gate: swap nearly exhausted (swapFree=${memInfo.swapFreeMb} MB of ${memInfo.swapTotalMb} MB, available=${availableMb} MB) — limiting to 1 running job (running=${runningSet.size}, batch ${allowed} → ${swapAllowed})`);
7994
+ }
7995
+ } else {
7996
+ swapGateLogged = false;
7997
+ }
7998
+ if (swapAllowed === 0) {
7999
+ return recordTick(
8000
+ { fired: false, reason: 'memory-deferred', deferredCount: batch.length, availableMb, swapFreeMb: memInfo.swapFreeMb, swapTotalMb: memInfo.swapTotalMb },
8001
+ { detail: `memory gate: swap nearly exhausted (${memInfo.swapFreeMb}/${memInfo.swapTotalMb} MB free), ${runningSet.size} job(s) running`, holds },
8002
+ );
8003
+ }
8004
+ const gatedBatch = batch.slice(0, swapAllowed);
7654
8005
  if (gatedBatch.length < batch.length) {
7655
8006
  console.log(`[scheduler] memory gate: available=${availableMb} MB — clamped batch ${batch.length} → ${gatedBatch.length} (host reserve ${RESERVED_HOST_MB} + ${MIN_FREE_MB_PER_JOB}/job, consumed=${consumedMb} MB)`);
7656
8007
  lastMemGate = { availableMb, threshold: RESERVED_HOST_MB + MIN_FREE_MB_PER_JOB * (runningSet.size + gatedBatch.length) - consumedMb, consumedMb, deferred: false, clamped: true, at: new Date().toISOString() };
@@ -7665,45 +8016,98 @@ async function tickBody(gen, { bypassLoadGate }) {
7665
8016
  // pickNextBatch → memory above) has already admitted `gatedBatch`. It
7666
8017
  // never touches running jobs and never becomes a second pool: it only
7667
8018
  // withholds this tick's launches while the 1-minute loadavg per core is
7668
- // over LOAD_GATE_PER_CORE. An explicit human Run now bypasses it.
8019
+ // over LOAD_GATE_PER_CORE AND a real CPU sample does not show the CPU mostly
8020
+ // idle (then it stands down and the batch launches). An explicit human Run now bypasses it.
8021
+ let launchBatch = gatedBatch;
8022
+ let top = [];
7669
8023
  const load = loadGate.evaluate({ bypass: bypassLoadGate });
7670
8024
  if (load.bypassed) {
7671
- console.log(`[scheduler] load gate: BYPASSED by run-now (loadavg1=${load.loadavg1} cores=${load.cores} ratio=${load.ratio} > ${load.threshold})`);
8025
+ const clampToOne = !!lastResort && load.saturated;
8026
+ if (clampToOne) launchBatch = gatedBatch.slice(0, 1);
8027
+ console.log(`[scheduler] load gate: BYPASSED by ${lastResort ? 'starvation watchdog' : 'run-now'} (loadavg1=${load.loadavg1} cores=${load.cores} ratio=${load.ratio} > ${load.threshold})${clampToOne ? ', saturated CPU: one job' : ''}`);
7672
8028
  } else if (load.gated) {
7673
8029
  const line = `[scheduler] load gate: loadavg1=${load.loadavg1} cores=${load.cores} ratio=${load.ratio} > ${load.threshold} — holding ${gatedBatch.length} eligible job(s)`;
7674
- if (load.escalate) {
7675
- const top = topCpuConsumers(3);
7676
- console.warn(`${line} for ${Math.round(load.gatedSinceMs / 60_000)}m; top CPU: ${top.length ? top.join(' | ') : 'n/a'}`);
7677
- } else {
7678
- console.log(line);
7679
- }
8030
+ console.log(line);
7680
8031
  if (load.shouldAudit) {
7681
8032
  appendAuditEvent('launch_load_gated', {
7682
- loadavg1: load.loadavg1, cores: load.cores, ratio: load.ratio, threshold: load.threshold,
7683
- held: gatedBatch.map((j) => j.slug), gatedSinceMs: load.gatedSinceMs,
8033
+ ...loadGateAuditFields(load),
8034
+ held: gatedBatch.map((j) => j.slug),
7684
8035
  });
7685
8036
  }
8037
+ if (load.escalated) {
8038
+ const escTop = topCpuConsumers(3);
8039
+ const escMins = Math.round(load.heldMs / 60_000);
8040
+ console.warn(`[scheduler] load gate: CPU saturated, held ${gatedBatch.length} job(s) for ${escMins}m — nothing launched; top CPU: ${escTop.length ? escTop.join(' | ') : 'n/a'}`);
8041
+ appendAuditEvent('load_gate_escalated', {
8042
+ ...loadGateAuditFields(load),
8043
+ held: gatedBatch.map((j) => j.slug),
8044
+ top: escTop,
8045
+ });
8046
+ sendIfAlive(mainWindow, 'schedule:stall', loadGateStallEvent(
8047
+ load, gatedBatch,
8048
+ `CPU saturated: load gate has held ${gatedBatch.length} job(s) for ${escMins}m with slots and memory free; nothing launched.`,
8049
+ ));
8050
+ }
7686
8051
  return recordTick(
7687
8052
  { fired: false, reason: 'load-deferred', deferredCount: gatedBatch.length, ratio: load.ratio, threshold: load.threshold },
7688
8053
  { detail: formatLoadGateDetail(load), holds },
7689
8054
  );
8055
+ } else if (load.yielded) {
8056
+ // The gate held this batch for the whole yield window with slots and
8057
+ // memory free and the CPU not saturated (or no sample): let ONE job through.
8058
+ launchBatch = gatedBatch.slice(0, 1);
8059
+ top = topCpuConsumers(3);
8060
+ const mins = Math.round(load.heldMs / 60_000);
8061
+ console.warn(`[scheduler] load gate: held ${gatedBatch.length} job(s) for ${mins}m with slots and memory free — letting ${launchBatch[0].slug} through; top CPU: ${top.length ? top.join(' | ') : 'n/a'}`);
8062
+ } else if (load.standDown) {
8063
+ console.log(`[scheduler] load gate: stood down — loadavg1=${load.loadavg1} cores=${load.cores} ratio=${load.ratio} > ${load.threshold} but CPU ${Math.round(load.cpuBusy * 100)}% busy over ${Math.round(load.cpuWindowMs / 1000)}s`);
8064
+ if (load.shouldAuditStandDown) {
8065
+ appendAuditEvent('load_gate_stood_down', loadGateAuditFields(load));
8066
+ }
7690
8067
  }
7691
8068
 
7692
- await mutate((s) => { s.lastRunAt = new Date().toISOString(); });
8069
+ await mutate((s) => {
8070
+ const nowIso = new Date().toISOString();
8071
+ s.lastRunAt = nowIso;
8072
+ if (!s.lastDispatchAtByCwd || typeof s.lastDispatchAtByCwd !== 'object' || Array.isArray(s.lastDispatchAtByCwd)) s.lastDispatchAtByCwd = {};
8073
+ for (const job of launchBatch) s.lastDispatchAtByCwd[job.cwd || DEFAULT_PROJECT_CWD] = nowIso;
8074
+ });
7693
8075
  if (stale()) return STALE_TICK;
7694
8076
  await broadcast();
7695
8077
  if (stale()) return STALE_TICK;
7696
8078
 
7697
8079
  const { runId, dir: runDir } = pickRunDir();
7698
- for (const job of gatedBatch) {
8080
+ let issued = 0;
8081
+ for (const job of launchBatch) {
7699
8082
  if (cancelToken.cancelled || stale()) break;
7700
8083
  // spawnJob is fire-and-forget; it calls tickQueue() on completion.
7701
8084
  // state.jobs is the queue's rows in scope at THIS dispatch (PRD 1408) —
7702
8085
  // threaded straight through so spawnJob's hasDownstreamValidator check
7703
8086
  // never re-reads the queue itself.
7704
8087
  spawnJob(job, runId, runDir, state.config.defaultCwd, null, state.jobs).catch((e) => reportSchedulerError('spawnJob dispatch rejected', job.slug, e));
8088
+ issued += 1;
8089
+ }
8090
+ if (issued > 0) {
8091
+ loadGate.endHold();
8092
+ if (load.bypassed && lastResort && load.saturated) {
8093
+ appendAuditEvent('load_gate_last_resort', {
8094
+ ...loadGateAuditFields(load),
8095
+ launched: launchBatch[0].slug, stillHeld: gatedBatch.slice(1).map((j) => j.slug),
8096
+ });
8097
+ }
8098
+ if (load.yielded) {
8099
+ const mins = Math.round(load.heldMs / 60_000);
8100
+ appendAuditEvent('load_gate_yielded', {
8101
+ ...loadGateAuditFields(load),
8102
+ launched: launchBatch[0].slug, stillHeld: gatedBatch.slice(1).map((j) => j.slug), top,
8103
+ });
8104
+ sendIfAlive(mainWindow, 'schedule:stall', loadGateStallEvent(
8105
+ load, gatedBatch,
8106
+ `CPU load gate held ${gatedBatch.length} job(s) for ${mins}m with slots and memory free; letting one through.`,
8107
+ ));
8108
+ }
7705
8109
  }
7706
- return recordTick({ fired: true, count: gatedBatch.length, group: gatedBatch[0]?.parallelGroup }, { holds });
8110
+ return recordTick({ fired: true, count: launchBatch.length, group: launchBatch[0]?.parallelGroup }, { holds });
7707
8111
  }
7708
8112
  }
7709
8113
 
@@ -7730,6 +8134,8 @@ function forceTickOutcome(result) {
7730
8134
  return { ok: true, kind: 'warn', message: `Deferred ${result.deferredCount} job(s) — low memory (${result.availableMb} MB available, need ${result.threshold} MB)` };
7731
8135
  case 'slots-exhausted':
7732
8136
  return { ok: true, kind: 'warn', message: `Deferred ${result.deferredCount} job(s) — all session slots in use (${(result.holders ?? []).map((h) => h.owner).join(', ')})` };
8137
+ case 'usage-meter-degraded':
8138
+ return { ok: true, kind: 'warn', message: `Deferred ${result.deferredCount} job(s) — usage meter cap held them (${stripTickDetailPrefix(result.detail) || 'meter degraded'})` };
7733
8139
  case 'held': {
7734
8140
  const detail = stripTickDetailPrefix(result.detail);
7735
8141
  return { ok: true, kind: 'warn', message: detail || 'Batch held' };
@@ -7887,14 +8293,14 @@ async function runQueueStarvationWatchdog(state, {
7887
8293
  // it can't influence, freezing the queue for hours (observed 2026-09-23:
7888
8294
  // 3 dispatchable, 0 running, lastTickReason 'load-deferred' unbroken from
7889
8295
  // 07:00→13:06). The gate is advisory headroom ("leave one core free"), not
7890
- // a resource guard; starting ONE batch cannot OOM the host. The slot pool
8296
+ // a resource guard; starting ONE batch cannot OOM the host (on a saturated CPU the batch is one job: lastResort). The slot pool
7891
8297
  // and memory gate — which DO guard real exhaustion — are unaffected by this
7892
8298
  // flag and still bound the batch. The watchdog is the automated equivalent
7893
8299
  // of a human Run-now, the other caller that legitimately bypasses load
7894
8300
  // (§2/§3, scheduler-operations.md). Latched to one forced tick per
7895
8301
  // QUEUE_STARVATION_MS per cwd, so this cannot thrash. Routed via
7896
8302
  // module.exports so tests can assert the bypass without driving real load.
7897
- await module.exports.tickQueue({ bypassLoadGate: true }).catch((e) => console.error('[scheduler] starvation tick error', e));
8303
+ await module.exports.tickQueue({ bypassLoadGate: true, lastResort: true }).catch((e) => console.error('[scheduler] starvation tick error', e));
7898
8304
  return primary;
7899
8305
  }
7900
8306
 
@@ -7918,12 +8324,13 @@ const starveEscalated = new Set();
7918
8324
  * gate. Exported for direct unit testing (attach a fake window via
7919
8325
  * attachWindow() first to assert the toast send).
7920
8326
  */
7921
- function runStarveEscalationSweep(starvedProjects) {
8327
+ function runStarveEscalationSweep(starvedProjects, jobs = [], launchBlocks = {}) {
7922
8328
  const { toEscalate, toClear } = starvation.selectStarveEscalations(starvedProjects, starveEscalated, STARVE_ESCALATION_MS);
7923
8329
  for (const cwd of toClear) starveEscalated.delete(cwd);
7924
8330
  for (const sp of toEscalate) {
7925
8331
  starveEscalated.add(sp.cwd);
7926
- const holdReason = lastTick?.reason ?? 'unknown';
8332
+ const projectRows = (Array.isArray(jobs) ? jobs : []).filter((j) => j && (j.cwd || DEFAULT_PROJECT_CWD) === sp.cwd);
8333
+ const holdReason = starvation.describeStarveHold({ projectRows, launchBlocks, lastTick, lastHoldTick });
7927
8334
  const mins = Math.round(sp.ageMs / 60_000);
7928
8335
  console.error(
7929
8336
  `[scheduler] PROJECT STARVE ESCALATED: project=${sp.cwd} pending=${sp.pendingCount} oldest=${sp.oldestPendingSlug} `
@@ -7934,7 +8341,7 @@ function runStarveEscalationSweep(starvedProjects) {
7934
8341
  cwd: sp.cwd, pendingCount: sp.pendingCount, oldestPendingSlug: sp.oldestPendingSlug, ageMs: sp.ageMs, holdReason,
7935
8342
  });
7936
8343
  sendIfAlive(mainWindow, 'schedule:stall', {
7937
- message: `Project starved: ${sp.cwd} has ${sp.pendingCount} pending PRD(s), oldest waiting ~${mins}m `
8344
+ message: `Project starved: ${sp.cwd} has ${sp.pendingCount} pending PRD(s), no dispatch for ~${mins}m `
7938
8345
  + `(hold reason: ${holdReason}) — check the Scheduler tab.`,
7939
8346
  total: sp.pendingCount,
7940
8347
  byProject: { [sp.cwd]: { starved: sp.pendingCount } },
@@ -7951,6 +8358,47 @@ function runStarveEscalationSweep(starvedProjects) {
7951
8358
  let queueHealthSweepCycle = 0;
7952
8359
  const QUEUE_HEALTH_SWEEP_EVERY_N_CYCLES = 20;
7953
8360
 
8361
+ // Leftover sweep: stops processes that outlived a finished job (setsid escapees,
8362
+ // jobs ended across an app restart, no-scope / no-systemd runs). Time-based so
8363
+ // poll backoff cannot stretch it.
8364
+ const JOB_LEFTOVER_SWEEP_INTERVAL_MS = 5 * 60_000;
8365
+ let lastJobLeftoverSweepAt = 0;
8366
+
8367
+ /**
8368
+ * Order matters: scan /proc BEFORE reading the queue — a process seen in the
8369
+ * scan spawned before the read, so the row read afterwards is running or later.
8370
+ */
8371
+ async function runJobLeftoverSweep(deps = {}) {
8372
+ const {
8373
+ now = Date.now(),
8374
+ platform = process.platform,
8375
+ scan = () => jobLeftovers.scanJobProcesses(),
8376
+ readState = readQueue,
8377
+ stop = (procs) => jobLeftovers.stopLeftovers(procs),
8378
+ } = deps;
8379
+ if (now - lastJobLeftoverSweepAt < JOB_LEFTOVER_SWEEP_INTERVAL_MS) return [];
8380
+ if (platform !== 'linux' || process.env.SM_E2E === '1') return [];
8381
+ // Fail closed under vitest: the queue is a sandbox with no rows, so every
8382
+ // marked process on the real machine would read as ended and get killed.
8383
+ // Same rule as assertNotLiveRoot in lib/scheduler/schedulerPaths.cjs.
8384
+ if (process.env.VITEST && !deps.scan) return [];
8385
+ lastJobLeftoverSweepAt = now;
8386
+ const scanned = scan();
8387
+ const state = await readState();
8388
+ if (!state || state.unreadable || !Array.isArray(state.jobs) || quarantinedCwdSet(state).size > 0) return [];
8389
+ const leftovers = jobLeftovers.selectLeftovers({
8390
+ scan: scanned, rows: state.jobs, runningSlugs: runningSet, now, selfPid: process.pid,
8391
+ });
8392
+ for (const { slug, procs } of leftovers) {
8393
+ const pids = stop(procs) ?? procs.map((p) => p.pid);
8394
+ const comms = [...new Set(procs.map((p) => p.comm))];
8395
+ const oldestEtimes = Math.max(...procs.map((p) => p.etimes || 0));
8396
+ appendAuditEvent('job_leftovers_stopped', { slug, pids, comms, etimes: oldestEtimes });
8397
+ console.log(`[scheduler] job leftovers stopped: ${slug} pids=${pids.join(',')} comms=${comms.join(',')} oldest=${Math.round(oldestEtimes)}s`);
8398
+ }
8399
+ return leftovers;
8400
+ }
8401
+
7954
8402
  /**
7955
8403
  * runQueueHealthSweep(jobs) — read-only reporting pass over the queue
7956
8404
  * snapshot reapDeadRunningJobs already read this cycle. Never transitions a
@@ -8184,6 +8632,8 @@ async function reapDeadRunningJobs() {
8184
8632
  await runBranchSweep(state.jobs);
8185
8633
  }
8186
8634
 
8635
+ runJobLeftoverSweep().catch((e) => console.warn('[scheduler] job leftover sweep error', e?.message));
8636
+
8187
8637
  if (dead.length === 0) return;
8188
8638
 
8189
8639
  // A rate-limited death is retryable, not terminal — mirror spawnJob's own
@@ -8347,6 +8797,7 @@ async function reapDeadRunningJobs() {
8347
8797
  if (resolved) landedCommitEvidence.set(d.slug, row.landedCommit);
8348
8798
  }));
8349
8799
 
8800
+ const budgetKillSettleSnapshots = [];
8350
8801
  await mutate(async (s) => {
8351
8802
  for (const { slug, pid, outcome, gateOutcome, pidless, reason, noOwnArtifact, failureOverride } of dead) {
8352
8803
  const idx = s.jobs.findIndex((x) => x.slug === slug);
@@ -8484,6 +8935,7 @@ async function reapDeadRunningJobs() {
8484
8935
  if (confirmedLandedCommit) s.jobs[idx].landedCommit = confirmedLandedCommit;
8485
8936
  if (landedCommit) s.jobs[idx].landedCommit = landedCommit;
8486
8937
  if (adoptedBudgetKill?.landedCommit) s.jobs[idx].landedCommit = adoptedBudgetKill.landedCommit;
8938
+ if (adoptedBudgetKill) budgetKillSettleSnapshots.push({ ...s.jobs[idx], verifierVerdict: 'budget_exceeded' });
8487
8939
  }
8488
8940
  // A pidless spawn that never wrote its own '<slug>.log' into the
8489
8941
  // batch runId dir it was stamped with must not keep that runId —
@@ -8533,6 +8985,8 @@ async function reapDeadRunningJobs() {
8533
8985
  }
8534
8986
  });
8535
8987
 
8988
+ for (const snap of budgetKillSettleSnapshots) armSettleAfterValidatorBudgetKill(snap);
8989
+
8536
8990
  await broadcast({ flush: true });
8537
8991
  tickQueue().catch(() => {});
8538
8992
  } catch (e) {
@@ -9651,9 +10105,10 @@ async function reverifyNeedsReview() {
9651
10105
  // already excludes every job this loop dispatches, so a resumable job
9652
10106
  // never also gets a fix-plan PRD authored in the same pass.
9653
10107
  {
9654
- for (const job of queueForResumeAndAutofix.jobs) {
9655
- const target = reviewLadder.selectResumeRecoveryTarget(job);
9656
- if (!target) continue;
10108
+ // Saturated CPU (>= 85% busy): start ONE per pass; the rest stay eligible
10109
+ // for the next pass (this path never reaches the load gate).
10110
+ const batch = reviewLadder.selectResumeRecoveryBatch(queueForResumeAndAutofix.jobs, { saturated: loadGate.isSaturated() });
10111
+ for (const { job, target } of batch) {
9657
10112
  console.log(`[scheduler] resume-recovery: needs_review ${job.slug} → resuming session ${target.sessionId}`);
9658
10113
  spawnResumeRecovery(job, target).catch((e) => {
9659
10114
  console.error('[scheduler] spawnResumeRecovery error', job.slug, e);
@@ -10256,7 +10711,7 @@ function rescheduleIntervalTick() {
10256
10711
  // else distinguishes "no pending work" from "pending work, never
10257
10712
  // started" — the 2026-09-01 NN-ordering starvation ran 3.5 h unnoticed.
10258
10713
  // Escalation only, same shape as the quarantine/overrun warnings above.
10259
- const starvedProjects = findStarvedProjects(s.jobs, Date.now(), STARVATION_ESCALATE_MS);
10714
+ const starvedProjects = findStarvedProjects(s.jobs, Date.now(), STARVATION_ESCALATE_MS, s.lastDispatchAtByCwd);
10260
10715
  for (const sp of starvedProjects) {
10261
10716
  console.warn(
10262
10717
  `[scheduler] PROJECT STARVED: project=${sp.cwd} pending=${sp.pendingCount} oldest=${sp.oldestPendingSlug} `
@@ -10271,7 +10726,7 @@ function rescheduleIntervalTick() {
10271
10726
  // strictly later than STARVATION_ESCALATE_MS, so this only ever fires on
10272
10727
  // a subset of the rows already reported above — same verdict, no
10273
10728
  // re-derivation.
10274
- runStarveEscalationSweep(starvedProjects);
10729
+ runStarveEscalationSweep(starvedProjects, s.jobs, s.launchBlocks);
10275
10730
 
10276
10731
  // Bounded failed -> pending auto-reset (PRD 1151), plus the stuck-failed
10277
10732
  // escalation now narrowed to only the rows that auto-reset gave up on.
@@ -10714,6 +11169,7 @@ async function listPrdsInternal({ cwd: rawCwd } = {}) {
10714
11169
  epicId: parsed.epicId ?? null,
10715
11170
  dependsOn: parsed.dependsOn ?? null,
10716
11171
  agentType: parsed.agentType ?? null,
11172
+ macroId: parsed.macroId ?? null,
10717
11173
  disposition: parsed.disposition ?? null,
10718
11174
  planId: parsed.planId ?? null,
10719
11175
  mtimeMs: stat.mtimeMs,
@@ -11371,6 +11827,12 @@ function registerAdminRoutes(adminHttp, remoteObj = remote) {
11371
11827
  }
11372
11828
 
11373
11829
  module.exports = {
11830
+ readValidatorGateMs,
11831
+ resolveValidatorEstimate,
11832
+ planJobScope,
11833
+ finalizeJobScope,
11834
+ sampleJobScope,
11835
+ readJobCgroupDir,
11374
11836
  normalizeConfig,
11375
11837
  recordTick,
11376
11838
  reportSchedulerError,
@@ -11380,6 +11842,7 @@ module.exports = {
11380
11842
  rescheduleIntervalTick,
11381
11843
  runQueueStarvationWatchdog,
11382
11844
  runStarveEscalationSweep,
11845
+ runJobLeftoverSweep,
11383
11846
  stripAppOwnedChurn,
11384
11847
  BUDGET_WARNING_FRACTION,
11385
11848
  registerScheduleHandlers,
@@ -11391,6 +11854,7 @@ module.exports = {
11391
11854
  computeDegradedBudget,
11392
11855
  writeQueue,
11393
11856
  _setPeriodicReverifyEnabledForTests,
11857
+ _setLoadGateForTests,
11394
11858
  _mutateForTests: mutate, // mutate() has no other exported call site; test-only seam.
11395
11859
  reconcile,
11396
11860
  broadcast,
@@ -11412,6 +11876,12 @@ module.exports = {
11412
11876
  pollRecoveryClearSource,
11413
11877
  memoryLimitedBatchSize,
11414
11878
  availableForJobs,
11879
+ parseMemInfo,
11880
+ readMemInfo,
11881
+ getAvailableMemMb,
11882
+ swapLimitedBatchSize,
11883
+ biasJobOomScore,
11884
+ OOM_SCORE_ADJ_JOB,
11415
11885
  reverifyNeedsReview,
11416
11886
  runGateShadow,
11417
11887
  awaitGateShadowIdle: async () => { while (gateShadowPending) await gateShadowPending; },
@@ -11454,6 +11924,7 @@ module.exports = {
11454
11924
  notifyOriginatingTab,
11455
11925
  flushDueReviewNotices,
11456
11926
  isNotifiableTerminalStatus,
11927
+ armSettleAfterValidatorBudgetKill,
11457
11928
  extractResultTextFromLog,
11458
11929
  resolveVerifyPrdPath,
11459
11930
  resolveFixPlanPath,