claude-code-session-manager 0.126.0 → 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.
- package/bin/cli.cjs +71 -9
- package/bin/supervise.cjs +84 -0
- package/dist/assets/{AgentLibrary-bzeuZN4F.js → AgentLibrary-DKQznr7o.js} +1 -1
- package/dist/assets/{Button-8dWfDDuQ.js → Button-CZXqmIiM.js} +1 -1
- package/dist/assets/{DataModel-D4ybBPZN.js → DataModel-piyV33To.js} +1 -1
- package/dist/assets/{History-hsztE6yh.js → History-BxwtrKF2.js} +1 -1
- package/dist/assets/{Hooks-CRmZMQaW.js → Hooks-DogeSPII.js} +1 -1
- package/dist/assets/{Library-Czt3Bojd.js → Library-BDt6EeQQ.js} +1 -1
- package/dist/assets/{ListDetail-Cr6Ct_WX.js → ListDetail-CwS-LKar.js} +1 -1
- package/dist/assets/{McpServers-CeXJ2bng.js → McpServers-D2HVljgS.js} +1 -1
- package/dist/assets/{Memory-caujO8O3.js → Memory-hNzuOGn8.js} +1 -1
- package/dist/assets/{Panel-D64i9tGz.js → Panel-BLDrsUeq.js} +1 -1
- package/dist/assets/{Permissions-DpWOIrvr.js → Permissions-DzZ5vaJW.js} +1 -1
- package/dist/assets/{Plugins-Bd1ekP5P.js → Plugins-Cz9yaxzG.js} +2 -2
- package/dist/assets/{ProvenanceBadge-B96A_uZf.js → ProvenanceBadge-CCgLO4m9.js} +1 -1
- package/dist/assets/{SaveBar-D0Y2t-Ao.js → SaveBar-Shmn699J.js} +1 -1
- package/dist/assets/{Scheduler-Y5_YbNrC.js → Scheduler-Bqr0WHNd.js} +1 -1
- package/dist/assets/{ScopeSwitcher-BmWA_dP9.js → ScopeSwitcher-CBx1fB5g.js} +1 -1
- package/dist/assets/{Settings-Bcf65bpL.js → Settings-Ci8in-yF.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-BeSNXloA.js → SkillReferenceGraph-BWwljba8.js} +1 -1
- package/dist/assets/{Skills-DwnQKJVc.js → Skills-BON6o-c4.js} +1 -1
- package/dist/assets/{SystemPrompt-Dih6SCmL.js → SystemPrompt-D5epIYYs.js} +1 -1
- package/dist/assets/{TagLibrary-BZ-Kp10P.js → TagLibrary-C2qDZROJ.js} +1 -1
- package/dist/assets/{TiptapBody-C2nEUmF7.js → TiptapBody-SZhI3-bW.js} +1 -1
- package/dist/assets/{Toggle-Dw8-zNQo.js → Toggle-C_qFDG0g.js} +1 -1
- package/dist/assets/{ViewTabs-CoYPKGN-.js → ViewTabs-C9q5WCEd.js} +1 -1
- package/dist/assets/{historyTotals-BbKcNpV7.js → historyTotals-BCl7IOhY.js} +1 -1
- package/dist/assets/{index-DgPUERhe.js → index-CMIYLbPb.js} +73 -73
- package/dist/assets/{settingsSchema-6doG_61l.js → settingsSchema-BBrRBrBr.js} +1 -1
- package/dist/assets/{skillFrontmatter-BYMYWDfb.js → skillFrontmatter-B01qJk6N.js} +1 -1
- package/dist/assets/{useAgentsDirWatch-Cqabjieh.js → useAgentsDirWatch-CuR3GSjS.js} +1 -1
- package/dist/index.html +1 -1
- package/dist-web/app.js +307 -307
- package/package.json +1 -1
- package/plugins/session-manager-dev/skills/develop/SKILL.md +3 -2
- package/scripts/scheduler-mcp-server.cjs +39 -1
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +37 -4
- package/src/main/crashDiagnostics.cjs +83 -8
- package/src/main/health.cjs +16 -5
- package/src/main/index.cjs +32 -0
- package/src/main/lib/chatBootRecovery.cjs +136 -0
- package/src/main/lib/chatInflight.cjs +88 -0
- package/src/main/lib/epic/epicDelegationStats.cjs +1 -0
- package/src/main/lib/epic/epicSweepValidator.cjs +60 -6
- package/src/main/lib/epic/epicValidationHook.cjs +14 -2
- package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +71 -15
- package/src/main/lib/mcpToolCatalog.cjs +22 -3
- package/src/main/lib/persona-macro/builtinMacros.cjs +12 -1
- package/src/main/lib/persona-macro/macroLibrary.cjs +57 -3
- package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
- package/src/main/lib/prd/prdCreate.cjs +5 -1
- package/src/main/lib/process/childWithLog.cjs +38 -95
- package/src/main/lib/process/memoryScope.cjs +140 -0
- package/src/main/lib/process/ozonePlatform.cjs +15 -0
- package/src/main/lib/process/procIdentity.cjs +10 -3
- package/src/main/lib/process/scopeOomPolicy.cjs +69 -0
- package/src/main/lib/scheduler/cpuSample.cjs +147 -0
- package/src/main/lib/scheduler/definitionOfDone.cjs +40 -0
- package/src/main/lib/scheduler/jobLeftovers.cjs +204 -0
- package/src/main/lib/scheduler/jobSupervisorRecord.cjs +2 -1
- package/src/main/lib/scheduler/loadGate.cjs +116 -45
- package/src/main/lib/scheduler/queueStore.cjs +5 -2
- package/src/main/lib/scheduler/schedulerBatch.cjs +10 -3
- package/src/main/lib/scheduler/schedulerConfig.cjs +7 -2
- package/src/main/lib/telemetry/crashTelemetry.cjs +8 -4
- package/src/main/scheduler/budget.cjs +31 -0
- package/src/main/scheduler/prdPaths.cjs +54 -0
- package/src/main/scheduler/reviewLadder.cjs +17 -0
- package/src/main/scheduler/starvation.cjs +22 -0
- package/src/main/scheduler.cjs +522 -68
- package/src/main/templates/PRD_AUTHORING.md +5 -2
- package/src/main/usage.cjs +4 -2
- package/src/preload/api.d.ts +12 -2
- package/src/seed/agents/demo-video-builder.md +62 -14
package/src/main/scheduler.cjs
CHANGED
|
@@ -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).
|
|
@@ -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
|
|
437
|
-
//
|
|
438
|
-
//
|
|
439
|
-
//
|
|
440
|
-
//
|
|
441
|
-
|
|
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
|
|
473
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
//
|
|
1514
|
-
//
|
|
1515
|
-
|
|
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
|
-
|
|
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
|
|
2354
|
-
*
|
|
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.
|
|
2360
|
-
|
|
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
|
*
|
|
@@ -4560,6 +4832,8 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
|
|
|
4560
4832
|
await ensureCliCapsProbed();
|
|
4561
4833
|
await ensureTimeoutShimOnce();
|
|
4562
4834
|
|
|
4835
|
+
const validatorEstimate = await resolveValidatorEstimate(job);
|
|
4836
|
+
|
|
4563
4837
|
return await new Promise((resolve) => {
|
|
4564
4838
|
const claudeBin = resolveClaudeBin();
|
|
4565
4839
|
// Strip Claude Code env and secrets that leak in when session-manager is
|
|
@@ -4704,8 +4978,12 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
|
|
|
4704
4978
|
// is calibrated against). Only a PRD with an
|
|
4705
4979
|
// explicit `budgetExempt: true` opts out entirely — logged once here so
|
|
4706
4980
|
// an unbounded job is never silently unbounded.
|
|
4707
|
-
const
|
|
4708
|
-
|
|
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);
|
|
4709
4987
|
const budgetExempt = budget.isJobBudgetExempt(job);
|
|
4710
4988
|
if (budgetExempt) {
|
|
4711
4989
|
safeLog(`[scheduler] wall-clock budget watchdog EXEMPT for ${job.slug} ` +
|
|
@@ -4735,7 +5013,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
|
|
|
4735
5013
|
action(ctx) {
|
|
4736
5014
|
const elapsedMs = Date.now() - ctx.startedAt;
|
|
4737
5015
|
ctx.safeLog(`\n[scheduler] wall-clock budget watchdog: ran ${Math.round(elapsedMs / 60_000)}m ` +
|
|
4738
|
-
`(> ${Math.round(jobBudgetMs / 60_000)}m budget, estimateMinutes=${
|
|
5016
|
+
`(> ${Math.round(jobBudgetMs / 60_000)}m budget, estimateMinutes=${budgetEstimate ?? 0}) — SIGTERM process group\n`);
|
|
4739
5017
|
ctx.killedByWatchdog = 'budget';
|
|
4740
5018
|
ctx.killTree('SIGTERM');
|
|
4741
5019
|
const budgetKillTimer = setTimeout(() => {
|
|
@@ -4772,22 +5050,26 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
|
|
|
4772
5050
|
return;
|
|
4773
5051
|
}
|
|
4774
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
|
+
|
|
4775
5057
|
const { child } = withChildAndLog({
|
|
4776
5058
|
fd,
|
|
4777
5059
|
logPath,
|
|
4778
5060
|
safeLog,
|
|
4779
5061
|
closeFd,
|
|
4780
5062
|
spawn: {
|
|
4781
|
-
command:
|
|
5063
|
+
command: launchSpawn.command,
|
|
4782
5064
|
stdinText: prompt,
|
|
4783
5065
|
// Resume mode passes `--resume <sessionId>` (reconnect to the SAME
|
|
4784
5066
|
// session) INSTEAD of `--session-id <sessionId>` (mint a new one) —
|
|
4785
5067
|
// never both, see buildClaudeSpawnArgs.
|
|
4786
|
-
args:
|
|
5068
|
+
args: launchSpawn.args || jobArgs,
|
|
4787
5069
|
options: {
|
|
4788
5070
|
cwd: spawnCwd,
|
|
4789
5071
|
env: childEnv,
|
|
4790
|
-
...(
|
|
5072
|
+
...(launchSpawn.argv0 ? { argv0: launchSpawn.argv0 } : {}),
|
|
4791
5073
|
...(jobSpawn.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
|
|
4792
5074
|
// detached:true puts the child in its own process group so we can kill
|
|
4793
5075
|
// the entire descendant tree (including any stray background bashes the
|
|
@@ -4798,11 +5080,12 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
|
|
|
4798
5080
|
},
|
|
4799
5081
|
},
|
|
4800
5082
|
watchdogs: [resultTailWatchdog, deadmanWatchdog, idleTailWatchdog, budgetWatchdog],
|
|
4801
|
-
onExit({ exitCode, signal, killedByWatchdog, error, spawnFailed,
|
|
5083
|
+
onExit({ exitCode, signal, killedByWatchdog, error, spawnFailed, pid, safeLog: sl }) {
|
|
5084
|
+
const leaked = jobLeftovers.listJobSurvivors(job.slug, pid);
|
|
4802
5085
|
const durationMs = Date.now() - startedAt;
|
|
4803
|
-
|
|
5086
|
+
finalizeJobScope(scopeState, sl);
|
|
4804
5087
|
if (leaked.length > 0) {
|
|
4805
|
-
sl(`\n[scheduler] leaked ${leaked.length} descendant(s)
|
|
5088
|
+
sl(`\n[scheduler] leaked ${leaked.length} descendant(s) left behind after the job exited: ` +
|
|
4806
5089
|
`${leaked.map((p) => `pid=${p.pid} comm=${p.comm} pcpu=${p.pcpu} etimes=${p.etimes}s`).join(', ')}\n`);
|
|
4807
5090
|
}
|
|
4808
5091
|
|
|
@@ -4862,7 +5145,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
|
|
|
4862
5145
|
// resolveBudgetKillOutcome's own header for why this is gated on
|
|
4863
5146
|
// killedBySignal, not on killedByWatchdog alone.
|
|
4864
5147
|
const budgetKillOutcome = budget.resolveBudgetKillOutcome({
|
|
4865
|
-
killedByWatchdog, killedBySignal, durationMs, jobBudgetMs, estimateMinutes:
|
|
5148
|
+
killedByWatchdog, killedBySignal, durationMs, jobBudgetMs, estimateMinutes: budgetEstimate,
|
|
4866
5149
|
});
|
|
4867
5150
|
const { budgetKillReason } = budgetKillOutcome;
|
|
4868
5151
|
const effectiveKilledByWatchdog = budgetKillOutcome.killedByWatchdog;
|
|
@@ -4899,6 +5182,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
|
|
|
4899
5182
|
worktreeDir: execCwd || null, worktreeBranch: execCwd ? `sm-job/${job.slug}` : null,
|
|
4900
5183
|
sessionId, startedAt, budgetMs: budgetExempt ? null : jobBudgetMs, maxDurationMs: null,
|
|
4901
5184
|
idleKillMs: IDLE_OUTPUT_KILL_MS, schedulerPid: process.pid, codeSha: SCHEDULER_CODE_SHA,
|
|
5185
|
+
scopeUnit: scopePlan.unit,
|
|
4902
5186
|
});
|
|
4903
5187
|
} catch (e) {
|
|
4904
5188
|
const message = e?.message ?? String(e);
|
|
@@ -4907,6 +5191,22 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
|
|
|
4907
5191
|
}
|
|
4908
5192
|
// Make this job the OOM killer's preferred victim over Electron.
|
|
4909
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
|
+
}
|
|
4910
5210
|
// Persist runtime.pid with one retry — still fire-and-forget (must
|
|
4911
5211
|
// never block the spawn), but a final failure is now loud instead of
|
|
4912
5212
|
// silently swallowed. A silent failure here is exactly what let the
|
|
@@ -7160,6 +7460,8 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
|
|
|
7160
7460
|
});
|
|
7161
7461
|
}
|
|
7162
7462
|
|
|
7463
|
+
if (needsReviewRcaSnapshot) armSettleAfterValidatorBudgetKill(needsReviewRcaSnapshot);
|
|
7464
|
+
|
|
7163
7465
|
if (needsReviewRcaSnapshot) {
|
|
7164
7466
|
// Fire-and-forget, mirroring the DoD drain hook: never blocks the status
|
|
7165
7467
|
// transition, never throws to this caller.
|
|
@@ -7442,9 +7744,10 @@ function tickWatchdogMs() {
|
|
|
7442
7744
|
return Number.isFinite(n) && n >= 0 ? n : 120_000;
|
|
7443
7745
|
}
|
|
7444
7746
|
|
|
7445
|
-
// `bypassLoadGate` is set
|
|
7446
|
-
//
|
|
7447
|
-
//
|
|
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.
|
|
7448
7751
|
/**
|
|
7449
7752
|
* Fail-CLOSED expiry of runtime reservations (slot tokens, quiet-machine
|
|
7450
7753
|
* lease, investigation set, worktree accounting) whose owner is provably
|
|
@@ -7474,11 +7777,11 @@ function runReservationExpiryPass(jobs, now = Date.now()) {
|
|
|
7474
7777
|
}
|
|
7475
7778
|
}
|
|
7476
7779
|
|
|
7477
|
-
function tickQueue({ bypassLoadGate = false } = {}) {
|
|
7780
|
+
function tickQueue({ bypassLoadGate = false, lastResort = false } = {}) {
|
|
7478
7781
|
const budgetMs = tickWatchdogMs();
|
|
7479
7782
|
const next = tickTail.then(() => {
|
|
7480
7783
|
const gen = tickGeneration;
|
|
7481
|
-
return withTimeout(() => tickBody(gen, { bypassLoadGate }), budgetMs, () => {
|
|
7784
|
+
return withTimeout(() => tickBody(gen, { bypassLoadGate, lastResort }), budgetMs, () => {
|
|
7482
7785
|
tickGeneration++; // fence the abandoned body
|
|
7483
7786
|
console.warn(`[scheduler] TICK WEDGED: tick body exceeded ${budgetMs}ms — resetting tick chain`);
|
|
7484
7787
|
if (!tickWedgeLatched) {
|
|
@@ -7501,8 +7804,11 @@ function tickQueue({ bypassLoadGate = false } = {}) {
|
|
|
7501
7804
|
// The stale sentinel a fenced body returns: never recorded, never acted on.
|
|
7502
7805
|
const STALE_TICK = Object.freeze({ fired: false, reason: 'stale-generation' });
|
|
7503
7806
|
|
|
7504
|
-
async function tickBody(gen, { bypassLoadGate }) {
|
|
7807
|
+
async function tickBody(gen, { bypassLoadGate, lastResort }) {
|
|
7505
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();
|
|
7506
7812
|
{
|
|
7507
7813
|
const stale = () => gen !== tickGeneration;
|
|
7508
7814
|
const state = await readQueue();
|
|
@@ -7517,7 +7823,10 @@ async function tickBody(gen, { bypassLoadGate }) {
|
|
|
7517
7823
|
// even while paused, before any early return below.
|
|
7518
7824
|
await superviseAdoptedRunsPass(state.jobs);
|
|
7519
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.
|
|
7520
7828
|
if (state.paused) {
|
|
7829
|
+
loadGate.endHold();
|
|
7521
7830
|
console.log('[scheduler] tickQueue skipped: paused');
|
|
7522
7831
|
return recordTick({ fired: false, reason: 'paused' }, { detail: 'scheduler paused' });
|
|
7523
7832
|
}
|
|
@@ -7525,6 +7834,7 @@ async function tickBody(gen, { bypassLoadGate }) {
|
|
|
7525
7834
|
// rate-limit pause can't overwrite it. Nothing new dispatches; running and
|
|
7526
7835
|
// investigating rows finish.
|
|
7527
7836
|
if (state.drain?.active) {
|
|
7837
|
+
loadGate.endHold();
|
|
7528
7838
|
return recordTick({ fired: false, reason: 'draining' }, { detail: 'draining for restart' });
|
|
7529
7839
|
}
|
|
7530
7840
|
if (cancelToken.cancelled) return { fired: false, reason: 'cancelled' };
|
|
@@ -7583,13 +7893,22 @@ async function tickBody(gen, { bypassLoadGate }) {
|
|
|
7583
7893
|
if (batch.length === 0 && freeSlots === 0) {
|
|
7584
7894
|
const snap = sessionSlots.snapshot();
|
|
7585
7895
|
const pendingCount = state.jobs.filter((j) => j.status === 'pending').length;
|
|
7586
|
-
|
|
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)`);
|
|
7587
7905
|
return recordTick(
|
|
7588
|
-
{ fired: false, reason:
|
|
7589
|
-
{ detail:
|
|
7906
|
+
{ fired: false, reason: hold.reason, deferredCount: pendingCount, holders: snap.holders },
|
|
7907
|
+
{ detail: hold.detail, holds },
|
|
7590
7908
|
);
|
|
7591
7909
|
}
|
|
7592
7910
|
if (batch.length === 0) {
|
|
7911
|
+
loadGate.endHold();
|
|
7593
7912
|
// Queue drained — run the definition-of-done gate fire-and-forget.
|
|
7594
7913
|
// Non-blocking: does not hold the mutate lock; errors are logged, not thrown.
|
|
7595
7914
|
// resolvePrdPath mirrors every other verify call site in this file (e.g.
|
|
@@ -7619,7 +7938,8 @@ async function tickBody(gen, { bypassLoadGate }) {
|
|
|
7619
7938
|
return recordTick({ fired: false, reason: 'drained' }, { holds });
|
|
7620
7939
|
}
|
|
7621
7940
|
|
|
7622
|
-
const
|
|
7941
|
+
const memInfo = readMemInfo();
|
|
7942
|
+
const availableMb = memInfo.availableMb;
|
|
7623
7943
|
// Reserve a fixed slice for the Electron host before the per-job gate, so a
|
|
7624
7944
|
// job is never started into the host's own headroom (that path OOM-kills
|
|
7625
7945
|
// Electron and SIGHUPs every pty — 2026-06-16 incident).
|
|
@@ -7650,7 +7970,22 @@ async function tickBody(gen, { bypassLoadGate }) {
|
|
|
7650
7970
|
{ detail: `memory gate: ${availableMb} MB free, need ${threshold} MB (consumed=${consumedMb} MB credited)`, holds },
|
|
7651
7971
|
);
|
|
7652
7972
|
}
|
|
7653
|
-
const
|
|
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);
|
|
7654
7989
|
if (gatedBatch.length < batch.length) {
|
|
7655
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)`);
|
|
7656
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() };
|
|
@@ -7665,45 +8000,98 @@ async function tickBody(gen, { bypassLoadGate }) {
|
|
|
7665
8000
|
// pickNextBatch → memory above) has already admitted `gatedBatch`. It
|
|
7666
8001
|
// never touches running jobs and never becomes a second pool: it only
|
|
7667
8002
|
// withholds this tick's launches while the 1-minute loadavg per core is
|
|
7668
|
-
// over LOAD_GATE_PER_CORE
|
|
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 = [];
|
|
7669
8007
|
const load = loadGate.evaluate({ bypass: bypassLoadGate });
|
|
7670
8008
|
if (load.bypassed) {
|
|
7671
|
-
|
|
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' : ''}`);
|
|
7672
8012
|
} else if (load.gated) {
|
|
7673
8013
|
const line = `[scheduler] load gate: loadavg1=${load.loadavg1} cores=${load.cores} ratio=${load.ratio} > ${load.threshold} — holding ${gatedBatch.length} eligible job(s)`;
|
|
7674
|
-
|
|
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
|
-
}
|
|
8014
|
+
console.log(line);
|
|
7680
8015
|
if (load.shouldAudit) {
|
|
7681
8016
|
appendAuditEvent('launch_load_gated', {
|
|
7682
|
-
|
|
7683
|
-
held: gatedBatch.map((j) => j.slug),
|
|
8017
|
+
...loadGateAuditFields(load),
|
|
8018
|
+
held: gatedBatch.map((j) => j.slug),
|
|
7684
8019
|
});
|
|
7685
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
|
+
}
|
|
7686
8035
|
return recordTick(
|
|
7687
8036
|
{ fired: false, reason: 'load-deferred', deferredCount: gatedBatch.length, ratio: load.ratio, threshold: load.threshold },
|
|
7688
8037
|
{ detail: formatLoadGateDetail(load), holds },
|
|
7689
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
|
+
}
|
|
7690
8051
|
}
|
|
7691
8052
|
|
|
7692
|
-
await mutate((s) => {
|
|
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
|
+
});
|
|
7693
8059
|
if (stale()) return STALE_TICK;
|
|
7694
8060
|
await broadcast();
|
|
7695
8061
|
if (stale()) return STALE_TICK;
|
|
7696
8062
|
|
|
7697
8063
|
const { runId, dir: runDir } = pickRunDir();
|
|
7698
|
-
|
|
8064
|
+
let issued = 0;
|
|
8065
|
+
for (const job of launchBatch) {
|
|
7699
8066
|
if (cancelToken.cancelled || stale()) break;
|
|
7700
8067
|
// spawnJob is fire-and-forget; it calls tickQueue() on completion.
|
|
7701
8068
|
// state.jobs is the queue's rows in scope at THIS dispatch (PRD 1408) —
|
|
7702
8069
|
// threaded straight through so spawnJob's hasDownstreamValidator check
|
|
7703
8070
|
// never re-reads the queue itself.
|
|
7704
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
|
+
}
|
|
7705
8093
|
}
|
|
7706
|
-
return recordTick({ fired: true, count:
|
|
8094
|
+
return recordTick({ fired: true, count: launchBatch.length, group: launchBatch[0]?.parallelGroup }, { holds });
|
|
7707
8095
|
}
|
|
7708
8096
|
}
|
|
7709
8097
|
|
|
@@ -7730,6 +8118,8 @@ function forceTickOutcome(result) {
|
|
|
7730
8118
|
return { ok: true, kind: 'warn', message: `Deferred ${result.deferredCount} job(s) — low memory (${result.availableMb} MB available, need ${result.threshold} MB)` };
|
|
7731
8119
|
case 'slots-exhausted':
|
|
7732
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'})` };
|
|
7733
8123
|
case 'held': {
|
|
7734
8124
|
const detail = stripTickDetailPrefix(result.detail);
|
|
7735
8125
|
return { ok: true, kind: 'warn', message: detail || 'Batch held' };
|
|
@@ -7887,14 +8277,14 @@ async function runQueueStarvationWatchdog(state, {
|
|
|
7887
8277
|
// it can't influence, freezing the queue for hours (observed 2026-09-23:
|
|
7888
8278
|
// 3 dispatchable, 0 running, lastTickReason 'load-deferred' unbroken from
|
|
7889
8279
|
// 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
|
|
8280
|
+
// a resource guard; starting ONE batch cannot OOM the host (on a saturated CPU the batch is one job: lastResort). The slot pool
|
|
7891
8281
|
// and memory gate — which DO guard real exhaustion — are unaffected by this
|
|
7892
8282
|
// flag and still bound the batch. The watchdog is the automated equivalent
|
|
7893
8283
|
// of a human Run-now, the other caller that legitimately bypasses load
|
|
7894
8284
|
// (§2/§3, scheduler-operations.md). Latched to one forced tick per
|
|
7895
8285
|
// QUEUE_STARVATION_MS per cwd, so this cannot thrash. Routed via
|
|
7896
8286
|
// 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));
|
|
8287
|
+
await module.exports.tickQueue({ bypassLoadGate: true, lastResort: true }).catch((e) => console.error('[scheduler] starvation tick error', e));
|
|
7898
8288
|
return primary;
|
|
7899
8289
|
}
|
|
7900
8290
|
|
|
@@ -7918,12 +8308,13 @@ const starveEscalated = new Set();
|
|
|
7918
8308
|
* gate. Exported for direct unit testing (attach a fake window via
|
|
7919
8309
|
* attachWindow() first to assert the toast send).
|
|
7920
8310
|
*/
|
|
7921
|
-
function runStarveEscalationSweep(starvedProjects) {
|
|
8311
|
+
function runStarveEscalationSweep(starvedProjects, jobs = [], launchBlocks = {}) {
|
|
7922
8312
|
const { toEscalate, toClear } = starvation.selectStarveEscalations(starvedProjects, starveEscalated, STARVE_ESCALATION_MS);
|
|
7923
8313
|
for (const cwd of toClear) starveEscalated.delete(cwd);
|
|
7924
8314
|
for (const sp of toEscalate) {
|
|
7925
8315
|
starveEscalated.add(sp.cwd);
|
|
7926
|
-
const
|
|
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 });
|
|
7927
8318
|
const mins = Math.round(sp.ageMs / 60_000);
|
|
7928
8319
|
console.error(
|
|
7929
8320
|
`[scheduler] PROJECT STARVE ESCALATED: project=${sp.cwd} pending=${sp.pendingCount} oldest=${sp.oldestPendingSlug} `
|
|
@@ -7934,7 +8325,7 @@ function runStarveEscalationSweep(starvedProjects) {
|
|
|
7934
8325
|
cwd: sp.cwd, pendingCount: sp.pendingCount, oldestPendingSlug: sp.oldestPendingSlug, ageMs: sp.ageMs, holdReason,
|
|
7935
8326
|
});
|
|
7936
8327
|
sendIfAlive(mainWindow, 'schedule:stall', {
|
|
7937
|
-
message: `Project starved: ${sp.cwd} has ${sp.pendingCount} pending PRD(s),
|
|
8328
|
+
message: `Project starved: ${sp.cwd} has ${sp.pendingCount} pending PRD(s), no dispatch for ~${mins}m `
|
|
7938
8329
|
+ `(hold reason: ${holdReason}) — check the Scheduler tab.`,
|
|
7939
8330
|
total: sp.pendingCount,
|
|
7940
8331
|
byProject: { [sp.cwd]: { starved: sp.pendingCount } },
|
|
@@ -7951,6 +8342,47 @@ function runStarveEscalationSweep(starvedProjects) {
|
|
|
7951
8342
|
let queueHealthSweepCycle = 0;
|
|
7952
8343
|
const QUEUE_HEALTH_SWEEP_EVERY_N_CYCLES = 20;
|
|
7953
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
|
+
|
|
7954
8386
|
/**
|
|
7955
8387
|
* runQueueHealthSweep(jobs) — read-only reporting pass over the queue
|
|
7956
8388
|
* snapshot reapDeadRunningJobs already read this cycle. Never transitions a
|
|
@@ -8184,6 +8616,8 @@ async function reapDeadRunningJobs() {
|
|
|
8184
8616
|
await runBranchSweep(state.jobs);
|
|
8185
8617
|
}
|
|
8186
8618
|
|
|
8619
|
+
runJobLeftoverSweep().catch((e) => console.warn('[scheduler] job leftover sweep error', e?.message));
|
|
8620
|
+
|
|
8187
8621
|
if (dead.length === 0) return;
|
|
8188
8622
|
|
|
8189
8623
|
// A rate-limited death is retryable, not terminal — mirror spawnJob's own
|
|
@@ -8347,6 +8781,7 @@ async function reapDeadRunningJobs() {
|
|
|
8347
8781
|
if (resolved) landedCommitEvidence.set(d.slug, row.landedCommit);
|
|
8348
8782
|
}));
|
|
8349
8783
|
|
|
8784
|
+
const budgetKillSettleSnapshots = [];
|
|
8350
8785
|
await mutate(async (s) => {
|
|
8351
8786
|
for (const { slug, pid, outcome, gateOutcome, pidless, reason, noOwnArtifact, failureOverride } of dead) {
|
|
8352
8787
|
const idx = s.jobs.findIndex((x) => x.slug === slug);
|
|
@@ -8484,6 +8919,7 @@ async function reapDeadRunningJobs() {
|
|
|
8484
8919
|
if (confirmedLandedCommit) s.jobs[idx].landedCommit = confirmedLandedCommit;
|
|
8485
8920
|
if (landedCommit) s.jobs[idx].landedCommit = landedCommit;
|
|
8486
8921
|
if (adoptedBudgetKill?.landedCommit) s.jobs[idx].landedCommit = adoptedBudgetKill.landedCommit;
|
|
8922
|
+
if (adoptedBudgetKill) budgetKillSettleSnapshots.push({ ...s.jobs[idx], verifierVerdict: 'budget_exceeded' });
|
|
8487
8923
|
}
|
|
8488
8924
|
// A pidless spawn that never wrote its own '<slug>.log' into the
|
|
8489
8925
|
// batch runId dir it was stamped with must not keep that runId —
|
|
@@ -8533,6 +8969,8 @@ async function reapDeadRunningJobs() {
|
|
|
8533
8969
|
}
|
|
8534
8970
|
});
|
|
8535
8971
|
|
|
8972
|
+
for (const snap of budgetKillSettleSnapshots) armSettleAfterValidatorBudgetKill(snap);
|
|
8973
|
+
|
|
8536
8974
|
await broadcast({ flush: true });
|
|
8537
8975
|
tickQueue().catch(() => {});
|
|
8538
8976
|
} catch (e) {
|
|
@@ -9651,9 +10089,10 @@ async function reverifyNeedsReview() {
|
|
|
9651
10089
|
// already excludes every job this loop dispatches, so a resumable job
|
|
9652
10090
|
// never also gets a fix-plan PRD authored in the same pass.
|
|
9653
10091
|
{
|
|
9654
|
-
|
|
9655
|
-
|
|
9656
|
-
|
|
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) {
|
|
9657
10096
|
console.log(`[scheduler] resume-recovery: needs_review ${job.slug} → resuming session ${target.sessionId}`);
|
|
9658
10097
|
spawnResumeRecovery(job, target).catch((e) => {
|
|
9659
10098
|
console.error('[scheduler] spawnResumeRecovery error', job.slug, e);
|
|
@@ -10256,7 +10695,7 @@ function rescheduleIntervalTick() {
|
|
|
10256
10695
|
// else distinguishes "no pending work" from "pending work, never
|
|
10257
10696
|
// started" — the 2026-09-01 NN-ordering starvation ran 3.5 h unnoticed.
|
|
10258
10697
|
// Escalation only, same shape as the quarantine/overrun warnings above.
|
|
10259
|
-
const starvedProjects = findStarvedProjects(s.jobs, Date.now(), STARVATION_ESCALATE_MS);
|
|
10698
|
+
const starvedProjects = findStarvedProjects(s.jobs, Date.now(), STARVATION_ESCALATE_MS, s.lastDispatchAtByCwd);
|
|
10260
10699
|
for (const sp of starvedProjects) {
|
|
10261
10700
|
console.warn(
|
|
10262
10701
|
`[scheduler] PROJECT STARVED: project=${sp.cwd} pending=${sp.pendingCount} oldest=${sp.oldestPendingSlug} `
|
|
@@ -10271,7 +10710,7 @@ function rescheduleIntervalTick() {
|
|
|
10271
10710
|
// strictly later than STARVATION_ESCALATE_MS, so this only ever fires on
|
|
10272
10711
|
// a subset of the rows already reported above — same verdict, no
|
|
10273
10712
|
// re-derivation.
|
|
10274
|
-
runStarveEscalationSweep(starvedProjects);
|
|
10713
|
+
runStarveEscalationSweep(starvedProjects, s.jobs, s.launchBlocks);
|
|
10275
10714
|
|
|
10276
10715
|
// Bounded failed -> pending auto-reset (PRD 1151), plus the stuck-failed
|
|
10277
10716
|
// escalation now narrowed to only the rows that auto-reset gave up on.
|
|
@@ -11371,6 +11810,12 @@ function registerAdminRoutes(adminHttp, remoteObj = remote) {
|
|
|
11371
11810
|
}
|
|
11372
11811
|
|
|
11373
11812
|
module.exports = {
|
|
11813
|
+
readValidatorGateMs,
|
|
11814
|
+
resolveValidatorEstimate,
|
|
11815
|
+
planJobScope,
|
|
11816
|
+
finalizeJobScope,
|
|
11817
|
+
sampleJobScope,
|
|
11818
|
+
readJobCgroupDir,
|
|
11374
11819
|
normalizeConfig,
|
|
11375
11820
|
recordTick,
|
|
11376
11821
|
reportSchedulerError,
|
|
@@ -11380,6 +11825,7 @@ module.exports = {
|
|
|
11380
11825
|
rescheduleIntervalTick,
|
|
11381
11826
|
runQueueStarvationWatchdog,
|
|
11382
11827
|
runStarveEscalationSweep,
|
|
11828
|
+
runJobLeftoverSweep,
|
|
11383
11829
|
stripAppOwnedChurn,
|
|
11384
11830
|
BUDGET_WARNING_FRACTION,
|
|
11385
11831
|
registerScheduleHandlers,
|
|
@@ -11391,6 +11837,7 @@ module.exports = {
|
|
|
11391
11837
|
computeDegradedBudget,
|
|
11392
11838
|
writeQueue,
|
|
11393
11839
|
_setPeriodicReverifyEnabledForTests,
|
|
11840
|
+
_setLoadGateForTests,
|
|
11394
11841
|
_mutateForTests: mutate, // mutate() has no other exported call site; test-only seam.
|
|
11395
11842
|
reconcile,
|
|
11396
11843
|
broadcast,
|
|
@@ -11412,6 +11859,12 @@ module.exports = {
|
|
|
11412
11859
|
pollRecoveryClearSource,
|
|
11413
11860
|
memoryLimitedBatchSize,
|
|
11414
11861
|
availableForJobs,
|
|
11862
|
+
parseMemInfo,
|
|
11863
|
+
readMemInfo,
|
|
11864
|
+
getAvailableMemMb,
|
|
11865
|
+
swapLimitedBatchSize,
|
|
11866
|
+
biasJobOomScore,
|
|
11867
|
+
OOM_SCORE_ADJ_JOB,
|
|
11415
11868
|
reverifyNeedsReview,
|
|
11416
11869
|
runGateShadow,
|
|
11417
11870
|
awaitGateShadowIdle: async () => { while (gateShadowPending) await gateShadowPending; },
|
|
@@ -11454,6 +11907,7 @@ module.exports = {
|
|
|
11454
11907
|
notifyOriginatingTab,
|
|
11455
11908
|
flushDueReviewNotices,
|
|
11456
11909
|
isNotifiableTerminalStatus,
|
|
11910
|
+
armSettleAfterValidatorBudgetKill,
|
|
11457
11911
|
extractResultTextFromLog,
|
|
11458
11912
|
resolveVerifyPrdPath,
|
|
11459
11913
|
resolveFixPlanPath,
|