Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: share one on-demand drain loop so #3294's registry guard covers both engines (#6618)

[._.]/ Adam Eivy056f18826826
diff --git a/server/services/cos.js b/server/services/cos.js
index 92a105119d..009644cfbb 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -22,15 +22,16 @@ import { getActiveProvider } from './providers.js';
import { isInternalTaskId } from '../lib/taskParser.js';
import { isAutoApprovableInvestigation } from '../lib/investigationTasks.js';
import { isRetryHeld, isStaleRetryHold } from '../lib/taskRetryHold.js';
-import { isAppOnCooldown, markAppReviewCooldown, bindAppReviewAgent, clearStaleActiveAgents } from './appActivity.js';
-import { getActiveApps } from './apps.js';
+import { isAppOnCooldown, clearStaleActiveAgents } from './appActivity.js';
+// The single Priority-0 on-demand loop body, shared with the evaluateTasks
+// engine in cosTaskGenerator.js so the two can no longer drift (#6618).
+import { drainOnDemandRequests } from './onDemandDrain.js';
import { logCosScheduleUpdate } from './userActionScheduleLog.js';
import { getPerformanceSummary, checkAndRehabilitateSkippedTasks, getLearningInsights } from './taskLearning.js';
import { schedule as scheduleEvent, cancel as cancelEvent } from './eventScheduler.js';
import { generateProactiveTasks as generateMissionTasks } from './missions.js';
import { recordJobExecution } from './autonomousJobs.js';
import { safeJSONParse, sleep, isTopLevelEntryName } from '../lib/fileUtils.js';
-import { onDemandRequestMetadata } from '../lib/quotaBurnOrigin.js';
import { ON_DEMAND_ORIGINS } from './taskScheduleConstants.js';
import { ServerError } from '../lib/errorHandler.js';
import { addNotification, NOTIFICATION_TYPES } from './notifications.js';
@@ -132,12 +133,7 @@ import {
evaluateTasks,
generateIdleReviewTask,
queueEligibleImprovementTasks,
- generateSelfImprovementTaskForType,
- generateManagedAppImprovementTaskForType,
recordDeferredPerpetualDispatch,
- applyOnDemandConsent,
- drainProgrammaticOnDemandRequests,
- emitOnDemandEmpty,
blockIfExceedsMaxSpawns,
selectDryRunAutoApproved,
isCooldownExemptTask,
@@ -1000,148 +996,24 @@ async function tryImmediateSpawn(task) {
async function spawnDequeuePriority0OnDemand(ctx) {
const { state, capacity, ignoreTaskId } = ctx;
- const taskScheduleMod = await import('./taskSchedule.js');
- const taskSchedule = await taskScheduleMod.loadSchedule();
- const onDemandRequests = await taskScheduleMod.getOnDemandRequests();
- // Stash the loaded schedule for Priority 2's disabled-analysis-type gate
- // (avoids a second load).
- ctx.taskSchedule = taskSchedule;
-
- // Programmatic handlers first, and outside the slot-bounded loop below: they
- // spawn nothing, so a full spawn budget must not hold a user's Run Now.
- const handledProgrammatically = await drainProgrammaticOnDemandRequests({
- taskScheduleMod, requests: onDemandRequests, schedule: taskSchedule, state
+ const { schedule } = await drainOnDemandRequests({ state }, {
+ capacityExhausted: () => capacity.spawned >= capacity.availableSlots,
+ // Priority 0 is a COMMITTED tier — the request is cleared and the app-review
+ // marker bound before this runs, and nothing persists the task on a denial,
+ // so it opts out of the local-endpoint cap (#4834).
+ canSpawn: (task) => capacity.canSpawnCommitted(task),
+ emitSpawn: (task) => {
+ cosEvents.emit('task:ready', task);
+ capacity.trackSpawn(task);
+ },
+ // Forward `ignoreTaskId` so a completion-triggered re-issue is dedup-safe
+ // against the still-in_progress task that triggered it.
+ addTaskOptions: { ignoreTaskId },
});
- // Track apps already marked review-started this cycle so multiple on-demand
- // requests for the same app don't each rewrite its activity record.
- const reviewStartedApps = new Set();
- for (const request of onDemandRequests) {
- // Already handled above (and its request cleared) — `onDemandRequests` is a
- // snapshot taken before that drain.
- if (handledProgrammatically.has(request.id)) continue;
- if (capacity.spawned >= capacity.availableSlots) break;
-
- if (!isImprovementEnabled(state)) {
- emitLog('warn', `On-demand request dropped — improvement is disabled (Config → Improve)`, { requestId: request.id, taskType: request.taskType });
- await taskScheduleMod.clearOnDemandRequest(request.id);
- continue;
- }
-
- // Skip if the task type was disabled after queuing
- if (!taskSchedule.tasks[request.taskType]?.enabled) {
- emitLog('info', `On-demand request skipped — task type '${request.taskType}' is disabled`, { requestId: request.id });
- await taskScheduleMod.clearOnDemandRequest(request.id);
- continue;
- }
-
- let task = null;
- const apps = await getActiveApps().catch(() => []);
- let targetApp = null;
-
- if (request.appId) {
- targetApp = apps.find(a => a.id === request.appId);
- if (!targetApp) {
- emitLog('warn', `On-demand request for unknown app: ${request.appId}`, { requestId: request.id });
- await taskScheduleMod.clearOnDemandRequest(request.id);
- continue;
- }
- }
-
- await taskScheduleMod.clearOnDemandRequest(request.id);
-
- // A HUMAN "Run" re-checks live state (park + convergence signature + dispatch
- // budget all cleared); an automated refill re-issue inherits them, or the drain
- // has no brakes left. The origin check lives inside applyOnDemandRunResets so
- // this engine and its two siblings can't drift on it.
- const userInitiated = await taskScheduleMod.applyOnDemandRunResets(request, targetApp?.id ?? null);
- const lane = userInitiated ? '' : ' (drain refill)';
-
- if (targetApp) {
- emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}${lane}`, { requestId: request.id, appId: targetApp.id });
- // Advance the cooldown eagerly (deduped per app per cycle), but defer
- // binding the active agent until a task is produced — a null result
- // here must not strand `activeAgentId` (issue #978).
- if (!reviewStartedApps.has(targetApp.id)) {
- await markAppReviewCooldown(targetApp.id);
- reviewStartedApps.add(targetApp.id);
- }
- await taskScheduleMod.recordExecution(`task:${request.taskType}`, targetApp.id);
- task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, {
- skipPreconditions: true,
- deferPerpetualDispatch: true,
- targetPullRequest: request.targetPullRequest ?? null,
- providerOverride: request.providerOverride ?? null,
- // Mirrors the sibling engine in cosTaskGenerator.js#spawnPriority0OnDemand
- // — either may drain any given request, so a quota-burn step's run
- // parameters have to reach the generator from both or the mode a
- // migrated issues-only step pinned depends on which engine got there
- // first.
- runOverrides: request.burn?.overrides?.params ?? null
- });
- if (task) {
- await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);
- }
- } else {
- emitLog('info', `Processing on-demand improvement: ${request.taskType}${lane}`, { requestId: request.id });
- await taskScheduleMod.recordExecution(`task:${request.taskType}`);
- await withStateLock(async () => {
- const s = await loadState();
- s.stats.lastSelfImprovement = new Date().toISOString();
- s.stats.lastSelfImprovementType = request.taskType;
- await saveState(s);
- });
- task = await generateSelfImprovementTaskForType(request.taskType, state);
- }
-
- applyOnDemandConsent(task);
- // Committed tier — the request is already cleared and the marker bound, and
- // this branch is the only thing that persists the task, so a denial would
- // discard the user's "Run". See canSpawnCommitted (#4834).
- if (task && capacity.canSpawnCommitted(task)) {
- // Mark this as a MANUAL (on-demand) run so a completed perpetual drain
- // continues in the same user-initiated lane instead of the auto-run-gated
- // queue path (see perpetualRefillPlan). Stamped before addTask so the
- // blocked-revive branch below inherits it via `task.metadata` too.
- // `onDemandRequestMetadata` also carries the request's ORIGIN, which
- // `perpetualRefillPlan` reads to decide whether the completed run may
- // continue its drain — and a quota burn's provenance when it is one.
- task.metadata = { ...(task.metadata || {}), ...onDemandRequestMetadata(request) };
- // Forward `ignoreTaskId` so a completion-triggered re-issue is dedup-safe:
- // the perpetual drain regenerates an identical first-line for the same app,
- // and `agent:completed` fires before the completing task's updateTask
- // settles it to `completed` — so without excluding it the re-issued claim is
- // rejected as a duplicate of the run that just finished and the drain stalls.
- const persisted = await addTask(task, 'internal', { raw: true, ignoreTaskId, suppressDequeue: true });
- if (!persisted?.duplicate) {
- await recordDeferredPerpetualDispatch(task, taskScheduleMod);
- cosEvents.emit('task:ready', task);
- capacity.trackSpawn(task);
- } else if (persisted.status === 'blocked') {
- // Explicit user Run colliding with a failure-blocked twin (#2614): the
- // retry path is reviving the existing task, not minting a duplicate —
- // and without this branch the Run is a silent no-op that strands the
- // bound on-demand review marker.
- await reviveBlockedTask(persisted.id, { priority: task.priority, metadata: task.metadata }, 'internal', { suppressDequeue: true });
- await recordDeferredPerpetualDispatch(task, taskScheduleMod);
- const revived = { ...task, id: persisted.id };
- cosEvents.emit('task:ready', revived);
- capacity.trackSpawn(revived);
- emitLog('info', `🔁 On-demand ${request.taskType} revived blocked task ${persisted.id}`, { taskId: persisted.id });
- }
- } else if (!task && userInitiated) {
- // Explicit user "Run" produced no task — surface WHY (parked / transient /
- // idle) so the trigger isn't a silent no-op. Shared with the sibling
- // spawnPriority0OnDemand engine so a request drained by either path gets
- // the same feedback. Because we reset the park BEFORE the fresh detection
- // above, the outcome classification reflects THIS check.
- //
- // `userInitiated` only: a drain refill ends by converging (that's the point),
- // and nobody is waiting on it, so toasting "nothing to do" for every automated
- // hop would turn a healthy overnight drain into a pile of notifications.
- await emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig: taskSchedule.tasks[request.taskType] });
- }
- }
+ // Stash the loaded schedule for Priority 2's disabled-analysis-type gate
+ // (avoids a second load).
+ ctx.taskSchedule = schedule;
}
/**
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 12ce76eb5b..852204f7c9 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -1636,55 +1636,23 @@ describe('cos.js source — priority + capacity invariants', () => {
.toMatch(/if\s*\(\s*canQueueImprovementTasks\(\s*state\s*\)\s*\)/);
});
- it('both on-demand loops dedupe the cooldown stamp per app via reviewStartedApps set', () => {
- // Multiple on-demand requests targeting the same app should advance its
- // cooldown only once per cycle — without the guard, each request rewrites
- // the same record. BOTH on-demand loops carry the duplication: the
- // startup/manual `evaluateTasks` loop AND the event-driven `dequeueNextTask`
- // loop (the common "Run Now" path). Pin (a) the set is declared and (b) the
- // cooldown stamp is gated on it in each.
- // Both engines' Priority-0 on-demand loops are now extracted helpers:
- // `spawnPriority0OnDemand` in cosTaskGenerator.js (issue #1082) and
- // `spawnDequeuePriority0OnDemand` in cos.js (issue #2530).
- for (const { fnName, src } of [
- { fnName: 'async function spawnPriority0OnDemand', src: GEN_SRC },
- { fnName: 'async function spawnDequeuePriority0OnDemand', src: COS_SRC },
+ it('the on-demand marker discipline lives in the shared drain, not in either engine', () => {
+ // Per-app cooldown dedupe (one markAppReviewCooldown per cycle however many
+ // requests name the app) and the #978 deferred bind (bindAppReviewAgent only
+ // once a task exists) used to be duplicated in both Priority-0 engines and
+ // guarded by grepping each body. Both are pinned behaviorally in
+ // onDemandDrain.test.js now; what matters here is that neither engine has
+ // grown its own copy back.
+ for (const [engine, src] of [
+ ['spawnPriority0OnDemand', GEN_SRC],
+ ['spawnDequeuePriority0OnDemand', COS_SRC],
]) {
- const fnBody = extractFnBody(src, src.indexOf(fnName));
- expect(
- fnBody,
- `${fnName} must declare a reviewStartedApps set to dedupe per-app marks`
- ).toMatch(/const\s+reviewStartedApps\s*=\s*new\s+Set\(/);
- expect(
- fnBody,
- `${fnName} must gate markAppReviewCooldown on !reviewStartedApps.has(targetApp.id)`
- ).toMatch(/if\s*\(\s*!\s*reviewStartedApps\.has\(\s*targetApp\.id\s*\)\s*\)/);
- }
- });
-
- it('on-demand loops defer bindAppReviewAgent until a task is produced (issue #978)', () => {
- // The phantom-active-agent bug: binding activeAgentId before the per-app
- // task generator runs strands the marker when the generator returns null.
- // Pin that both on-demand loops (a) advance the cooldown with
- // markAppReviewCooldown, NOT markAppReviewStarted, and (b) only bind the
- // active agent inside an `if (task)` guard after generation.
- for (const { fnName, src } of [
- { fnName: 'async function spawnPriority0OnDemand', src: GEN_SRC },
- { fnName: 'async function spawnDequeuePriority0OnDemand', src: COS_SRC },
- ]) {
- const fnBody = extractFnBody(src, src.indexOf(fnName));
- expect(
- fnBody,
- `${fnName} must advance cooldown via markAppReviewCooldown (not the conflated markAppReviewStarted)`
- ).toMatch(/markAppReviewCooldown\(\s*targetApp\.id\s*\)/);
- expect(
- fnBody,
- `${fnName} must NOT call markAppReviewStarted (conflates cooldown + bind, the #978 bug)`
- ).not.toMatch(/markAppReviewStarted\(/);
- expect(
- fnBody,
- `${fnName} must bind the active agent only after a task exists`
- ).toMatch(/if\s*\(\s*task\s*\)\s*\{\s*await\s+bindAppReviewAgent\(\s*targetApp\.id/);
+ const fnBody = extractFnBody(src, src.indexOf(`async function ${engine}`));
+ expect(fnBody, `${engine} must delegate to the shared drain`).toContain('drainOnDemandRequests(');
+ for (const marker of ['reviewStartedApps', 'markAppReviewCooldown', 'bindAppReviewAgent']) {
+ expect(fnBody, `${engine} must not re-implement ${marker} — it belongs to onDemandDrain.js`)
+ .not.toContain(marker);
+ }
}
});
@@ -2388,19 +2356,18 @@ describe('cos.js source — agent:completed triggers perpetual refill', () => {
expect(returnAfterTrigger).toBeLessThan(queueIdx);
});
- it('the on-demand spawn engine forwards ignoreTaskId to addTask', () => {
+ it('the dequeue on-demand engine hands its ignoreTaskId to the shared drain', () => {
// The completion-triggered re-issue must be dedup-safe against the
- // still-in_progress completing task, so the engine's addTask must forward
- // the dequeue's ignoreTaskId.
+ // still-in_progress completing task, so the dequeue engine forwards its
+ // ignoreTaskId into the addTask options the shared drain applies. That
+ // forwarding is one of the three real differences between the engines, and
+ // both sides of it are pinned behaviorally in onDemandDrain.test.js.
const engIdx = COS_SRC.indexOf('async function spawnDequeuePriority0OnDemand');
expect(engIdx, 'spawnDequeuePriority0OnDemand must exist').toBeGreaterThan(-1);
- const engSlice = COS_SRC.slice(engIdx, engIdx + 6400);
- // The metadata merge itself is pinned once, in cosTaskGenerator.test.js —
- // that guard greps the full statement against BOTH engine sources, so
- // repeating a weaker subset here would only ever fail alongside it.
+ const engBody = extractFnBody(COS_SRC, engIdx);
expect(
- /addTask\(\s*task\s*,\s*'internal'\s*,\s*\{[\s\S]*?raw:\s*true[\s\S]*?ignoreTaskId[\s\S]*?\}\s*\)/.test(engSlice),
- 'on-demand engine must forward ignoreTaskId to addTask'
+ /addTaskOptions:\s*\{\s*ignoreTaskId\s*\}/.test(engBody),
+ 'the dequeue engine must pass ignoreTaskId through addTaskOptions'
).toBe(true);
});
diff --git a/server/services/cosTaskGenerator.auditMode.test.js b/server/services/cosTaskGenerator.auditMode.test.js
index be655773cb..fc46cf067d 100644
--- a/server/services/cosTaskGenerator.auditMode.test.js
+++ b/server/services/cosTaskGenerator.auditMode.test.js
@@ -324,18 +324,15 @@ describe('mode is honored identically from schedule, manual run, and quota burn'
expect(task.metadata.notARealFlag).toBeUndefined();
});
- // Both on-demand engines may drain any given request (see
- // `onDemandRequestMetadata`), so a burn's run parameters have to be forwarded
- // from BOTH or the mode a migrated step pinned would depend on which engine
- // got there first. Asserted at the source because the two engines are a
- // deliberate mirror and only their agreement is the invariant.
- it('both on-demand engines forward the burn step run parameters', async () => {
+ // Either Priority-0 engine may drain any given request, so a burn step's run
+ // parameters must reach the generator whichever one got there first. They do
+ // by construction now — both engines delegate to the one shared drain — so
+ // this asserts the forwarding survives in that single owner.
+ it('the shared on-demand drain forwards the burn step run parameters', async () => {
const { readFile } = await import('fs/promises');
const { PATHS } = await import('../lib/fileUtils.js');
- for (const file of ['server/services/cosTaskGenerator.js', 'server/services/cos.js']) {
- const source = await readFile(`${PATHS.root}/${file}`, 'utf8');
- expect(source, file).toContain('runOverrides: request.burn?.overrides?.params ?? null');
- }
+ const source = await readFile(`${PATHS.root}/server/services/onDemandDrain.js`, 'utf8');
+ expect(source).toContain('runOverrides: request.burn?.overrides?.params ?? null');
});
});
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index cceb6356e3..a2e912f6c6 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -30,7 +30,7 @@ import { join } from 'path';
import { sanitizeTaskMetadata, PIPELINE_STAGE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, resolveClaimReviewerConfig, reviewerConfigMetadata, hasReviewerOverride } from '../lib/validation.js';
import { PATHS } from '../lib/fileUtils.js';
import { isPlainObject } from '../lib/objects.js';
-import { hasQuotaBurnProvenance, onDemandRequestMetadata } from '../lib/quotaBurnOrigin.js';
+import { hasQuotaBurnProvenance } from '../lib/quotaBurnOrigin.js';
import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, diagnoseUnpickablePlan } from '../lib/planIds.js';
import { loadState, saveState, withStateLock, isImprovementEnabled, isDaemonRunning } from './cosState.js';
import { getDomainMode } from '../lib/domainAutonomy.js';
@@ -38,11 +38,14 @@ import { remainingActionBudget } from '../lib/domainBudgets.js';
import { getDomainBudgetStatus } from './domainUsage.js';
import { pendingCosActionReservations } from './cosAdmissionReservations.js';
import { cosEvents, emitLog } from './cosEvents.js';
-import { addTask, updateTask, reviveBlockedTask, getAllTasks, getCosTasks, firstLine } from './cosTaskStore.js';
+import { addTask, updateTask, getAllTasks, getCosTasks, firstLine } from './cosTaskStore.js';
import { PRIORITY_VALUES } from '../lib/taskParser.js';
import { recordDecision, DECISION_TYPES } from './decisionLog.js';
import { isAppOnCooldown, markAppReviewCooldown, bindAppReviewAgent, markIdleReviewStarted, getNextAppForReview, loadAppActivity, isAppActivityOnCooldown } from './appActivity.js';
import { getActiveApps, getAppTaskTypeOverrides } from './apps.js';
+// The single Priority-0 on-demand loop body, shared with the dequeueNextTask
+// engine in cos.js so the two can no longer drift (#6618).
+import { drainOnDemandRequests } from './onDemandDrain.js';
import { resolveAgentProviderPin } from './appTaskProviderPin.js';
import { getTaskTypeConfidence } from './taskLearning.js';
import { classifySafetyKind, requiresSafetyApproval } from './taskLearning/safetyKind.js';
@@ -767,146 +770,14 @@ async function resolveAutonomyBudget(state, runningAgentEntries) {
async function spawnPriority0OnDemand(ctx) {
const { state, availableSlots, tasksToSpawn, canSpawnTask, trackSpawn } = ctx;
- const taskSchedule = await import('./taskSchedule.js');
- const liveSchedule = await taskSchedule.loadSchedule();
- const onDemandRequests = await taskSchedule.getOnDemandRequests();
-
- // Track apps already marked review-started this cycle so multiple on-demand
- // requests for the same app don't each rewrite its activity record.
- const reviewStartedApps = new Set();
- // The app registry can't change mid-loop, so read it once per cycle rather
- // than once per request (getActiveApps' 2s cache can miss at a boundary).
- // `null` means the read FAILED, which is not the same as "no active apps":
- // an empty list would make every app-targeted request below look like it
- // names an unknown app and get cleared, silently dropping user-initiated
- // work. On a failure we leave the requests queued for the next cycle.
- const apps = onDemandRequests.length > 0 ? await getActiveApps().catch(() => null) : [];
-
- // Programmatic handlers first, and outside the slot-bounded loop below: they
- // spawn nothing, so a busy autonomy budget must not hold a user's Run Now.
- const handledProgrammatically = await drainProgrammaticOnDemandRequests({
- taskScheduleMod: taskSchedule, requests: onDemandRequests, schedule: liveSchedule, state
+ await drainOnDemandRequests({ state }, {
+ capacityExhausted: () => tasksToSpawn.length >= availableSlots,
+ canSpawn: (task) => canSpawnTask(task),
+ emitSpawn: (task) => {
+ tasksToSpawn.push(task);
+ trackSpawn(task);
+ },
});
-
- if (!apps) {
- emitLog('warn', `On-demand requests deferred — the app registry could not be read this cycle`);
- } else if (onDemandRequests.length > 0 && tasksToSpawn.length < availableSlots) {
- for (const request of onDemandRequests) {
- // Already handled above (and its request cleared) — `onDemandRequests` is
- // a snapshot taken before that drain.
- if (handledProgrammatically.has(request.id)) continue;
- if (tasksToSpawn.length >= availableSlots) break;
-
- if (!isImprovementEnabled(state)) {
- emitLog('warn', `On-demand request dropped — improvement is disabled (Config → Improve)`, { requestId: request.id, taskType: request.taskType });
- await taskSchedule.clearOnDemandRequest(request.id);
- continue;
- }
-
- // Skip if the task type was disabled or removed after queuing — parity with dequeueNextTask.
- if (!liveSchedule.tasks[request.taskType]?.enabled) {
- emitLog('info', `On-demand request skipped — task type '${request.taskType}' is disabled`, { requestId: request.id });
- await taskSchedule.clearOnDemandRequest(request.id);
- continue;
- }
-
- let task = null;
- // Determine target app (if any)
- let targetApp = null;
-
- if (request.appId) {
- targetApp = apps.find(a => a.id === request.appId);
- if (!targetApp) {
- emitLog('warn', `On-demand request for unknown app: ${request.appId}`, { requestId: request.id });
- await taskSchedule.clearOnDemandRequest(request.id);
- continue;
- }
- }
-
- await taskSchedule.clearOnDemandRequest(request.id);
-
- // Only a human "Run" may clear the drain's brakes; an automated refill
- // (origin: 'refill') inherits them. The policy — and the origin check — lives
- // in applyOnDemandRunResets so this engine and its siblings can't drift.
- const userInitiated = await taskSchedule.applyOnDemandRunResets(request, targetApp?.id ?? null);
- const lane = userInitiated ? '' : ' (drain refill)';
-
- if (targetApp) {
- emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}${lane}`, { requestId: request.id, appId: targetApp.id });
- // Advance the cooldown eagerly (deduped per app per cycle), but defer
- // binding the active agent until a task is produced — a null result
- // here must not strand `activeAgentId` (issue #978).
- if (!reviewStartedApps.has(targetApp.id)) {
- await markAppReviewCooldown(targetApp.id);
- reviewStartedApps.add(targetApp.id);
- }
- await taskSchedule.recordExecution(`task:${request.taskType}`, targetApp.id);
- task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, {
- skipPreconditions: true,
- deferPerpetualDispatch: true,
- targetPullRequest: request.targetPullRequest ?? null,
- providerOverride: request.providerOverride ?? null,
- // A quota-burn step's per-invocation run parameters. They must reach
- // the PROMPT, so unlike the provider/model/effort pins they cannot
- // ride the post-generation `onDemandRequestMetadata` stamp below —
- // the generator overlays them before it picks the mode banner.
- // `normalizeQuotaBurnProvenance` (lib/quotaBurnOrigin.js) has to keep
- // `overrides.params` for a step to reach this; it drops them today,
- // so a burn currently runs the task's SAVED mode, which is correct
- // for every step until the migration starts pinning one.
- runOverrides: request.burn?.overrides?.params ?? null
- });
- if (task) {
- await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);
- }
- } else {
- emitLog('info', `Processing on-demand improvement: ${request.taskType}${lane}`, { requestId: request.id });
- await taskSchedule.recordExecution(`task:${request.taskType}`);
- await withStateLock(async () => {
- const s = await loadState();
- s.stats.lastSelfImprovement = new Date().toISOString();
- s.stats.lastSelfImprovementType = request.taskType;
- await saveState(s);
- });
- task = await generateSelfImprovementTaskForType(request.taskType, state);
- }
-
- applyOnDemandConsent(task);
- if (task && canSpawnTask(task)) {
- // Mark this a MANUAL (on-demand) run so its perpetual drain continues in
- // the on-demand lane (see perpetualRefillPlan in cos.js). BOTH on-demand
- // engines must stamp it — either may drain a given request. Stamped before
- // addTask so the blocked-revive branch inherits it via `task.metadata`.
- // `onDemandRequestMetadata` also carries the request's ORIGIN, which
- // `perpetualRefillPlan` reads to decide whether the completed run may
- // continue its drain — and a quota burn's provenance when it is one.
- task.metadata = { ...(task.metadata || {}), ...onDemandRequestMetadata(request) };
- const persisted = await addTask(task, 'internal', { raw: true, suppressDequeue: true });
- if (!persisted?.duplicate) {
- await recordDeferredPerpetualDispatch(task, taskSchedule);
- tasksToSpawn.push(task);
- trackSpawn(task);
- } else if (persisted.status === 'blocked') {
- // Explicit user Run colliding with a failure-blocked twin (#2614):
- // revive the existing task instead of silently dropping the Run and
- // stranding the bound on-demand review marker. Mirrors the sibling
- // dequeueNextTask on-demand engine in cos.js.
- await reviveBlockedTask(persisted.id, { priority: task.priority, metadata: task.metadata }, 'internal', { suppressDequeue: true });
- await recordDeferredPerpetualDispatch(task, taskSchedule);
- const revived = { ...task, id: persisted.id };
- tasksToSpawn.push(revived);
- trackSpawn(revived);
- emitLog('info', `🔁 On-demand ${request.taskType} revived blocked task ${persisted.id}`, { taskId: persisted.id });
- }
- } else if (!task && userInitiated) {
- // Explicit user Run produced no task on THIS engine too — same feedback
- // as cos.dequeueNextTask so a request drained here isn't a silent no-op.
- // An automated refill is skipped for the same reason it is there: it ends
- // by converging, and nobody is waiting on the toast.
- await emitOnDemandEmpty({ taskScheduleMod: taskSchedule, request, targetApp, taskConfig: liveSchedule.tasks[request.taskType] });
- }
- }
- }
}
/**
@@ -2084,7 +1955,7 @@ async function generateManagedAppImprovementTask(app, state, { ignoreTaskId = nu
await taskSchedule.clearOnDemandRequest(request.id);
// Only a human "Run" may clear the drain's brakes (park state, dispatch
// count); the policy lives in applyOnDemandRunResets so this idle-review
- // path can't drift from its spawnPriority0OnDemand siblings — without it,
+ // path can't drift from the shared on-demand drain — without it,
// a currently drain-capped or parked perpetual type dequeued here stays
// capped/parked and the explicit "Run" silently produces no task.
await taskSchedule.applyOnDemandRunResets(request, app.id);
@@ -2285,9 +2156,9 @@ export async function drainProgrammaticOnDemandRequests({ taskScheduleMod, reque
* - 'idle' → a non-perpetual task produced no task: a genuine "nothing to
* do", NOT a failure (e.g. pr-watcher with no new PRs).
*
- * Called from BOTH on-demand drain engines (cos.dequeueNextTask and
- * spawnPriority0OnDemand below) so a user Run gets feedback no matter which one
- * drains the request. `taskConfig` is the already-loaded interval for the task,
+ * Called from the shared on-demand drain (onDemandDrain.js), which both
+ * Priority-0 engines delegate to, so a user Run gets the same feedback no matter
+ * which one drains the request. `taskConfig` is the already-loaded interval for the task,
* passed in to avoid re-reading the schedule. The event fires ONLY on the
* user-initiated on-demand path, so the client can toast it without
* background-park noise.
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 8ecc5faf5a..0cafdee21d 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -107,6 +107,8 @@ const PRESTEP_SRC = readFileSync(join(__dirname, 'cosTaskPreStepBlocks.js'), 'ut
// both, so moving code between them can neither break it nor silently disarm it.
const LAYER_SRC = `${GEN_SRC}\n${PRESTEP_SRC}`;
const COS_SRC = readFileSync(join(__dirname, 'cos.js'), 'utf-8');
+// The ONE Priority-0 on-demand loop body both engines delegate to (#6618).
+const DRAIN_SRC = readFileSync(join(__dirname, 'onDemandDrain.js'), 'utf-8');
const task = (id, metadata = {}) => ({ id, metadata });
const noCooldown = () => Promise.resolve(false);
@@ -250,34 +252,44 @@ describe('dry-run hook wiring matches each engine execute path', () => {
});
});
-// Both on-demand spawn engines must merge the request's own metadata onto the
-// generated task through `onDemandRequestMetadata`, or a MANUAL "Run Now"
-// perpetual drain processed by whichever engine forgot would refill through the
-// auto-run-gated queue lane and stall after one item (see perpetualRefillPlan in
-// cos.js) — and a QUOTA BURN would arrive with no provenance, reading as an
-// ordinary manual run that then drains its whole backlog outside the burn gates.
-// The cos.js engine's stamp + ignoreTaskId forwarding is pinned in cos.test.js;
-// this pins the sibling evaluateTasks engine here so the mirror can't drift.
+// The two Priority-0 on-demand engines used to be hand-mirrored line for line,
+// and every guard on their parity was a source grep against each engine body —
+// which is exactly why #3294's registry-failure fix could land on ONE of them
+// and stay green (#6618). The loop lives in onDemandDrain.js now and both
+// engines are thin adapters over it, so the parity is structural: the behavior
+// is pinned once, behaviorally, in onDemandDrain.test.js.
//
-// It greps for the shared CALL rather than the fork itself: the fork lives in
-// one place now (lib/quotaBurnOrigin.js, unit-tested directly), and the only
-// thing an engine can still get wrong is failing to consult it.
-describe('both on-demand engines merge onDemandRequestMetadata', () => {
- const onDemandStamp = (src, engineFn) => {
- const start = src.indexOf(engineFn);
- expect(start, `${engineFn} must exist`).toBeGreaterThan(-1);
- // Scan to the next top-level function so the assertion is scoped to this engine.
- const next = src.indexOf('\nasync function ', start + 1);
- return src.slice(start, next === -1 ? src.length : next);
- };
- const MERGE = /task\.metadata = \{ \.\.\.\(task\.metadata \|\| \{\}\), \.\.\.onDemandRequestMetadata\(request\) \}/;
-
- it('evaluateTasks engine (spawnPriority0OnDemand) merges the request metadata before addTask', () => {
- expect(MERGE.test(onDemandStamp(GEN_SRC, 'async function spawnPriority0OnDemand'))).toBe(true);
- });
+// What still needs a source guard is the DELEGATION itself — a future edit that
+// re-inlines a loop into either engine is the regression, and no behavioral test
+// of the shared module can see it.
+describe('both on-demand engines delegate to the shared drain', () => {
+ for (const [engine, src] of [
+ ['cosTaskGenerator.spawnPriority0OnDemand', () => GEN_SRC],
+ ['cos.spawnDequeuePriority0OnDemand', () => COS_SRC],
+ ]) {
+ it(`${engine} calls drainOnDemandRequests and owns no request loop of its own`, () => {
+ const text = src();
+ expect(text).toMatch(/import \{ drainOnDemandRequests \} from '\.\/onDemandDrain\.js'/);
+ expect(text).toContain('drainOnDemandRequests({ state }, {');
+ expect(
+ text,
+ `${engine} must not re-inline the on-demand loop — it belongs to onDemandDrain.js`
+ ).not.toMatch(/for \(const request of onDemandRequests\)/);
+ });
+ }
- it('dequeueNextTask engine (spawnDequeuePriority0OnDemand) merges the request metadata before addTask', () => {
- expect(MERGE.test(onDemandStamp(COS_SRC, 'async function spawnDequeuePriority0OnDemand'))).toBe(true);
+ it('the shared drain reads the app registry once per cycle with the failure sentinel', () => {
+ // #3294's fix, now in the one place both engines run. `null` = the read
+ // FAILED (defer); `[]` = a real empty registry (clear as unknown-app). The
+ // read sits OUTSIDE the loop, so a 3-request cycle can't miss getActiveApps'
+ // 2s cache at a boundary. Behavior is pinned in onDemandDrain.test.js.
+ expect(DRAIN_SRC).toMatch(/const apps = onDemandRequests\.length > 0 \? await getActiveApps\(\)\.catch\(\(\) => null\) : \[\];/);
+ expect(DRAIN_SRC, 'a [] fallback is the #6618 defect — it clears the request as unknown-app')
+ .not.toMatch(/getActiveApps\(\)\.catch\(\(\) => \[\]\)/);
+ const readIdx = DRAIN_SRC.indexOf('await getActiveApps()');
+ const loopIdx = DRAIN_SRC.indexOf('for (const request of onDemandRequests)');
+ expect(readIdx).toBeGreaterThan(-1);
+ expect(loopIdx).toBeGreaterThan(readIdx);
});
});
@@ -355,31 +367,16 @@ describe('isConfiguredApprovalRequired', () => {
});
});
-describe('both on-demand engines apply consent before addTask', () => {
+describe('the on-demand consent flip reaches every drain path', () => {
// Run Now is the user's sign-off. Without this flip, a safety-kind or
// low-confidence type (release-check used to match `\brelease\b`) is
// persisted as APPROVAL, Priority 2 will not pick it, and force-spawn
// refuses it — so "Run Now" sits in awaiting-approve forever.
- const engineBody = (src, engineFn) => {
- const start = src.indexOf(engineFn);
- expect(start, `${engineFn} must exist`).toBeGreaterThan(-1);
- const next = src.indexOf('\nasync function ', start + 1);
- return src.slice(start, next === -1 ? src.length : next);
- };
-
- it('evaluateTasks engine consents before canSpawn / addTask', () => {
- const engine = engineBody(GEN_SRC, 'async function spawnPriority0OnDemand');
- expect(engine.indexOf('applyOnDemandConsent(task)')).toBeGreaterThan(-1);
- expect(engine.indexOf('applyOnDemandConsent(task)')).toBeLessThan(engine.indexOf('canSpawnTask(task)'));
- });
-
- it('dequeueNextTask engine consents before canSpawn / addTask', () => {
- const engine = engineBody(COS_SRC, 'async function spawnDequeuePriority0OnDemand');
- expect(engine.indexOf('applyOnDemandConsent(task)')).toBeGreaterThan(-1);
- // Match either admit method: Priority 0 is a COMMITTED tier, so it calls
- // `canSpawnCommitted` rather than `canSpawn` (#4834).
- expect(engine.indexOf('applyOnDemandConsent(task)')).toBeLessThan(engine.search(/capacity\.canSpawn(Committed)?\(task/));
- });
+ //
+ // The two Priority-0 engines run ONE shared drain now, and its
+ // consent-before-admission ordering is pinned behaviorally in
+ // onDemandDrain.test.js. What is left here is the THIRD path — idle review
+ // stealing a queued on-demand request — which carries its own copy.
it('idle-review steal path consents when it drains an on-demand request', () => {
const start = GEN_SRC.indexOf('async function generateManagedAppImprovementTask(app, state');
@@ -1720,36 +1717,40 @@ describe('pr-reviewer security preflight wiring', () => {
/**
* The loop's root cause: the drain's completion refill re-issues itself through the
- * on-demand lane, and BOTH on-demand engines treated every request as a human "Run"
+ * on-demand lane, and the on-demand drain treated every request as a human "Run"
* — resetting the park, the convergence signature, and the dispatch counter, i.e.
- * every brake the drain has. Either engine may drain a given request, so both must
- * gate the reset on origin.
+ * every brake the drain has. The reset is gated on ORIGIN now, and it lives in
+ * taskSchedule.applyOnDemandRunResets (behaviorally tested there) so no drain path
+ * can reach around it.
*/
describe('automated drain refills do not clear their own convergence brakes', () => {
it('the refill stamps origin: refill', () => {
expect(COS_SRC).toMatch(/triggerOnDemandTask\(plan\.taskType, plan\.appId, \{\s*emit: false, origin: taskScheduleMod\.ON_DEMAND_ORIGINS\.REFILL\s*\}\)/);
});
- // The origin check lives in taskSchedule.applyOnDemandRunResets (behaviorally
- // tested there), so what matters HERE is that no engine reaches around it: an
- // engine calling the reset primitives directly is the exact regression, since
- // that is the shape the loop had.
- for (const [engine, src] of [['cos.dequeueNextTask', () => COS_SRC], ['cosTaskGenerator.spawnPriority0OnDemand', () => GEN_SRC]]) {
- it(`${engine} resets on-demand state only through applyOnDemandRunResets`, () => {
- const text = src();
- expect(text).toMatch(/const userInitiated = await task[Ss]chedule(Mod)?\.applyOnDemandRunResets\(request, targetApp\?\.id \?\? null\)/);
+ // A drain path calling the reset primitives directly is the exact regression,
+ // since that is the shape the loop had. The shared drain is one of three
+ // callers; the scan covers every module that touches an on-demand request.
+ for (const [where, src] of [
+ ['onDemandDrain', () => DRAIN_SRC],
+ ['cos.js', () => COS_SRC],
+ ['cosTaskGenerator.js', () => GEN_SRC],
+ ]) {
+ it(`${where} resets on-demand state only through applyOnDemandRunResets`, () => {
for (const fn of ['resetPerpetualForManualRun', 'clearTaskTypeFailurePark']) {
- const direct = text.split('\n').filter((l) => l.includes(`.${fn}(request.taskType`));
- expect(direct, `${engine} must not call ${fn} directly — go through applyOnDemandRunResets`).toEqual([]);
+ const direct = src().split('\n').filter((l) => l.includes(`.${fn}(request.taskType`));
+ expect(direct, `${where} must not call ${fn} directly — go through applyOnDemandRunResets`).toEqual([]);
}
});
-
- // A refill that toasts "nothing to do" turns a healthy overnight drain into a
- // pile of notifications nobody asked for.
- it(`${engine} only reports an empty result for a user-initiated request`, () => {
- expect(src()).toMatch(/\}\s*else if \(!task && userInitiated\) \{/);
- });
}
+
+ it('the shared drain gates the reset on the request and reports only a user-initiated empty', () => {
+ // A refill that toasts "nothing to do" turns a healthy overnight drain into
+ // a pile of notifications nobody asked for. Both halves are pinned
+ // behaviorally in onDemandDrain.test.js; this keeps the call shape honest.
+ expect(DRAIN_SRC).toMatch(/const userInitiated = await taskScheduleMod\.applyOnDemandRunResets\(request, targetApp\?\.id \?\? null\)/);
+ expect(DRAIN_SRC).toMatch(/\}\s*else if \(!task && userInitiated\) \{/);
+ });
});
// The claim button on the managed-app Issues tab, the Agent Operations `/do:next`
diff --git a/server/services/onDemandDrain.js b/server/services/onDemandDrain.js
new file mode 100644
index 0000000000..681e7d58c2
--- /dev/null
+++ b/server/services/onDemandDrain.js
@@ -0,0 +1,222 @@
+/**
+ * On-demand request drain — the ONE loop body both Priority 0 engines run.
+ *
+ * PortOS has two on-demand engines draining the SAME queue: the periodic
+ * `evaluateTasks` engine (`cosTaskGenerator.js#spawnPriority0OnDemand`) and the
+ * event-driven `dequeueNextTask` engine (`cos.js#spawnDequeuePriority0OnDemand`).
+ * Which one drains a given request is a race — `quotaBurnAcceptance.js` states
+ * that contract plainly — so any behavior either engine has, the other must have
+ * too. They used to be hand-mirrored line-for-line, and the registry-failure fix
+ * in #3294 landed on ONLY the generator: a request drained by the cos.js copy
+ * while `getActiveApps()` was failing had its user-initiated "Run Now" silently
+ * destroyed (issue #6618).
+ *
+ * The loop lives here now, so there is nothing left to mirror. Each engine
+ * supplies an `adapter` for the only three things that genuinely differ:
+ *
+ * - `capacityExhausted()` / `canSpawn(task)` — the generator fills a
+ * `tasksToSpawn` array against `availableSlots`; the dequeue engine runs the
+ * `cosDequeue.js` capacity tracker and admits via `canSpawnCommitted`
+ * (Priority 0 is a COMMITTED tier — see #4834).
+ * - `emitSpawn(task)` — push-to-array + `trackSpawn` vs
+ * `cosEvents.emit('task:ready', …)` + `capacity.trackSpawn`.
+ * - `addTaskOptions` — the `{ ignoreTaskId }` only the dequeue engine forwards.
+ *
+ * The generator's registry read is canonical and both engines now get it: ONE
+ * `getActiveApps()` per cycle, outside the loop, with `null` meaning the read
+ * FAILED (distinct from "no active apps") so a failure DEFERS the requests
+ * instead of clearing them.
+ */
+
+import { emitLog } from './cosEvents.js';
+import { getActiveApps } from './apps.js';
+import { loadState, saveState, withStateLock, isImprovementEnabled } from './cosState.js';
+import { markAppReviewCooldown, bindAppReviewAgent } from './appActivity.js';
+import { onDemandRequestMetadata } from '../lib/quotaBurnOrigin.js';
+import { addTask, reviveBlockedTask } from './cosTaskStore.js';
+
+/**
+ * Drain the on-demand request queue, generating + persisting a task per request
+ * and handing each admitted task to the caller's `adapter.emitSpawn`.
+ *
+ * @param {{ state: object }} ctx Shared CoS state for this cycle.
+ * @param {{
+ * capacityExhausted: () => boolean,
+ * canSpawn: (task: object) => boolean,
+ * emitSpawn: (task: object) => void,
+ * addTaskOptions?: object,
+ * }} adapter The three per-engine differences.
+ * @returns {Promise<{ schedule: object }>} The loaded schedule, so a caller that
+ * needs it downstream (dequeueNextTask's Priority 2 disabled-analysis-type
+ * gate) reuses this load instead of issuing a second one.
+ */
+export async function drainOnDemandRequests(ctx, adapter) {
+ const { state } = ctx;
+ const { capacityExhausted, canSpawn, emitSpawn, addTaskOptions = {} } = adapter;
+
+ // Deferred so the static import graph stays acyclic: cosTaskGenerator.js
+ // imports THIS module, and these six helpers are declared there. Deferring to
+ // call time is the same idiom the engines already use for taskSchedule.js.
+ const {
+ generateManagedAppImprovementTaskForType,
+ generateSelfImprovementTaskForType,
+ recordDeferredPerpetualDispatch,
+ applyOnDemandConsent,
+ drainProgrammaticOnDemandRequests,
+ emitOnDemandEmpty,
+ } = await import('./cosTaskGenerator.js');
+
+ const taskScheduleMod = await import('./taskSchedule.js');
+ const schedule = await taskScheduleMod.loadSchedule();
+ const onDemandRequests = await taskScheduleMod.getOnDemandRequests();
+
+ // Track apps already marked review-started this cycle so multiple on-demand
+ // requests for the same app don't each rewrite its activity record.
+ const reviewStartedApps = new Set();
+ // The app registry can't change mid-loop, so read it once per cycle rather
+ // than once per request (getActiveApps' 2s cache can miss at a boundary).
+ // `null` means the read FAILED, which is not the same as "no active apps":
+ // an empty list would make every app-targeted request below look like it
+ // names an unknown app and get cleared, silently dropping user-initiated
+ // work. On a failure we leave the requests queued for the next cycle.
+ const apps = onDemandRequests.length > 0 ? await getActiveApps().catch(() => null) : [];
+
+ // Programmatic handlers first, and outside the slot-bounded loop below: they
+ // spawn nothing, so a busy autonomy budget must not hold a user's Run Now.
+ const handledProgrammatically = await drainProgrammaticOnDemandRequests({
+ taskScheduleMod, requests: onDemandRequests, schedule, state
+ });
+
+ if (!apps) {
+ emitLog('warn', `On-demand requests deferred — the app registry could not be read this cycle`);
+ return { schedule };
+ }
+
+ for (const request of onDemandRequests) {
+ // Already handled above (and its request cleared) — `onDemandRequests` is
+ // a snapshot taken before that drain.
+ if (handledProgrammatically.has(request.id)) continue;
+ if (capacityExhausted()) break;
+
+ if (!isImprovementEnabled(state)) {
+ emitLog('warn', `On-demand request dropped — improvement is disabled (Config → Improve)`, { requestId: request.id, taskType: request.taskType });
+ await taskScheduleMod.clearOnDemandRequest(request.id);
+ continue;
+ }
+
+ // Skip if the task type was disabled or removed after queuing.
+ if (!schedule.tasks[request.taskType]?.enabled) {
+ emitLog('info', `On-demand request skipped — task type '${request.taskType}' is disabled`, { requestId: request.id });
+ await taskScheduleMod.clearOnDemandRequest(request.id);
+ continue;
+ }
+
+ let task = null;
+ // Determine target app (if any)
+ let targetApp = null;
+
+ if (request.appId) {
+ targetApp = apps.find(a => a.id === request.appId);
+ if (!targetApp) {
+ emitLog('warn', `On-demand request for unknown app: ${request.appId}`, { requestId: request.id });
+ await taskScheduleMod.clearOnDemandRequest(request.id);
+ continue;
+ }
+ }
+
+ await taskScheduleMod.clearOnDemandRequest(request.id);
+
+ // A HUMAN "Run" re-checks live state (park + convergence signature + dispatch
+ // budget all cleared); an automated refill (origin: 'refill') inherits them,
+ // or the drain has no brakes left. The origin check lives inside
+ // applyOnDemandRunResets so this drain and the refill lane can't drift on it.
+ const userInitiated = await taskScheduleMod.applyOnDemandRunResets(request, targetApp?.id ?? null);
+ const lane = userInitiated ? '' : ' (drain refill)';
+
+ if (targetApp) {
+ emitLog('info', `Processing on-demand improvement: ${request.taskType} for ${targetApp.name}${lane}`, { requestId: request.id, appId: targetApp.id });
+ // Advance the cooldown eagerly (deduped per app per cycle), but defer
+ // binding the active agent until a task is produced — a null result
+ // here must not strand `activeAgentId` (issue #978).
+ if (!reviewStartedApps.has(targetApp.id)) {
+ await markAppReviewCooldown(targetApp.id);
+ reviewStartedApps.add(targetApp.id);
+ }
+ await taskScheduleMod.recordExecution(`task:${request.taskType}`, targetApp.id);
+ task = await generateManagedAppImprovementTaskForType(request.taskType, targetApp, state, {
+ skipPreconditions: true,
+ deferPerpetualDispatch: true,
+ targetPullRequest: request.targetPullRequest ?? null,
+ providerOverride: request.providerOverride ?? null,
+ // A quota-burn step's per-invocation run parameters. They must reach
+ // the PROMPT, so unlike the provider/model/effort pins they cannot
+ // ride the post-generation `onDemandRequestMetadata` stamp below —
+ // the generator overlays them before it picks the mode banner.
+ // `normalizeQuotaBurnProvenance` (lib/quotaBurnOrigin.js) has to keep
+ // `overrides.params` for a step to reach this; it drops them today,
+ // so a burn currently runs the task's SAVED mode, which is correct
+ // for every step until the migration starts pinning one.
+ runOverrides: request.burn?.overrides?.params ?? null
+ });
+ if (task) {
+ await bindAppReviewAgent(targetApp.id, `on-demand-${Date.now()}`);
+ }
+ } else {
+ emitLog('info', `Processing on-demand improvement: ${request.taskType}${lane}`, { requestId: request.id });
+ await taskScheduleMod.recordExecution(`task:${request.taskType}`);
+ await withStateLock(async () => {
+ const s = await loadState();
+ s.stats.lastSelfImprovement = new Date().toISOString();
+ s.stats.lastSelfImprovementType = request.taskType;
+ await saveState(s);
+ });
+ task = await generateSelfImprovementTaskForType(request.taskType, state);
+ }
+
+ applyOnDemandConsent(task);
+ // Priority 0 is a COMMITTED tier: the request is already cleared and the
+ // marker bound, and this branch is the only thing that persists the task, so
+ // a denial would discard the user's "Run". See canSpawnCommitted (#4834).
+ if (task && canSpawn(task)) {
+ // Mark this a MANUAL (on-demand) run so its perpetual drain continues in
+ // the on-demand lane (see perpetualRefillPlan in cos.js). Stamped before
+ // addTask so the blocked-revive branch inherits it via `task.metadata`.
+ // `onDemandRequestMetadata` also carries the request's ORIGIN, which
+ // `perpetualRefillPlan` reads to decide whether the completed run may
+ // continue its drain — and a quota burn's provenance when it is one.
+ task.metadata = { ...(task.metadata || {}), ...onDemandRequestMetadata(request) };
+ // `addTaskOptions` carries the dequeue engine's `ignoreTaskId` so a
+ // completion-triggered re-issue is dedup-safe: the perpetual drain
+ // regenerates an identical first-line for the same app, and
+ // `agent:completed` fires before the completing task's updateTask settles
+ // it to `completed` — so without excluding it the re-issued claim is
+ // rejected as a duplicate of the run that just finished and the drain stalls.
+ const persisted = await addTask(task, 'internal', { raw: true, ...addTaskOptions, suppressDequeue: true });
+ if (!persisted?.duplicate) {
+ await recordDeferredPerpetualDispatch(task, taskScheduleMod);
+ emitSpawn(task);
+ } else if (persisted.status === 'blocked') {
+ // Explicit user Run colliding with a failure-blocked twin (#2614):
+ // revive the existing task instead of silently dropping the Run and
+ // stranding the bound on-demand review marker.
+ await reviveBlockedTask(persisted.id, { priority: task.priority, metadata: task.metadata }, 'internal', { suppressDequeue: true });
+ await recordDeferredPerpetualDispatch(task, taskScheduleMod);
+ const revived = { ...task, id: persisted.id };
+ emitSpawn(revived);
+ emitLog('info', `🔁 On-demand ${request.taskType} revived blocked task ${persisted.id}`, { taskId: persisted.id });
+ }
+ } else if (!task && userInitiated) {
+ // Explicit user "Run" produced no task — surface WHY (parked / transient /
+ // idle) so the trigger isn't a silent no-op. Because we reset the park
+ // BEFORE the fresh detection above, the outcome classification reflects
+ // THIS check.
+ //
+ // `userInitiated` only: a drain refill ends by converging (that's the point),
+ // and nobody is waiting on it, so toasting "nothing to do" for every automated
+ // hop would turn a healthy overnight drain into a pile of notifications.
+ await emitOnDemandEmpty({ taskScheduleMod, request, targetApp, taskConfig: schedule.tasks[request.taskType] });
+ }
+ }
+
+ return { schedule };
+}
diff --git a/server/services/onDemandDrain.test.js b/server/services/onDemandDrain.test.js
new file mode 100644
index 0000000000..a6fe2d1929
--- /dev/null
+++ b/server/services/onDemandDrain.test.js
@@ -0,0 +1,396 @@
+/**
+ * Behavioral contract for the ONE on-demand drain both Priority 0 engines run.
+ *
+ * PortOS has two on-demand engines racing the same queue —
+ * `cosTaskGenerator.js#spawnPriority0OnDemand` (periodic `evaluateTasks`) and
+ * `cos.js#spawnDequeuePriority0OnDemand` (event-driven `dequeueNextTask`) — and
+ * which one drains a given request is a race. While the loop was hand-mirrored,
+ * the ONLY guards on that parity were source greps against each engine's body,
+ * and they still passed while #3294's registry-failure fix sat in the generator
+ * copy alone: a request drained by the cos.js copy during a `getActiveApps()`
+ * failure had the user's "Run Now" silently deleted (#6618).
+ *
+ * These run the shared loop through BOTH engines' adapters, so a divergence has
+ * to be a real behavioral difference rather than a grep that stopped matching.
+ * The registry-failure case below is the one that was live-broken: it fails
+ * against `cos.js` on unmodified `main`, where the read was `catch(() => [])`
+ * inside the loop and the request was cleared as an "unknown app".
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ getActiveApps: vi.fn(),
+ isImprovementEnabled: vi.fn(() => true),
+ loadState: vi.fn(async () => ({ stats: {} })),
+ saveState: vi.fn(async () => {}),
+ withStateLock: vi.fn(async (fn) => fn()),
+ markAppReviewCooldown: vi.fn(async () => {}),
+ bindAppReviewAgent: vi.fn(async () => {}),
+ addTask: vi.fn(async () => ({ id: 'persisted-1' })),
+ reviveBlockedTask: vi.fn(async () => {}),
+ loadSchedule: vi.fn(async () => ({ tasks: { 'code-quality': { enabled: true } } })),
+ getOnDemandRequests: vi.fn(async () => []),
+ clearOnDemandRequest: vi.fn(async () => {}),
+ applyOnDemandRunResets: vi.fn(async () => true),
+ recordExecution: vi.fn(async () => {}),
+ generateManagedAppImprovementTaskForType: vi.fn(async () => ({ id: 'gen-1', priority: 'HIGH' })),
+ generateSelfImprovementTaskForType: vi.fn(async () => ({ id: 'self-1', priority: 'HIGH' })),
+ recordDeferredPerpetualDispatch: vi.fn(async () => {}),
+ applyOnDemandConsent: vi.fn((t) => t),
+ drainProgrammaticOnDemandRequests: vi.fn(async () => new Set()),
+ emitOnDemandEmpty: vi.fn(async () => {}),
+}));
+
+vi.mock('./apps.js', () => ({ getActiveApps: (...a) => mocks.getActiveApps(...a) }));
+vi.mock('./cosState.js', () => ({
+ isImprovementEnabled: (...a) => mocks.isImprovementEnabled(...a),
+ loadState: (...a) => mocks.loadState(...a),
+ saveState: (...a) => mocks.saveState(...a),
+ withStateLock: (...a) => mocks.withStateLock(...a),
+}));
+vi.mock('./appActivity.js', () => ({
+ markAppReviewCooldown: (...a) => mocks.markAppReviewCooldown(...a),
+ bindAppReviewAgent: (...a) => mocks.bindAppReviewAgent(...a),
+}));
+vi.mock('./cosTaskStore.js', () => ({
+ addTask: (...a) => mocks.addTask(...a),
+ reviveBlockedTask: (...a) => mocks.reviveBlockedTask(...a),
+}));
+vi.mock('./taskSchedule.js', () => ({
+ loadSchedule: (...a) => mocks.loadSchedule(...a),
+ getOnDemandRequests: (...a) => mocks.getOnDemandRequests(...a),
+ clearOnDemandRequest: (...a) => mocks.clearOnDemandRequest(...a),
+ applyOnDemandRunResets: (...a) => mocks.applyOnDemandRunResets(...a),
+ recordExecution: (...a) => mocks.recordExecution(...a),
+}));
+vi.mock('./cosTaskGenerator.js', () => ({
+ generateManagedAppImprovementTaskForType: (...a) => mocks.generateManagedAppImprovementTaskForType(...a),
+ generateSelfImprovementTaskForType: (...a) => mocks.generateSelfImprovementTaskForType(...a),
+ recordDeferredPerpetualDispatch: (...a) => mocks.recordDeferredPerpetualDispatch(...a),
+ applyOnDemandConsent: (...a) => mocks.applyOnDemandConsent(...a),
+ drainProgrammaticOnDemandRequests: (...a) => mocks.drainProgrammaticOnDemandRequests(...a),
+ emitOnDemandEmpty: (...a) => mocks.emitOnDemandEmpty(...a),
+}));
+
+const { drainOnDemandRequests } = await import('./onDemandDrain.js');
+
+const APP = { id: 'acme', name: 'Acme App' };
+const STATE = { agents: {}, stats: {}, config: {} };
+
+// The two real adapters, reproduced from the engines they belong to. Each test
+// runs the shared loop through BOTH, so a behavior that only holds for one is a
+// failure rather than an untested corner.
+function generatorAdapter({ availableSlots = 5 } = {}) {
+ const tasksToSpawn = [];
+ return {
+ spawned: tasksToSpawn,
+ adapter: {
+ capacityExhausted: () => tasksToSpawn.length >= availableSlots,
+ canSpawn: () => true,
+ emitSpawn: (task) => tasksToSpawn.push(task),
+ },
+ };
+}
+
+function dequeueAdapter({ availableSlots = 5, ignoreTaskId = 'completing-task' } = {}) {
+ const spawned = [];
+ return {
+ spawned,
+ adapter: {
+ capacityExhausted: () => spawned.length >= availableSlots,
+ canSpawn: () => true,
+ emitSpawn: (task) => spawned.push(task),
+ addTaskOptions: { ignoreTaskId },
+ },
+ };
+}
+
+const ENGINES = [
+ ['evaluateTasks (spawnPriority0OnDemand)', generatorAdapter],
+ ['dequeueNextTask (spawnDequeuePriority0OnDemand)', dequeueAdapter],
+];
+
+const appRequest = (overrides = {}) => ({
+ id: 'req-1', taskType: 'code-quality', appId: 'acme', ...overrides
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.isImprovementEnabled.mockReturnValue(true);
+ mocks.loadState.mockResolvedValue({ stats: {} });
+ mocks.withStateLock.mockImplementation(async (fn) => fn());
+ mocks.loadSchedule.mockResolvedValue({ tasks: { 'code-quality': { enabled: true } } });
+ mocks.getOnDemandRequests.mockResolvedValue([]);
+ mocks.applyOnDemandRunResets.mockResolvedValue(true);
+ mocks.getActiveApps.mockResolvedValue([APP]);
+ mocks.addTask.mockResolvedValue({ id: 'persisted-1' });
+ mocks.generateManagedAppImprovementTaskForType.mockResolvedValue({ id: 'gen-1', priority: 'HIGH' });
+ mocks.generateSelfImprovementTaskForType.mockResolvedValue({ id: 'self-1', priority: 'HIGH' });
+ mocks.drainProgrammaticOnDemandRequests.mockResolvedValue(new Set());
+ mocks.applyOnDemandConsent.mockImplementation((t) => t);
+});
+
+// ── The #6618 defect ────────────────────────────────────────────────────────
+describe.each(ENGINES)('%s — a failing app registry defers, never clears', (_name, makeAdapter) => {
+ beforeEach(() => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ mocks.getActiveApps.mockRejectedValue(new Error('registry read failed'));
+ });
+
+ it('leaves the app-targeted request queued', async () => {
+ const { adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ // The pre-fix cos.js form (`catch(() => [])`) fell through to the
+ // unknown-app branch and destroyed the user's Run Now here.
+ expect(mocks.clearOnDemandRequest).not.toHaveBeenCalled();
+ });
+
+ it('emits no task and generates nothing', async () => {
+ const { spawned, adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(spawned).toEqual([]);
+ expect(mocks.generateManagedAppImprovementTaskForType).not.toHaveBeenCalled();
+ expect(mocks.addTask).not.toHaveBeenCalled();
+ });
+
+ it('leaves the app-review marker untouched so nothing is stranded', async () => {
+ const { adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.markAppReviewCooldown).not.toHaveBeenCalled();
+ expect(mocks.bindAppReviewAgent).not.toHaveBeenCalled();
+ });
+});
+
+describe.each(ENGINES)('%s — registry read cost', (_name, makeAdapter) => {
+ it('reads the registry once per cycle, not once per request', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([
+ appRequest({ id: 'req-1' }), appRequest({ id: 'req-2' }), appRequest({ id: 'req-3' })
+ ]);
+ const { adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.getActiveApps).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not read the registry at all when the queue is empty', async () => {
+ const { adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.getActiveApps).not.toHaveBeenCalled();
+ });
+
+ it('an EMPTY registry still clears an app-targeted request as unknown', async () => {
+ // The sentinel's other half: `[]` is a successful read of zero apps, which
+ // genuinely means the named app is gone. Only `null` (a failed read) defers.
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ mocks.getActiveApps.mockResolvedValue([]);
+ const { spawned, adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.clearOnDemandRequest).toHaveBeenCalledWith('req-1');
+ expect(spawned).toEqual([]);
+ });
+});
+
+// ── The parity the deleted "Mirrors the sibling engine" comments asserted ────
+describe.each(ENGINES)('%s — on-demand metadata stamp', (_name, makeAdapter) => {
+ it('stamps onDemand + the request origin onto the task before addTask', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest({ origin: 'refill' })]);
+ const { spawned, adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+
+ expect(spawned).toHaveLength(1);
+ expect(spawned[0].metadata).toMatchObject({ onDemand: true, onDemandOrigin: 'refill' });
+ // Stamped BEFORE persistence, so the blocked-revive branch inherits it.
+ expect(mocks.addTask.mock.calls[0][0].metadata).toMatchObject({ onDemand: true });
+ });
+
+ it('applies the Run Now consent before the admission check', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ const order = [];
+ mocks.applyOnDemandConsent.mockImplementation((t) => { order.push('consent'); return t; });
+ const { adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, {
+ ...adapter,
+ canSpawn: () => { order.push('canSpawn'); return true; },
+ });
+ expect(order).toEqual(['consent', 'canSpawn']);
+ });
+});
+
+describe.each(ENGINES)('%s — empty-result feedback', (_name, makeAdapter) => {
+ it('reports an empty result for a user-initiated Run', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ mocks.generateManagedAppImprovementTaskForType.mockResolvedValue(null);
+ mocks.applyOnDemandRunResets.mockResolvedValue(true);
+ const { adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.emitOnDemandEmpty).toHaveBeenCalledTimes(1);
+ expect(mocks.emitOnDemandEmpty.mock.calls[0][0]).toMatchObject({ targetApp: APP });
+ });
+
+ it('stays silent for an automated drain refill', async () => {
+ // A converging overnight drain must not turn into a pile of toasts.
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ mocks.generateManagedAppImprovementTaskForType.mockResolvedValue(null);
+ mocks.applyOnDemandRunResets.mockResolvedValue(false);
+ const { adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.emitOnDemandEmpty).not.toHaveBeenCalled();
+ });
+
+ it('resets the drain brakes only through applyOnDemandRunResets', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ const { adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.applyOnDemandRunResets).toHaveBeenCalledWith(expect.objectContaining({ id: 'req-1' }), 'acme');
+ });
+});
+
+describe.each(ENGINES)('%s — blocked-duplicate revive (#2614)', (_name, makeAdapter) => {
+ it('revives the blocked twin and emits it under the existing task id', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ mocks.addTask.mockResolvedValue({ id: 'blocked-7', duplicate: true, status: 'blocked' });
+ const { spawned, adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+
+ expect(mocks.reviveBlockedTask).toHaveBeenCalledWith(
+ 'blocked-7',
+ expect.objectContaining({ metadata: expect.objectContaining({ onDemand: true }) }),
+ 'internal',
+ { suppressDequeue: true }
+ );
+ expect(spawned).toHaveLength(1);
+ expect(spawned[0].id).toBe('blocked-7');
+ });
+
+ it('drops a non-blocked duplicate without reviving or emitting', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ mocks.addTask.mockResolvedValue({ id: 'dup-1', duplicate: true, status: 'pending' });
+ const { spawned, adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.reviveBlockedTask).not.toHaveBeenCalled();
+ expect(spawned).toEqual([]);
+ });
+});
+
+describe.each(ENGINES)('%s — app-review marker discipline (#978)', (_name, makeAdapter) => {
+ it('advances one app cooldown per cycle no matter how many requests name it', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([
+ appRequest({ id: 'req-1' }), appRequest({ id: 'req-2' })
+ ]);
+ const { adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.markAppReviewCooldown).toHaveBeenCalledTimes(1);
+ expect(mocks.markAppReviewCooldown).toHaveBeenCalledWith('acme');
+ });
+
+ it('binds the active agent only once a task actually exists', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ mocks.generateManagedAppImprovementTaskForType.mockResolvedValue(null);
+ const { adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ // The cooldown still advanced — only the bind is deferred, so a null
+ // generator result can't strand `activeAgentId`.
+ expect(mocks.markAppReviewCooldown).toHaveBeenCalledTimes(1);
+ expect(mocks.bindAppReviewAgent).not.toHaveBeenCalled();
+ });
+});
+
+describe.each(ENGINES)('%s — skip gates', (_name, makeAdapter) => {
+ it('drops the request when improvement is disabled', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ mocks.isImprovementEnabled.mockReturnValue(false);
+ const { spawned, adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.clearOnDemandRequest).toHaveBeenCalledWith('req-1');
+ expect(spawned).toEqual([]);
+ });
+
+ it('drops the request when its task type was disabled after queuing', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ mocks.loadSchedule.mockResolvedValue({ tasks: { 'code-quality': { enabled: false } } });
+ const { spawned, adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.clearOnDemandRequest).toHaveBeenCalledWith('req-1');
+ expect(spawned).toEqual([]);
+ });
+
+ it('skips a request the programmatic drain already handled', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ mocks.drainProgrammaticOnDemandRequests.mockResolvedValue(new Set(['req-1']));
+ const { spawned, adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.clearOnDemandRequest).not.toHaveBeenCalled();
+ expect(spawned).toEqual([]);
+ });
+
+ it('stops draining once the adapter reports capacity exhausted', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([
+ appRequest({ id: 'req-1' }), appRequest({ id: 'req-2' })
+ ]);
+ const { spawned, adapter } = makeAdapter({ availableSlots: 1 });
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(spawned).toHaveLength(1);
+ expect(mocks.clearOnDemandRequest).toHaveBeenCalledTimes(1);
+ });
+
+ it('routes an app-less request through the self-improvement generator', async () => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest({ appId: null })]);
+ const { spawned, adapter } = makeAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.generateSelfImprovementTaskForType).toHaveBeenCalledWith('code-quality', STATE);
+ expect(mocks.markAppReviewCooldown).not.toHaveBeenCalled();
+ expect(spawned).toHaveLength(1);
+ });
+});
+
+// ── The three real differences the adapters own ─────────────────────────────
+describe('the per-engine adapter differences', () => {
+ beforeEach(() => {
+ mocks.getOnDemandRequests.mockResolvedValue([appRequest()]);
+ });
+
+ it('the dequeue engine forwards ignoreTaskId so a completion re-issue is dedup-safe', async () => {
+ const { adapter } = dequeueAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.addTask).toHaveBeenCalledWith(
+ expect.anything(), 'internal',
+ { raw: true, ignoreTaskId: 'completing-task', suppressDequeue: true }
+ );
+ });
+
+ it('the generator engine sends no ignoreTaskId — it has no completing task to exclude', async () => {
+ const { adapter } = generatorAdapter();
+ await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(mocks.addTask).toHaveBeenCalledWith(
+ expect.anything(), 'internal', { raw: true, suppressDequeue: true }
+ );
+ });
+
+ it('a denied admission discards nothing else — the request stays cleared and no task is emitted', async () => {
+ // Priority 0 is a COMMITTED tier: `canSpawn` returning false is the
+ // destructive case cosDequeue's `canSpawnCommitted` exists to avoid, so the
+ // engines never pass a capacity predicate that can deny here. Pin the shape
+ // anyway so the shared loop's behavior under a denial is not a surprise.
+ const { spawned, adapter } = generatorAdapter();
+ await drainOnDemandRequests({ state: STATE }, { ...adapter, canSpawn: () => false });
+ expect(spawned).toEqual([]);
+ expect(mocks.addTask).not.toHaveBeenCalled();
+ expect(mocks.emitOnDemandEmpty).not.toHaveBeenCalled();
+ });
+
+ it('returns the loaded schedule so a caller reuses it instead of loading twice', async () => {
+ const schedule = { tasks: { 'code-quality': { enabled: true } } };
+ mocks.loadSchedule.mockResolvedValue(schedule);
+ const { adapter } = dequeueAdapter();
+ const result = await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(result.schedule).toBe(schedule);
+ expect(mocks.loadSchedule).toHaveBeenCalledTimes(1);
+ });
+
+ it('returns the schedule even when the registry read defers the whole cycle', async () => {
+ mocks.getActiveApps.mockRejectedValue(new Error('registry read failed'));
+ const { adapter } = dequeueAdapter();
+ const result = await drainOnDemandRequests({ state: STATE }, adapter);
+ expect(result.schedule).toEqual({ tasks: { 'code-quality': { enabled: true } } });
+ });
+});
diff --git a/server/services/quotaBurnAcceptance.js b/server/services/quotaBurnAcceptance.js
index 219383dd73..e268c60ad9 100644
--- a/server/services/quotaBurnAcceptance.js
+++ b/server/services/quotaBurnAcceptance.js
@@ -5,7 +5,8 @@
* task the user already owns (`quotaBurnInvoke.js` →
* `taskSchedule.triggerOnDemandTask`). The request lands on the schedule now and
* one of the two on-demand engines (`cos.js#spawnDequeuePriority0OnDemand`,
- * `cosTaskGenerator.js#spawnPriority0OnDemand`) generates the task later — or
+ * `cosTaskGenerator.js#spawnPriority0OnDemand` — both thin adapters over the
+ * shared `onDemandDrain.js` loop) generates the task later — or
* refuses it: improvement switched off, the task type disabled since queuing, an
* app that has gone away, a generator that produced nothing, an identical twin
* already queued. So "we recorded a request" is NOT "work started", and charging