claude-code-session-manager 0.125.1 → 0.127.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 (97) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/bin/cli.cjs +71 -9
  3. package/bin/supervise.cjs +84 -0
  4. package/dist/assets/{AgentLibrary-DjEH5SoY.js → AgentLibrary-DKQznr7o.js} +1 -1
  5. package/dist/assets/{Button-B8NLivk-.js → Button-CZXqmIiM.js} +1 -1
  6. package/dist/assets/{DataModel-CHiBk8m_.js → DataModel-piyV33To.js} +1 -1
  7. package/dist/assets/{History-DttgrJO0.js → History-BxwtrKF2.js} +1 -1
  8. package/dist/assets/{Hooks-Bvy0BH1u.js → Hooks-DogeSPII.js} +1 -1
  9. package/dist/assets/{Library-UbBOgkkP.js → Library-BDt6EeQQ.js} +1 -1
  10. package/dist/assets/{ListDetail-xOyOpVZX.js → ListDetail-CwS-LKar.js} +1 -1
  11. package/dist/assets/{McpServers-CoGL0ddv.js → McpServers-D2HVljgS.js} +1 -1
  12. package/dist/assets/{Memory-Cise856d.js → Memory-hNzuOGn8.js} +1 -1
  13. package/dist/assets/{Panel-Cj72VO5s.js → Panel-BLDrsUeq.js} +1 -1
  14. package/dist/assets/{Permissions-BoJ9AB-G.js → Permissions-DzZ5vaJW.js} +1 -1
  15. package/dist/assets/{Plugins-DfT24sAZ.js → Plugins-Cz9yaxzG.js} +2 -2
  16. package/dist/assets/{ProvenanceBadge-ChkIslT4.js → ProvenanceBadge-CCgLO4m9.js} +1 -1
  17. package/dist/assets/{SaveBar-RCXr0jey.js → SaveBar-Shmn699J.js} +1 -1
  18. package/dist/assets/{Scheduler-B70tknnx.js → Scheduler-Bqr0WHNd.js} +1 -1
  19. package/dist/assets/{ScopeSwitcher-p_tgO5Sa.js → ScopeSwitcher-CBx1fB5g.js} +1 -1
  20. package/dist/assets/{Settings-wHiAxTfI.js → Settings-Ci8in-yF.js} +1 -1
  21. package/dist/assets/{SkillReferenceGraph-D_Pt35vb.js → SkillReferenceGraph-BWwljba8.js} +1 -1
  22. package/dist/assets/{Skills-DUvOrgw9.js → Skills-BON6o-c4.js} +1 -1
  23. package/dist/assets/{SystemPrompt-BrNIdy68.js → SystemPrompt-D5epIYYs.js} +1 -1
  24. package/dist/assets/{TagLibrary-CDRatxXG.js → TagLibrary-C2qDZROJ.js} +1 -1
  25. package/dist/assets/{TiptapBody-BF8PxUDj.js → TiptapBody-SZhI3-bW.js} +1 -1
  26. package/dist/assets/{Toggle-CQH8NGXW.js → Toggle-C_qFDG0g.js} +1 -1
  27. package/dist/assets/{ViewTabs-DwnxqCVs.js → ViewTabs-C9q5WCEd.js} +1 -1
  28. package/dist/assets/{historyTotals-KINLTHQ4.js → historyTotals-BCl7IOhY.js} +1 -1
  29. package/dist/assets/{index-CfR3NU2t.js → index-CMIYLbPb.js} +581 -581
  30. package/dist/assets/{settingsSchema-BUcHqLnt.js → settingsSchema-BBrRBrBr.js} +1 -1
  31. package/dist/assets/{skillFrontmatter-BwwkyuMD.js → skillFrontmatter-B01qJk6N.js} +1 -1
  32. package/dist/assets/{useAgentsDirWatch-Coem9Wg-.js → useAgentsDirWatch-CuR3GSjS.js} +1 -1
  33. package/dist/index.html +1 -1
  34. package/dist-web/{assets/app.js → app.js} +351 -351
  35. package/dist-web/index.html +2 -2
  36. package/package.json +2 -2
  37. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  38. package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -2
  39. package/plugins/session-manager-dev/skills/send-feedback/SKILL.md +10 -2
  40. package/scripts/scheduler-mcp-server.cjs +56 -5
  41. package/src/main/build-info.json +4 -4
  42. package/src/main/chatRunner.cjs +73 -6
  43. package/src/main/crashDiagnostics.cjs +83 -8
  44. package/src/main/health.cjs +16 -5
  45. package/src/main/index.cjs +32 -0
  46. package/src/main/lib/chatBootRecovery.cjs +136 -0
  47. package/src/main/lib/chatInflight.cjs +88 -0
  48. package/src/main/lib/epic/epicDelegationStats.cjs +1 -0
  49. package/src/main/lib/epic/epicMint.cjs +6 -0
  50. package/src/main/lib/epic/epicSweepValidator.cjs +60 -6
  51. package/src/main/lib/epic/epicValidationHook.cjs +14 -2
  52. package/src/main/lib/epic/epicWorktreeMerge.cjs +9 -1
  53. package/src/main/lib/feedback-remote/autoStartedSession.cjs +102 -0
  54. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +130 -15
  55. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +71 -15
  56. package/src/main/lib/feedback-remote/remoteAssets.cjs +25 -1
  57. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +13 -2
  58. package/src/main/lib/git/gitExec.cjs +11 -1
  59. package/src/main/lib/git/gitWorktree.cjs +255 -9
  60. package/src/main/lib/git/jobWorktree.cjs +5 -0
  61. package/src/main/lib/mcpToolCatalog.cjs +27 -5
  62. package/src/main/lib/persona-macro/builtinMacros.cjs +12 -1
  63. package/src/main/lib/persona-macro/macroLibrary.cjs +78 -3
  64. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  65. package/src/main/lib/prd/prdCreate.cjs +5 -1
  66. package/src/main/lib/prd/prdDeclaredPaths.cjs +29 -2
  67. package/src/main/lib/process/childWithLog.cjs +38 -95
  68. package/src/main/lib/process/memoryScope.cjs +140 -0
  69. package/src/main/lib/process/ozonePlatform.cjs +15 -0
  70. package/src/main/lib/process/procIdentity.cjs +10 -3
  71. package/src/main/lib/process/scopeOomPolicy.cjs +69 -0
  72. package/src/main/lib/promptSessionSchema.cjs +6 -1
  73. package/src/main/lib/scheduler/cpuSample.cjs +147 -0
  74. package/src/main/lib/scheduler/definitionOfDone.cjs +40 -0
  75. package/src/main/lib/scheduler/jobLeftovers.cjs +204 -0
  76. package/src/main/lib/scheduler/jobSupervisorRecord.cjs +2 -1
  77. package/src/main/lib/scheduler/landedSinceRun.cjs +13 -5
  78. package/src/main/lib/scheduler/loadGate.cjs +116 -45
  79. package/src/main/lib/scheduler/queueStore.cjs +5 -2
  80. package/src/main/lib/scheduler/rcaReport.cjs +1 -0
  81. package/src/main/lib/scheduler/reviewNotice.cjs +1 -0
  82. package/src/main/lib/scheduler/schedulerBatch.cjs +10 -3
  83. package/src/main/lib/scheduler/schedulerConfig.cjs +7 -2
  84. package/src/main/lib/telemetry/crashTelemetry.cjs +8 -4
  85. package/src/main/runVerify.cjs +59 -110
  86. package/src/main/scheduler/budget.cjs +31 -0
  87. package/src/main/scheduler/gitTreeGuard.cjs +51 -1
  88. package/src/main/scheduler/prdPaths.cjs +54 -0
  89. package/src/main/scheduler/reviewLadder.cjs +28 -5
  90. package/src/main/scheduler/starvation.cjs +22 -0
  91. package/src/main/scheduler.cjs +662 -90
  92. package/src/main/templates/PRD_AUTHORING.md +10 -3
  93. package/src/main/usage.cjs +4 -2
  94. package/src/main/webRemote.cjs +3 -0
  95. package/src/preload/api.d.ts +19 -3
  96. package/src/seed/agents/demo-video-builder.md +62 -14
  97. /package/dist-web/{assets/app.css → app.css} +0 -0
@@ -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');
@@ -117,8 +118,9 @@ const { verifyRun, parseLog, scanSentinel, scanForeignWipPathsClaim } = require(
117
118
  const { latestTerminalOutcomeForSlug, COMPLETED_EQUIVALENT_VERDICTS } = require('./lib/scheduler/terminalRunOutcome.cjs');
118
119
  const { isFixPlanSlug, classifyDiscoveredFixPlan, resolveIsFixPlan } = require('./lib/scheduler/fixPlanSlug.cjs');
119
120
  const { landedSinceRun, landedOnMainSince } = require('./lib/scheduler/landedSinceRun.cjs');
120
- const { declaredPathsForPrd } = require('./lib/prd/prdDeclaredPaths.cjs');
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).
@@ -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 = [];
@@ -1794,8 +1977,23 @@ async function reconcile(state) {
1794
1977
  }
1795
1978
 
1796
1979
  let staleNewDiscoveryCount = 0;
1980
+ // Reads use queueStore's cached project list (up to 120 s old) while PRD
1981
+ // discovery sees every project. A project with a real queue file that this
1982
+ // read never covered looks empty, so minting would write a shard holding
1983
+ // only fresh rows over the real ones (same danger listPrdFiles guards for
1984
+ // quarantined shards). Skip such PRDs and bust the cache for the next read.
1985
+ const covered = Array.isArray(state.sourceCwds) ? new Set(state.sourceCwds) : null;
1986
+ const uncovered = new Map();
1797
1987
  for (const [slug, p] of onDisk) {
1798
1988
  if (seen.has(slug)) continue;
1989
+ if (covered) {
1990
+ const mintCwd = p.cwd ?? deriveProjectCwdFromPrdPath(p.path) ?? null;
1991
+ if (mintCwd && !covered.has(mintCwd) && fs.existsSync(queueStore.projectQueuePath(mintCwd))) {
1992
+ if (!uncovered.has(mintCwd)) uncovered.set(mintCwd, []);
1993
+ uncovered.get(mintCwd).push(slug);
1994
+ continue;
1995
+ }
1996
+ }
1799
1997
  // Security gate: a PRD's file location IS its Epic membership
1800
1998
  // (prdLocations.deriveEpicIdFromPrdPath / p.epicId). Before this check,
1801
1999
  // the scheduler queued ANY .md file it found under an Epic's prds/ dir
@@ -1961,6 +2159,11 @@ async function reconcile(state) {
1961
2159
  } catch { /* stat is best-effort reporting only */ }
1962
2160
  next.push(entry);
1963
2161
  }
2162
+ if (uncovered.size > 0) {
2163
+ queueStore.bustCwdCache();
2164
+ console.warn(`[scheduler] reconcile: skipped minting PRDs for project(s) whose queue file this read did not cover: ${[...uncovered.keys()].join(', ')}`);
2165
+ for (const [cwd, skippedPrds] of uncovered) appendAuditEvent('reconcile_uncovered_project', { cwd, skippedPrds });
2166
+ }
1964
2167
  if (staleNewDiscoveryCount > 0) {
1965
2168
  console.warn(`[scheduler] reconcile: ${staleNewDiscoveryCount} PRD(s) discovered this pass were already older than one poll interval with no prior queue row`);
1966
2169
  }
@@ -2295,7 +2498,8 @@ let cancelToken = { cancelled: false };
2295
2498
  let lastMemGate = null;
2296
2499
  // CPU-load launch gate (PRD 1085, lib/scheduler/loadGate.cjs) — innermost launch
2297
2500
  // predicate after pool → project cap → memory. Withholds launches only.
2298
- const loadGate = createLoadGate();
2501
+ let loadGate = createLoadGate();
2502
+ function _setLoadGateForTests(gate) { loadGate = gate; }
2299
2503
 
2300
2504
  // Last tickQueue outcome, kept for the UI. tickQueue already computes a precise
2301
2505
  // reason for every way a batch can come back empty (dependency holds, slot
@@ -2304,6 +2508,9 @@ const loadGate = createLoadGate();
2304
2508
  // actually pinned at 1 with nothing on screen explaining why. This is that
2305
2509
  // explanation, recorded once per tick and broadcast with the rest of the state.
2306
2510
  let lastTick = null;
2511
+ // Last tick that did NOT fire for a real hold (not already-running/drained); a fired
2512
+ // tick stores no reason, so the starve alert reads this to still name the limiter.
2513
+ let lastHoldTick = null;
2307
2514
  // Strips the leading '[scheduler] <word> [..]: ' prefix from a tick detail.
2308
2515
  // keepWord=true strips only the '[scheduler] ' tag and keeps '<word>: ' (the
2309
2516
  // heartbeat wants the hold kind, e.g. 'quiet-machine: lease held ...').
@@ -2313,6 +2520,7 @@ function stripTickDetailPrefix(detail, { keepWord = false } = {}) {
2313
2520
  }
2314
2521
  function recordTick(outcome, extra = {}) {
2315
2522
  lastTick = { ...outcome, ...extra, at: new Date().toISOString() };
2523
+ if (!outcome.fired && outcome.reason !== 'already-running' && outcome.reason !== 'drained') lastHoldTick = lastTick;
2316
2524
  return outcome;
2317
2525
  }
2318
2526
 
@@ -2350,14 +2558,29 @@ function applyPauseCleared(wasPaused, token) {
2350
2558
  /**
2351
2559
  * Human-readable explanation for a `reason: 'load-deferred'` tick, surfaced
2352
2560
  * 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
2561
+ * the threshold and how long this gate itself has held a batch that slots and
2562
+ * memory admitted (heldMs). Pure so it's unit-testable without driving tickQueue's full
2356
2563
  * fs/worktree machinery.
2357
2564
  */
2358
2565
  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`;
2566
+ const heldMinutes = Math.round(load.heldMs / 60_000);
2567
+ const cpu = load.cpuBusy == null
2568
+ ? 'no CPU sample yet'
2569
+ : `CPU ${Math.round(load.cpuBusy * 100)}% busy over ${Math.round(load.cpuWindowMs / 1000)}s`;
2570
+ return `CPU load gate: loadavg1 ${load.loadavg1} / ${load.cores} cores = ${load.ratio} > threshold ${load.threshold}, ${cpu}, held ${heldMinutes}m with slots and memory free`;
2571
+ }
2572
+
2573
+ function loadGateAuditFields(load) {
2574
+ return {
2575
+ loadavg1: load.loadavg1, cores: load.cores, ratio: load.ratio, threshold: load.threshold,
2576
+ cpuBusy: load.cpuBusy, cpuIowait: load.cpuIowait, cpuWindowMs: load.cpuWindowMs, heldMs: load.heldMs,
2577
+ };
2578
+ }
2579
+
2580
+ function loadGateStallEvent(load, batch, lead) {
2581
+ const byProject = {};
2582
+ for (const j of batch) byProject[j.cwd] = { held: (byProject[j.cwd]?.held || 0) + 1 };
2583
+ return { message: `${lead} ${formatLoadGateDetail(load)}`, total: batch.length, byProject };
2361
2584
  }
2362
2585
 
2363
2586
  function attachWindow(w) { mainWindow = w; }
@@ -3082,6 +3305,30 @@ async function resolveFixPlanPath(failedJob) {
3082
3305
  * scheduleSettle option: arms the debounced Epic settle runner with live deps.
3083
3306
  * `remote` is defined later in the module but only read at call time.
3084
3307
  */
3308
+ async function readValidatorGateMs(cwd, epicId, slugs) {
3309
+ const texts = await prdPaths.readEpicPrdTexts(cwd, epicId, slugs);
3310
+ const out = new Map();
3311
+ for (const [slug, text] of texts) out.set(slug, gateTimeoutMs(text));
3312
+ return out;
3313
+ }
3314
+
3315
+ /**
3316
+ * resolveValidatorEstimate(job) → number | null — sizes a planner-written
3317
+ * validator (no estimateMinutes) from its dependsOn PRDs' gate timeouts.
3318
+ * Never rejects.
3319
+ */
3320
+ async function resolveValidatorEstimate(job, { readGateMs = readValidatorGateMs } = {}) {
3321
+ try {
3322
+ if (!job || job.agentType !== 'validator' || job.estimateMinutes != null) return null;
3323
+ if (!Array.isArray(job.dependsOn) || job.dependsOn.length === 0) return null;
3324
+ const gateMap = await readGateMs(job.cwd, job.epicId || job.sourcePromptId, job.dependsOn);
3325
+ const values = job.dependsOn.map((slug) => (gateMap && typeof gateMap.get === 'function' ? gateMap.get(slug) : undefined));
3326
+ return validatorEstimateMinutes(values, { factor: budget.JOB_BUDGET_FACTOR });
3327
+ } catch {
3328
+ return null;
3329
+ }
3330
+ }
3331
+
3085
3332
  function defaultScheduleSettle({ cwd, epicId }) {
3086
3333
  const deps = {
3087
3334
  loadJobs: async () => (await readQueue()).jobs || [],
@@ -3094,12 +3341,37 @@ function defaultScheduleSettle({ cwd, epicId }) {
3094
3341
  return null;
3095
3342
  }
3096
3343
  },
3344
+ readGateMs: readValidatorGateMs,
3345
+ jobBudget: { factor: budget.JOB_BUDGET_FACTOR, ceilingMs: budget.JOB_BUDGET_CEILING_MS },
3097
3346
  sendPrompt: (tabId, prompt) => enqueueExternalPrompt(tabId, prompt, { origin: 'scheduler' }),
3098
3347
  appendResponseEvent: appendResponseEventIfKnown,
3099
3348
  };
3100
3349
  epicValidationHook.scheduleEpicSettle({ cwd, epicId }, (args) => epicValidationHook.runEpicSettle(args, deps));
3101
3350
  }
3102
3351
 
3352
+ /**
3353
+ * armSettleAfterValidatorBudgetKill(job, { scheduleSettle }) → boolean
3354
+ *
3355
+ * A park never arms the settle (isNotifiableTerminalStatus excludes
3356
+ * needs_review), budget_exceeded is excluded from the review heal ladder, and
3357
+ * a split's carried PRDs only move on a settle — so a budget-killed validator
3358
+ * would strand them with no digest. Arms the settle for that one case only
3359
+ * (validator + budget_exceeded). Call OUTSIDE mutate with a row snapshot.
3360
+ * Returns whether it armed; never throws.
3361
+ */
3362
+ function armSettleAfterValidatorBudgetKill(job, { scheduleSettle = defaultScheduleSettle } = {}) {
3363
+ try {
3364
+ if (!job || job.agentType !== 'validator' || job.verifierVerdict !== 'budget_exceeded') return false;
3365
+ const epicId = job.epicId || job.sourcePromptId;
3366
+ if (!job.cwd || !epicId) return false;
3367
+ scheduleSettle({ cwd: job.cwd, epicId });
3368
+ return true;
3369
+ } catch (e) {
3370
+ console.error('[scheduler] armSettleAfterValidatorBudgetKill error', job && job.slug, e);
3371
+ return false;
3372
+ }
3373
+ }
3374
+
3103
3375
  /**
3104
3376
  * notifyOriginatingTab(job) → void
3105
3377
  *
@@ -3499,15 +3771,20 @@ function classifyFailureOutcome({ exitCode, networkError, durationMs, transientR
3499
3771
 
3500
3772
  /**
3501
3773
  * Evidence gathering for the commit-guard's already-satisfied-on-main
3502
- * exemption (PRD 1136): does a commit reachable from `main`, landed AFTER
3774
+ * exemption (PRD 1136): does a commit reachable from the base branch, landed AFTER
3503
3775
  * this job's `queuedAt`, touch a path this PRD itself declares? Scoped to
3504
3776
  * the PRD's own declared paths via declaredPathsForPrd — the same
3505
3777
  * path-extraction computeLooksDone already uses — so an unrelated commit
3506
- * elsewhere in the repo is never credited to this job. Returns `[]` (never
3507
- * fabricates evidence) when the PRD names no paths or has no `queuedAt`.
3778
+ * elsewhere in the repo is never credited to this job. The window starts at the
3779
+ * earlier valid date of the row's `queuedAt` and the PRD's own `issuedAt` (a
3780
+ * re-minted row gets a new queuedAt; issuedAt survives). Returns `[]` (never
3781
+ * fabricates evidence) when the PRD names no paths or neither date is valid.
3508
3782
  *
3509
- * Requires EVERY declared path to have landed, not just one — declaredPathsForPrd's
3510
- * regex matches any backtick-quoted path in the PRD's Implementation notes or
3783
+ * The PRD's `# Files` list is the declared change set; the backtick scan is
3784
+ * only for PRDs with no Files section.
3785
+ *
3786
+ * Requires EVERY declared path to have landed, not just one — for legacy PRDs
3787
+ * declaredPathsForPrd's regex matches any backtick-quoted path in the PRD's Implementation notes or
3511
3788
  * Acceptance criteria, including a path cited only as context (e.g.
3512
3789
  * `` `src/main/scheduler.cjs:1234` `` pointing at a call site, not a file this
3513
3790
  * PRD's own work touches). Unlike computeLooksDone's identical path-overlap
@@ -3525,14 +3802,20 @@ function classifyFailureOutcome({ exitCode, networkError, durationMs, transientR
3525
3802
  * @returns {Promise<string[]>} full commit SHAs reachable from main, newest first
3526
3803
  */
3527
3804
  async function findSatisfyingCommitOnMain(job) {
3528
- if (!job?.queuedAt) return [];
3805
+ if (!job) return [];
3529
3806
  const prdPath = (await resolveVerifyPrdPath(job)) ?? prdPaths.archivedPrdPathForJob(job);
3530
3807
  const paths = declaredPathsForPrd(prdPath);
3531
3808
  if (!paths.length) return [];
3809
+ const starts = [job.queuedAt, issuedAtForPrd(prdPath)]
3810
+ .map((d) => (d ? Date.parse(d) : NaN))
3811
+ .filter((t) => Number.isFinite(t));
3812
+ if (!starts.length) return [];
3813
+ const since = new Date(Math.min(...starts)).toISOString();
3532
3814
  await gitTreeGuard.fetchAllRefs(job.cwd);
3533
- const perPathCommits = await Promise.all(paths.map((p) => landedOnMainSince(job.cwd, job.queuedAt, [p])));
3815
+ const baseBranch = job.worktreeBaseBranch || await jobWorktree.resolveDefaultBranch(job.cwd);
3816
+ const perPathCommits = await Promise.all(paths.map((p) => landedOnMainSince(job.cwd, since, [p], { baseBranch })));
3534
3817
  if (perPathCommits.some((commits) => commits.length === 0)) return [];
3535
- return landedOnMainSince(job.cwd, job.queuedAt, paths);
3818
+ return landedOnMainSince(job.cwd, since, paths, { baseBranch });
3536
3819
  }
3537
3820
 
3538
3821
  /**
@@ -3894,7 +4177,7 @@ function stampIntegrationFailure(row, integration) {
3894
4177
  async function resolveHeadShasForPass(jobs) {
3895
4178
  const byCwd = new Map();
3896
4179
  for (const j of jobs || []) {
3897
- if (!j || j.status !== 'needs_review' || j.integrationFailureKind !== 'content_conflict') continue;
4180
+ if (!j || j.status !== 'needs_review' || !reviewLadder.isHeadSensitiveFailureKind(j.integrationFailureKind)) continue;
3898
4181
  const cwd = j.cwd || DEFAULT_PROJECT_CWD;
3899
4182
  if (!byCwd.has(cwd)) byCwd.set(cwd, gitTreeGuard.gitHead(cwd));
3900
4183
  }
@@ -4549,6 +4832,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4549
4832
  await ensureCliCapsProbed();
4550
4833
  await ensureTimeoutShimOnce();
4551
4834
 
4835
+ const validatorEstimate = await resolveValidatorEstimate(job);
4836
+
4552
4837
  return await new Promise((resolve) => {
4553
4838
  const claudeBin = resolveClaudeBin();
4554
4839
  // Strip Claude Code env and secrets that leak in when session-manager is
@@ -4693,8 +4978,12 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4693
4978
  // is calibrated against). Only a PRD with an
4694
4979
  // explicit `budgetExempt: true` opts out entirely — logged once here so
4695
4980
  // an unbounded job is never silently unbounded.
4696
- const jobBudgetMs = budget.computeJobBudgetMs(
4697
- job.estimateMinutes ?? resolvePersonaDefaultEstimate(job.cwd, job.agentType || DEFAULT_PRD_AGENT_TYPE));
4981
+ const budgetEstimate = budget.resolveBudgetEstimate({
4982
+ estimateMinutes: job.estimateMinutes,
4983
+ validatorEstimate,
4984
+ personaEstimate: job.estimateMinutes != null ? null : resolvePersonaDefaultEstimate(job.cwd, job.agentType || DEFAULT_PRD_AGENT_TYPE),
4985
+ });
4986
+ const jobBudgetMs = budget.computeJobBudgetMs(budgetEstimate);
4698
4987
  const budgetExempt = budget.isJobBudgetExempt(job);
4699
4988
  if (budgetExempt) {
4700
4989
  safeLog(`[scheduler] wall-clock budget watchdog EXEMPT for ${job.slug} ` +
@@ -4724,7 +5013,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4724
5013
  action(ctx) {
4725
5014
  const elapsedMs = Date.now() - ctx.startedAt;
4726
5015
  ctx.safeLog(`\n[scheduler] wall-clock budget watchdog: ran ${Math.round(elapsedMs / 60_000)}m ` +
4727
- `(> ${Math.round(jobBudgetMs / 60_000)}m budget, estimateMinutes=${job.estimateMinutes ?? 0}) — SIGTERM process group\n`);
5016
+ `(> ${Math.round(jobBudgetMs / 60_000)}m budget, estimateMinutes=${budgetEstimate ?? 0}) — SIGTERM process group\n`);
4728
5017
  ctx.killedByWatchdog = 'budget';
4729
5018
  ctx.killTree('SIGTERM');
4730
5019
  const budgetKillTimer = setTimeout(() => {
@@ -4761,22 +5050,26 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4761
5050
  return;
4762
5051
  }
4763
5052
 
5053
+ const scopePlan = planJobScope({ jobSpawn, jobArgs, slug: job.slug, startedAt });
5054
+ const scopeState = { unit: scopePlan.unit, pid: null, cgroupDir: null, finalized: false };
5055
+ const launchSpawn = scopePlan.spawn;
5056
+
4764
5057
  const { child } = withChildAndLog({
4765
5058
  fd,
4766
5059
  logPath,
4767
5060
  safeLog,
4768
5061
  closeFd,
4769
5062
  spawn: {
4770
- command: jobSpawn.command,
5063
+ command: launchSpawn.command,
4771
5064
  stdinText: prompt,
4772
5065
  // Resume mode passes `--resume <sessionId>` (reconnect to the SAME
4773
5066
  // session) INSTEAD of `--session-id <sessionId>` (mint a new one) —
4774
5067
  // never both, see buildClaudeSpawnArgs.
4775
- args: jobSpawn.args || jobArgs,
5068
+ args: launchSpawn.args || jobArgs,
4776
5069
  options: {
4777
5070
  cwd: spawnCwd,
4778
5071
  env: childEnv,
4779
- ...(jobSpawn.argv0 ? { argv0: jobSpawn.argv0 } : {}),
5072
+ ...(launchSpawn.argv0 ? { argv0: launchSpawn.argv0 } : {}),
4780
5073
  ...(jobSpawn.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
4781
5074
  // detached:true puts the child in its own process group so we can kill
4782
5075
  // the entire descendant tree (including any stray background bashes the
@@ -4787,11 +5080,12 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4787
5080
  },
4788
5081
  },
4789
5082
  watchdogs: [resultTailWatchdog, deadmanWatchdog, idleTailWatchdog, budgetWatchdog],
4790
- onExit({ exitCode, signal, killedByWatchdog, error, spawnFailed, leakedDescendants, safeLog: sl }) {
5083
+ onExit({ exitCode, signal, killedByWatchdog, error, spawnFailed, pid, safeLog: sl }) {
5084
+ const leaked = jobLeftovers.listJobSurvivors(job.slug, pid);
4791
5085
  const durationMs = Date.now() - startedAt;
4792
- const leaked = leakedDescendants ?? [];
5086
+ finalizeJobScope(scopeState, sl);
4793
5087
  if (leaked.length > 0) {
4794
- sl(`\n[scheduler] leaked ${leaked.length} descendant(s) swept from job process group: ` +
5088
+ sl(`\n[scheduler] leaked ${leaked.length} descendant(s) left behind after the job exited: ` +
4795
5089
  `${leaked.map((p) => `pid=${p.pid} comm=${p.comm} pcpu=${p.pcpu} etimes=${p.etimes}s`).join(', ')}\n`);
4796
5090
  }
4797
5091
 
@@ -4851,7 +5145,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4851
5145
  // resolveBudgetKillOutcome's own header for why this is gated on
4852
5146
  // killedBySignal, not on killedByWatchdog alone.
4853
5147
  const budgetKillOutcome = budget.resolveBudgetKillOutcome({
4854
- killedByWatchdog, killedBySignal, durationMs, jobBudgetMs, estimateMinutes: job.estimateMinutes,
5148
+ killedByWatchdog, killedBySignal, durationMs, jobBudgetMs, estimateMinutes: budgetEstimate,
4855
5149
  });
4856
5150
  const { budgetKillReason } = budgetKillOutcome;
4857
5151
  const effectiveKilledByWatchdog = budgetKillOutcome.killedByWatchdog;
@@ -4888,6 +5182,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4888
5182
  worktreeDir: execCwd || null, worktreeBranch: execCwd ? `sm-job/${job.slug}` : null,
4889
5183
  sessionId, startedAt, budgetMs: budgetExempt ? null : jobBudgetMs, maxDurationMs: null,
4890
5184
  idleKillMs: IDLE_OUTPUT_KILL_MS, schedulerPid: process.pid, codeSha: SCHEDULER_CODE_SHA,
5185
+ scopeUnit: scopePlan.unit,
4891
5186
  });
4892
5187
  } catch (e) {
4893
5188
  const message = e?.message ?? String(e);
@@ -4896,6 +5191,22 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4896
5191
  }
4897
5192
  // Make this job the OOM killer's preferred victim over Electron.
4898
5193
  biasJobOomScore(child.pid);
5194
+ if (scopeState.unit) {
5195
+ // systemd-run moves itself into the scope just before exec; read the
5196
+ // cgroup now (the process may be gone at finalize), retrying briefly.
5197
+ scopeState.pid = child.pid;
5198
+ scopeState.cgroupDir = readJobCgroupDir(child.pid, scopeState.unit);
5199
+ startJobScopeSampling(scopeState);
5200
+ for (const delay of scopeState.cgroupDir ? [] : [500, 3000]) {
5201
+ const t = setTimeout(() => {
5202
+ if (!scopeState.cgroupDir && !scopeState.finalized) {
5203
+ scopeState.cgroupDir = readJobCgroupDir(child.pid, scopeState.unit);
5204
+ startJobScopeSampling(scopeState);
5205
+ }
5206
+ }, delay);
5207
+ if (t.unref) t.unref();
5208
+ }
5209
+ }
4899
5210
  // Persist runtime.pid with one retry — still fire-and-forget (must
4900
5211
  // never block the spawn), but a final failure is now loud instead of
4901
5212
  // silently swallowed. A silent failure here is exactly what let the
@@ -4997,7 +5308,26 @@ The fix-plan PRD you write for this MUST instruct its executor to, in order:
4997
5308
  1. Check for a salvage patch (named \`<slug>.uncommitted.patch\` in the run directory${failedJob.salvagePatch ? `, e.g. \`${failedJob.salvagePatch}\`` : ''}) and, if found, apply it to the working tree BEFORE inspecting \`git status\`/\`git diff\` in ${cwd} for uncommitted changes matching the original PRD's acceptance criteria.
4998
5309
  2. If the work is present (via the applied patch or already in the tree) and satisfies the acceptance criteria, run the project's verify commands and COMMIT it — do not re-implement or re-plan the PRD from scratch.
4999
5310
  3. Only fall back to re-implementing whatever acceptance criteria are genuinely missing after applying any salvage patch, not the whole PRD.` : '';
5000
- return `You are investigating a failed scheduled job in the session-manager queue. Your ONLY job is to write a fix-plan PRD file. Do NOT attempt the fix yourself.${deadFixChildNote}${abandonedBackgroundTaskNote}
5311
+ const runCommitNotLandedNote = failedJob.verifierVerdict === 'run_commit_not_landed' ? `
5312
+
5313
+ # Known failure class: run_commit_not_landed
5314
+ This job's verifier verdict is \`run_commit_not_landed\`: the run committed its work on a detached
5315
+ HEAD or a branch that never reached the base, and the scheduler pinned each such commit under
5316
+ \`refs/sm-stranded/${failedJob.slug}/\`. The finished work EXISTS; it just never landed. This is NOT
5317
+ evidence the work failed.
5318
+
5319
+ The job's worktree is gone, but the git object store is shared with every new worktree, so a
5320
+ \`git cherry-pick <sha>\` of a pinned commit works from any checkout of ${cwd}. List the pinned commits with:
5321
+
5322
+ git -C ${cwd} for-each-ref refs/sm-stranded/${failedJob.slug}/
5323
+
5324
+ If no pin exists, the failure log names the SHA instead (${failedLogPath}).
5325
+
5326
+ The fix-plan PRD you write for this MUST instruct its executor to, in order:
5327
+ 1. Cherry-pick the pinned commits onto the base branch, oldest first.
5328
+ 2. Run the original PRD's gate on the result.
5329
+ 3. Then re-implement only the acceptance criteria that do not apply or are still missing after the cherry-pick — do not re-implement or re-plan the whole PRD from scratch.` : '';
5330
+ return `You are investigating a failed scheduled job in the session-manager queue. Your ONLY job is to write a fix-plan PRD file. Do NOT attempt the fix yourself.${deadFixChildNote}${abandonedBackgroundTaskNote}${runCommitNotLandedNote}
5001
5331
 
5002
5332
  # Failed job
5003
5333
  - Slug: ${failedJob.slug}
@@ -5159,7 +5489,7 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
5159
5489
  // Mechanical recovery (PRD 1130): same first-refusal treatment — a job
5160
5490
  // eligible for a pure-git retry must never also get a cold-read fix-plan
5161
5491
  // PRD authored in the same pass.
5162
- if (reviewLadder.selectMechanicalRecoveryTarget(failedJob, failedJob.integrationFailureKind === 'content_conflict' ? await gitTreeGuard.gitHead(failedJob.cwd || DEFAULT_PROJECT_CWD) : null)) {
5492
+ if (reviewLadder.selectMechanicalRecoveryTarget(failedJob, reviewLadder.isHeadSensitiveFailureKind(failedJob.integrationFailureKind) ? await gitTreeGuard.gitHead(failedJob.cwd || DEFAULT_PROJECT_CWD) : null)) {
5163
5493
  console.log(`[scheduler] skip investigation: ${failedJob.slug} is mechanical-recovery eligible`);
5164
5494
  return { deferred: false };
5165
5495
  }
@@ -5654,6 +5984,16 @@ async function finalizeJobWorktree({ job, runId = null, runDir, worktree, guardC
5654
5984
  let mergeAutoResolved = null;
5655
5985
  let mergeAutoResolvedPaths = null;
5656
5986
  let integratedSha = null;
5987
+ const worktreeHead = { action: 'unknown', finalHead: null, stranded: [] };
5988
+ const addStranded = (list) => {
5989
+ for (const c of Array.isArray(list) ? list : []) {
5990
+ if (c && c.sha && !worktreeHead.stranded.some((x) => x.sha === c.sha)) worktreeHead.stranded.push({ sha: c.sha, ref: c.ref || null });
5991
+ }
5992
+ };
5993
+ const pinUnlanded = async () => {
5994
+ if (typeof jw.pinUnlandedWorktreeCommits !== 'function') return;
5995
+ addStranded(await jw.pinUnlandedWorktreeCommits({ cwd: guardCwd, dir: worktree.dir, branch: worktree.branch, key: job.slug }));
5996
+ };
5657
5997
  try {
5658
5998
  worktreeLeftoverDirty = (await uncommitted(worktree.dir)) || [];
5659
5999
  // Salvage the worktree's full diff (tracked + untracked) to the run
@@ -5669,11 +6009,32 @@ async function finalizeJobWorktree({ job, runId = null, runDir, worktree, guardC
5669
6009
  console.log(`[scheduler] ${job.slug}: salvaged ${salvage.bytes} byte(s) of uncommitted worktree diff to ${salvagePath}`);
5670
6010
  }
5671
6011
  }
6012
+ // Carried base WIP the job left byte-identical to the base is not the job's
6013
+ // dirt. Filtered AFTER the salvage so the patch still holds the full diff.
6014
+ if (worktreeLeftoverDirty.length && Array.isArray(carriedPaths) && carriedPaths.length && typeof jw.unchangedCarriedPaths === 'function') {
6015
+ const same = new Set(await jw.unchangedCarriedPaths({ cwd: guardCwd, dir: worktree.dir, paths: carriedPaths }));
6016
+ if (same.size) worktreeLeftoverDirty = worktreeLeftoverDirty.filter((p) => !same.has(p));
6017
+ }
6018
+ // Where did HEAD end up? A commit on a detached HEAD must end on the job
6019
+ // branch (fast-forward) or be pinned (diverged) before the checkout goes.
6020
+ if (typeof jw.reconcileWorktreeHead === 'function') {
6021
+ const rec = await jw.reconcileWorktreeHead({ cwd: guardCwd, dir: worktree.dir, branch: worktree.branch, key: job.slug });
6022
+ worktreeHead.action = rec?.action || 'unknown';
6023
+ worktreeHead.finalHead = rec?.finalHead || null;
6024
+ if (rec?.pinnedRef && rec.finalHead) addStranded([{ sha: rec.finalHead, ref: rec.pinnedRef }]);
6025
+ }
5672
6026
  if (await runCancelled(job.slug, runId)) {
5673
6027
  // Cancelled mid-run: keep the commit on the job branch only.
5674
6028
  appendAuditEvent('job_cancel_integration_skipped', { slug: job.slug, runId, branch: worktree.branch });
6029
+ await pinUnlanded();
6030
+ await jw.cleanupJobWorktree({ cwd: guardCwd, dir: worktree.dir, branch: worktree.branch, keepBranch: true });
6031
+ return { worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha: null, cancelled: true, worktreeHead };
6032
+ }
6033
+ if (worktreeHead.action === 'diverged') {
6034
+ console.error(`[scheduler] ${job.slug}: worktree HEAD diverged from ${worktree.branch} — not integrating; commit pinned`);
6035
+ await pinUnlanded();
5675
6036
  await jw.cleanupJobWorktree({ cwd: guardCwd, dir: worktree.dir, branch: worktree.branch, keepBranch: true });
5676
- return { worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha: null, cancelled: true };
6037
+ return { worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha: null, cancelled: false, worktreeHead };
5677
6038
  }
5678
6039
  const integration = await jw.integrateJobBranch({ cwd: guardCwd, branch: worktree.branch, slug: job.slug, carriedPaths, baseBranch: worktree.baseBranch });
5679
6040
  if (integration.ok && integration.reason === 'carried-wip-only') {
@@ -5692,6 +6053,7 @@ async function finalizeJobWorktree({ job, runId = null, runDir, worktree, guardC
5692
6053
  console.log(`[scheduler] ${job.slug}: merge auto-resolved (${integration.autoResolved}) — discarded ${mergeAutoResolvedPaths.length} identical working-tree duplicate(s): ${mergeAutoResolvedPaths.join(', ')}`);
5693
6054
  }
5694
6055
  }
6056
+ if (!integration.ok || !integration.integrated) await pinUnlanded();
5695
6057
  await jw.cleanupJobWorktree({
5696
6058
  cwd: guardCwd,
5697
6059
  dir: worktree.dir,
@@ -5706,7 +6068,7 @@ async function finalizeJobWorktree({ job, runId = null, runDir, worktree, guardC
5706
6068
  await jw.cleanupJobWorktree({ cwd: guardCwd, dir: worktree.dir, branch: worktree.branch, keepBranch: true });
5707
6069
  } catch { /* already reported above */ }
5708
6070
  }
5709
- return { worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha, cancelled: false };
6071
+ return { worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha, cancelled: false, worktreeHead };
5710
6072
  }
5711
6073
 
5712
6074
  /**
@@ -6151,6 +6513,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6151
6513
  let mergeAutoResolved = null;
6152
6514
  let mergeAutoResolvedPaths = null;
6153
6515
  let integratedSha = null;
6516
+ let worktreeHead = null;
6154
6517
  // A job's uncommitted-work patch, whichever isolation mode produced it —
6155
6518
  // set by EITHER branch below, never both (worktree.ok picks exactly one
6156
6519
  // shape for the whole run). Named generically (not "worktree...") because
@@ -6186,7 +6549,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6186
6549
  }, reviewInRun, worktree.ok ? worktree.setup : { ran: false, ok: false, reason: 'in-place', waitedMs: 0, ms: 0, commands: [] });
6187
6550
  } finally {
6188
6551
  if (worktree.ok) {
6189
- ({ worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha } =
6552
+ ({ worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha, worktreeHead } =
6190
6553
  await finalizeJobWorktree({ job, runId, runDir, worktree, guardCwd, carriedPaths }));
6191
6554
  } else {
6192
6555
  // In-place run (non-git cwd, cap reached, env-disabled, or a carry-over
@@ -6244,6 +6607,11 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6244
6607
  ...worktreeLeftoverDirty,
6245
6608
  ])]);
6246
6609
 
6610
+ // The dirt the commit guard judges: a worktree run is judged on its own
6611
+ // worktree's real dirt only (main-checkout changes belong to the owner or
6612
+ // a sibling); an in-place run on the baseline delta.
6613
+ const jobDirt = worktree.ok ? stripAppOwnedChurn(worktreeLeftoverDirty) : newlyDirtyAll;
6614
+
6247
6615
  if (res.launchFailure) {
6248
6616
  await handleLaunchFailure({ job, res, runId, runDir, launchKey, launchEnv, claudeVersion: claudeVersionNow });
6249
6617
  return;
@@ -6461,16 +6829,22 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6461
6829
  // verdict owns the needs_review reason and the pattern hit is demoted to an
6462
6830
  // annotation, so a real "finish protocol incomplete" is distinguishable from
6463
6831
  // transcript noise in the queue (feedback 2026-06-10 addendum).
6464
- const guardWillRefire = verifyResult && verifyResult.downgradeTo === 'pending';
6832
+ // The skip decision is one pure function (gitTreeGuard.commitGuardSkipped):
6833
+ // re-fire, run_commit_not_landed, and completed-equivalent verdicts skip,
6834
+ // except a worktree pass_no_commit_* run that left newly dirty files.
6465
6835
  const guardArtifactVerified = verifyResult?.verdict === 'pass_no_commit_artifact_verified';
6466
- const guardIsLegitimateNoOp = verifyResult && !guardArtifactVerified && COMPLETED_EQUIVALENT_VERDICTS.has(verifyResult.verdict);
6467
- if (res.exitCode === 0 && !res.rateLimited && !guardWillRefire && !guardIsLegitimateNoOp) {
6836
+ if (res.exitCode === 0 && !res.rateLimited && !gitTreeGuard.commitGuardSkipped({
6837
+ verifyResult,
6838
+ ranInWorktree: Boolean(worktree.ok),
6839
+ newlyDirty: jobDirt,
6840
+ landedCommit: jobLandedCommitThisRun,
6841
+ })) {
6468
6842
  // afterGuardCwd === null means non-git cwd (or git errored) —
6469
6843
  // best-effort skip, same as always; only a git-status result (even an
6470
6844
  // empty one) counts as evidence for the zero-edit path. newlyDirtyAll
6471
6845
  // was computed once, above, right after the try/finally.
6472
6846
  if (afterGuardCwd !== null) {
6473
- const newlyDirty = newlyDirtyAll;
6847
+ const newlyDirty = jobDirt || [];
6474
6848
  const guardState = await readQueue().catch(() => ({ jobs: [] }));
6475
6849
  const siblingRunning = (guardState.jobs || []).some(
6476
6850
  (j) => j.slug !== job.slug && j.status === 'running' && (j.cwd || defaultCwd) === guardCwd,
@@ -6484,7 +6858,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6484
6858
  siblingRunning,
6485
6859
  ranInWorktree: worktree.ok,
6486
6860
  jobSelfCommitted,
6487
- legitimateNoOp: guardIsLegitimateNoOp,
6861
+ legitimateNoOp: false,
6488
6862
  isFixPlanJob: resolveIsFixPlan(job.slug, job.isFixPlan),
6489
6863
  artifactVerified: guardArtifactVerified,
6490
6864
  verifyResult,
@@ -6521,6 +6895,16 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6521
6895
  verifyResult = worktreeIntegrationVerdict({ failure: worktreeIntegrationFailure, detail: worktreeIntegrationDetail, slug: job.slug });
6522
6896
  }
6523
6897
 
6898
+ // A commit that was pinned instead of landed (detached HEAD, diverged
6899
+ // branch, cancelled) is never a success, even over already_satisfied_on_main.
6900
+ if (res.exitCode === 0 && !res.rateLimited && !worktreeIntegrationFailure) {
6901
+ const stranded = gitTreeGuard.strandedCommitVerdict({ worktreeHead, landedCommit: jobLandedCommitThisRun });
6902
+ if (stranded) {
6903
+ verifyResult = stranded;
6904
+ console.log(`[scheduler] ${job.slug}: ${stranded.reason} → needs_review`);
6905
+ }
6906
+ }
6907
+
6524
6908
  // Shared-tree stash guard (incident 2026-09-01): only meaningful for an
6525
6909
  // IN-PLACE run — worktree.ok isolates the job's git state into its own
6526
6910
  // checkout, so nothing there can leak into guardCwd. Best-effort and run
@@ -6632,7 +7016,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6632
7016
  let terminalNotifySnapshot = null;
6633
7017
  const newlyCompletedPrds = [];
6634
7018
  // Base HEAD for the mechanical-recovery futility check — read here, never inside mutate() (no I/O).
6635
- const finalizeHeadSha = worktreeIntegrationDetail && worktreeIntegrationDetail.failureKind === 'content_conflict'
7019
+ const finalizeHeadSha = worktreeIntegrationDetail && reviewLadder.isHeadSensitiveFailureKind(worktreeIntegrationDetail.failureKind)
6636
7020
  ? await gitTreeGuard.gitHead(guardCwd) : null;
6637
7021
  await mutate((s) => {
6638
7022
  const i2 = s.jobs.findIndex((x) => x.slug === job.slug);
@@ -7065,6 +7449,9 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7065
7449
  launchEnvApplied: launchEnv ? Object.keys(launchEnv) : [],
7066
7450
  filesChanged: Array.isArray(newlyDirtyAll) ? newlyDirtyAll.length : null,
7067
7451
  landedCommit: jobLandedCommitThisRun ?? null,
7452
+ worktreeFinalHead: worktreeHead?.finalHead ?? null,
7453
+ worktreeHeadAction: worktreeHead?.action ?? null,
7454
+ strandedCommits: (worktreeHead?.stranded || []).map((c) => c.sha),
7068
7455
  });
7069
7456
 
7070
7457
  if (terminalNotifySnapshot) {
@@ -7073,6 +7460,8 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7073
7460
  });
7074
7461
  }
7075
7462
 
7463
+ if (needsReviewRcaSnapshot) armSettleAfterValidatorBudgetKill(needsReviewRcaSnapshot);
7464
+
7076
7465
  if (needsReviewRcaSnapshot) {
7077
7466
  // Fire-and-forget, mirroring the DoD drain hook: never blocks the status
7078
7467
  // transition, never throws to this caller.
@@ -7355,9 +7744,10 @@ function tickWatchdogMs() {
7355
7744
  return Number.isFinite(n) && n >= 0 ? n : 120_000;
7356
7745
  }
7357
7746
 
7358
- // `bypassLoadGate` is set only by the explicit human run-now / force-tick
7359
- // paths (via runDueJobs): the human is asking, so the CPU-load gate yields
7360
- // and logs that it did. Every automatic caller leaves it false.
7747
+ // `bypassLoadGate` is set by the human run-now / force-tick paths (via
7748
+ // runDueJobs) and by the starvation watchdog. `lastResort` marks the watchdog:
7749
+ // on a saturated CPU its bypassed tick sends one job; a human run-now keeps
7750
+ // the whole batch. Every other automatic caller leaves both false.
7361
7751
  /**
7362
7752
  * Fail-CLOSED expiry of runtime reservations (slot tokens, quiet-machine
7363
7753
  * lease, investigation set, worktree accounting) whose owner is provably
@@ -7387,11 +7777,11 @@ function runReservationExpiryPass(jobs, now = Date.now()) {
7387
7777
  }
7388
7778
  }
7389
7779
 
7390
- function tickQueue({ bypassLoadGate = false } = {}) {
7780
+ function tickQueue({ bypassLoadGate = false, lastResort = false } = {}) {
7391
7781
  const budgetMs = tickWatchdogMs();
7392
7782
  const next = tickTail.then(() => {
7393
7783
  const gen = tickGeneration;
7394
- return withTimeout(() => tickBody(gen, { bypassLoadGate }), budgetMs, () => {
7784
+ return withTimeout(() => tickBody(gen, { bypassLoadGate, lastResort }), budgetMs, () => {
7395
7785
  tickGeneration++; // fence the abandoned body
7396
7786
  console.warn(`[scheduler] TICK WEDGED: tick body exceeded ${budgetMs}ms — resetting tick chain`);
7397
7787
  if (!tickWedgeLatched) {
@@ -7414,8 +7804,11 @@ function tickQueue({ bypassLoadGate = false } = {}) {
7414
7804
  // The stale sentinel a fenced body returns: never recorded, never acted on.
7415
7805
  const STALE_TICK = Object.freeze({ fired: false, reason: 'stale-generation' });
7416
7806
 
7417
- async function tickBody(gen, { bypassLoadGate }) {
7807
+ async function tickBody(gen, { bypassLoadGate, lastResort }) {
7418
7808
  const tickStartedAt = Date.now();
7809
+ // evaluate() only runs once slots and memory admit a batch, so the CPU sampler
7810
+ // needs every tick to keep a reference reading about a minute old.
7811
+ loadGate.observe();
7419
7812
  {
7420
7813
  const stale = () => gen !== tickGeneration;
7421
7814
  const state = await readQueue();
@@ -7430,7 +7823,10 @@ async function tickBody(gen, { bypassLoadGate }) {
7430
7823
  // even while paused, before any early return below.
7431
7824
  await superviseAdoptedRunsPass(state.jobs);
7432
7825
  if (stale()) return STALE_TICK;
7826
+ // endHold() at the paused, drain and empty-batch returns: nothing is waiting
7827
+ // on the load gate at these points, so a stale hold clock must not carry over.
7433
7828
  if (state.paused) {
7829
+ loadGate.endHold();
7434
7830
  console.log('[scheduler] tickQueue skipped: paused');
7435
7831
  return recordTick({ fired: false, reason: 'paused' }, { detail: 'scheduler paused' });
7436
7832
  }
@@ -7438,6 +7834,7 @@ async function tickBody(gen, { bypassLoadGate }) {
7438
7834
  // rate-limit pause can't overwrite it. Nothing new dispatches; running and
7439
7835
  // investigating rows finish.
7440
7836
  if (state.drain?.active) {
7837
+ loadGate.endHold();
7441
7838
  return recordTick({ fired: false, reason: 'draining' }, { detail: 'draining for restart' });
7442
7839
  }
7443
7840
  if (cancelToken.cancelled) return { fired: false, reason: 'cancelled' };
@@ -7496,13 +7893,22 @@ async function tickBody(gen, { bypassLoadGate }) {
7496
7893
  if (batch.length === 0 && freeSlots === 0) {
7497
7894
  const snap = sessionSlots.snapshot();
7498
7895
  const pendingCount = state.jobs.filter((j) => j.status === 'pending').length;
7499
- console.log(`[scheduler] slot gate: 0 of ${snap.total} session slots free (${snap.holders.map((h) => h.owner).join(', ')}) — deferring ${pendingCount} pending job(s)`);
7896
+ const hold = budget.describeSlotHold({
7897
+ total: snap.total,
7898
+ inUse: snap.inUse,
7899
+ holders: snap.holders,
7900
+ degradedCap: degradedConcurrencyCapValue,
7901
+ running: runningSet.size,
7902
+ deferredCount: pendingCount,
7903
+ });
7904
+ console.log(`[scheduler] slot gate: ${hold.reason} — ${hold.detail} — deferring ${pendingCount} pending job(s)`);
7500
7905
  return recordTick(
7501
- { fired: false, reason: 'slots-exhausted', deferredCount: pendingCount, holders: snap.holders },
7502
- { detail: `${snap.total} of ${snap.total} session slots busy (${snap.holders.map((h) => h.owner).join(', ')})`, holds },
7906
+ { fired: false, reason: hold.reason, deferredCount: pendingCount, holders: snap.holders },
7907
+ { detail: hold.detail, holds },
7503
7908
  );
7504
7909
  }
7505
7910
  if (batch.length === 0) {
7911
+ loadGate.endHold();
7506
7912
  // Queue drained — run the definition-of-done gate fire-and-forget.
7507
7913
  // Non-blocking: does not hold the mutate lock; errors are logged, not thrown.
7508
7914
  // resolvePrdPath mirrors every other verify call site in this file (e.g.
@@ -7532,7 +7938,8 @@ async function tickBody(gen, { bypassLoadGate }) {
7532
7938
  return recordTick({ fired: false, reason: 'drained' }, { holds });
7533
7939
  }
7534
7940
 
7535
- const availableMb = getAvailableMemMb();
7941
+ const memInfo = readMemInfo();
7942
+ const availableMb = memInfo.availableMb;
7536
7943
  // Reserve a fixed slice for the Electron host before the per-job gate, so a
7537
7944
  // job is never started into the host's own headroom (that path OOM-kills
7538
7945
  // Electron and SIGHUPs every pty — 2026-06-16 incident).
@@ -7563,7 +7970,22 @@ async function tickBody(gen, { bypassLoadGate }) {
7563
7970
  { detail: `memory gate: ${availableMb} MB free, need ${threshold} MB (consumed=${consumedMb} MB credited)`, holds },
7564
7971
  );
7565
7972
  }
7566
- const gatedBatch = batch.slice(0, allowed);
7973
+ const swapAllowed = swapLimitedBatchSize(memInfo, runningSet.size, allowed);
7974
+ if (swapAllowed < allowed) {
7975
+ if (!swapGateLogged) {
7976
+ swapGateLogged = true;
7977
+ 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})`);
7978
+ }
7979
+ } else {
7980
+ swapGateLogged = false;
7981
+ }
7982
+ if (swapAllowed === 0) {
7983
+ return recordTick(
7984
+ { fired: false, reason: 'memory-deferred', deferredCount: batch.length, availableMb, swapFreeMb: memInfo.swapFreeMb, swapTotalMb: memInfo.swapTotalMb },
7985
+ { detail: `memory gate: swap nearly exhausted (${memInfo.swapFreeMb}/${memInfo.swapTotalMb} MB free), ${runningSet.size} job(s) running`, holds },
7986
+ );
7987
+ }
7988
+ const gatedBatch = batch.slice(0, swapAllowed);
7567
7989
  if (gatedBatch.length < batch.length) {
7568
7990
  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)`);
7569
7991
  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() };
@@ -7578,45 +8000,98 @@ async function tickBody(gen, { bypassLoadGate }) {
7578
8000
  // pickNextBatch → memory above) has already admitted `gatedBatch`. It
7579
8001
  // never touches running jobs and never becomes a second pool: it only
7580
8002
  // withholds this tick's launches while the 1-minute loadavg per core is
7581
- // over LOAD_GATE_PER_CORE. An explicit human Run now bypasses it.
8003
+ // over LOAD_GATE_PER_CORE AND a real CPU sample does not show the CPU mostly
8004
+ // idle (then it stands down and the batch launches). An explicit human Run now bypasses it.
8005
+ let launchBatch = gatedBatch;
8006
+ let top = [];
7582
8007
  const load = loadGate.evaluate({ bypass: bypassLoadGate });
7583
8008
  if (load.bypassed) {
7584
- console.log(`[scheduler] load gate: BYPASSED by run-now (loadavg1=${load.loadavg1} cores=${load.cores} ratio=${load.ratio} > ${load.threshold})`);
8009
+ const clampToOne = !!lastResort && load.saturated;
8010
+ if (clampToOne) launchBatch = gatedBatch.slice(0, 1);
8011
+ 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' : ''}`);
7585
8012
  } else if (load.gated) {
7586
8013
  const line = `[scheduler] load gate: loadavg1=${load.loadavg1} cores=${load.cores} ratio=${load.ratio} > ${load.threshold} — holding ${gatedBatch.length} eligible job(s)`;
7587
- if (load.escalate) {
7588
- const top = topCpuConsumers(3);
7589
- console.warn(`${line} for ${Math.round(load.gatedSinceMs / 60_000)}m; top CPU: ${top.length ? top.join(' | ') : 'n/a'}`);
7590
- } else {
7591
- console.log(line);
7592
- }
8014
+ console.log(line);
7593
8015
  if (load.shouldAudit) {
7594
8016
  appendAuditEvent('launch_load_gated', {
7595
- loadavg1: load.loadavg1, cores: load.cores, ratio: load.ratio, threshold: load.threshold,
7596
- held: gatedBatch.map((j) => j.slug), gatedSinceMs: load.gatedSinceMs,
8017
+ ...loadGateAuditFields(load),
8018
+ held: gatedBatch.map((j) => j.slug),
7597
8019
  });
7598
8020
  }
8021
+ if (load.escalated) {
8022
+ const escTop = topCpuConsumers(3);
8023
+ const escMins = Math.round(load.heldMs / 60_000);
8024
+ 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'}`);
8025
+ appendAuditEvent('load_gate_escalated', {
8026
+ ...loadGateAuditFields(load),
8027
+ held: gatedBatch.map((j) => j.slug),
8028
+ top: escTop,
8029
+ });
8030
+ sendIfAlive(mainWindow, 'schedule:stall', loadGateStallEvent(
8031
+ load, gatedBatch,
8032
+ `CPU saturated: load gate has held ${gatedBatch.length} job(s) for ${escMins}m with slots and memory free; nothing launched.`,
8033
+ ));
8034
+ }
7599
8035
  return recordTick(
7600
8036
  { fired: false, reason: 'load-deferred', deferredCount: gatedBatch.length, ratio: load.ratio, threshold: load.threshold },
7601
8037
  { detail: formatLoadGateDetail(load), holds },
7602
8038
  );
8039
+ } else if (load.yielded) {
8040
+ // The gate held this batch for the whole yield window with slots and
8041
+ // memory free and the CPU not saturated (or no sample): let ONE job through.
8042
+ launchBatch = gatedBatch.slice(0, 1);
8043
+ top = topCpuConsumers(3);
8044
+ const mins = Math.round(load.heldMs / 60_000);
8045
+ 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'}`);
8046
+ } else if (load.standDown) {
8047
+ 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`);
8048
+ if (load.shouldAuditStandDown) {
8049
+ appendAuditEvent('load_gate_stood_down', loadGateAuditFields(load));
8050
+ }
7603
8051
  }
7604
8052
 
7605
- await mutate((s) => { s.lastRunAt = new Date().toISOString(); });
8053
+ await mutate((s) => {
8054
+ const nowIso = new Date().toISOString();
8055
+ s.lastRunAt = nowIso;
8056
+ if (!s.lastDispatchAtByCwd || typeof s.lastDispatchAtByCwd !== 'object' || Array.isArray(s.lastDispatchAtByCwd)) s.lastDispatchAtByCwd = {};
8057
+ for (const job of launchBatch) s.lastDispatchAtByCwd[job.cwd || DEFAULT_PROJECT_CWD] = nowIso;
8058
+ });
7606
8059
  if (stale()) return STALE_TICK;
7607
8060
  await broadcast();
7608
8061
  if (stale()) return STALE_TICK;
7609
8062
 
7610
8063
  const { runId, dir: runDir } = pickRunDir();
7611
- for (const job of gatedBatch) {
8064
+ let issued = 0;
8065
+ for (const job of launchBatch) {
7612
8066
  if (cancelToken.cancelled || stale()) break;
7613
8067
  // spawnJob is fire-and-forget; it calls tickQueue() on completion.
7614
8068
  // state.jobs is the queue's rows in scope at THIS dispatch (PRD 1408) —
7615
8069
  // threaded straight through so spawnJob's hasDownstreamValidator check
7616
8070
  // never re-reads the queue itself.
7617
8071
  spawnJob(job, runId, runDir, state.config.defaultCwd, null, state.jobs).catch((e) => reportSchedulerError('spawnJob dispatch rejected', job.slug, e));
8072
+ issued += 1;
8073
+ }
8074
+ if (issued > 0) {
8075
+ loadGate.endHold();
8076
+ if (load.bypassed && lastResort && load.saturated) {
8077
+ appendAuditEvent('load_gate_last_resort', {
8078
+ ...loadGateAuditFields(load),
8079
+ launched: launchBatch[0].slug, stillHeld: gatedBatch.slice(1).map((j) => j.slug),
8080
+ });
8081
+ }
8082
+ if (load.yielded) {
8083
+ const mins = Math.round(load.heldMs / 60_000);
8084
+ appendAuditEvent('load_gate_yielded', {
8085
+ ...loadGateAuditFields(load),
8086
+ launched: launchBatch[0].slug, stillHeld: gatedBatch.slice(1).map((j) => j.slug), top,
8087
+ });
8088
+ sendIfAlive(mainWindow, 'schedule:stall', loadGateStallEvent(
8089
+ load, gatedBatch,
8090
+ `CPU load gate held ${gatedBatch.length} job(s) for ${mins}m with slots and memory free; letting one through.`,
8091
+ ));
8092
+ }
7618
8093
  }
7619
- return recordTick({ fired: true, count: gatedBatch.length, group: gatedBatch[0]?.parallelGroup }, { holds });
8094
+ return recordTick({ fired: true, count: launchBatch.length, group: launchBatch[0]?.parallelGroup }, { holds });
7620
8095
  }
7621
8096
  }
7622
8097
 
@@ -7643,6 +8118,8 @@ function forceTickOutcome(result) {
7643
8118
  return { ok: true, kind: 'warn', message: `Deferred ${result.deferredCount} job(s) — low memory (${result.availableMb} MB available, need ${result.threshold} MB)` };
7644
8119
  case 'slots-exhausted':
7645
8120
  return { ok: true, kind: 'warn', message: `Deferred ${result.deferredCount} job(s) — all session slots in use (${(result.holders ?? []).map((h) => h.owner).join(', ')})` };
8121
+ case 'usage-meter-degraded':
8122
+ return { ok: true, kind: 'warn', message: `Deferred ${result.deferredCount} job(s) — usage meter cap held them (${stripTickDetailPrefix(result.detail) || 'meter degraded'})` };
7646
8123
  case 'held': {
7647
8124
  const detail = stripTickDetailPrefix(result.detail);
7648
8125
  return { ok: true, kind: 'warn', message: detail || 'Batch held' };
@@ -7800,14 +8277,14 @@ async function runQueueStarvationWatchdog(state, {
7800
8277
  // it can't influence, freezing the queue for hours (observed 2026-09-23:
7801
8278
  // 3 dispatchable, 0 running, lastTickReason 'load-deferred' unbroken from
7802
8279
  // 07:00→13:06). The gate is advisory headroom ("leave one core free"), not
7803
- // a resource guard; starting ONE batch cannot OOM the host. The slot pool
8280
+ // a resource guard; starting ONE batch cannot OOM the host (on a saturated CPU the batch is one job: lastResort). The slot pool
7804
8281
  // and memory gate — which DO guard real exhaustion — are unaffected by this
7805
8282
  // flag and still bound the batch. The watchdog is the automated equivalent
7806
8283
  // of a human Run-now, the other caller that legitimately bypasses load
7807
8284
  // (§2/§3, scheduler-operations.md). Latched to one forced tick per
7808
8285
  // QUEUE_STARVATION_MS per cwd, so this cannot thrash. Routed via
7809
8286
  // module.exports so tests can assert the bypass without driving real load.
7810
- await module.exports.tickQueue({ bypassLoadGate: true }).catch((e) => console.error('[scheduler] starvation tick error', e));
8287
+ await module.exports.tickQueue({ bypassLoadGate: true, lastResort: true }).catch((e) => console.error('[scheduler] starvation tick error', e));
7811
8288
  return primary;
7812
8289
  }
7813
8290
 
@@ -7831,12 +8308,13 @@ const starveEscalated = new Set();
7831
8308
  * gate. Exported for direct unit testing (attach a fake window via
7832
8309
  * attachWindow() first to assert the toast send).
7833
8310
  */
7834
- function runStarveEscalationSweep(starvedProjects) {
8311
+ function runStarveEscalationSweep(starvedProjects, jobs = [], launchBlocks = {}) {
7835
8312
  const { toEscalate, toClear } = starvation.selectStarveEscalations(starvedProjects, starveEscalated, STARVE_ESCALATION_MS);
7836
8313
  for (const cwd of toClear) starveEscalated.delete(cwd);
7837
8314
  for (const sp of toEscalate) {
7838
8315
  starveEscalated.add(sp.cwd);
7839
- const holdReason = lastTick?.reason ?? 'unknown';
8316
+ const projectRows = (Array.isArray(jobs) ? jobs : []).filter((j) => j && (j.cwd || DEFAULT_PROJECT_CWD) === sp.cwd);
8317
+ const holdReason = starvation.describeStarveHold({ projectRows, launchBlocks, lastTick, lastHoldTick });
7840
8318
  const mins = Math.round(sp.ageMs / 60_000);
7841
8319
  console.error(
7842
8320
  `[scheduler] PROJECT STARVE ESCALATED: project=${sp.cwd} pending=${sp.pendingCount} oldest=${sp.oldestPendingSlug} `
@@ -7847,7 +8325,7 @@ function runStarveEscalationSweep(starvedProjects) {
7847
8325
  cwd: sp.cwd, pendingCount: sp.pendingCount, oldestPendingSlug: sp.oldestPendingSlug, ageMs: sp.ageMs, holdReason,
7848
8326
  });
7849
8327
  sendIfAlive(mainWindow, 'schedule:stall', {
7850
- message: `Project starved: ${sp.cwd} has ${sp.pendingCount} pending PRD(s), oldest waiting ~${mins}m `
8328
+ message: `Project starved: ${sp.cwd} has ${sp.pendingCount} pending PRD(s), no dispatch for ~${mins}m `
7851
8329
  + `(hold reason: ${holdReason}) — check the Scheduler tab.`,
7852
8330
  total: sp.pendingCount,
7853
8331
  byProject: { [sp.cwd]: { starved: sp.pendingCount } },
@@ -7864,6 +8342,47 @@ function runStarveEscalationSweep(starvedProjects) {
7864
8342
  let queueHealthSweepCycle = 0;
7865
8343
  const QUEUE_HEALTH_SWEEP_EVERY_N_CYCLES = 20;
7866
8344
 
8345
+ // Leftover sweep: stops processes that outlived a finished job (setsid escapees,
8346
+ // jobs ended across an app restart, no-scope / no-systemd runs). Time-based so
8347
+ // poll backoff cannot stretch it.
8348
+ const JOB_LEFTOVER_SWEEP_INTERVAL_MS = 5 * 60_000;
8349
+ let lastJobLeftoverSweepAt = 0;
8350
+
8351
+ /**
8352
+ * Order matters: scan /proc BEFORE reading the queue — a process seen in the
8353
+ * scan spawned before the read, so the row read afterwards is running or later.
8354
+ */
8355
+ async function runJobLeftoverSweep(deps = {}) {
8356
+ const {
8357
+ now = Date.now(),
8358
+ platform = process.platform,
8359
+ scan = () => jobLeftovers.scanJobProcesses(),
8360
+ readState = readQueue,
8361
+ stop = (procs) => jobLeftovers.stopLeftovers(procs),
8362
+ } = deps;
8363
+ if (now - lastJobLeftoverSweepAt < JOB_LEFTOVER_SWEEP_INTERVAL_MS) return [];
8364
+ if (platform !== 'linux' || process.env.SM_E2E === '1') return [];
8365
+ // Fail closed under vitest: the queue is a sandbox with no rows, so every
8366
+ // marked process on the real machine would read as ended and get killed.
8367
+ // Same rule as assertNotLiveRoot in lib/scheduler/schedulerPaths.cjs.
8368
+ if (process.env.VITEST && !deps.scan) return [];
8369
+ lastJobLeftoverSweepAt = now;
8370
+ const scanned = scan();
8371
+ const state = await readState();
8372
+ if (!state || state.unreadable || !Array.isArray(state.jobs) || quarantinedCwdSet(state).size > 0) return [];
8373
+ const leftovers = jobLeftovers.selectLeftovers({
8374
+ scan: scanned, rows: state.jobs, runningSlugs: runningSet, now, selfPid: process.pid,
8375
+ });
8376
+ for (const { slug, procs } of leftovers) {
8377
+ const pids = stop(procs) ?? procs.map((p) => p.pid);
8378
+ const comms = [...new Set(procs.map((p) => p.comm))];
8379
+ const oldestEtimes = Math.max(...procs.map((p) => p.etimes || 0));
8380
+ appendAuditEvent('job_leftovers_stopped', { slug, pids, comms, etimes: oldestEtimes });
8381
+ console.log(`[scheduler] job leftovers stopped: ${slug} pids=${pids.join(',')} comms=${comms.join(',')} oldest=${Math.round(oldestEtimes)}s`);
8382
+ }
8383
+ return leftovers;
8384
+ }
8385
+
7867
8386
  /**
7868
8387
  * runQueueHealthSweep(jobs) — read-only reporting pass over the queue
7869
8388
  * snapshot reapDeadRunningJobs already read this cycle. Never transitions a
@@ -8097,6 +8616,8 @@ async function reapDeadRunningJobs() {
8097
8616
  await runBranchSweep(state.jobs);
8098
8617
  }
8099
8618
 
8619
+ runJobLeftoverSweep().catch((e) => console.warn('[scheduler] job leftover sweep error', e?.message));
8620
+
8100
8621
  if (dead.length === 0) return;
8101
8622
 
8102
8623
  // A rate-limited death is retryable, not terminal — mirror spawnJob's own
@@ -8153,13 +8674,44 @@ async function reapDeadRunningJobs() {
8153
8674
  const rowCwd = row.cwd || state.config?.defaultCwd || DEFAULT_PROJECT_CWD;
8154
8675
  if (!gitTreeGuard.isGitRepoSync(rowCwd)) continue;
8155
8676
  const branch = jobWorktree.branchNameFor(d.slug);
8677
+ // Reconcile the worktree's real HEAD into the branch first: a detached
8678
+ // commit would otherwise leave the branch unmoved and read as integrated.
8679
+ let headReconcile = null;
8680
+ const wtDir = row.runtime?.cwd;
8681
+ if (typeof wtDir === 'string' && wtDir && wtDir !== rowCwd && fs.existsSync(wtDir)) {
8682
+ try {
8683
+ headReconcile = await jobWorktree.reconcileWorktreeHead({ cwd: rowCwd, dir: wtDir, branch, key: d.slug });
8684
+ } catch { headReconcile = null; }
8685
+ }
8156
8686
  const integrated = await gitTreeGuard.isBranchAlreadyIntegrated(rowCwd, branch);
8157
8687
  const headNow = await gitTreeGuard.gitHead(rowCwd);
8158
8688
  const guardHeadBeforeVal = row.guardHeadBefore || null;
8159
8689
  let landedCommit = null;
8160
8690
  let notLandedInfo = null;
8161
8691
  let effectiveSuccess = true;
8162
- if (integrated === null) {
8692
+ // The boot sweep runs before this reaper and removes the worktree, pinning
8693
+ // its unique commits; the branch then sits at the fork point and reads as
8694
+ // integrated. Consult the job's own pins so that case parks instead.
8695
+ const startedMs = Date.parse(row.startedAt);
8696
+ let strandedPins = [];
8697
+ try {
8698
+ strandedPins = await jobWorktree.listStrandedPins({
8699
+ cwd: rowCwd, key: d.slug, sinceMs: Number.isFinite(startedMs) ? startedMs : 0,
8700
+ });
8701
+ } catch { strandedPins = []; }
8702
+ const pinVerdict = headReconcile?.action === 'diverged'
8703
+ ? null
8704
+ : gitTreeGuard.strandedCommitVerdict({ worktreeHead: { stranded: strandedPins }, landedCommit: null });
8705
+ if (headReconcile?.action === 'diverged') {
8706
+ effectiveSuccess = false;
8707
+ notLandedInfo = {
8708
+ verdict: 'run_commit_not_landed',
8709
+ reason: `worktree HEAD ${headReconcile.finalHead} diverged from ${branch}; commit pinned at ${headReconcile.pinnedRef || 'no ref'} — never landed`,
8710
+ };
8711
+ } else if (pinVerdict) {
8712
+ effectiveSuccess = false;
8713
+ notLandedInfo = { verdict: pinVerdict.verdict, reason: pinVerdict.reason };
8714
+ } else if (integrated === null) {
8163
8715
  // No sm-job/<slug> branch — an in-place run (or worktree isolation
8164
8716
  // disabled). Prove landing via the exact same HEAD-advance evidence
8165
8717
  // the live commit-guard already uses — reused, not re-derived.
@@ -8229,6 +8781,7 @@ async function reapDeadRunningJobs() {
8229
8781
  if (resolved) landedCommitEvidence.set(d.slug, row.landedCommit);
8230
8782
  }));
8231
8783
 
8784
+ const budgetKillSettleSnapshots = [];
8232
8785
  await mutate(async (s) => {
8233
8786
  for (const { slug, pid, outcome, gateOutcome, pidless, reason, noOwnArtifact, failureOverride } of dead) {
8234
8787
  const idx = s.jobs.findIndex((x) => x.slug === slug);
@@ -8366,6 +8919,7 @@ async function reapDeadRunningJobs() {
8366
8919
  if (confirmedLandedCommit) s.jobs[idx].landedCommit = confirmedLandedCommit;
8367
8920
  if (landedCommit) s.jobs[idx].landedCommit = landedCommit;
8368
8921
  if (adoptedBudgetKill?.landedCommit) s.jobs[idx].landedCommit = adoptedBudgetKill.landedCommit;
8922
+ if (adoptedBudgetKill) budgetKillSettleSnapshots.push({ ...s.jobs[idx], verifierVerdict: 'budget_exceeded' });
8369
8923
  }
8370
8924
  // A pidless spawn that never wrote its own '<slug>.log' into the
8371
8925
  // batch runId dir it was stamped with must not keep that runId —
@@ -8415,6 +8969,8 @@ async function reapDeadRunningJobs() {
8415
8969
  }
8416
8970
  });
8417
8971
 
8972
+ for (const snap of budgetKillSettleSnapshots) armSettleAfterValidatorBudgetKill(snap);
8973
+
8418
8974
  await broadcast({ flush: true });
8419
8975
  tickQueue().catch(() => {});
8420
8976
  } catch (e) {
@@ -9533,9 +10089,10 @@ async function reverifyNeedsReview() {
9533
10089
  // already excludes every job this loop dispatches, so a resumable job
9534
10090
  // never also gets a fix-plan PRD authored in the same pass.
9535
10091
  {
9536
- for (const job of queueForResumeAndAutofix.jobs) {
9537
- const target = reviewLadder.selectResumeRecoveryTarget(job);
9538
- if (!target) continue;
10092
+ // Saturated CPU (>= 85% busy): start ONE per pass; the rest stay eligible
10093
+ // for the next pass (this path never reaches the load gate).
10094
+ const batch = reviewLadder.selectResumeRecoveryBatch(queueForResumeAndAutofix.jobs, { saturated: loadGate.isSaturated() });
10095
+ for (const { job, target } of batch) {
9539
10096
  console.log(`[scheduler] resume-recovery: needs_review ${job.slug} → resuming session ${target.sessionId}`);
9540
10097
  spawnResumeRecovery(job, target).catch((e) => {
9541
10098
  console.error('[scheduler] spawnResumeRecovery error', job.slug, e);
@@ -10138,7 +10695,7 @@ function rescheduleIntervalTick() {
10138
10695
  // else distinguishes "no pending work" from "pending work, never
10139
10696
  // started" — the 2026-09-01 NN-ordering starvation ran 3.5 h unnoticed.
10140
10697
  // Escalation only, same shape as the quarantine/overrun warnings above.
10141
- const starvedProjects = findStarvedProjects(s.jobs, Date.now(), STARVATION_ESCALATE_MS);
10698
+ const starvedProjects = findStarvedProjects(s.jobs, Date.now(), STARVATION_ESCALATE_MS, s.lastDispatchAtByCwd);
10142
10699
  for (const sp of starvedProjects) {
10143
10700
  console.warn(
10144
10701
  `[scheduler] PROJECT STARVED: project=${sp.cwd} pending=${sp.pendingCount} oldest=${sp.oldestPendingSlug} `
@@ -10153,7 +10710,7 @@ function rescheduleIntervalTick() {
10153
10710
  // strictly later than STARVATION_ESCALATE_MS, so this only ever fires on
10154
10711
  // a subset of the rows already reported above — same verdict, no
10155
10712
  // re-derivation.
10156
- runStarveEscalationSweep(starvedProjects);
10713
+ runStarveEscalationSweep(starvedProjects, s.jobs, s.launchBlocks);
10157
10714
 
10158
10715
  // Bounded failed -> pending auto-reset (PRD 1151), plus the stuck-failed
10159
10716
  // escalation now narrowed to only the rows that auto-reset gave up on.
@@ -11253,6 +11810,12 @@ function registerAdminRoutes(adminHttp, remoteObj = remote) {
11253
11810
  }
11254
11811
 
11255
11812
  module.exports = {
11813
+ readValidatorGateMs,
11814
+ resolveValidatorEstimate,
11815
+ planJobScope,
11816
+ finalizeJobScope,
11817
+ sampleJobScope,
11818
+ readJobCgroupDir,
11256
11819
  normalizeConfig,
11257
11820
  recordTick,
11258
11821
  reportSchedulerError,
@@ -11262,6 +11825,7 @@ module.exports = {
11262
11825
  rescheduleIntervalTick,
11263
11826
  runQueueStarvationWatchdog,
11264
11827
  runStarveEscalationSweep,
11828
+ runJobLeftoverSweep,
11265
11829
  stripAppOwnedChurn,
11266
11830
  BUDGET_WARNING_FRACTION,
11267
11831
  registerScheduleHandlers,
@@ -11273,6 +11837,7 @@ module.exports = {
11273
11837
  computeDegradedBudget,
11274
11838
  writeQueue,
11275
11839
  _setPeriodicReverifyEnabledForTests,
11840
+ _setLoadGateForTests,
11276
11841
  _mutateForTests: mutate, // mutate() has no other exported call site; test-only seam.
11277
11842
  reconcile,
11278
11843
  broadcast,
@@ -11294,6 +11859,12 @@ module.exports = {
11294
11859
  pollRecoveryClearSource,
11295
11860
  memoryLimitedBatchSize,
11296
11861
  availableForJobs,
11862
+ parseMemInfo,
11863
+ readMemInfo,
11864
+ getAvailableMemMb,
11865
+ swapLimitedBatchSize,
11866
+ biasJobOomScore,
11867
+ OOM_SCORE_ADJ_JOB,
11297
11868
  reverifyNeedsReview,
11298
11869
  runGateShadow,
11299
11870
  awaitGateShadowIdle: async () => { while (gateShadowPending) await gateShadowPending; },
@@ -11336,6 +11907,7 @@ module.exports = {
11336
11907
  notifyOriginatingTab,
11337
11908
  flushDueReviewNotices,
11338
11909
  isNotifiableTerminalStatus,
11910
+ armSettleAfterValidatorBudgetKill,
11339
11911
  extractResultTextFromLog,
11340
11912
  resolveVerifyPrdPath,
11341
11913
  resolveFixPlanPath,