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

run a quota-burn step through the referenced task's own invocation path (#6378)

[._.]/ Adam Eivyc02c62f76330
diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.md
index 62bda0be2e..3f14cea332 100644
--- a/docs/QUOTA-BURN.md
+++ b/docs/QUOTA-BURN.md
@@ -377,12 +377,15 @@ folds those overrides into the single plan (each app's family prompt becomes an
| `server/lib/quotaBurnConfig.js` | Plan shape, job-type catalog, total normalization |
| `server/lib/universeBibleCompleteness.js` | What "described" means per kind + depth — the field vocabulary the describe job scans with |
| `server/lib/quotaBurnPresets.js` | Ready-made single-focus audit prompts for `agent-prompt` jobs |
+| `server/lib/quotaBurnTaskRef.js` | The step→scheduled-task reference model, its overrides bag, and the availability resolver |
+| `server/lib/quotaBurnOrigin.js` | Burn provenance on an on-demand request, and the metadata both on-demand engines stamp from it |
| `server/lib/quotaWindows.js` | Classifies a window by period — target (broadest) vs limiting (narrowest) |
| `server/services/quotaBurnStore.js` | `data/cos/quota-burn.json` + the run log |
| `server/services/quotaBurn.js` | `evaluateFamily` — the one gate ladder both selection and the page's skip reasons read — plus the dispatch ledger |
| `server/services/quotaBurnCompletions.js` | The `run once` completion ledger and its re-arm |
| `server/services/quotaBurnDenials.js` | The observed-refusal ledger and its `agent:completed` subscriber |
-| `server/services/quotaBurnJobs/` | The burn job registry and the `agent-prompt` executor |
+| `server/services/quotaBurnInvoke.js` | The shared invocation path: resolves a step's reference, enforces the schedule's own gates, and dispatches through canonical task generation |
+| `server/services/quotaBurnJobs/` | The frozen legacy job registry and the `agent-prompt` executor, kept until un-migrated plans are converted |
| `server/services/scheduledHandlers/` | The programmatic handlers (universe bible descriptions/images) — shared by Scheduled Tasks and Quota Burn |
| `server/services/quotaBurnRunner.js` | The loop, the cycle, and the status feed |
| `server/routes/quotaBurn.js` | `/api/quota-burn` |
diff --git a/server/lib/README.md b/server/lib/README.md
index ac091d5f7c..b86eabb088 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -62,7 +62,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `persistentMindThinkingPresets.js` | Also owns bounded self-thinking request schemas, durable request normalization, and fixed switching limits. Saved named temporary thinking presets for the persistent mind (exact provider/model/effort alternates to its one home profile): default-empty durable shape, normalization that drops half-pinned entries, strict API schema, whole-list replace merge, preset lookup, strict accepted-selection schema/normalization, and route equality independent of labels. Storage only — saving or selecting a preset starts no inference. |
| `heavyJobClaim.js` | Cross-process, machine-wide accelerator claim: `claimHeavyLocalJob({ kind, id, timeoutMs? })` either acquires an ephemeral `data/` lock or reports its active holder; dead-PID claims are reclaimed, and a spawned child can take over the recorded PID across a server restart. |
| `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |
+| `autonomousJobTask.js` | `generatedJobTaskFields` — flattens a `generateTaskFromJob` result into the top-level keys the non-raw `cos.addTask` path maps onto metadata. One allowlist shared by the manual "Run now" endpoint and the quota-burn lane, so a key added to the generator cannot reach one and not the other. Pure. |
| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Owns the dispatch-cap sentinel too (`QUOTA_BURN_UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap`) — -1 means the window is not counted, and is the default. Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225, and the `run once` vocabulary (`quotaBurnJobKey` / `jobIsSpent`, plus the two family predicates `familyIsConfigured` and `familyHasRunnableJobs`). Pure — no storage, no provider I/O. |
+| `quotaBurnOrigin.js` | Quota-burn PROVENANCE on an on-demand scheduled-task request: `normalizeQuotaBurnProvenance` (family + burn-step id required, plus the limiting-window reset and the provider/model/effort overrides) and `quotaBurnTaskMetadata`, the single spread both on-demand engines apply so a reference-dispatched burn stamps the same `quotaBurnFamily` / `quotaBurnLimitingResetAt` keys the retired direct executor did. Import-light on purpose — `taskScheduleConstants.js` declares the origin string and must not drag the quota-burn config graph. |
| `quotaBurnPresets.js` | `QUOTA_BURN_PROMPT_PRESETS` — ready-made single-focus audit prompts for `agent-prompt` burn jobs (UX, a11y, mobile, failure paths, perf, test gaps, dead code, data safety, docs, security), each filing GitHub issues and changing no code. Templates: picking one COPIES its prompt into the job, so editing them never rewrites a configured job. `findQuotaBurnPreset(id)`. |
| `auditCatalog.js` | Shared catalog of scheduled AUDIT task types (`AUDIT_DEFINITIONS` / `AUDIT_TASK_TYPES`) that can either implement a fix or file tracker issues. `isFileIssuesMode`, `auditDoWorkRequiresWorktree`, `getAuditFilingPreset`, `modeContractFor`, `applyAuditModeWrapper`. Each quota-burn audit preset maps to a scheduled type here (guarded by `auditCatalog.test.js`). Pure — no I/O. |
| `quotaBurnTaskRef.js` | The quota-burn STEP model: a discriminated scheduled-task reference (`builtin` task type + validated target app, or `custom` app-job id whose own scope is authoritative) plus the per-invocation `overrides` bag (provider/model/effort/params — unset inherits the task's saved settings, and nothing written here edits the schedule). `normalizeQuotaBurnTaskRef` / `normalizeQuotaBurnOverrides` / `normalizeQuotaBurnParams`, the `QUOTA_BURN_UNAVAILABLE` reason codes, `resolveQuotaBurnStepAvailability` (catalog passed IN, so this stays pure) / `applyQuotaBurnAvailability`, and `quotaBurnStepIsDispatchable`. |
diff --git a/server/lib/autonomousJobTask.js b/server/lib/autonomousJobTask.js
new file mode 100644
index 0000000000..b4de471593
--- /dev/null
+++ b/server/lib/autonomousJobTask.js
@@ -0,0 +1,47 @@
+/**
+ * The projection that turns a generated autonomous-job task back into the
+ * top-level fields `cos.addTask` maps onto `metadata`.
+ *
+ * `generateTaskFromJob` (`services/autonomousJobs/skillTemplates.js`) builds the
+ * task the SCHEDULED fire emits straight onto `task:ready`, metadata and all.
+ * Every other caller queues it through the non-raw `addTask` path instead, which
+ * only reads top-level keys — so each of them has to flatten the same bag.
+ *
+ * That flattening is an allowlist, which is exactly why it lives here once: a
+ * key added to the generator and missed by one caller silently vanishes from
+ * that lane, and the task still queues, so nothing fails loudly. (`noChangeSuccess`
+ * had to be added twice for this reason.) Callers layer their OWN posture on top
+ * of the spread — `approvalRequired`, `context`, provider pins, quota-burn
+ * provenance — because that is where they legitimately differ.
+ *
+ * Pure: `server/lib/` rather than beside the generator, because it needs none of
+ * the generator's app / skill-template / data-input I/O and both callers'
+ * suites double that module.
+ */
+
+/** @param {object} generated - a `generateTaskFromJob` result */
+export function generatedJobTaskFields(generated) {
+ const meta = generated?.metadata || {};
+ return {
+ description: generated?.description,
+ priority: generated?.priority,
+ prompt: meta.prompt,
+ // App-scoped jobs carry the target app so `prepareAgentWorkspace` resolves
+ // the agent's workspace to the app's repoPath instead of the PortOS root.
+ app: meta.app,
+ useWorktree: meta.useWorktree,
+ openPR: meta.openPR,
+ simplify: meta.simplify,
+ // A marked audit may complete successfully with a verified empty branch.
+ noChangeSuccess: meta.noChangeSuccess,
+ // Read by the `job:spawned` listener, which records the execution and
+ // re-registers the saved schedule.
+ autonomousJob: meta.autonomousJob,
+ jobId: meta.jobId,
+ // Per-job AI overrides: `addTask` maps these onto `metadata.provider` /
+ // `.model` / `.effort`, which the spawner resolves against.
+ provider: meta.provider,
+ model: meta.model,
+ effort: meta.effort,
+ };
+}
diff --git a/server/lib/index.js b/server/lib/index.js
index c35f12babb..825ec83cb9 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -18,6 +18,7 @@
// names are the canonical PortOS-wide schemas.
export * from './appDeployFlags.js';
export * from './apiContractSchemas.js';
+export * from './autonomousJobTask.js';
export * from './asyncApiSpec.js';
export * from './avatarVariants.js';
export * from './avatarStyles.js';
@@ -190,6 +191,7 @@ export * from './providerTranscriptUsage.js';
// duplicate-identifier collision check.
export * as reviewerConfig from './reviewerConfig.js';
export * from './quotaBurnConfig.js';
+export * from './quotaBurnOrigin.js';
export * from './quotaBurnPresets.js';
export * from './auditCatalog.js';
export * from './quotaBurnTaskRef.js';
diff --git a/server/lib/quotaBurnOrigin.js b/server/lib/quotaBurnOrigin.js
new file mode 100644
index 0000000000..3ed4005cab
--- /dev/null
+++ b/server/lib/quotaBurnOrigin.js
@@ -0,0 +1,107 @@
+/**
+ * Quota-burn PROVENANCE carried on an on-demand scheduled-task request, and the
+ * metadata an on-demand engine stamps from it.
+ *
+ * A burn step no longer queues its own synthesized task: it asks the schedule to
+ * run a task the user already owns (`quotaBurnInvoke.js` →
+ * `taskSchedule.triggerOnDemandTask` with `origin: 'quota-burn'`). Acceptance is
+ * therefore ASYNCHRONOUS — 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 — so
+ * the "which burn was this?" facts have to ride ON the request and be stamped
+ * onto the task the engine produces.
+ *
+ * Pure, and deliberately import-light (`objects.js` only): `taskScheduleConstants.js`
+ * declares the origin strings and is reached by a large share of the server suite,
+ * so this module must never pull the quota-burn config graph in behind it
+ * (server/AGENTS.md, "Import scoping"). That is also why `onDemandOrigin` below
+ * is copied through as an opaque string rather than validated against the enum.
+ *
+ * The two long-lived keys — `quotaBurnFamily` and `quotaBurnLimitingResetAt` —
+ * are the SAME ones the legacy `quotaBurnJobs/agentPrompt.js` executor stamps,
+ * on purpose: `cosTaskGenerator.js#isCooldownExemptTask`, the runner's completion
+ * continuation, and `quotaBurnDenials.js` all read them off the finished agent,
+ * and a reference-dispatched burn must be indistinguishable to those readers.
+ */
+
+import { isPlainObject } from './objects.js';
+
+const MAX_FIELD = 64;
+
+const trimmed = (value, max = MAX_FIELD) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
+const nullable = (value, max = MAX_FIELD) => trimmed(value, max) || null;
+
+/**
+ * Normalize the `burn` block of an on-demand request. Returns `null` unless it
+ * names BOTH the family whose window is being spent and the burn step that asked
+ * — without either, nothing downstream can attribute the run, and an
+ * unattributable burn is worse than no burn: `isCooldownExemptTask` would treat
+ * an ordinary task as burn-exempt, and the denial ledger would credit a refusal
+ * to the wrong family.
+ *
+ * `overrides` carries only the three per-invocation settings the generated task
+ * can absorb AFTER generation — the provider, model and reasoning effort the
+ * spawner reads straight off `task.metadata`. A step's run `params` are NOT here:
+ * they have to reach the PROMPT, which means the generator itself must overlay
+ * them onto the task's saved `taskMetadata`, and that plumbing belongs with the
+ * audit-mode contract that needs it (#6380). Paths that consume params directly
+ * — the programmatic scheduled handlers and custom-job generation — read them
+ * from the step, and never travel through a request at all.
+ */
+export function normalizeQuotaBurnProvenance(raw) {
+ if (!isPlainObject(raw)) return null;
+ const family = trimmed(raw.family);
+ const stepId = trimmed(raw.stepId);
+ if (!family || !stepId) return null;
+ const limitingResetAt = Number(raw.limitingResetAt);
+ const overrides = isPlainObject(raw.overrides) ? raw.overrides : {};
+ return {
+ family,
+ stepId,
+ limitingResetAt: Number.isFinite(limitingResetAt) ? limitingResetAt : null,
+ overrides: {
+ providerId: nullable(overrides.providerId),
+ model: nullable(overrides.model),
+ effort: nullable(overrides.effort),
+ },
+ };
+}
+
+/**
+ * The metadata BOTH on-demand engines merge onto the task they just generated
+ * for a request — `cos.js#spawnDequeuePriority0OnDemand` and
+ * `cosTaskGenerator.js#spawnPriority0OnDemand`, either of which may drain any
+ * given request. One helper rather than the expression written out twice: the
+ * engines are an exact mirror, and a rule repeated in two places is a rule that
+ * eventually holds in one.
+ *
+ * `onDemand` says the task came out of the request queue at all; `onDemandOrigin`
+ * says WHO asked, and is what `perpetualRefillPlan` reads to decide whether the
+ * completed run may continue its perpetual drain. They are separate keys because
+ * they are separate facts — folding "a human asked" into `onDemand` is what made
+ * a burn indistinguishable from a Run Now, and forced the exclusion to be
+ * re-asserted as a second key-specific rule in `cos.js`.
+ *
+ * `null` origin means "not recorded", which every reader treats as a human Run:
+ * that is what a request queued before the field existed is.
+ */
+export function onDemandRequestMetadata(request) {
+ const burn = normalizeQuotaBurnProvenance(request?.burn);
+ const requestId = trimmed(request?.id, 128);
+ return {
+ onDemand: true,
+ onDemandOrigin: nullable(request?.origin),
+ ...(burn ? {
+ quotaBurnFamily: burn.family,
+ // Omitted rather than nulled when unreadable: `cosTaskStore` only persists
+ // a FINITE value, so writing an explicit null here would make the raw-task
+ // path disagree with the mapped one.
+ ...(burn.limitingResetAt === null ? {} : { quotaBurnLimitingResetAt: burn.limitingResetAt }),
+ quotaBurnStepId: burn.stepId,
+ ...(requestId ? { quotaBurnRequestId: requestId } : {}),
+ ...(burn.overrides.providerId ? { provider: burn.overrides.providerId } : {}),
+ ...(burn.overrides.model ? { model: burn.overrides.model } : {}),
+ ...(burn.overrides.effort ? { effort: burn.overrides.effort } : {}),
+ } : {}),
+ };
+}
diff --git a/server/lib/quotaBurnOrigin.test.js b/server/lib/quotaBurnOrigin.test.js
new file mode 100644
index 0000000000..3e7ccd3760
--- /dev/null
+++ b/server/lib/quotaBurnOrigin.test.js
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest';
+import { normalizeQuotaBurnProvenance, onDemandRequestMetadata } from './quotaBurnOrigin.js';
+
+const provenance = (overrides = {}) => ({ family: 'grok', stepId: 'step-1', ...overrides });
+
+describe('normalizeQuotaBurnProvenance', () => {
+ it('keeps the family, step, limiting reset and the three override pins', () => {
+ expect(normalizeQuotaBurnProvenance(provenance({
+ limitingResetAt: 1700000000000,
+ overrides: { providerId: 'grok-tui', model: 'm', effort: 'high' },
+ }))).toEqual({
+ family: 'grok',
+ stepId: 'step-1',
+ limitingResetAt: 1700000000000,
+ overrides: { providerId: 'grok-tui', model: 'm', effort: 'high' },
+ });
+ });
+
+ it('rejects a block that cannot attribute the burn', () => {
+ // Family AND step are both required: without the family nothing can credit a
+ // provider refusal, and without the step the run log cannot say what ran.
+ expect(normalizeQuotaBurnProvenance({ stepId: 'step-1' })).toBeNull();
+ expect(normalizeQuotaBurnProvenance({ family: 'grok' })).toBeNull();
+ expect(normalizeQuotaBurnProvenance(null)).toBeNull();
+ expect(normalizeQuotaBurnProvenance('grok')).toBeNull();
+ });
+
+ it('nulls an unreadable limiting reset rather than passing NaN downstream', () => {
+ expect(normalizeQuotaBurnProvenance(provenance({ limitingResetAt: 'soon' })).limitingResetAt).toBeNull();
+ expect(normalizeQuotaBurnProvenance(provenance()).limitingResetAt).toBeNull();
+ });
+});
+
+describe('onDemandRequestMetadata', () => {
+ it('records that the task came from the request queue, and who asked', () => {
+ expect(onDemandRequestMetadata({ id: 'demand-1', origin: 'user' }))
+ .toEqual({ onDemand: true, onDemandOrigin: 'user' });
+ expect(onDemandRequestMetadata({ id: 'demand-2', origin: 'refill' }))
+ .toEqual({ onDemand: true, onDemandOrigin: 'refill' });
+ });
+
+ it('leaves the origin null when the request predates the field', () => {
+ // Readers treat a null origin as a human Run — the safe default for a queue
+ // that is otherwise human-filled.
+ expect(onDemandRequestMetadata({ id: 'demand-3' }))
+ .toEqual({ onDemand: true, onDemandOrigin: null });
+ });
+
+ it('stamps the burn provenance and request identity a burn task must carry', () => {
+ expect(onDemandRequestMetadata({
+ id: 'demand-7',
+ origin: 'quota-burn',
+ burn: provenance({ limitingResetAt: 42, overrides: { providerId: 'grok-tui' } }),
+ })).toEqual({
+ onDemand: true,
+ onDemandOrigin: 'quota-burn',
+ quotaBurnFamily: 'grok',
+ quotaBurnLimitingResetAt: 42,
+ quotaBurnStepId: 'step-1',
+ quotaBurnRequestId: 'demand-7',
+ provider: 'grok-tui',
+ });
+ });
+
+ it('omits an absent limiting reset instead of writing null onto the task', () => {
+ // `cosTaskStore` only persists a FINITE `quotaBurnLimitingResetAt`; emitting
+ // an explicit null here would make the raw-task path disagree with it.
+ expect(onDemandRequestMetadata({ id: 'demand-7', origin: 'quota-burn', burn: provenance() }))
+ .not.toHaveProperty('quotaBurnLimitingResetAt');
+ });
+
+ it('adds no burn keys for a request whose provenance cannot be attributed', () => {
+ expect(onDemandRequestMetadata({ id: 'demand-8', origin: 'quota-burn', burn: { family: 'grok' } }))
+ .toEqual({ onDemand: true, onDemandOrigin: 'quota-burn' });
+ });
+});
diff --git a/server/routes/cosJobRoutes.js b/server/routes/cosJobRoutes.js
index 35d7ea98f7..141d6c32d5 100644
--- a/server/routes/cosJobRoutes.js
+++ b/server/routes/cosJobRoutes.js
@@ -12,6 +12,7 @@ import { getUserTimezone } from '../services/userTimezone.js';
import { asyncHandler, ServerError, failValidation } from '../lib/errorHandler.js';
import { createCosJobSchema, updateCosJobSchema } from '../lib/validation.js';
import { getTaskDataInputCatalog } from '../lib/taskDataInputCatalog.js';
+import { generatedJobTaskFields } from '../lib/autonomousJobTask.js';
const router = Router();
@@ -192,30 +193,14 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {
// them an app-scoped job triggered manually would run in the PortOS root
// (the scheduled path emits the full task object via task:ready and is unaffected).
const taskResult = await cos.addTask({
- description: task.description,
- priority: task.priority,
+ // The generator's own field projection — the app scope, the git-workflow
+ // options, the provider/model/effort pins, the job:spawned markers and the
+ // no-change-success contract — so a manual trigger queues exactly what the
+ // scheduled path emits. Shared with the quota-burn lane
+ // (`quotaBurnInvoke.js`), which layers a different approval posture on top.
+ ...generatedJobTaskFields(task),
context: `Manually triggered autonomous job: ${job.name}`,
- approvalRequired: false,
- app: task.metadata?.app,
- useWorktree: task.metadata?.useWorktree,
- openPR: task.metadata?.openPR,
- simplify: task.metadata?.simplify,
- // Forward the job's AI provider/model override so a manual trigger uses the
- // same provider/model the scheduled path would (addTask maps these top-level
- // keys onto metadata.provider/metadata.model). Effort follows the same path
- // so a manual run cannot silently lose its saved reasoning override.
- provider: task.metadata?.provider,
- model: task.metadata?.model,
- effort: task.metadata?.effort,
- prompt: task.metadata?.prompt,
- // Preserve the markers consumed by the job:spawned listener so Run now
- // records the execution and re-registers the saved schedule.
- autonomousJob: task.metadata?.autonomousJob,
- jobId: task.metadata?.jobId,
- // A marked audit may complete successfully with a verified empty branch;
- // preserve that contract on the manually queued task as well as the
- // scheduled task path.
- noChangeSuccess: task.metadata?.noChangeSuccess
+ approvalRequired: false
}, 'internal', { suppressDequeue: true });
if (!taskResult?.id) {
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 097947bb12..87525a093b 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -837,6 +837,10 @@ async function runAgentSpawn(task) {
// the auto-run-gated queue lane. `isTruthyMeta` accepts the boolean set at
// spawn AND the string `"true"` a COS-TASKS.md round-trip yields.
taskOnDemand: isTruthyMeta(task.metadata?.onDemand),
+ // WHO asked for that on-demand run. `perpetualRefillPlan` needs it to tell
+ // a human Run (which keeps draining) from an automated origin such as a
+ // quota burn (which is one unit and stops).
+ taskOnDemandOrigin: task.metadata?.onDemandOrigin || null,
// The single PR a pr-reviewer run was narrowed to. Same hand-picked-projection
// reason as the keys around it: perpetualRefillPlan must see from the AGENT
// record that this run was scoped, or its untargeted re-issue silently widens
diff --git a/server/services/cos.js b/server/services/cos.js
index 46ee084187..737e4761a7 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -30,6 +30,8 @@ import { schedule as scheduleEvent, cancel as cancelEvent } from './eventSchedul
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';
import { todayInTimezone } from '../lib/timezone.js';
@@ -1086,7 +1088,10 @@ async function spawnDequeuePriority0OnDemand(ctx) {
// 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.
- task.metadata = { ...(task.metadata || {}), onDemand: true };
+ // `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
@@ -1506,6 +1511,13 @@ function agentScheduledType(agent) {
|| null;
}
+/**
+ * The on-demand origins whose completed perpetual run may re-issue itself: a
+ * human Run, and the drain re-issuing itself through the same lane. Everything
+ * else — a quota burn today, whatever is added tomorrow — stops after one unit.
+ */
+const DRAINABLE_ON_DEMAND_ORIGINS = new Set([ON_DEMAND_ORIGINS.USER, ON_DEMAND_ORIGINS.REFILL]);
+
export function isPerpetualRefillCandidate(agent, schedule) {
const analysisType = agentScheduledType(agent);
if (!analysisType) return false;
@@ -1550,6 +1562,16 @@ export function perpetualRefillPlan(agent, schedule) {
// silently promote that click into a sweep of every open contributor PR.
if (agent?.metadata?.taskTargetPullRequest) return { lane: 'skip' };
if (agent?.metadata?.taskOnDemand) {
+ // Which ORIGINS may keep draining in this lane, as an allowlist rather than
+ // a growing list of exclusions — so an automated origin added later fails
+ // CLOSED. A QUOTA BURN invokes exactly ONE unit of its referenced task: the
+ // burn has its own continuation (quotaBurnRunner#onBurnAgentCompleted) behind
+ // the window/reserve/cap ladder, and refilling here as well would walk the
+ // whole backlog outside every one of those gates, on the very subscription
+ // the plan was rationing. An unrecorded origin is a human Run — that is what
+ // a task queued before the field existed is.
+ const origin = agent?.metadata?.taskOnDemandOrigin || ON_DEMAND_ORIGINS.USER;
+ if (!DRAINABLE_ON_DEMAND_ORIGINS.has(origin)) return { lane: 'skip' };
return { lane: 'onDemand', taskType: agentScheduledType(agent), appId: agent?.metadata?.taskApp || null };
}
return { lane: 'queue' };
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index d1fb6b5268..12ce76eb5b 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -2270,6 +2270,34 @@ describe('perpetualRefillPlan — manual vs scheduled drain lane', () => {
)).toEqual({ lane: 'skip' });
});
+ it('does not refill a QUOTA BURN run — a burn invokes exactly one unit', () => {
+ // The burn has its own continuation (quotaBurnRunner#onBurnAgentCompleted)
+ // behind the window/reserve/cap ladder. Letting the perpetual drain refill
+ // too would walk the whole backlog outside every one of those gates, on the
+ // very subscription the plan was rationing.
+ expect(perpetualRefillPlan(
+ agent({ taskAnalysisType: 'claim-issue', taskApp: 'app-42', taskOnDemand: true, taskOnDemandOrigin: 'quota-burn' }),
+ schedule,
+ )).toEqual({ lane: 'skip' });
+ });
+
+ it('does not refill an UNKNOWN on-demand origin either — the lane allowlist fails closed', () => {
+ // The rule is an allowlist, not a list of exclusions: an automated origin
+ // added later must stop after one unit by default rather than silently
+ // acquiring a human Run's drain.
+ expect(perpetualRefillPlan(
+ agent({ taskAnalysisType: 'claim-issue', taskOnDemand: true, taskOnDemandOrigin: 'some-future-automation' }),
+ schedule,
+ )).toEqual({ lane: 'skip' });
+ });
+
+ it('treats an unrecorded origin as a human Run (tasks queued before the field existed)', () => {
+ expect(perpetualRefillPlan(
+ agent({ taskAnalysisType: 'claim-issue', taskOnDemand: true, taskApp: 'app-42' }),
+ schedule,
+ )).toEqual({ lane: 'onDemand', taskType: 'claim-issue', appId: 'app-42' });
+ });
+
it('skips a non-candidate even when it is marked on-demand (disabled / non-perpetual / unknown)', () => {
expect(perpetualRefillPlan(agent({ taskAnalysisType: 'claim-issue-disabled', taskOnDemand: true }), schedule))
.toEqual({ lane: 'skip' });
@@ -2360,18 +2388,16 @@ describe('cos.js source — agent:completed triggers perpetual refill', () => {
expect(returnAfterTrigger).toBeLessThan(queueIdx);
});
- it('the on-demand spawn engine marks generated tasks on-demand and forwards ignoreTaskId to addTask', () => {
- // For the manual continuation to be recognized on completion, the on-demand
- // engine must stamp metadata.onDemand; and 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.
+ it('the on-demand spawn engine forwards ignoreTaskId to addTask', () => {
+ // 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.
const engIdx = COS_SRC.indexOf('async function spawnDequeuePriority0OnDemand');
expect(engIdx, 'spawnDequeuePriority0OnDemand must exist').toBeGreaterThan(-1);
const engSlice = COS_SRC.slice(engIdx, engIdx + 6400);
- expect(
- /onDemand:\s*true/.test(engSlice),
- 'on-demand engine must stamp metadata.onDemand: true before addTask'
- ).toBe(true);
+ // 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.
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'
diff --git a/server/services/cosJobScheduler.js b/server/services/cosJobScheduler.js
index 5ed8475f64..7815dfc16b 100644
--- a/server/services/cosJobScheduler.js
+++ b/server/services/cosJobScheduler.js
@@ -188,6 +188,21 @@ function addSpawningJob(jobId) {
}, 5 * 60 * 1000));
}
+/**
+ * Whether this custom job already has a fire in flight — an agent registered and
+ * running, or one handed to `spawningJobIds` whose agent has not registered yet.
+ *
+ * Exported because a quota burn asks the same question before queuing a job
+ * (`quotaBurnInvoke.js`), and asking only the running-agent half of it — which
+ * is all a caller outside this module can see, since `spawningJobIds` is
+ * process-local — leaves the whole spawn window open to a double-queue.
+ */
+export function isJobFireInFlight(jobId, state) {
+ if (spawningJobIds.has(jobId)) return true;
+ return Object.values(state?.agents || {})
+ .some((agent) => agent?.status === 'running' && agent?.metadata?.jobId === jobId);
+}
+
export function clearSpawningJob(jobId) {
spawningJobIds.delete(jobId);
const timeout = spawningJobTimeouts.get(jobId);
@@ -338,15 +353,8 @@ export async function executeScheduledJob(jobId) {
// Don't re-register the timer here — the job:spawned handler will do it
// after recordJobExecution updates lastRun. Re-registering with stale
// lastRun causes a 1-second re-fire loop.
- if (spawningJobIds.has(jobId)) {
- emitLog('debug', `Job ${job.name} skipped - already spawning`, { jobId });
- return;
- }
- const agentAlreadyRunning = Object.values(state.agents).some(
- a => a.status === 'running' && a.metadata?.jobId === jobId
- );
- if (agentAlreadyRunning) {
- emitLog('debug', `Job ${job.name} skipped - agent already running`, { jobId });
+ if (isJobFireInFlight(jobId, state)) {
+ emitLog('debug', `Job ${job.name} skipped - a fire is already in flight`, { jobId });
return;
}
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index ff9d939ece..a825ff4332 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -30,6 +30,7 @@ import { sanitizeTaskMetadata, PIPELINE_STAGE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS,
import { PATHS } from '../lib/fileUtils.js';
import { MODEL_ABUSE_GUARD_ID, normalizeEligibilityFacts } from '../lib/modelAbuseGuard.js';
import { isPlainObject } from '../lib/objects.js';
+import { onDemandRequestMetadata } 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';
@@ -861,7 +862,10 @@ async function spawnPriority0OnDemand(ctx) {
// 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`.
- task.metadata = { ...(task.metadata || {}), onDemand: true };
+ // `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);
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 22f464302d..d97ad058cc 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -244,13 +244,19 @@ describe('dry-run hook wiring matches each engine execute path', () => {
});
});
-// Both on-demand spawn engines must stamp `metadata.onDemand` on the generated
-// task, 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). The cos.js engine's stamp +
-// ignoreTaskId forwarding is pinned in cos.test.js; this pins the sibling
-// evaluateTasks engine here so the two-engine mirror can't drift by a comment.
-describe('both on-demand engines stamp metadata.onDemand', () => {
+// 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.
+//
+// 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);
@@ -258,15 +264,14 @@ describe('both on-demand engines stamp metadata.onDemand', () => {
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) stamps onDemand before addTask', () => {
- const engine = onDemandStamp(GEN_SRC, 'async function spawnPriority0OnDemand');
- expect(/task\.metadata = \{ \.\.\.\(task\.metadata \|\| \{\}\), onDemand: true \}/.test(engine)).toBe(true);
+ it('evaluateTasks engine (spawnPriority0OnDemand) merges the request metadata before addTask', () => {
+ expect(MERGE.test(onDemandStamp(GEN_SRC, 'async function spawnPriority0OnDemand'))).toBe(true);
});
- it('dequeueNextTask engine (spawnDequeuePriority0OnDemand) stamps onDemand before addTask', () => {
- const engine = onDemandStamp(COS_SRC, 'async function spawnDequeuePriority0OnDemand');
- expect(/task\.metadata = \{ \.\.\.\(task\.metadata \|\| \{\}\), onDemand: true \}/.test(engine)).toBe(true);
+ it('dequeueNextTask engine (spawnDequeuePriority0OnDemand) merges the request metadata before addTask', () => {
+ expect(MERGE.test(onDemandStamp(COS_SRC, 'async function spawnDequeuePriority0OnDemand'))).toBe(true);
});
});
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 35cecd4009..88d3f2b322 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -538,6 +538,12 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
if (Number.isFinite(taskData.quotaBurnLimitingResetAt)) {
metadata.quotaBurnLimitingResetAt = taskData.quotaBurnLimitingResetAt;
}
+ // Which STEP of the plan asked. The built-in lane stamps this (and the
+ // request id) straight onto the generated task's metadata via
+ // `lib/quotaBurnOrigin.js`; a custom-job burn reaches disk through this
+ // non-raw path instead, so the key has to be mapped here or the two lanes
+ // would carry different provenance for the same feature.
+ if (taskData.quotaBurnStepId) metadata.quotaBurnStepId = taskData.quotaBurnStepId;
if (planOnly) {
// Plan-and-file is a single bounded CoS action. The bundled plan-task
// command is already issue-only, so pass its supported `--yes` flag to
diff --git a/server/services/quotaBurnInvoke.js b/server/services/quotaBurnInvoke.js
new file mode 100644
index 0000000000..57d18ea88b
--- /dev/null
+++ b/server/services/quotaBurnInvoke.js
@@ -0,0 +1,503 @@
+/**
+ * The ONE path a quota-burn step takes to run its work.
+ *
+ * A burn step is a REFERENCE to a scheduled task the user already owns
+ * (`lib/quotaBurnTaskRef.js`), so "running" it means invoking that task the way
+ * anything else invokes it — never re-implementing it. That is the whole point
+ * of the reference model: the legacy `quotaBurnJobs/agentPrompt.js` executor
+ * calls `cosTaskStore.addTask` directly with a synthesized free-form task, which
+ * walks past canonical task generation and every gate that lives in it. That
+ * executor still runs the un-migrated legacy steps until #6381 converts them and
+ * retires it; nothing NEW goes through it.
+ *
+ * Three reference shapes, three canonical invocations — and no fourth:
+ *
+ * built-in AGENT task → `taskSchedule.triggerOnDemandTask(type, appId,
+ * { origin: QUOTA_BURN, burn })`. The on-demand
+ * engines generate the task; acceptance is
+ * ASYNCHRONOUS, and the burn provenance rides on the
+ * request (`lib/quotaBurnOrigin.js`).
+ * built-in PROGRAMMATIC → `scheduledHandlers.runScheduledHandler` directly,
+ * with the burning `family`. That registry documents
+ * the burn as its second sanctioned caller precisely
+ * so the render backend stays pinned to the
+ * subscription being drained; routing it through the
+ * request queue would drop `family` on the floor
+ * (`cosTaskGenerator#drainProgrammaticOnDemandRequests`
+ * passes none) and spend the wrong provider.
+ * CUSTOM app job → `autonomousJobs.generateTaskFromJob` + `addTask`,
+ * the same pair the scheduled fire uses.
+ *
+ * **This is not the manual endpoint.** `routes/cosJobRoutes.js`'s
+ * `POST /jobs/:id/trigger` deliberately hands a human three privileges an
+ * unattended burn must never inherit — `approvalRequired: false` regardless of
+ * the job's autonomy level, `forceSpawnTask` past the autonomous scheduling
+ * gates, and `reviveBlockedTask` on a failure-blocked twin. A burn queues the
+ * task and stops: the daemon decides when it spawns, a blocked twin stays
+ * blocked, and a job that would need a human to approve it is REFUSED rather
+ * than parked awaiting approval — parking one would consume the family's
+ * dispatch budget for work that spends nothing.
+ *
+ * `force` reaches here already meaning "the user clicked ▶": it bypasses the
+ * QUOTA gates in `quotaBurn.js#evaluateFamily`, and nothing else. Task
+ * eligibility, approval, scope and enabled state all still hold — those are
+ * facts about whether the work may run at all, not about this window's budget.
+ */
+
+import {
+ QUOTA_BURN_TASK_REF_KIND,
+ QUOTA_BURN_UNAVAILABLE,
+ resolveQuotaBurnStepAvailability,
+} from '../lib/quotaBurnTaskRef.js';
+import { generatedJobTaskFields } from '../lib/autonomousJobTask.js';
+import { isProgrammaticScheduledTaskType } from '../lib/taskTargetScope.js';
+import { ON_DEMAND_ORIGINS } from './taskScheduleConstants.js';
+
+/** The autonomy level a custom job must carry for an UNATTENDED burn to run it. */
+const UNATTENDED_AUTONOMY_LEVEL = 'yolo';
+
+const declined = (reason) => ({ dispatched: false, reason });
+const noWork = (detail) => ({ count: 0, detail });
+// `Object.hasOwn`, not a truthiness check, so a reference naming an inherited
+// key like `constructor` cannot resolve to anything.
+const entryOf = (map, key) => (map && Object.hasOwn(map, key) ? map[key] : null);
+
+/**
+ * The live task catalog `resolveQuotaBurnStepAvailability` resolves a reference
+ * against: `{ builtin: { [taskType]: { enabled, eligible, appIds } },
+ * custom: { [jobId]: { enabled, eligible, appId } } }`.
+ *
+ * `enabled` folds the instance-FEATURE gate in with the user's switch, because a
+ * feature-off task is equally un-runnable and the reason codes carry no separate
+ * verdict for it; the invocation path re-checks both and reports the precise one.
+ * `eligible` is the picker restriction: a type another automation owns
+ * (`userInvokable: false`) and a custom job that is not an agent job — a shell
+ * command or a built-in script handler — are not things a burn may invoke.
+ *
+ * `appIds` per built-in type is the set of ACTIVE managed apps that have the
+ * type switched on, so a reference to an app that was removed (or had the type
+ * turned off) resolves as wrong-scope instead of silently dispatching nothing.
+ *
+ * Each entry also carries the record it was derived from — the task's schedule
+ * config, the custom job — and the catalog carries the `queued` set of on-demand
+ * requests already waiting, all read off the SAME schedule/app/job snapshot.
+ * `loadSchedule()` is uncached (a disk read plus a deep merge over every default
+ * interval), so going back to the stores per step made the status page's probe
+ * pay that whole cost once per configured step. The pure resolver ignores every
+ * key it does not know.
+ */
+export async function getQuotaBurnTaskCatalog() {
+ const [{ loadSchedule }, { getTaskTypeInvocation }, { getActiveApps }, { createFeatureGate }, { getAllJobs }] =
+ await Promise.all([
+ import('./taskScheduleStore.js'),
+ import('./taskScheduleRegistry.js'),
+ import('./apps.js'),
+ import('./taskSchedule.js'),
+ import('./autonomousJobs.js'),
+ ]);
+
+ const [schedule, apps, jobs] = await Promise.all([
+ loadSchedule(),
+ getActiveApps().catch(() => []),
+ getAllJobs().catch(() => []),
+ ]);
+
+ // The overrides come off the app records `getActiveApps` already returned.
+ // `getAppTaskTypeOverrides(id)` would re-enter the app store twice per app to
+ // produce the same answer for this filter — the legacy migration it also runs
+ // only ever synthesizes `{ enabled: false }` entries, which are exactly what
+ // gets discarded here. Other callers still perform that migration.
+ const appIdsByTaskType = new Map();
+ for (const app of apps) {
+ for (const [taskType, override] of Object.entries(app.taskTypeOverrides || {})) {
+ if (override?.enabled !== true) continue;
+ if (!appIdsByTaskType.has(taskType)) appIdsByTaskType.set(taskType, []);
+ appIdsByTaskType.get(taskType).push(app.id);
+ }
+ }
+
+ // The schedule's own memoized gate, not a second copy: the burn catalog's
+ // `enabled` verdict has to agree with the one `triggerOnDemandTask` applies,
+ // and two implementations of one rule drift silently.
+ const featureEnabled = createFeatureGate();
+ const builtin = {};
+ await Promise.all(Object.entries(schedule?.tasks || {}).map(async ([taskType, config]) => {
+ builtin[taskType] = {
+ enabled: config?.enabled === true && await featureEnabled(config),
+ eligible: getTaskTypeInvocation(taskType).userInvokable !== false,
+ appIds: appIdsByTaskType.get(taskType) || [],
+ config,
+ };
+ }));
+
+ const custom = Object.fromEntries((jobs || []).map((job) => [job.id, {
+ enabled: job.enabled === true,
+ eligible: isBurnEligibleCustomJob(job),
+ appId: job.appId || null,
+ job,
+ }]));
+
+ return { builtin, custom, queued: queuedOnDemandKeys(schedule) };
+}
+
+/** `taskType` + app scope of every on-demand request already waiting to drain. */
+const onDemandKey = (taskType, appId) => `${taskType}::${appId ?? ''}`;
+const queuedOnDemandKeys = (schedule) =>
+ new Set((schedule?.onDemandRequests || []).map((request) => onDemandKey(request.taskType, request.appId)));
+
+/**
+ * Whether a custom app job is something a burn may invoke at all.
+ *
+ * A `shell` job runs an allowlisted command and a `script` job runs a built-in
+ * handler — neither spends provider quota, which is the only thing a burn is
+ * for. Everything else is an agent job (`type` is absent on jobs written before
+ * the field existed, and those are agent jobs).
+ */
+export function isBurnEligibleCustomJob(job) {
+ return Boolean(job) && (!job.type || job.type === 'agent');
+}
+
+/**
+ * Resolve a step against the live catalog into everything an invocation needs,
+ * or the `unavailable` verdict that stops it.
+ *
+ * `effective` is the settings the invocation will actually run with: the step's
+ * per-invocation overrides layered over the referenced task's SAVED settings.
+ * An unset override inherits; nothing here writes back to the schedule or the
+ * job record.
+ */
+export async function resolveQuotaBurnStep(step, catalog = null) {
+ const resolvedCatalog = catalog || await getQuotaBurnTaskCatalog();
+ const unavailable = resolveQuotaBurnStepAvailability(step, resolvedCatalog);
+ if (unavailable) return { unavailable };
+
+ const ref = step.taskRef;
+ if (ref.kind === QUOTA_BURN_TASK_REF_KIND.CUSTOM) {
+ // An EMPTY catalog (the caller's read failed) answers no existence question,
+ // so the resolver above passed the step through. Display can afford that;
+ // dispatch cannot — with no record to read there are no saved settings to
+ // inherit, and running on the overrides alone would silently change the work.
+ const job = entryOf(resolvedCatalog.custom, ref.jobId)?.job;
+ if (!job) {
+ return { unavailable: { code: QUOTA_BURN_UNAVAILABLE.DANGLING_JOB, reason: `custom scheduled job "${ref.jobId}" could not be read` } };
+ }
+ return { kind: 'custom', catalog: resolvedCatalog, ref, job, effective: effectiveSettings(step, job) };
+ }
+
+ const interval = entryOf(resolvedCatalog.builtin, ref.taskType)?.config;
+ if (!interval) {
+ return { unavailable: { code: QUOTA_BURN_UNAVAILABLE.UNKNOWN_TASK, reason: `scheduled task "${ref.taskType}" could not be read` } };
+ }
+ return {
+ kind: isProgrammaticScheduledTaskType(ref.taskType) ? 'programmatic' : 'builtin',
+ // Handed back so a caller that resolved through a catalog keeps reading that
+ // one snapshot instead of going back to the (uncached) schedule store.
+ catalog: resolvedCatalog,
+ ref,
+ interval,
+ effective: effectiveSettings(step, interval),
+ };
+}
+
+/**
+ * Layer a step's overrides over a task's saved settings.
+ *
+ * Presence, not truthiness: `normalizeQuotaBurnJob` already reduces an unset
+ * override to `null`, so `??` is the correct join — a step that pins nothing
+ * inherits, and a step that pins something wins. `params` MERGE key-by-key
+ * rather than replacing the bag, so overriding one run parameter does not blank
+ * every other saved one.
+ */
+export function effectiveSettings(step, saved) {
+ const overrides = step?.overrides || {};
+ return {
+ providerId: overrides.providerId ?? saved?.providerId ?? null,
+ model: overrides.model ?? saved?.model ?? null,
+ effort: overrides.effort ?? saved?.effort ?? null,
+ params: { ...(saved?.taskMetadata || {}), ...(overrides.params || {}) },
+ };
+}
+
+/**
+ * `countPending(reference) → { count, detail, context? }` — the shared probe
+ * contract the runner's ordered selection and the status page both read.
+ *
+ * Side-effect free, always: it writes nothing, enqueues nothing, and makes no
+ * AI provider call (AGENTS.md — no cold-bootstrap LLM calls; the status page
+ * calls this for every configured step on every load).
+ *
+ * - an eligible AI agent task (built-in or custom) reports ONE ready unit —
+ * a task is one unit of work, and there is no backlog to count;
+ * - an ineligible, disabled, dangling or ALREADY-ACTIVE task reports zero
+ * with the reason, so the runner skips it and the page can say why;
+ * - a programmatic handler reports its own domain backlog count, and may hand
+ * back the opaque `context` its scan produced for `run` to reuse.
+ */
+export async function countQuotaBurnStepPending({ step, family, catalog = null } = {}) {
+ const resolved = await resolveQuotaBurnStep(step, catalog);
+ if (resolved.unavailable) return noWork(resolved.unavailable.reason);
+
+ if (resolved.kind === 'programmatic') {
+ const { countScheduledHandlerPending } = await import('./scheduledHandlers/index.js');
+ return countScheduledHandlerPending({
+ taskType: resolved.ref.taskType,
+ params: resolved.effective.params,
+ job: resolved.effective,
+ family,
+ });
+ }
+
+ // Approval outranks the provider check, matching the order `runCustomJobStep`
+ // applies — a job the burn may never run at all should say so rather than
+ // report a provider problem the user would then go and "fix".
+ const approval = resolved.kind === 'custom' ? unattendedApprovalRefusal(resolved.job) : null;
+ if (approval) return noWork(approval);
+
+ // Both agent lanes need a provider in the burning family before they can
+ // report a ready unit — a step whose family has none is not "one unit of work
+ // waiting", it is unrunnable, and the runner has to move to the next step
+ // rather than dispatch onto some other subscription.
+ const picked = await resolveStepProvider(resolved.effective, family);
+ if (picked.error) return noWork(picked.error);
+
+ if (resolved.kind === 'custom') {
+ const active = await activeCustomJobReason(resolved.job);
+ return active ? noWork(active) : { count: 1, detail: `ready to queue "${resolved.job.name}" via ${picked.provider.id}` };
+ }
+
+ const queued = await queuedOnDemandReason(resolved.catalog?.queued, resolved.ref.taskType, resolved.ref.appId);
+ return queued
+ ? noWork(queued)
+ : { count: 1, detail: `ready to run scheduled task "${resolved.ref.taskType}" via ${picked.provider.id}` };
+}
+
+/**
+ * The provider a burn will actually spend, or a refusal.
+ *
+ * A burn exists to draw down ONE family's window, so this is not optional
+ * plumbing: without it a step whose family has no enabled CLI/TUI provider would
+ * queue on whatever the daemon picks and spend a different subscription
+ * entirely, and a pin naming another family's provider would do the same on
+ * purpose. `providerForFamily` honors an explicit pin WITHOUT re-checking its
+ * family (by design — the pin is how you name a specific binary), so the family
+ * check is made here, against the resolved provider record rather than its id:
+ * the command basename is what identifies a family (`antigravity-cli` is
+ * `agy`), and an id-substring rule strands whole families.
+ *
+ * Programmatic handlers do NOT come through here — each resolves its own
+ * backend from the `family` it is handed (`prefer: 'cli'`, and the render
+ * backend is not always a provider at all).
+ */
+async function resolveStepProvider(effective, family) {
+ const { noProviderReason, matchesFamily, resolveBurnProvider } = await import('./scheduledHandlers/providerPick.js');
+ const provider = await resolveBurnProvider({ job: { providerId: effective.providerId }, family });
+ if (!provider) {
+ return {
+ error: effective.providerId
+ ? `pinned provider "${effective.providerId}" is not an enabled CLI/TUI provider`
+ : noProviderReason(family),
+ };
+ }
+ if (!matchesFamily(provider, family.id)) {
+ return { error: `pinned provider "${provider.id}" does not belong to the ${family.id} family` };
+ }
+ return { provider };
+}
+
+/**
+ * Why an unattended burn may not run this custom job, or null.
+ *
+ * `autonomyLevel` is the job's own statement about whether it may run without a
+ * human confirming it (`generateTaskFromJob` turns `yolo` into `autoApprove`).
+ * Anything below that needs an approval a burn cannot give, and the manual
+ * endpoint's `approvalRequired: false` is exactly the bypass this path must not
+ * inherit — so it refuses instead, with the level named so the row is
+ * actionable.
+ */
+function unattendedApprovalRefusal(job) {
+ return job.autonomyLevel === UNATTENDED_AUTONOMY_LEVEL
+ ? null
+ : `custom scheduled job "${job.name}" needs approval to run (autonomy level "${job.autonomyLevel || 'manager'}") — a quota burn cannot approve it`;
+}
+
+/**
+ * Whether an equivalent invocation of this custom job is already in flight.
+ *
+ * `cosJobScheduler.isJobFireInFlight` is the scheduler's OWN admission check,
+ * shared rather than copied: half of it (`spawningJobIds`) is process-local
+ * state a re-implementation here could not see at all, which would leave the
+ * whole spawn window open for a burn to double-queue a job the clock just fired.
+ */
+async function activeCustomJobReason(job) {
+ const [{ loadState }, { isJobFireInFlight }] = await Promise.all([
+ import('./cosState.js'),
+ import('./cosJobScheduler.js'),
+ ]);
+ const state = await loadState().catch(() => null);
+ if (!state) return null;
+ return isJobFireInFlight(job.id, state) ? `a run of "${job.name}" is already in flight` : null;
+}
+
+/**
+ * Whether this built-in task already has an on-demand request waiting.
+ *
+ * Two burn cycles can otherwise stack requests for the same task faster than the
+ * engines drain them: the second would spend the family's budget on a task the
+ * first already asked for. `addTask`'s duplicate detection catches the collision
+ * one step later, but only after the cap was already charged.
+ */
+async function queuedOnDemandReason(queued, taskType, appId) {
+ const pending = queued instanceof Set
+ ? queued.has(onDemandKey(taskType, appId))
+ // No snapshot (a caller passed a bare catalog, or the read failed): ask the
+ // schedule directly rather than reporting "nothing queued", which would let
+ // a second cycle stack a duplicate request onto the family's budget.
+ : (await import('./taskSchedule.js')
+ .then(({ getOnDemandRequests }) => getOnDemandRequests())
+ .catch(() => []))
+ .some((request) => onDemandKey(request.taskType, request.appId) === onDemandKey(taskType, appId));
+ return pending ? `an on-demand run of "${taskType}" is already queued` : null;
+}
+
+/**
+ * Invoke one burn step. Returns the registry's dispatch shape —
+ * `{ dispatched, summary?, reason?, detail? }` — so the runner's accounting,
+ * run log and skip reporting read identically whichever reference shape ran.
+ *
+ * A decline is reported, never thrown: work that failed to start must not
+ * charge the window's cap.
+ */
+export async function invokeQuotaBurnStep({ step, family, candidate, context, force = false, catalog = null } = {}) {
+ const resolved = await resolveQuotaBurnStep(step, catalog);
+ if (resolved.unavailable) return declined(resolved.unavailable.reason);
+
+ if (resolved.kind === 'programmatic') return runProgrammaticStep({ resolved, family, context, force });
+ if (resolved.kind === 'custom') return runCustomJobStep({ resolved, step, family, candidate });
+ return runBuiltinTaskStep({ resolved, step, family, candidate });
+}
+
+/**
+ * A programmatic handler runs INLINE — PortOS performs the work itself, spawns
+ * no agent and consumes no slot, so there is nothing to generate and nothing to
+ * wait for. `family` is what keeps the render backend pinned to the window being
+ * drained (see `scheduledHandlers/index.js`).
+ */
+async function runProgrammaticStep({ resolved, family, context, force }) {
+ const { runScheduledHandler } = await import('./scheduledHandlers/index.js');
+ return runScheduledHandler({
+ taskType: resolved.ref.taskType,
+ params: resolved.effective.params,
+ job: resolved.effective,
+ family,
+ context,
+ force,
+ });
+}
+
+/**
+ * A built-in agent task goes through the schedule's own on-demand lane, so the
+ * master Improve gate, the enabled + instance-feature gates, target scope and
+ * invocation eligibility are all enforced by `triggerOnDemandTask` itself rather
+ * than restated here — one ladder, not two.
+ *
+ * `force` is NOT passed through: it means "past the quota gates", and the
+ * schedule's gates are not quota gates.
+ */
+async function runBuiltinTaskStep({ resolved, step, family, candidate }) {
+ const picked = await resolveStepProvider(resolved.effective, family);
+ if (picked.error) return declined(picked.error);
+
+ const { triggerOnDemandTask } = await import('./taskSchedule.js');
+ const request = await triggerOnDemandTask(resolved.ref.taskType, resolved.ref.appId, {
+ origin: ON_DEMAND_ORIGINS.QUOTA_BURN,
+ burn: {
+ family: family.id,
+ stepId: step.id,
+ limitingResetAt: candidate?.limitingResetAt ?? null,
+ overrides: {
+ // The RESOLVED provider, not the step's pin: an unpinned step must still
+ // land on this family's provider rather than the daemon's active one, or
+ // the burn spends a window nobody asked it to.
+ providerId: picked.provider.id,
+ model: resolved.effective.model,
+ effort: resolved.effective.effort,
+ },
+ },
+ });
+ if (request?.error) return declined(request.error);
+
+ console.log(`🔥 Quota-burn requested scheduled task ${resolved.ref.taskType} for ${family.id} (${request.id})`);
+ return {
+ dispatched: true,
+ summary: `Requested "${resolved.ref.taskType}"${resolved.ref.appId ? ` for ${resolved.ref.appId}` : ''}`,
+ detail: {
+ requestId: request.id,
+ taskType: resolved.ref.taskType,
+ appId: resolved.ref.appId,
+ providerId: picked.provider.id,
+ model: resolved.effective.model,
+ effort: resolved.effective.effort,
+ },
+ };
+}
+
+/**
+ * A custom app job is generated by the job's own generator and queued with
+ * `addTask` — the same pair the scheduled fire uses — carrying the step's
+ * provider/model/effort overrides and the burn provenance.
+ *
+ * `approvalRequired` follows the job's autonomy level (already gated to `yolo`
+ * above, so it lands `false` legitimately rather than by bypass); no
+ * `forceSpawnTask`, and a blocked twin is reported as a decline instead of
+ * revived. See this module's header for why each of those matters.
+ */
+async function runCustomJobStep({ resolved, step, family, candidate }) {
+ const approval = unattendedApprovalRefusal(resolved.job);
+ if (approval) return declined(approval);
+ const picked = await resolveStepProvider(resolved.effective, family);
+ if (picked.error) return declined(picked.error);
+
+ const [{ generateTaskFromJob }, { addTask }] = await Promise.all([
+ import('./autonomousJobs.js'),
+ import('./cosTaskStore.js'),
+ ]);
+ const generated = await generateTaskFromJob(resolved.job);
+ const persisted = await addTask({
+ // The generator's own field projection, shared with the manual endpoint so
+ // a key added to `generateTaskFromJob` cannot reach one lane and not the
+ // other. Everything below OVERRIDES it — that is where the two legitimately
+ // differ.
+ ...generatedJobTaskFields(generated),
+ context: `Quota burn (${family.id}): ${resolved.job.name}`,
+ approvalRequired: !generated.autoApprove,
+ // The step's overrides win over the job's saved pins (see effectiveSettings),
+ // and an unpinned step still lands on THIS family's provider.
+ provider: picked.provider.id,
+ model: resolved.effective.model || undefined,
+ effort: resolved.effective.effort || undefined,
+ // Same provenance keys the built-in lane stamps via the request, so
+ // `isCooldownExemptTask`, the completion continuation and the denial ledger
+ // cannot tell the two lanes apart.
+ quotaBurnFamily: family.id,
+ quotaBurnLimitingResetAt: candidate?.limitingResetAt ?? null,
+ quotaBurnStepId: step.id,
+ }, 'internal', { suppressDequeue: true });
+
+ if (!persisted?.id) return declined(`"${resolved.job.name}" was not queued`);
+ // A blocked twin stays blocked: reviving it is the manual endpoint's explicit
+ // retry, and an unattended burn has no such intent to express.
+ if (persisted.duplicate) return declined(`an identical "${resolved.job.name}" task is already ${persisted.status}`);
+
+ console.log(`🔥 Quota-burn queued custom job ${resolved.job.id} as task ${persisted.id} for ${family.id}`);
+ return {
+ dispatched: true,
+ summary: `Queued "${resolved.job.name}" via ${picked.provider.id}`,
+ detail: {
+ taskId: persisted.id,
+ jobId: resolved.job.id,
+ providerId: picked.provider.id,
+ model: resolved.effective.model,
+ effort: resolved.effective.effort,
+ },
+ };
+}
diff --git a/server/services/quotaBurnInvoke.test.js b/server/services/quotaBurnInvoke.test.js
new file mode 100644
index 0000000000..e26fa5ae57
--- /dev/null
+++ b/server/services/quotaBurnInvoke.test.js
@@ -0,0 +1,489 @@
+/**
+ * The shared quota-burn invocation path.
+ *
+ * Every collaborator this module reaches is a service with its own storage, so
+ * they are doubled and the module's OWN contract is what is under test: which
+ * reference shape routes where, which gate refuses with which reason, what the
+ * effective settings resolve to, and what provenance reaches the queue. The
+ * doubles record their calls so the two negative contracts that matter most —
+ * "a probe writes nothing" and "a burn does not inherit the manual endpoint's
+ * privileges" — are asserted directly rather than inferred.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const state = {
+ schedule: {},
+ apps: [],
+ appOverrides: {},
+ features: {},
+ jobs: [],
+ providers: [],
+ onDemandRequests: [],
+ inFlightJobIds: [],
+ agents: {},
+ triggered: [],
+ triggerResult: null,
+ added: [],
+ addResult: null,
+ handlerCalls: [],
+ handlerPending: { count: 3, detail: '3 entries', context: { scanned: true } },
+ handlerRun: { dispatched: true, summary: 'rendered 3' },
+ generated: null,
+};
+
+vi.mock('./taskScheduleStore.js', () => ({
+ loadSchedule: vi.fn(async () => ({ tasks: state.schedule, onDemandRequests: state.onDemandRequests })),
+}));
+
+vi.mock('./apps.js', () => ({
+ getActiveApps: vi.fn(async () => state.apps.map((app) => ({ ...app, taskTypeOverrides: state.appOverrides[app.id] || {} }))),
+}));
+
+vi.mock('./cosJobScheduler.js', () => ({
+ isJobFireInFlight: vi.fn((jobId) => state.inFlightJobIds.includes(jobId)),
+}));
+
+// `lib/autonomousJobTask.js` is deliberately NOT doubled: it is a pure
+// projection, and the point of sharing it is that the burn lane cannot drop a
+// key the generator emits — a double would assert nothing.
+vi.mock('./autonomousJobs.js', () => ({
+ getAllJobs: vi.fn(async () => state.jobs),
+ generateTaskFromJob: vi.fn(async (job) => (state.generated = {
+ id: `${job.id}-gen`,
+ description: `Run ${job.name}`,
+ priority: 'MEDIUM',
+ autoApprove: job.autonomyLevel === 'yolo',
+ metadata: { autonomousJob: true, jobId: job.id, prompt: 'do the work', app: job.appId || undefined },
+ })),
+}));
+
+vi.mock('./providers.js', () => ({
+ getAllProviders: vi.fn(async () => state.providers),
+}));
+
+vi.mock('./cosState.js', () => ({
+ loadState: vi.fn(async () => ({ agents: state.agents })),
+}));
+
+vi.mock('./cosTaskStore.js', () => ({
+ addTask: vi.fn(async (task, taskType, options) => {
+ state.added.push({ task, taskType, options });
+ return state.addResult ?? { id: 'sys-1', ...task };
+ }),
+}));
+
+vi.mock('./taskSchedule.js', () => ({
+ // The schedule's own memoized gate, doubled at the same altitude the catalog
+ // consumes it — one call per distinct feature id, absent feature => enabled.
+ createFeatureGate: vi.fn(() => async (config) => !config?.feature || state.features[config.feature] !== false),
+ getOnDemandRequests: vi.fn(async () => state.onDemandRequests),
+ triggerOnDemandTask: vi.fn(async (taskType, appId, options) => {
+ state.triggered.push({ taskType, appId, options });
+ return state.triggerResult ?? { id: 'demand-1', taskType, appId, ...options };
+ }),
+}));
+
+vi.mock('./scheduledHandlers/index.js', () => ({
+ countScheduledHandlerPending: vi.fn(async (args) => {
+ state.handlerCalls.push({ op: 'count', ...args });
+ return state.handlerPending;
+ }),
+ runScheduledHandler: vi.fn(async (args) => {
+ state.handlerCalls.push({ op: 'run', ...args });
+ return state.handlerRun;
+ }),
+}));
+
+const {
+ countQuotaBurnStepPending,
+ effectiveSettings,
+ getQuotaBurnTaskCatalog,
+ invokeQuotaBurnStep,
+ isBurnEligibleCustomJob,
+ resolveQuotaBurnStep,
+} = await import('./quotaBurnInvoke.js');
+const { normalizeQuotaBurnJob } = await import('../lib/quotaBurnConfig.js');
+const { addTask } = await import('./cosTaskStore.js');
+
+const grok = { id: 'grok', reservePercent: 0, maxDispatchesPerWindow: -1 };
+const candidate = { limitingResetAt: 1700000000000 };
+
+const step = (raw) => normalizeQuotaBurnJob({ id: 'step-1', enabled: true, ...raw });
+
+beforeEach(() => {
+ state.schedule = {
+ ux: { enabled: true, providerId: null, model: 'saved-model', effort: 'medium', taskMetadata: { fileIssues: true, depth: 'full' } },
+ 'pr-reviewer': { enabled: true, taskMetadata: {} },
+ 'universe-bible-images': { enabled: true, providerId: null, model: null, effort: null, taskMetadata: { maxEntries: 5 } },
+ 'jira-sprint-manager': { enabled: true, feature: 'jira', taskMetadata: {} },
+ 'model-comparison-refresh': { enabled: true, taskMetadata: {} },
+ };
+ state.apps = [{ id: 'app-1', name: 'Example App' }];
+ state.appOverrides = { 'app-1': { ux: { enabled: true }, 'pr-reviewer': { enabled: true } } };
+ state.features = {};
+ state.jobs = [
+ { id: 'job-a', name: 'Nightly sweep', type: 'agent', enabled: true, autonomyLevel: 'yolo', appId: 'app-1', providerId: null, model: null, effort: null, taskMetadata: { useWorktree: true } },
+ { id: 'job-manual', name: 'Needs a human', type: 'agent', enabled: true, autonomyLevel: 'manager' },
+ { id: 'job-shell', name: 'Disk check', type: 'shell', enabled: true, autonomyLevel: 'yolo' },
+ { id: 'job-script', name: 'Catalog refresh', type: 'script', enabled: true, autonomyLevel: 'yolo' },
+ ];
+ state.providers = [
+ { id: 'grok-cli', command: '/usr/local/bin/grok', type: 'cli', enabled: true },
+ { id: 'grok-tui', command: '/usr/local/bin/grok', type: 'tui', enabled: true },
+ { id: 'codex-tui', command: '/usr/local/bin/codex', type: 'tui', enabled: true },
+ ];
+ state.onDemandRequests = [];
+ state.inFlightJobIds = [];
+ state.agents = {};
+ state.triggered = [];
+ state.triggerResult = null;
+ state.added = [];
+ state.addResult = null;
+ state.handlerCalls = [];
+ state.handlerPending = { count: 3, detail: '3 entries', context: { scanned: true } };
+ state.handlerRun = { dispatched: true, summary: 'rendered 3' };
+ state.generated = null;
+ vi.clearAllMocks();
+});
+
+describe('getQuotaBurnTaskCatalog', () => {
+ it('reports a feature-gated task as unavailable while its feature is off', async () => {
+ expect((await getQuotaBurnTaskCatalog()).builtin['jira-sprint-manager'].enabled).toBe(true);
+ state.features.jira = false;
+ expect((await getQuotaBurnTaskCatalog()).builtin['jira-sprint-manager'].enabled).toBe(false);
+ });
+
+ it('lists only the apps that have a built-in type switched on', async () => {
+ state.apps = [{ id: 'app-1' }, { id: 'app-2' }];
+ const { builtin } = await getQuotaBurnTaskCatalog();
+ expect(builtin.ux.appIds).toEqual(['app-1']);
+ });
+
+ it('marks shell and script jobs ineligible and agent jobs eligible', async () => {
+ const { custom } = await getQuotaBurnTaskCatalog();
+ expect(custom['job-a'].eligible).toBe(true);
+ expect(custom['job-shell'].eligible).toBe(false);
+ expect(custom['job-script'].eligible).toBe(false);
+ });
+
+ it('treats a job written before `type` existed as an agent job', () => {
+ expect(isBurnEligibleCustomJob({ id: 'legacy' })).toBe(true);
+ });
+});
+
+describe('resolved effective settings', () => {
+ it('layers the step overrides over the task\'s saved settings and merges params', async () => {
+ const resolved = await resolveQuotaBurnStep(step({
+ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' },
+ overrides: { model: 'burn-model', params: { depth: 'shallow' } },
+ }));
+ expect(resolved.effective).toEqual({
+ providerId: null,
+ model: 'burn-model',
+ effort: 'medium',
+ // `depth` overridden, `fileIssues` inherited — an override replaces one key,
+ // never the whole saved bag.
+ params: { fileIssues: true, depth: 'shallow' },
+ });
+ });
+
+ it('inherits every unset override', () => {
+ expect(effectiveSettings({ overrides: {} }, { providerId: 'p', model: 'm', effort: 'e', taskMetadata: { a: 1 } }))
+ .toEqual({ providerId: 'p', model: 'm', effort: 'e', params: { a: 1 } });
+ });
+});
+
+describe('refusal paths', () => {
+ const refuse = async (raw, family = grok) =>
+ invokeQuotaBurnStep({ step: step(raw), family, candidate });
+
+ const dispatchedNothing = () => {
+ expect(state.triggered).toHaveLength(0);
+ expect(state.added).toHaveLength(0);
+ expect(state.handlerCalls.filter((call) => call.op === 'run')).toHaveLength(0);
+ };
+
+ it('refuses a disabled task type', async () => {
+ state.schedule.ux.enabled = false;
+ const result = await refuse({ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } });
+ expect(result).toEqual({ dispatched: false, reason: expect.stringContaining('is disabled') });
+ dispatchedNothing();
+ });
+
+ it('refuses a task whose instance feature is off', async () => {
+ state.features.jira = false;
+ const result = await refuse({ taskRef: { kind: 'builtin', taskType: 'jira-sprint-manager' } });
+ expect(result.dispatched).toBe(false);
+ expect(result.reason).toContain('is disabled');
+ dispatchedNothing();
+ });
+
+ it('refuses a built-in reference this install does not ship', async () => {
+ const result = await refuse({ taskRef: { kind: 'builtin', taskType: 'not-a-task' } });
+ expect(result.reason).toContain('is not available on this install');
+ dispatchedNothing();
+ });
+
+ it('refuses a managed-app type with no app named, and an install-wide type with one', async () => {
+ expect((await refuse({ taskRef: { kind: 'builtin', taskType: 'pr-reviewer' } })).reason)
+ .toContain('must name a managed app');
+ expect((await refuse({ taskRef: { kind: 'builtin', taskType: 'model-comparison-refresh', appId: 'app-1' } })).reason)
+ .toContain('runs install-wide');
+ dispatchedNothing();
+ });
+
+ it('refuses an app the type is not configured for', async () => {
+ const result = await refuse({ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-9' } });
+ expect(result.reason).toContain('not configured for app "app-9"');
+ dispatchedNothing();
+ });
+
+ it('refuses a dangling custom-job reference', async () => {
+ const result = await refuse({ taskRef: { kind: 'custom', jobId: 'job-gone' } });
+ expect(result.reason).toContain('no longer exists');
+ dispatchedNothing();
+ });
+
+ it('refuses a custom job that would need a human to approve it', async () => {
+ const result = await refuse({ taskRef: { kind: 'custom', jobId: 'job-manual' } });
+ expect(result.reason).toContain('needs approval to run');
+ expect(result.reason).toContain('manager');
+ dispatchedNothing();
+ });
+
+ it('refuses a shell job, which spends no provider quota at all', async () => {
+ const result = await refuse({ taskRef: { kind: 'custom', jobId: 'job-shell' } });
+ expect(result.reason).toContain('cannot be invoked by a quota burn');
+ dispatchedNothing();
+ });
+
+ it('refuses a provider pin belonging to another family', async () => {
+ const result = await refuse({
+ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' },
+ overrides: { providerId: 'codex-tui' },
+ });
+ expect(result.reason).toContain('does not belong to the grok family');
+ dispatchedNothing();
+ });
+
+ it('refuses when the burning family has no enabled CLI/TUI provider', async () => {
+ state.providers = [{ id: 'codex-tui', command: '/usr/local/bin/codex', type: 'tui', enabled: true }];
+ const result = await refuse({ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } });
+ expect(result.reason).toContain('no enabled CLI/TUI provider in the grok family');
+ dispatchedNothing();
+ });
+
+ it('still refuses an ineligible or unapproved task under force', async () => {
+ // `force` means "past the QUOTA gates" (window / reserve / cap / denial) and
+ // nothing more — eligibility and approval are facts about whether the work
+ // may run at all, which no amount of user intent changes.
+ const forced = (raw) => invokeQuotaBurnStep({ step: step(raw), family: grok, candidate, force: true });
+ expect((await forced({ taskRef: { kind: 'custom', jobId: 'job-shell' } })).dispatched).toBe(false);
+ expect((await forced({ taskRef: { kind: 'custom', jobId: 'job-manual' } })).reason).toContain('needs approval');
+ state.schedule.ux.enabled = false;
+ expect((await forced({ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } })).reason).toContain('is disabled');
+ dispatchedNothing();
+ });
+
+ it('refuses when the catalog could not be read, rather than running on overrides alone', async () => {
+ // An empty catalog is what a transient store failure degrades to. Display
+ // tolerates it (the plan is not orphaned); dispatch must not — with no saved
+ // record to inherit from, the work would silently become something else.
+ const result = await invokeQuotaBurnStep({
+ step: step({ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }),
+ family: grok,
+ candidate,
+ catalog: {},
+ });
+ expect(result.reason).toContain('could not be read');
+ dispatchedNothing();
+ });
+
+ it('refuses an un-migrated legacy step rather than guessing a reference for it', async () => {
+ const result = await refuse({ jobType: 'agent-prompt', params: { appId: 'app-1', prompt: 'go' } });
+ expect(result.reason).toContain('waiting to be migrated');
+ dispatchedNothing();
+ });
+});
+
+describe('built-in agent task invocation', () => {
+ const uxStep = () => step({
+ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' },
+ overrides: { effort: 'high' },
+ });
+
+ it('routes through the schedule\'s on-demand lane with quota-burn provenance', async () => {
+ const result = await invokeQuotaBurnStep({ step: uxStep(), family: grok, candidate });
+ expect(result.dispatched).toBe(true);
+ expect(state.triggered).toEqual([{
+ taskType: 'ux',
+ appId: 'app-1',
+ options: {
+ origin: 'quota-burn',
+ burn: {
+ family: 'grok',
+ stepId: 'step-1',
+ limitingResetAt: candidate.limitingResetAt,
+ // The RESOLVED provider, and the family's TUI at that — an unpinned
+ // step must not fall through to whatever the daemon is running.
+ overrides: { providerId: 'grok-tui', model: 'saved-model', effort: 'high' },
+ },
+ },
+ }]);
+ // Canonical generation owns the task; nothing is queued behind its back.
+ expect(state.added).toHaveLength(0);
+ });
+
+ it('reports the schedule\'s own refusal verbatim instead of dispatching', async () => {
+ state.triggerResult = { error: 'Improvement is disabled — enable it in CoS → Config to run on-demand tasks' };
+ const result = await invokeQuotaBurnStep({ step: uxStep(), family: grok, candidate });
+ expect(result).toEqual({ dispatched: false, reason: state.triggerResult.error });
+ });
+});
+
+describe('custom app job invocation', () => {
+ const jobStep = () => step({ taskRef: { kind: 'custom', jobId: 'job-a' }, overrides: { model: 'burn-model' } });
+
+ it('queues through the job\'s own generator with the step\'s overrides and burn provenance', async () => {
+ const result = await invokeQuotaBurnStep({ step: jobStep(), family: grok, candidate });
+ expect(result.dispatched).toBe(true);
+ expect(state.added).toHaveLength(1);
+ const [{ task, taskType, options }] = state.added;
+ expect(taskType).toBe('internal');
+ expect(options).toEqual({ suppressDequeue: true });
+ expect(task).toMatchObject({
+ // Carried by the shared `generatedJobTaskFields` projection…
+ jobId: 'job-a',
+ autonomousJob: true,
+ app: 'app-1',
+ // …and overridden by the burn's own posture.
+ provider: 'grok-tui',
+ model: 'burn-model',
+ quotaBurnFamily: 'grok',
+ quotaBurnStepId: 'step-1',
+ quotaBurnLimitingResetAt: candidate.limitingResetAt,
+ });
+ });
+
+ it('does NOT inherit the manual endpoint\'s approval bypass, force-spawn or revive', async () => {
+ await invokeQuotaBurnStep({ step: jobStep(), family: grok, candidate });
+ const [{ task }] = state.added;
+ // The manual endpoint hardcodes `approvalRequired: false`; a burn derives it
+ // from the job's own autonomy level (gated to `yolo`, so it lands false
+ // legitimately) — the value is the same here, the SOURCE is the contract.
+ expect(task.approvalRequired).toBe(false);
+ expect(addTask).toHaveBeenCalledTimes(1);
+ // The absence of a call is only assertable by reading the source. Comments
+ // are stripped first, or the module header explaining WHY it must not use
+ // these would defeat the guard — and `./cos.js` is checked too, since it is
+ // the only module either escalation could come from.
+ const code = (await import('fs'))
+ .readFileSync(new URL('./quotaBurnInvoke.js', import.meta.url), 'utf8')
+ .replace(/\/\*[\s\S]*?\*\//g, '')
+ .replace(/(^|[^:])\/\/.*$/gm, '$1');
+ // The stripper must not have blanked the file — without this the two
+ // negative assertions below pass on an empty string.
+ expect(code).toMatch(/triggerOnDemandTask\s*\(/);
+ expect(code).not.toMatch(/forceSpawnTask\s*\(/);
+ expect(code).not.toMatch(/reviveBlockedTask\s*\(/);
+ expect(code).not.toContain("'./cos.js'");
+ });
+
+ it('declines rather than reviving when a blocked twin already exists', async () => {
+ state.addResult = { id: 'sys-9', duplicate: true, status: 'blocked' };
+ const result = await invokeQuotaBurnStep({ step: jobStep(), family: grok, candidate });
+ expect(result).toEqual({ dispatched: false, reason: expect.stringContaining('already blocked') });
+ });
+});
+
+describe('programmatic handler invocation', () => {
+ const imagesStep = () => step({
+ taskRef: { kind: 'builtin', taskType: 'universe-bible-images' },
+ overrides: { params: { maxEntries: 2 } },
+ });
+
+ it('runs the shared handler inline, pinned to the burning family', async () => {
+ const context = { scanned: true };
+ const result = await invokeQuotaBurnStep({ step: imagesStep(), family: grok, candidate, context, force: true });
+ expect(result).toEqual(state.handlerRun);
+ expect(state.handlerCalls).toEqual([{
+ op: 'run',
+ taskType: 'universe-bible-images',
+ params: { maxEntries: 2 },
+ job: { providerId: null, model: null, effort: null, params: { maxEntries: 2 } },
+ family: grok,
+ context,
+ force: true,
+ }]);
+ // No task, no request: PortOS performs this work itself.
+ expect(state.added).toHaveLength(0);
+ expect(state.triggered).toHaveLength(0);
+ });
+
+ it('reports the handler\'s own backlog count and hands its context back', async () => {
+ const pending = await countQuotaBurnStepPending({ step: imagesStep(), family: grok });
+ expect(pending).toEqual(state.handlerPending);
+ });
+});
+
+describe('countPending contract', () => {
+ it('reports one ready unit for an eligible built-in agent task', async () => {
+ const pending = await countQuotaBurnStepPending({
+ step: step({ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }),
+ family: grok,
+ });
+ expect(pending.count).toBe(1);
+ expect(pending.detail).toContain('ux');
+ });
+
+ it('reports one ready unit for an eligible custom job', async () => {
+ const pending = await countQuotaBurnStepPending({
+ step: step({ taskRef: { kind: 'custom', jobId: 'job-a' } }),
+ family: grok,
+ });
+ expect(pending.count).toBe(1);
+ });
+
+ it('reports zero with a reason for an already-queued built-in run', async () => {
+ state.onDemandRequests = [{ id: 'demand-0', taskType: 'ux', appId: 'app-1' }];
+ const pending = await countQuotaBurnStepPending({
+ step: step({ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }),
+ family: grok,
+ });
+ expect(pending).toEqual({ count: 0, detail: 'an on-demand run of "ux" is already queued' });
+ });
+
+ it('reports zero with a reason while a run of the custom job is already in flight', async () => {
+ // Through the scheduler's OWN admission predicate, which also covers the
+ // spawn window this module cannot see.
+ state.inFlightJobIds = ['job-a'];
+ const pending = await countQuotaBurnStepPending({
+ step: step({ taskRef: { kind: 'custom', jobId: 'job-a' } }),
+ family: grok,
+ });
+ expect(pending).toEqual({ count: 0, detail: 'a run of "Nightly sweep" is already in flight' });
+ });
+
+ it('reports zero with a reason for a disabled, dangling or ineligible reference', async () => {
+ state.jobs = state.jobs.map((job) => (job.id === 'job-a' ? { ...job, enabled: false } : job));
+ const disabled = await countQuotaBurnStepPending({ step: step({ taskRef: { kind: 'custom', jobId: 'job-a' } }), family: grok });
+ expect(disabled).toEqual({ count: 0, detail: expect.stringContaining('is disabled') });
+
+ const dangling = await countQuotaBurnStepPending({ step: step({ taskRef: { kind: 'custom', jobId: 'nope' } }), family: grok });
+ expect(dangling).toEqual({ count: 0, detail: expect.stringContaining('no longer exists') });
+ });
+
+ it('probes without writing, enqueuing, or calling a provider', async () => {
+ const steps = [
+ step({ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }),
+ step({ taskRef: { kind: 'custom', jobId: 'job-a' } }),
+ step({ taskRef: { kind: 'builtin', taskType: 'universe-bible-images' } }),
+ ];
+ for (const one of steps) await countQuotaBurnStepPending({ step: one, family: grok });
+ expect(state.added).toHaveLength(0);
+ expect(state.triggered).toHaveLength(0);
+ // The one handler call a probe may make is the handler's OWN probe, which
+ // carries the same no-side-effects contract.
+ expect(state.handlerCalls.every((call) => call.op === 'count')).toBe(true);
+ });
+});
diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.js
index 1d20f08f79..f3718ea5a2 100644
--- a/server/services/quotaBurnRunner.js
+++ b/server/services/quotaBurnRunner.js
@@ -42,7 +42,9 @@ import { getQuotaBurnCompletions, recordQuotaBurnJobCompletion } from './quotaBu
import { getActiveQuotaBurnBlocks, recordBurnAgentCompletion } from './quotaBurnDenials.js';
import { getQuotaBurnConfig, getQuotaBurnRuns, recordQuotaBurnRun } from './quotaBurnStore.js';
import { countJobPending, runBurnJob } from './quotaBurnJobs/index.js';
+import { countQuotaBurnStepPending, getQuotaBurnTaskCatalog, invokeQuotaBurnStep } from './quotaBurnInvoke.js';
import { familyHasRunnableJobs, familyIsConfigured, jobIsSpent, quotaBurnJobKey } from '../lib/quotaBurnConfig.js';
+import { applyQuotaBurnAvailability } from '../lib/quotaBurnTaskRef.js';
import { windowLabelOf } from '../lib/quotaWindows.js';
import { WAIT } from '../lib/staleWhileRevalidate.js';
import { cosEvents } from './cosEvents.js';
@@ -80,6 +82,50 @@ const selectJobs = (family, { jobId = null, force = false, completions = {} } =
*/
const wireShape = (pending) => ({ count: pending?.count ?? 0, detail: pending?.detail ?? '' });
+/**
+ * The two invocation lanes, chosen by what the step actually names.
+ *
+ * A step carrying a `taskRef` runs through the shared reference path
+ * (`quotaBurnInvoke.js`) — canonical task generation, all its gates. A step
+ * still carrying a legacy `jobType` has no reference to run yet, so it keeps
+ * going through the frozen `JOB_MODULES` registry until #6381's migration
+ * converts it. Never both, and never a guess: `normalizeQuotaBurnJob` already
+ * makes the two mutually exclusive.
+ */
+/**
+ * What a step names, for the run log and the skip report: the scheduled task it
+ * references, or the legacy job type. `jobType` is null on a reference step, so
+ * recording it unconditionally wrote `jobType: undefined` on every one of them.
+ */
+const stepIdentity = (job) => (job?.taskRef
+ ? { taskRef: job.taskRef }
+ : { jobType: job?.jobType ?? null });
+
+const probeStep = ({ job, family, catalog }) => (job?.taskRef
+ ? countQuotaBurnStepPending({ step: job, family, catalog })
+ : countJobPending({ job, family }));
+
+const runStep = ({ job, family, candidate, context, force, catalog }) => (job?.taskRef
+ ? invokeQuotaBurnStep({ step: job, family, candidate, context, force, catalog })
+ : runBurnJob({ job, family, candidate, context, force }));
+
+/**
+ * The live task catalog, read at most once per cycle/status pass and only when a
+ * reference step is actually present — it reads the schedule, the app registry
+ * and the custom-job store, and a plan made entirely of legacy steps needs none
+ * of them, and neither does an unreadable one. Both come back EMPTY rather than
+ * as a third state: `resolveQuotaBurnStepAvailability` reads `{}` as "ask no
+ * catalog questions", so target scope is still judged (it is decidable from the
+ * reference alone), no step is mass-orphaned by a transient read failure, and a
+ * legacy-only plan resolves to exactly the verdict it already had.
+ */
+const catalogFor = async (jobs) => ((jobs || []).some((job) => job?.taskRef)
+ ? await getQuotaBurnTaskCatalog().catch((err) => {
+ console.error(`❌ Quota-burn could not read the scheduled-task catalog: ${err.message}`);
+ return {};
+ })
+ : {});
+
/**
* The plan, re-anchored to start just AFTER the job this family last dispatched.
*
@@ -126,7 +172,7 @@ async function lastDispatchedJobByFamily() {
* and `run` needs the very same scan to know what to render. Without the
* passthrough that multi-megabyte read happened twice per dispatch.
*/
-async function dispatchFromCandidate(candidate, { jobId = null, force = false, afterJobId = null, completions = {} } = {}) {
+async function dispatchFromCandidate(candidate, { jobId = null, force = false, afterJobId = null, completions = {}, catalog = {} } = {}) {
const attempts = [];
// A forced run of a NAMED job skips the pending probe entirely and calls the
// job directly. The probe exists to pick which job in the plan to run; when
@@ -138,14 +184,14 @@ async function dispatchFromCandidate(candidate, { jobId = null, force = false, a
// its own cooldown too.
const targeted = force && jobId;
for (const job of rotatePlanAfter(selectJobs(candidate.family, { jobId, force, completions }), afterJobId)) {
- const pending = targeted ? null : await countJobPending({ job, family: candidate.family });
+ const pending = targeted ? null : await probeStep({ job, family: candidate.family, catalog });
if (pending && !(pending.count > 0)) {
- attempts.push({ jobId: job.id, jobType: job.jobType, skipped: pending.detail || 'no pending work' });
+ attempts.push({ jobId: job.id, ...stepIdentity(job), skipped: pending.detail || 'no pending work' });
continue;
}
- const result = await runBurnJob({ job, family: candidate.family, candidate, context: pending?.context, force });
+ const result = await runStep({ job, family: candidate.family, candidate, context: pending?.context, force, catalog });
if (!result.dispatched) {
- attempts.push({ jobId: job.id, jobType: job.jobType, skipped: result.reason || 'declined' });
+ attempts.push({ jobId: job.id, ...stepIdentity(job), skipped: result.reason || 'declined' });
continue;
}
return { dispatched: true, job, result, attempts };
@@ -322,13 +368,17 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
// cycle, before any dispatch, so two families in the same cycle can't see each
// other's fresh run-log entries.
const cursors = await lastDispatchedJobByFamily();
+ // ONE catalog for the whole cycle. It reads the schedule, the app registry and
+ // the custom-job store, none of which vary per family — building it inside the
+ // loop paid all three once per enabled family, every tick.
+ const catalog = await catalogFor(candidates.flatMap((entry) => entry.family.jobs || []));
// Every eligible family gets its own dispatch — see the module header. The
// loop does NOT break on the first success: `candidates` is already the set
// that passed the full gate ladder, and each entry spends a different
// provider's window.
for (const candidate of candidates) {
const outcome = await dispatchFromCandidate(candidate, {
- jobId, force, completions, afterJobId: cursors.get(candidate.family.id) || null,
+ jobId, force, completions, catalog, afterJobId: cursors.get(candidate.family.id) || null,
});
attempts.push(...outcome.attempts.map((entry) => ({ familyId: candidate.family.id, ...entry })));
if (!outcome.dispatched) continue;
@@ -357,7 +407,7 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
dispatched: true,
familyId: candidate.family.id,
jobId: outcome.job.id,
- jobType: outcome.job.jobType,
+ ...stepIdentity(outcome.job),
dispatchKey: candidate.dispatchKey,
charged: candidate.charge,
hoursUntilReset: Math.round(candidate.hoursUntilReset * 10) / 10,
@@ -416,8 +466,9 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
export async function getQuotaBurnStatus({ refresh = false } = {}) {
// Independent reads: only `quotas` is slow (a PTY scrape on the Refresh path),
// and nothing else waits on it.
- const [config, quotas, dispatches, blocks, completions, runs] = await Promise.all([
- getQuotaBurnConfig(),
+ const configPromise = getQuotaBurnConfig();
+ const [config, quotas, dispatches, blocks, completions, runs, catalog] = await Promise.all([
+ configPromise,
getProviderQuotas({ wait: refresh ? WAIT.FRESH : WAIT.NEVER }).catch((err) => {
console.error(`❌ Quota-burn status could not read provider quota: ${err.message}`);
return [];
@@ -434,6 +485,9 @@ export async function getQuotaBurnStatus({ refresh = false } = {}) {
// while on the cycle's path it is re-spending quota on finished work.
getQuotaBurnCompletions().then((ledger) => ledger || {}),
getQuotaBurnRuns(),
+ // Depends only on the config, never on `quotas` — so it overlaps the PTY
+ // scrape the Refresh path waits on instead of queueing behind it.
+ configPromise.then((cfg) => catalogFor(Object.values(cfg.families).flatMap((family) => family.jobs || []))),
]);
const cards = new Map(quotas.map((card) => [card.family, card]));
@@ -485,13 +539,16 @@ export async function getQuotaBurnStatus({ refresh = false } = {}) {
// for the universe jobs a picked-universe payload. The page renders
// `count` and `detail` only, so shipping the rest would put probe
// internals on the wire and grow with every job type.
- pending: family.enabled && !spent ? wireShape(await countJobPending({ job, family })) : null,
+ pending: family.enabled && !spent ? wireShape(await probeStep({ job, family, catalog })) : null,
};
})),
};
}));
- return { config, status: { running, families, runs } };
+ // Availability is a fact about the catalog RIGHT NOW — a reference whose task
+ // was disabled or deleted has to render its reason and lose its Run affordance
+ // — so it is stamped onto the config the page receives and never onto disk.
+ return { config: applyQuotaBurnAvailability(config, catalog), status: { running, families, runs } };
}
/**
diff --git a/server/services/quotaBurnRunner.test.js b/server/services/quotaBurnRunner.test.js
index 7a009c7e96..93ebd2b477 100644
--- a/server/services/quotaBurnRunner.test.js
+++ b/server/services/quotaBurnRunner.test.js
@@ -18,6 +18,11 @@ const state = {
completionsUnreadable: false,
settled: [],
settleError: null,
+ invokePending: {},
+ invoked: [],
+ invokeResult: undefined,
+ catalog: { builtin: {}, custom: {} },
+ catalogReads: 0,
};
vi.mock('./providerUsage.js', () => ({
@@ -30,6 +35,19 @@ vi.mock('./quotaBurnStore.js', () => ({
recordQuotaBurnRun: vi.fn(async (entry) => { state.runs.unshift(entry); }),
}));
+// The shared REFERENCE path. Doubled at the same altitude as the legacy
+// registry above, so this suite keeps testing the runner's own contract — which
+// lane a step takes, in what order, and what gets charged — rather than a second
+// copy of the invocation logic (`quotaBurnInvoke.test.js` owns that).
+vi.mock('./quotaBurnInvoke.js', () => ({
+ getQuotaBurnTaskCatalog: vi.fn(async () => { state.catalogReads += 1; return state.catalog; }),
+ countQuotaBurnStepPending: vi.fn(async ({ step }) => state.invokePending[step.id] ?? { count: 0, detail: 'nothing' }),
+ invokeQuotaBurnStep: vi.fn(async ({ step, family, candidate, force }) => {
+ state.invoked.push({ stepId: step.id, familyId: family.id, charge: candidate.charge, force });
+ return state.invokeResult ?? { dispatched: true, summary: `invoked ${step.id}` };
+ }),
+}));
+
vi.mock('./quotaBurnJobs/index.js', () => ({
countJobPending: vi.fn(async ({ job }) => state.pending[job.id] ?? { count: 0, detail: 'nothing' }),
runBurnJob: vi.fn(async ({ job, family, candidate, context }) => {
@@ -78,6 +96,7 @@ vi.mock('./quotaBurnCompletions.js', () => ({
}));
const { normalizeQuotaBurnConfig } = await import('../lib/quotaBurnConfig.js');
+const { countJobPending, runBurnJob } = await import('./quotaBurnJobs/index.js');
const { getQuotaBurnStatus, runQuotaBurnCycle, rotatePlanAfter, __tickQuotaBurn, __onBurnAgentCompleted, __resetQuotaBurnRunner } = await import('./quotaBurnRunner.js');
const card = (family, percentRemaining = 50) => ({
@@ -116,6 +135,11 @@ beforeEach(() => {
state.settled = [];
state.settleError = null;
state.jobResult = undefined;
+ state.invokePending = {};
+ state.invoked = [];
+ state.invokeResult = undefined;
+ state.catalog = { builtin: {}, custom: {} };
+ state.catalogReads = 0;
__resetQuotaBurnRunner();
});
@@ -302,8 +326,11 @@ describe('runQuotaBurnCycle', () => {
describe('getQuotaBurnStatus', () => {
it('returns the config it loaded so the route need not re-read it', async () => {
+ // Value, not identity: availability is stamped onto a COPY on the way out
+ // (a fact about the catalog right now, never persisted). The contract is
+ // that the route gets the plan back without a second file read.
const { config } = await getQuotaBurnStatus();
- expect(config).toBe(state.config);
+ expect(config).toStrictEqual(state.config);
});
it('reports the live window and the reason a family would not burn', async () => {
@@ -756,3 +783,95 @@ describe('run-once jobs', () => {
expect(grok.skipReason).toBe('every enabled job has already run once');
});
});
+
+// A step names its work in exactly one of two ways, and the runner has to send
+// each to the right executor: a `taskRef` step through the shared reference path
+// (canonical task generation + its gates), a legacy `jobType` step through the
+// frozen registry until #6381's migration converts it. Sending a reference to the
+// legacy registry would report "unknown job type" forever; sending a legacy step
+// to the reference path would report "waiting to be migrated" and strand every
+// un-upgraded install's plan.
+describe('reference steps route through the shared invocation path', () => {
+ const refPlan = (jobs) => normalizeQuotaBurnConfig({
+ enabled: true,
+ families: { grok: { enabled: true, resetWithinHours: 24, jobs } },
+ });
+
+ it('probes and runs a taskRef step through quotaBurnInvoke, not the legacy registry', async () => {
+ state.config = refPlan([{ id: 'ref', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }]);
+ state.invokePending = { ref: { count: 1, detail: 'ready' } };
+
+ const result = await runQuotaBurnCycle();
+
+ expect(result.dispatched).toBe(true);
+ expect(state.invoked).toEqual([{ stepId: 'ref', familyId: 'grok', charge: true, force: false }]);
+ expect(countJobPending).not.toHaveBeenCalled();
+ expect(runBurnJob).not.toHaveBeenCalled();
+ });
+
+ it('keeps legacy jobType steps on the legacy registry', async () => {
+ state.pending = { second: { count: 1 } };
+ await runQuotaBurnCycle();
+ expect(state.ran.map((entry) => entry.jobId)).toEqual(['second']);
+ expect(state.invoked).toHaveLength(0);
+ });
+
+ it('preserves first-enabled-with-pending-work selection across both lanes', async () => {
+ state.config = refPlan([
+ { id: 'legacy', enabled: true, jobType: 'agent-prompt', params: {} },
+ { id: 'ref', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } },
+ ]);
+ // The legacy step reports nothing to do, so the walk must fall through to the
+ // reference step rather than stopping at the first row.
+ state.pending = { legacy: { count: 0, detail: 'no pending work' } };
+ state.invokePending = { ref: { count: 1, detail: 'ready' } };
+
+ const result = await runQuotaBurnCycle();
+ expect(result.jobId).toBe('ref');
+ expect(state.ran).toHaveLength(0);
+ });
+
+ it('reads the scheduled-task catalog once per cycle, and not at all for a legacy-only plan', async () => {
+ state.config = refPlan([
+ { id: 'a', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } },
+ { id: 'b', enabled: true, taskRef: { kind: 'custom', jobId: 'job-a' } },
+ ]);
+ await runQuotaBurnCycle();
+ expect(state.catalogReads).toBe(1);
+
+ state.catalogReads = 0;
+ state.config = plan();
+ await runQuotaBurnCycle();
+ expect(state.catalogReads).toBe(0);
+ });
+
+ it('threads force through to the reference path so a targeted run skips the probe', async () => {
+ state.config = refPlan([{ id: 'ref', enabled: false, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }]);
+ await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', jobId: 'ref', force: true });
+ expect(state.invoked).toEqual([{ stepId: 'ref', familyId: 'grok', charge: false, force: true }]);
+ // A forced run of a NAMED step bypasses the probe entirely — the click IS the
+ // selection — and comes back uncharged.
+ expect(state.recorded).toHaveLength(0);
+ });
+
+ it('does not charge the window when the reference path declines', async () => {
+ state.config = refPlan([{ id: 'ref', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }]);
+ state.invokePending = { ref: { count: 1 } };
+ state.invokeResult = { dispatched: false, reason: 'scheduled task "ux" is disabled' };
+
+ const result = await runQuotaBurnCycle();
+ expect(result.dispatched).toBe(false);
+ expect(result.reason).toContain('is disabled');
+ expect(state.recorded).toHaveLength(0);
+ });
+
+ it('probes reference steps for the status page through the same path', async () => {
+ state.config = refPlan([{ id: 'ref', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }]);
+ state.invokePending = { ref: { count: 1, detail: 'ready to run scheduled task "ux"' } };
+
+ const { status } = await getQuotaBurnStatus();
+ const grok = status.families.find((family) => family.id === 'grok');
+ expect(grok.jobs).toEqual([{ id: 'ref', ranAt: null, pending: { count: 1, detail: 'ready to run scheduled task "ux"' } }]);
+ expect(countJobPending).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/scheduledHandlers/providerPick.js b/server/services/scheduledHandlers/providerPick.js
index 8061f5a734..cdfbf0aaa7 100644
--- a/server/services/scheduledHandlers/providerPick.js
+++ b/server/services/scheduledHandlers/providerPick.js
@@ -60,8 +60,13 @@ export function providerForFamily(providers, { familyId, providerId, prefer = 't
*
* The id substring stays as a fallback for a provider registered under a wrapper
* script whose basename isn't the family name.
+ *
+ * Exported because `providerForFamily` deliberately honors an explicit
+ * `providerId` pin without re-checking it — a caller that must refuse an
+ * out-of-family pin (`quotaBurnInvoke.js`, where the pin would spend the wrong
+ * subscription) asks this directly rather than re-deriving the rule.
*/
-const matchesFamily = (provider, familyId) => {
+export const matchesFamily = (provider, familyId) => {
const needle = String(familyId || '').toLowerCase();
if (!needle) return false;
return commandBasename(provider.command) === needle
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 7f877effc7..171aa82393 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -34,7 +34,7 @@ import {
ON_DEMAND_ORIGINS,
decodeIntervalType,
isCronExpression,
- isRefillRequest
+ isUserOriginRequest
} from './taskScheduleConstants.js';
import {
DEFAULT_TASK_INTERVALS,
@@ -54,6 +54,7 @@ import { loadSchedule, updateSchedule } from './taskScheduleStore.js';
import { isInstanceFeatureEnabled } from './instanceFeatures.js';
import { recordUserAction } from './userActions.js';
import { getTaskDataInputCatalog } from '../lib/taskDataInputCatalog.js';
+import { normalizeQuotaBurnProvenance } from '../lib/quotaBurnOrigin.js';
import {
clearFailureLedgerFields,
clearTaskTypeFailurePark,
@@ -63,7 +64,7 @@ import {
export { PROMPT_VERSIONS, REFERENCE_WATCH_AUDITED_VERSION } from './taskPromptDefaults.js';
export {
- INTERVAL_TYPES, ON_DEMAND_ORIGINS, isRefillRequest
+ INTERVAL_TYPES, ON_DEMAND_ORIGINS, isRefillRequest, isUserOriginRequest
} from './taskScheduleConstants.js';
export {
DEFAULT_BRANCHES_PER_AGENT, DEFAULT_TASK_INTERVALS, INSTALL_WIDE_TASK_TYPES,
@@ -82,7 +83,7 @@ export {
} from './taskScheduleBackoff.js';
export { addTemplateTask, deleteTemplateTask, getTemplateTasks } from './taskScheduleTemplates.js';
-const createFeatureGate = () => {
+export const createFeatureGate = () => {
const enabledByFeature = new Map();
return async (interval) => {
const featureId = interval?.feature;
@@ -739,7 +740,12 @@ export async function resetPerpetualForManualRun(taskType, appId = null) {
* applied) — callers use it to decide whether user-facing feedback is warranted
*/
export async function applyOnDemandRunResets(request, appId = null) {
- if (isRefillRequest(request)) return false;
+ // Every AUTOMATED origin inherits the brakes — the drain's own refill and a
+ // quota burn alike. Written as "is this a human?" rather than "is this a
+ // refill?" so an origin added later fails CLOSED instead of silently
+ // acquiring a human's park/convergence resets (a burn that cleared them would
+ // re-run a converged drain every time its window opened).
+ if (!isUserOriginRequest(request)) return false;
// A user-initiated "Run" must re-check live state, never honor a stale park or
// convergence verdict.
await resetPerpetualForManualRun(request.taskType, appId);
@@ -1091,12 +1097,21 @@ export async function getNextTaskType(appId = null, { perpetualOnly = false, con
* perpetual drain re-issued ITSELF through the same lane after a completed run —
* automated, and therefore NOT allowed to clear its own brakes.
*/
-export async function triggerOnDemandTask(taskType, appId = null, { emit = true, origin = ON_DEMAND_ORIGINS.USER, targetPullRequest = null } = {}) {
+export async function triggerOnDemandTask(taskType, appId = null, { emit = true, origin = ON_DEMAND_ORIGINS.USER, targetPullRequest = null, burn = null } = {}) {
// A targeted run names ONE open PR/MR instead of letting the task pick from
// the app's whole open set (the PR/MR row's "Review this PR" button). Coerced
// and validated here so a bad value can't reach the generator's forge filter.
const requested = Number(targetPullRequest);
const scopedPullRequest = Number.isInteger(requested) && requested > 0 ? requested : null;
+ // Burn provenance rides ON the request because acceptance is asynchronous —
+ // an on-demand engine generates the task minutes later and stamps these keys
+ // onto it (lib/quotaBurnOrigin.js). Refused BEFORE the schedule write rather
+ // than dropped: an unattributable burn would leave a task that reads as
+ // cooldown-exempt with no family to credit its refusal to.
+ const burnProvenance = origin === ON_DEMAND_ORIGINS.QUOTA_BURN ? normalizeQuotaBurnProvenance(burn) : null;
+ if (origin === ON_DEMAND_ORIGINS.QUOTA_BURN && !burnProvenance) {
+ return { error: 'A quota-burn request must name the burning family and its burn step' };
+ }
const request = await updateSchedule(async (schedule) => {
// Cheap per-task-type check first; the master-flag check pays a state.json read.
const tasks = schedule.tasks || {};
@@ -1110,8 +1125,12 @@ export async function triggerOnDemandTask(taskType, appId = null, { emit = true,
return { result: { error: `Task type '${taskType}' requires the '${tasks[taskType].feature}' feature` }, changed: false };
}
const invocation = getTaskTypeInvocation(taskType);
- if (origin === ON_DEMAND_ORIGINS.USER && !invocation.userInvokable) {
- return { result: { error: `Task type '${taskType}' is managed by another automation and cannot be run manually` }, changed: false };
+ // A quota burn faces this gate alongside a human Run: a type owned by
+ // another automation is not something an unattended burn may commandeer
+ // either. Only the drain's own REFILL is exempt — it is that automation
+ // re-issuing itself.
+ if (origin !== ON_DEMAND_ORIGINS.REFILL && !invocation.userInvokable) {
+ return { result: { error: `Task type '${taskType}' is managed by another automation and cannot be invoked on demand` }, changed: false };
}
if (requiresManagedAppTarget(taskType) && !appId) {
return { result: { error: `Task type '${taskType}' requires a managed app target` }, changed: false };
@@ -1136,7 +1155,8 @@ export async function triggerOnDemandTask(taskType, appId = null, { emit = true,
appId,
origin,
requestedAt: new Date().toISOString(),
- ...(scopedPullRequest ? { targetPullRequest: scopedPullRequest } : {})
+ ...(scopedPullRequest ? { targetPullRequest: scopedPullRequest } : {}),
+ ...(burnProvenance ? { burn: burnProvenance } : {})
};
schedule.onDemandRequests.push(request);
@@ -1149,7 +1169,7 @@ export async function triggerOnDemandTask(taskType, appId = null, { emit = true,
// drain re-issues itself through this same lane with `origin: REFILL` — logging
// that would fill the ledger with events the user never performed and make
// "what did I trigger?" unanswerable.
- if (origin === ON_DEMAND_ORIGINS.USER) {
+ if (isUserOriginRequest(request)) {
await recordUserAction({
type: 'cos.schedule.trigger',
target: taskType,
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 94f1cbd505..d692e751e1 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -2239,12 +2239,77 @@ describe('taskSchedule', () => {
expect(writeFile).not.toHaveBeenCalled()
})
+ it('clears NOTHING for a quota burn either — it is automation, not a human Run', async () => {
+ // A burn that cleared the park would re-run a converged drain every time
+ // its window opened, which is the opposite of "invoke this once".
+ mockSchedule(parked())
+ expect(await applyOnDemandRunResets({ taskType: 'branch-reconcile', origin: ON_DEMAND_ORIGINS.QUOTA_BURN }, 'app-1')).toBe(false)
+ expect(writeFile).not.toHaveBeenCalled()
+ })
+
it('treats a pre-origin request as user-initiated (safe default for a human-filled queue)', async () => {
mockSchedule(parked())
expect(await applyOnDemandRunResets({ taskType: 'branch-reconcile' }, 'app-1')).toBe(true)
})
})
+ // A quota burn asks the schedule to run a task the user already owns. The
+ // request has to carry enough to attribute the burn later — acceptance is
+ // asynchronous, so nothing else can reconstruct it — and it must face the
+ // same invocation-eligibility gate a human Run does.
+ describe('quota-burn origin', () => {
+ const burn = { family: 'grok', stepId: 'step-1', limitingResetAt: 1700000000000, overrides: { providerId: 'grok-tui', model: null, effort: null } }
+ const trigger = (options) => triggerOnDemandTask('security', null, { emit: false, origin: ON_DEMAND_ORIGINS.QUOTA_BURN, ...options })
+
+ it('persists the burn provenance on the queued request', async () => {
+ mockSchedule({ tasks: { security: { type: 'on-demand', enabled: true } } })
+ const request = await trigger({ burn })
+ expect(request.origin).toBe(ON_DEMAND_ORIGINS.QUOTA_BURN)
+ expect(request.burn).toEqual(burn)
+ // And it survives the write, so an engine draining it after a restart
+ // still knows which family and step to credit.
+ const written = JSON.parse(writeFile.mock.calls.at(-1)[1]).onDemandRequests.at(-1)
+ expect(written.burn).toEqual(burn)
+ })
+
+ it('refuses a burn request that cannot be attributed, before touching the schedule', async () => {
+ mockSchedule({ tasks: { security: { type: 'on-demand', enabled: true } } })
+ expect((await trigger({ burn: { family: 'grok' } })).error).toMatch(/must name the burning family and its burn step/)
+ expect(writeFile).not.toHaveBeenCalled()
+ })
+
+ it('is not written to the operator-action ledger', async () => {
+ mockSchedule({ tasks: { security: { type: 'on-demand', enabled: true } } })
+ await trigger({ burn })
+ expect(recordUserAction).not.toHaveBeenCalled()
+ })
+
+ it('faces the same gates a human Run does', async () => {
+ mockSchedule({ tasks: { security: { type: 'on-demand', enabled: false } } })
+ expect((await trigger({ burn })).error).toMatch(/disabled/i)
+ mockSchedule({ tasks: { security: { type: 'on-demand', enabled: true } } })
+ expect((await triggerOnDemandTask('not-a-task', null, { emit: false, origin: ON_DEMAND_ORIGINS.QUOTA_BURN, burn })).error)
+ .toMatch(/Unknown task type/)
+ })
+
+ // The invocation-eligibility gate is the one that cannot be exercised
+ // behaviorally: `TASK_TYPE_INVOCATION` is deliberately empty today, so no
+ // shipped type is subsidiary and there is nothing to refuse. The rule still
+ // has to hold the day one is added, and the failure mode is silent — an
+ // unattended burn commandeering a task another automation owns — so the
+ // shape is pinned here. Only REFILL (that automation re-issuing itself) is
+ // exempt; a burn is gated exactly like a human Run.
+ it('exempts only a drain refill from the invocation-eligibility gate', async () => {
+ // `fs` is doubled for this suite, so read through the real one.
+ const { readFileSync } = await vi.importActual('node:fs')
+ const src = readFileSync(new URL('./taskSchedule.js', import.meta.url), 'utf8')
+ expect(src).toMatch(/if \(origin !== ON_DEMAND_ORIGINS\.REFILL && !invocation\.userInvokable\)/)
+ // Probe: the previous, narrower gate must be gone, or the assertion above
+ // could pass on a file that still only checks USER somewhere else.
+ expect(src).not.toMatch(/origin === ON_DEMAND_ORIGINS\.USER && !invocation\.userInvokable/)
+ })
+ })
+
it('isRefillRequest only matches an explicit refill origin', () => {
expect(isRefillRequest({ origin: ON_DEMAND_ORIGINS.REFILL })).toBe(true)
expect(isRefillRequest({ origin: ON_DEMAND_ORIGINS.USER })).toBe(false)
diff --git a/server/services/taskScheduleConstants.js b/server/services/taskScheduleConstants.js
index c30aab0824..1040614954 100644
--- a/server/services/taskScheduleConstants.js
+++ b/server/services/taskScheduleConstants.js
@@ -38,8 +38,30 @@ export const DEFAULT_PERPETUAL_RECHECK_MS = DAY_MS;
export const FAILURE_BACKOFF_BASE_MS = HOUR_MS;
export const FAILURE_BACKOFF_CAP_MS = DAY_MS;
export const FAILURE_PARK_THRESHOLD = 5;
-export const ON_DEMAND_ORIGINS = { USER: 'user', REFILL: 'refill' };
+/**
+ * Who asked for an on-demand run.
+ *
+ * USER — a human pressed Run. The only origin that clears the drain's
+ * brakes (park, convergence signature, dispatch counter) and the
+ * only one written to the operator-action ledger.
+ * REFILL — the perpetual drain re-issuing ITSELF through the same lane.
+ * QUOTA_BURN — a quota-burn step invoking a task the user already owns
+ * (`quotaBurnInvoke.js`). Automated, so it clears no brakes; it
+ * carries a `burn` provenance block (`lib/quotaBurnOrigin.js`)
+ * naming the family and step, and it is subject to the SAME
+ * invocation-eligibility gate a human Run faces.
+ *
+ * A request written before `origin` existed carries none, which reads as USER.
+ */
+export const ON_DEMAND_ORIGINS = { USER: 'user', REFILL: 'refill', QUOTA_BURN: 'quota-burn' };
export const isRefillRequest = (request) => request?.origin === ON_DEMAND_ORIGINS.REFILL;
+/**
+ * Whether a human asked for this run. Absent origin reads as USER (see above),
+ * so this is NOT `!isRefillRequest` — every automated origin added later fails
+ * CLOSED into "not a human" instead of silently inheriting a human's brakes.
+ */
+export const isUserOriginRequest = (request) =>
+ (request?.origin ?? ON_DEMAND_ORIGINS.USER) === ON_DEMAND_ORIGINS.USER;
const RECONCILE_DRAIN_TASK_TYPES = new Set(['branch-reconcile', 'issue-reconcile']);
export const isReconcileDrainTaskType = (taskType) => RECONCILE_DRAIN_TASK_TYPES.has(taskType);