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

feat: convert legacy quota-burn prompt plans to scheduled-task references (#6381)

[._.]/ Adam Eivy270028d3fb40
diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.md
index 7c1a5af2c2..0a74a93ecf 100644
--- a/docs/QUOTA-BURN.md
+++ b/docs/QUOTA-BURN.md
@@ -528,12 +528,44 @@ model stores a `jobType` and a free-form `params` bag instead of a `taskRef`.
Those steps still **load** — an install upgrading across the reference model must
not lose its plan — and `normalizeQuotaBurnJob` marks each one
`legacy-unmigrated` rather than guessing which scheduled task its copied prompt
-meant. The page renders that reason and no run affordance, so the step keeps its
-place, its order and its name while the conversion service converts it; picking a
-task from the row's own picker converts it by hand at any time. Guessing at
-normalization time would either strand the user's edits or silently duplicate an
-automation, which is why the conversion is a migration rather than a read-time
-inference.
+meant. Guessing at normalization time would either strand the user's edits or
+silently duplicate an automation, which is why the conversion is a migration
+rather than a read-time inference.
+
+Migration `359-quota-burn-task-references.js` performs it, over the one decision
+in `lib/quotaBurnLegacyConversion.js`:
+
+- A prompt that is still a **recognized, unmodified shipped preset** becomes a
+ reference to the scheduled audit it was cloned from (`auditCatalog.js`), with
+ `fileIssues: true` pinned **explicitly** — every burn preset was an issues-only
+ audit, and a scheduled default that says otherwise (or changes later) must not
+ turn it into code-writing work.
+- The two **programmatic** types become references to the scheduled handlers that
+ already implement them, run params intact.
+- Anything **customized, unrecognized, or without a target app** becomes an
+ on-demand **custom scheduled task** holding the user's exact prompt and
+ workflow settings, which the step then references. Recognition is
+ `matchStoredAuditPreset` — migration 305's mission-half rule — never a label
+ and never a partial match: when in doubt the conversion keeps the text, because
+ a preserved prompt is recoverable and a discarded one is not.
+
+Step ids, order, labels, disabled state and `runOnce` survive untouched, so the
+completion ledger, the dispatch ledger and the reservation keys all still resolve.
+A converted built-in reference only becomes **runnable** once its target app has
+that scheduled task enabled — the shared availability ladder decides that, and the
+migration deliberately does not enable a task type on the user's behalf. The
+pre-conversion plan is parked at `data/cos/quota-burn.pre-359.json`.
+
+Until a plan is converted, its steps keep their place, order and name while
+rendering `legacy-unmigrated` and no run affordance — picking a task from the
+row's own picker converts one by hand at any time.
+
+Conversion is idempotent and interrupt-safe: a step that already carries a
+`taskRef` is skipped, and a custom conversion addresses its task by a
+deterministic `job-burn-<family>-<step>` id, so a re-run or a resumed run reuses
+the task it created rather than minting a duplicate automation. The same service
+runs on the PUT path, so a body from an older client is converted before it
+reaches disk instead of being persisted as a step the runner can only refuse.
## Code map
@@ -545,7 +577,8 @@ inference.
| `server/lib/quotaBurnOrigin.js` | Burn provenance on an on-demand request, and the metadata both on-demand engines stamp from it |
| `server/lib/taskTargetScope.js` | Which task types act on one app, install-wide, or are programmatic — read by the resolver and the schema |
| `server/lib/auditCatalog.js` | The audit task types and their file-issues-vs-do-the-work contract |
-| `server/lib/quotaBurnPresets.js` | FROZEN legacy prompt presets — a compatibility input for un-migrated plans |
+| `server/lib/quotaBurnPresets.js` | FROZEN legacy prompt presets — a compatibility input, plus `matchStoredAuditPreset`, the recognition rule migration 359 converts on |
+| `server/lib/quotaBurnLegacyConversion.js` | The ONE legacy-step → reference decision, shared by migration 359 and the PUT compat path |
| `server/lib/universeBibleCompleteness.js` | What "described" means per kind + depth — the field vocabulary the describe task scans with |
| `server/lib/quotaWindows.js` | Classifies a window by period — target (broadest) vs limiting (narrowest) |
| `server/services/quotaBurnInvoke.js` | The shared invocation path: builds the task catalog, resolves a step, layers its overrides, enforces the schedule's own gates, and dispatches |
@@ -556,7 +589,7 @@ inference.
| `server/services/quotaBurnDenials.js` | The observed-refusal ledger and its `agent:completed` subscriber |
| `server/services/quotaBurnRunner.js` | The loop, the cycle, and the status feed (which stamps availability onto the config the page reads) |
| `server/services/scheduledHandlers/` | The programmatic handlers (universe bible descriptions/images) — shared by Scheduled Tasks and Quota Burn |
-| `server/services/quotaBurnJobs/` | The frozen legacy job registry, kept until un-migrated plans are converted |
+| `server/services/quotaBurnConversion.js` | The runtime adapter for that decision: creates the custom task and rewrites the step on a legacy PUT |
| `server/routes/quotaBurn.js` | `/api/quota-burn` — plan, status, apps/providers catalog, manual runs, re-arm |
| `client/src/lib/quotaBurnTasks.js` | The client's view of the shared task catalog: grouping, search, reference keys, effective settings, and the PUT payload |
| `client/src/lib/quotaBurnPatch.js` | The optimistic config merge (mirrors `saveQuotaBurnConfig`) and the dispatch-cap sentinel |
diff --git a/scripts/lib/migrationOwnedPaths.js b/scripts/lib/migrationOwnedPaths.js
index 57e6768917..42d0edca48 100644
--- a/scripts/lib/migrationOwnedPaths.js
+++ b/scripts/lib/migrationOwnedPaths.js
@@ -21,4 +21,11 @@ export const MIGRATION_OWNED_PATHS = new Set([
// to it. Derived from the user's records; a shipped seed would masquerade as
// their pre-graph configuration and destroy the recovery path.
'private/providers.pre-graph.json',
+ // Migration 359 rewrites the install's own burn plan into scheduled-task
+ // references, and parks the pre-conversion copy beside it. Both are derived
+ // from the user's records; a shipped seed would be converted in place of
+ // their plan (setup-data runs first) and would masquerade as the recovery
+ // copy of a plan they never had.
+ 'cos/quota-burn.json',
+ 'cos/quota-burn.pre-359.json',
]);
diff --git a/scripts/migrations/359-quota-burn-task-references.js b/scripts/migrations/359-quota-burn-task-references.js
new file mode 100644
index 0000000000..9d5ae58773
--- /dev/null
+++ b/scripts/migrations/359-quota-burn-task-references.js
@@ -0,0 +1,167 @@
+/**
+ * Convert legacy quota-burn plans into scheduled-task REFERENCES.
+ *
+ * A burn step used to BE its work: a copied prompt in a free-form `params` bag
+ * keyed by a quota-only `jobType`, executed by a registry that existed for
+ * nothing else. #6381 retires that registry, so an install that upgrades across
+ * it would find every step in `data/cos/quota-burn.json` unavailable — its plan
+ * intact but unrunnable — until this migration points each step at a scheduled
+ * task the user owns.
+ *
+ * The decision itself is NOT here. `lib/quotaBurnLegacyConversion.js` owns it,
+ * and the live compat path (`services/quotaBurnConversion.js`, for a payload an
+ * older client still PUTs) reads the same module: two conversions would drift
+ * the first time either was tightened, and the drift would land as a duplicated
+ * automation or a silently downgraded reference. This file is the adapter — it
+ * reads two JSON files, creates the custom jobs the conversion asked for, and
+ * writes the rewritten plan.
+ *
+ * **Gated on its INPUT, and ships no seed.** `data/cos/quota-burn.json` is
+ * DERIVED from the install's own records, so per AGENTS.md it must never ship a
+ * `data.reference/` seed (setup-data runs first and would land shipped defaults
+ * where the user's plan was, and this migration — gating on the input — would
+ * then convert the seed instead of their plan). The path is declared in
+ * `scripts/lib/migrationOwnedPaths.js`, whose guard test fails if a seed
+ * appears.
+ *
+ * **Idempotent and interrupt-safe.** A step that already carries a `taskRef` is
+ * skipped, so a second run converts nothing. A custom conversion addresses its
+ * job by a deterministic `job-burn-<family>-<step>` id, so a resumed run finds
+ * the job it created last time instead of minting a duplicate automation. The
+ * jobs file is written BEFORE the plan: an interrupt between the two leaves a
+ * created job that nothing references yet (inert — it is on-demand, so no clock
+ * fires it) rather than a plan referencing a job that does not exist. Nothing
+ * here dispatches anything, so no run is ever added.
+ */
+
+import { readFile } from 'fs/promises';
+import { join } from 'path';
+import { atomicWrite } from '../../server/lib/fileCore.js';
+import { normalizeQuotaBurnJob } from '../../server/lib/quotaBurnConfig.js';
+import {
+ applyQuotaBurnStepConversion,
+ planQuotaBurnStepConversion,
+} from '../../server/lib/quotaBurnLegacyConversion.js';
+
+const QUOTA_BURN_PATH = join('data', 'cos', 'quota-burn.json');
+const JOBS_PATH = join('data', 'cos', 'autonomous-jobs.json');
+
+/**
+ * Where the pre-conversion plan is copied before anything is rewritten.
+ *
+ * Recognizing a shipped preset is a structural heuristic (migration 305's
+ * mission-half rule), and a heuristic can be wrong in the user's disfavour —
+ * here that would mean a prompt they had edited being read as ours and mapped
+ * onto a shipped task. `data/` is gitignored runtime state with nothing to
+ * recover from, so one copy taken before the first rewrite makes the whole
+ * question moot: the conversion stops being irreversible. Same posture, and the
+ * same reasoning, as migration 305's backup.
+ */
+const BACKUP_PATH = join('data', 'cos', 'quota-burn.pre-359.json');
+
+/**
+ * Absent → `null` (nothing to migrate). Unparseable → THROW.
+ *
+ * Swallowing a parse error would return the same `null` as "this install has no
+ * burn plan", the migration would report 0 conversions, and the runner would
+ * record 359 as applied — so once the user repaired their JSON, the conversion
+ * that is the whole point of this migration would never run again. Failing
+ * loudly on a corrupt file is the only outcome that stays recoverable.
+ */
+async function readJson(fullPath, label) {
+ const raw = await readFile(fullPath, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) return null;
+ try {
+ // The raw text rides along so a backup is a byte-for-byte copy of what was
+ // on disk, not a re-serialization that could differ in formatting.
+ return { raw, value: JSON.parse(raw) };
+ } catch (err) {
+ throw new Error(`${label} is not valid JSON (${err.message}) — repair it and re-run migrations`);
+ }
+}
+
+const writeJson = (fullPath, value) => atomicWrite(fullPath, `${JSON.stringify(value, null, 2)}\n`);
+
+export default {
+ async up({ rootDir }) {
+ const planPath = join(rootDir, QUOTA_BURN_PATH);
+ const plan = await readJson(planPath, QUOTA_BURN_PATH);
+ // Gated on the INPUT: no burn plan on this install means there is nothing to
+ // convert, not that an output is missing.
+ if (!plan?.value?.families) return { converted: 0 };
+
+ const config = plan.value;
+ const pending = [];
+ let unconverted = 0;
+
+ for (const [familyId, family] of Object.entries(config.families)) {
+ const jobs = Array.isArray(family?.jobs) ? family.jobs : [];
+ jobs.forEach((raw, index) => {
+ const step = normalizeQuotaBurnJob(raw, index);
+ const outcome = step ? planQuotaBurnStepConversion(step, { familyId }) : null;
+ if (outcome) {
+ pending.push({ familyId, index, step, outcome });
+ return;
+ }
+ // A step that already carries a reference is simply done. One that still
+ // names a `jobType` the conversion has no rule for is left EXACTLY as it
+ // is — its label, order and settings are the user's — and counted, so it
+ // is reported rather than silently invisible.
+ if (!step?.taskRef && raw?.jobType) unconverted += 1;
+ });
+ }
+
+ if (!pending.length) {
+ if (unconverted) console.log(`✋ ${QUOTA_BURN_PATH}: left ${unconverted} step(s) that name no convertible work`);
+ return { converted: 0, unconverted };
+ }
+
+ // Jobs FIRST — see the header. Existing ids are left exactly as they are:
+ // a re-run must reuse the job it created, never overwrite edits made since.
+ const newJobs = pending.map(({ outcome }) => outcome.customJob).filter(Boolean);
+ if (newJobs.length) {
+ const stored = await readJson(join(rootDir, JOBS_PATH), JOBS_PATH);
+ const data = stored?.value?.jobs ? stored.value : { version: 1, lastUpdated: new Date().toISOString(), jobs: [] };
+ const existing = new Set(data.jobs.map((job) => job?.id));
+ const added = newJobs.filter((job) => !existing.has(job.id));
+ if (added.length) {
+ data.jobs.push(...added);
+ data.lastUpdated = new Date().toISOString();
+ await writeJson(join(rootDir, JOBS_PATH), data);
+ for (const job of added) console.log(`🆕 ${JOBS_PATH}: created on-demand custom task ${job.id}`);
+ }
+ }
+
+ for (const { familyId, index, step, outcome } of pending) {
+ const converted = applyQuotaBurnStepConversion(step, outcome);
+ const raw = config.families[familyId].jobs[index];
+ // Written onto the STORED object so anything this migration does not know
+ // about (a field a newer PortOS added, a key a user hand-edited in) rides
+ // through untouched. Only the step's IDENTITY changes.
+ // `id` is stamped when the stored step had none: it is what the run-once
+ // ledger, the dispatch records and the converted task's own id all key on,
+ // and leaving it to a positional fallback would move it the first time a
+ // step ahead of it was deleted.
+ Object.assign(raw, { id: step.id, taskRef: converted.taskRef, overrides: converted.overrides, params: converted.overrides.params, unavailable: null });
+ delete raw.jobType;
+ const names = outcome.customJob ? `custom task ${outcome.customJob.id}` : `scheduled task ${converted.taskRef.taskType}`;
+ console.log(`🔁 ${QUOTA_BURN_PATH}: ${familyId}/${step.id} now references ${names}`);
+ }
+
+ await atomicWrite(join(rootDir, BACKUP_PATH), plan.raw);
+ console.log(`💾 ${QUOTA_BURN_PATH}: previous plan saved to ${BACKUP_PATH}`);
+ await writeJson(planPath, config);
+
+ // A converted built-in reference is only RUNNABLE where the target app has
+ // that scheduled task switched on — the shared availability ladder decides
+ // that, not this migration, and enabling a task type here would silently arm
+ // a recurring automation the user never asked for. Said once, so a step that
+ // shows as unavailable on the Quota Burn page has an explanation.
+ console.log(`ℹ️ ${QUOTA_BURN_PATH}: a converted step runs once its target app has that scheduled task enabled`);
+ if (unconverted) console.log(`✋ ${QUOTA_BURN_PATH}: left ${unconverted} step(s) that name no convertible work`);
+ return { converted: pending.length, customTasks: pending.filter(({ outcome }) => outcome.customJob).length, unconverted };
+ },
+};
diff --git a/scripts/migrations/359-quota-burn-task-references.test.js b/scripts/migrations/359-quota-burn-task-references.test.js
new file mode 100644
index 0000000000..b37ba6d2a3
--- /dev/null
+++ b/scripts/migrations/359-quota-burn-task-references.test.js
@@ -0,0 +1,236 @@
+/**
+ * Migration 359 — legacy burn plans become scheduled-task references.
+ *
+ * Fixture-driven and placeholder-only: no value here is copied from a live
+ * install (AGENTS.md, Sensitive Data & Privacy). The one real string is a
+ * SHIPPED preset prompt, imported from the module that ships it, because
+ * recognition is the behaviour under test and a hand-written approximation
+ * would assert a rule the product does not have.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './359-quota-burn-task-references.js';
+import { QUOTA_BURN_PROMPT_PRESETS, AUDIT_CONTRACT_HEADING } from '../../server/lib/quotaBurnPresets.js';
+
+const uxPreset = QUOTA_BURN_PROMPT_PRESETS.find((preset) => preset.id === 'ux-audit');
+const docsPreset = QUOTA_BURN_PROMPT_PRESETS.find((preset) => preset.id === 'docs-audit');
+
+/** A prompt the user edited: the shipped mission with a step of their own added. */
+const customizedPrompt = uxPreset.params.prompt.replace(
+ AUDIT_CONTRACT_HEADING,
+ `${AUDIT_CONTRACT_HEADING}\n\n0. **Also check the onboarding flow.** Our own extra step.`,
+);
+
+let root;
+const planPath = () => join(root, 'data', 'cos', 'quota-burn.json');
+const jobsPath = () => join(root, 'data', 'cos', 'autonomous-jobs.json');
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));
+const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);
+
+const legacyPlan = () => ({
+ enabled: true,
+ checkIntervalMinutes: 30,
+ families: {
+ grok: {
+ enabled: true,
+ jobs: [
+ {
+ id: 'step-preset', enabled: true, label: 'Nightly UX sweep', jobType: 'agent-prompt',
+ params: { ...uxPreset.params, appId: 'app-example' },
+ },
+ {
+ id: 'step-custom', enabled: false, label: 'House style pass', runOnce: true, jobType: 'agent-prompt',
+ params: { appId: 'app-example', prompt: customizedPrompt, useWorktree: true, discardWorktree: true },
+ },
+ {
+ id: 'step-programmatic', enabled: true, jobType: 'universe-bible-images',
+ params: { universeId: 'universe-example', maxEntries: 4 },
+ },
+ {
+ id: 'step-no-app', enabled: true, jobType: 'agent-prompt',
+ params: { ...docsPreset.params },
+ },
+ ],
+ },
+ claude: { enabled: false, jobs: [] },
+ },
+});
+
+const run = () => migration.up({ rootDir: root });
+const steps = () => readJson(planPath()).families.grok.jobs;
+const step = (id) => steps().find((entry) => entry.id === id);
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), 'portos-359-'));
+ mkdirSync(join(root, 'data', 'cos'), { recursive: true });
+});
+afterEach(() => rmSync(root, { recursive: true, force: true }));
+
+describe('migration 359', () => {
+ it('does nothing when the install has no burn plan — it gates on its INPUT', async () => {
+ await expect(run()).resolves.toEqual({ converted: 0 });
+ expect(existsSync(planPath())).toBe(false);
+ expect(existsSync(jobsPath())).toBe(false);
+ });
+
+ it('refuses to run on a corrupt plan rather than recording itself as applied', async () => {
+ writeFileSync(planPath(), '{ not json');
+ await expect(run()).rejects.toThrow(/not valid JSON/);
+ });
+
+ it('maps a recognized shipped preset onto its scheduled counterpart, issues-only', async () => {
+ writeJson(planPath(), legacyPlan());
+ await run();
+
+ const converted = step('step-preset');
+ expect(converted.taskRef).toEqual({ kind: 'builtin', taskType: 'ux', appId: 'app-example' });
+ expect(converted.jobType).toBeUndefined();
+ // Explicit `true` even though `ux` already defaults to filing: the shipped
+ // default is not the promise — the burn was an issues-only audit, and a
+ // catalog default that flipped later must not turn it into code work.
+ expect(converted.overrides.params.fileIssues).toBe(true);
+ // The step's own identity is untouched, so the run-once ledger and every
+ // dispatch record still key on it.
+ expect(converted).toMatchObject({ id: 'step-preset', enabled: true, label: 'Nightly UX sweep' });
+ });
+
+ it('preserves a material execution override on a recognized preset', async () => {
+ const plan = legacyPlan();
+ plan.families.grok.jobs[0].params.discardWorktree = true;
+ writeJson(planPath(), plan);
+ await run();
+ expect(step('step-preset').overrides.params).toMatchObject({ fileIssues: true, discardWorktree: true });
+ });
+
+ it('turns a customized prompt into an on-demand custom task rather than guessing a shipped one', async () => {
+ writeJson(planPath(), legacyPlan());
+ await run();
+
+ const converted = step('step-custom');
+ expect(converted.taskRef).toEqual({ kind: 'custom', jobId: 'job-burn-grok-step-custom' });
+ // Disabled and one-shot state belong to the step, and survive the rewrite.
+ expect(converted).toMatchObject({ enabled: false, runOnce: true });
+
+ const job = readJson(jobsPath()).jobs.find((entry) => entry.id === 'job-burn-grok-step-custom');
+ expect(job.promptTemplate).toBe(customizedPrompt);
+ expect(job).toMatchObject({
+ name: 'House style pass',
+ appId: 'app-example',
+ type: 'agent',
+ // Disabled FROM THE CLOCK, not from invocation: nothing fires it on a
+ // schedule, but the burn can still invoke it, and unattended invocation
+ // needs the autonomy level the legacy executor implicitly had.
+ interval: 'on-demand',
+ intervalMs: null,
+ enabled: true,
+ autonomyLevel: 'yolo',
+ });
+ // The posture the retired executor derived at dispatch: a discarded worktree
+ // lands no code, so PR + simplify are off and a clean tree is a success.
+ expect(job.taskMetadata).toEqual({
+ useWorktree: true, openPR: false, simplify: false,
+ discardWorktree: true, noCodeOutput: true, worktreeChangesExpected: false,
+ });
+ });
+
+ it('points the two programmatic types at their scheduled handlers, params intact', async () => {
+ writeJson(planPath(), legacyPlan());
+ await run();
+ const converted = step('step-programmatic');
+ expect(converted.taskRef).toEqual({ kind: 'builtin', taskType: 'universe-bible-images', appId: null });
+ expect(converted.overrides.params).toEqual({ universeId: 'universe-example', maxEntries: 4 });
+ });
+
+ it('keeps a step with no target app as non-runnable instead of retargeting it', async () => {
+ // It could not run before (the legacy executor refused "no managed app
+ // selected"), so it must not become newly live against PortOS's own
+ // checkout. Its text and settings are preserved in a DISABLED custom task.
+ writeJson(planPath(), legacyPlan());
+ await run();
+ expect(step('step-no-app').taskRef).toEqual({ kind: 'custom', jobId: 'job-burn-grok-step-no-app' });
+ const job = readJson(jobsPath()).jobs.find((entry) => entry.id === 'job-burn-grok-step-no-app');
+ expect(job).toMatchObject({ enabled: false, appId: null });
+ expect(job.promptTemplate).toBe(docsPreset.params.prompt);
+ });
+
+ it('keeps plan order and leaves other families alone', async () => {
+ writeJson(planPath(), legacyPlan());
+ await run();
+ expect(steps().map((entry) => entry.id)).toEqual(['step-preset', 'step-custom', 'step-programmatic', 'step-no-app']);
+ expect(readJson(planPath()).families.claude).toEqual({ enabled: false, jobs: [] });
+ });
+
+ it('parks the pre-conversion plan so a misread heuristic stays recoverable', async () => {
+ const original = legacyPlan();
+ writeJson(planPath(), original);
+ await run();
+ expect(readJson(join(root, 'data', 'cos', 'quota-burn.pre-359.json'))).toEqual(original);
+ });
+
+ it('is idempotent: a second run converts nothing and adds no task', async () => {
+ writeJson(planPath(), legacyPlan());
+ const first = await run();
+ const afterFirst = readJson(planPath());
+ const jobsAfterFirst = readJson(jobsPath()).jobs.map((entry) => entry.id);
+
+ const second = await run();
+
+ expect(first.converted).toBe(4);
+ expect(second).toMatchObject({ converted: 0 });
+ expect(readJson(planPath())).toEqual(afterFirst);
+ expect(readJson(jobsPath()).jobs.map((entry) => entry.id)).toEqual(jobsAfterFirst);
+ });
+
+ it('resumes an interrupted run without duplicating the custom task', async () => {
+ // The crash window the write order exists for: the jobs file landed, the
+ // plan did not. Re-running must reuse the job it already created — a second
+ // copy would be a duplicate automation the user never configured.
+ writeJson(planPath(), legacyPlan());
+ await run();
+ const jobsAfterCrash = readJson(jobsPath());
+ writeJson(planPath(), legacyPlan());
+
+ await run();
+
+ const ids = readJson(jobsPath()).jobs.map((entry) => entry.id);
+ expect(ids).toEqual(jobsAfterCrash.jobs.map((entry) => entry.id));
+ expect(ids.filter((id) => id === 'job-burn-grok-step-custom')).toHaveLength(1);
+ expect(step('step-custom').taskRef).toEqual({ kind: 'custom', jobId: 'job-burn-grok-step-custom' });
+ });
+
+ it('never overwrites a custom task the user has since edited', async () => {
+ writeJson(planPath(), legacyPlan());
+ await run();
+ const jobs = readJson(jobsPath());
+ const edited = jobs.jobs.find((entry) => entry.id === 'job-burn-grok-step-custom');
+ edited.promptTemplate = 'the user rewrote this';
+ writeJson(jobsPath(), jobs);
+ writeJson(planPath(), legacyPlan());
+
+ await run();
+
+ expect(readJson(jobsPath()).jobs.find((entry) => entry.id === 'job-burn-grok-step-custom').promptTemplate)
+ .toBe('the user rewrote this');
+ });
+
+ it('appends to an existing jobs file instead of replacing it', async () => {
+ writeJson(jobsPath(), { version: 1, lastUpdated: '2020-01-01T00:00:00.000Z', jobs: [{ id: 'job-existing', name: 'Example job' }] });
+ writeJson(planPath(), legacyPlan());
+ await run();
+ expect(readJson(jobsPath()).jobs.map((entry) => entry.id))
+ .toEqual(['job-existing', 'job-burn-grok-step-custom', 'job-burn-grok-step-no-app']);
+ });
+
+ it('leaves a step that names no convertible work exactly as it is', async () => {
+ writeJson(planPath(), { families: { grok: { enabled: true, jobs: [{ id: 'mystery', enabled: true, jobType: 'retired-type', params: { prompt: 'x' } }] } } });
+ const result = await run();
+ // Counted, not converted and not dropped: `retired-type` is outside the
+ // legacy alphabet, so there is no work to point a reference at, and
+ // inventing one would spend real quota on something never configured.
+ expect(result).toEqual({ converted: 0, unconverted: 1 });
+ expect(steps()[0]).toEqual({ id: 'mystery', enabled: true, jobType: 'retired-type', params: { prompt: 'x' } });
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 8921ff97b7..1093a909e1 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -63,9 +63,10 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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. |
+| `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 retired executor's task-description parser (`QUOTA_BURN_TASK_PREFIX` / `quotaBurnFamilyOfDescription`), kept for migration 225, and the `run once` vocabulary (`quotaBurnJobKey` / `jobIsSpent`, plus the two family predicates `familyIsConfigured` and `familyHasRunnableJobs`). Pure — no storage, no provider I/O. |
+| `quotaBurnLegacyConversion.js` | The ONE rule turning a LEGACY quota-burn step (copied prompt + quota-only `jobType`) into a scheduled-task reference, shared by migration 359 and the live compat path so the two cannot drift. `planQuotaBurnStepConversion` decides between three outcomes — a recognized unmodified shipped preset onto its scheduled audit counterpart with issues-only pinned explicitly (`AUDIT_TASK_TYPE_BY_PRESET_ID`, inverted from `auditCatalog.js`), the two programmatic types onto their scheduled handlers, and anything customized or targetless onto a `buildQuotaBurnCustomJob` on-demand custom task addressed by the deterministic `quotaBurnCustomJobId` (which is what makes a repeated or resumed conversion create no duplicate). `legacyAgentTaskMetadata` reproduces the retired executor's dispatch posture; `applyQuotaBurnStepConversion` rewrites the step, preserving id, label, enabled and run-once state. Recognition is `matchStoredAuditPreset`, never a label or a partial match. |
| `quotaBurnOrigin.js` | Quota-burn PROVENANCE on an on-demand scheduled-task request and on the task it produces. `normalizeQuotaBurnProvenance` reads the request block (family + burn-step id required, plus the limiting-window reset and the provider/model/effort overrides); `QUOTA_BURN_PROVENANCE_FIELDS` is the ONE block definition every persistence and projection hop derives from, spread by `quotaBurnTaskMetadata` (flat task-metadata keys), `quotaBurnAgentMetadata` (the agent projection) and read back by `quotaBurnProvenance` / `hasQuotaBurnProvenance`, which accept both the flat keys and a nested `quotaBurn` block. `onDemandRequestMetadata` is the single spread both on-demand engines apply. 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)`. |
+| `quotaBurnPresets.js` | FROZEN compatibility-and-migration input (#6381). `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)`; `matchStoredAuditPreset` is migration 305's recognition rule (match the MISSION half, gated on the shipped contract anchors + headings) and `upgradeStoredAuditPrompt` is the refresh built on it. |
| `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`, `isExplicitFileIssuesRequest`, `FILE_ISSUES_DELIVERY_SETTINGS` (the one delivery posture every file-issues lane stamps), `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`, `quotaBurnStepIsDispatchable`, and `evaluateOnDemandEligibility` — the ONE on-demand gate ladder (`enabled` / instance feature / invocation eligibility / target scope / per-app switch / master Improve) shared with `taskSchedule.triggerOnDemandTask`, with `enabledAppIdsByTaskType` deriving its per-app input. |
| `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body, `run once` re-arm body). |
diff --git a/server/lib/autonomousJobTask.js b/server/lib/autonomousJobTask.js
index b4de471593..f86af46cb4 100644
--- a/server/lib/autonomousJobTask.js
+++ b/server/lib/autonomousJobTask.js
@@ -34,6 +34,14 @@ export function generatedJobTaskFields(generated) {
simplify: meta.simplify,
// A marked audit may complete successfully with a verified empty branch.
noChangeSuccess: meta.noChangeSuccess,
+ // The report-shaped posture: the deliverable is an action performed DURING
+ // the run, or a scratch checkout nothing may land from. `FILE_ISSUES_DELIVERY_SETTINGS`
+ // stamps `noCodeOutput` on every issues-only job, and a job converted from a
+ // legacy quota-burn step carries both (#6381) — missing here, the burn lane
+ // queued them as ordinary code work and told the agent to push.
+ noCodeOutput: meta.noCodeOutput,
+ discardWorktree: meta.discardWorktree,
+ worktreeChangesExpected: meta.worktreeChangesExpected,
// Read by the `job:spawned` listener, which records the execution and
// re-registers the saved schedule.
autonomousJob: meta.autonomousJob,
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 33910f5829..43ce143324 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -474,6 +474,17 @@ export const createCosJobSchema = z.object({
// useWorktree/openPR/simplify keys above. Zod strips unknown keys, so
// without this row the flag never survives a job create/update.
fileIssues: z.boolean().optional(),
+ // The two "lands no code" postures, which are NOT the same. `noCodeOutput`
+ // = the deliverable is something the agent DOES during the run (files an
+ // issue, calls an endpoint), so there is no branch and every commit/push/PR
+ // instruction is stripped from the prompt. `discardWorktree` = it wants a
+ // scratch checkout but nothing in it may land — without which
+ // `useWorktree` + `openPR: false` is the AUTO-MERGE posture. Both are
+ // carried by a job converted from a legacy quota-burn step (#6381), and Zod
+ // strips unknown keys, so without these rows the posture would silently
+ // vanish the first time the user saved that job.
+ noCodeOutput: z.boolean().optional(),
+ discardWorktree: z.boolean().optional(),
}).optional(),
});
diff --git a/server/lib/index.js b/server/lib/index.js
index a40d295d22..47d2e6c9d1 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -191,6 +191,7 @@ export * from './providerTranscriptUsage.js';
// duplicate-identifier collision check.
export * as reviewerConfig from './reviewerConfig.js';
export * from './quotaBurnConfig.js';
+export * from './quotaBurnLegacyConversion.js';
export * from './quotaBurnOrigin.js';
export * from './quotaBurnPresets.js';
export * from './auditCatalog.js';
diff --git a/server/lib/quotaBurnConfig.js b/server/lib/quotaBurnConfig.js
index b7333ddf71..04edce1678 100644
--- a/server/lib/quotaBurnConfig.js
+++ b/server/lib/quotaBurnConfig.js
@@ -35,20 +35,17 @@ import { BIBLE_DESCRIBE_DEPTHS, BIBLE_DESCRIBE_SCOPES } from './universeBibleCom
export const QUOTA_BURN_FAMILIES = Object.freeze(['claude', 'codex', 'agy', 'grok']);
/**
- * How a queued burn task's description opens: `[Quota burn: <family>] …`.
+ * How a burn task queued by the RETIRED executor opened: `[Quota burn: <family>] …`.
*
- * `quotaBurnJobs/agentPrompt.js` mints it; migration 225 matches it to back-fill
- * `metadata.quotaBurnFamily` onto tasks queued before that stamp existed. Shared
- * because the two live in different trees and a reworded description would
- * silently make the migration a no-op — leaving exactly the stranded tasks it
- * exists to rescue.
+ * Nothing mints this any more — a burn is dispatched through canonical task
+ * generation and carries `metadata.quotaBurnFamily` from the start (#6381). It
+ * survives as a parser only, for migration 225, which back-fills that metadata
+ * onto tasks queued before the stamp existed and has nothing else to read them
+ * by. Reword it and the migration silently becomes a no-op, leaving exactly the
+ * stranded tasks it exists to rescue.
*/
export const QUOTA_BURN_TASK_PREFIX = '[Quota burn: ';
-/** The description a burn task is queued under. Parsed back by `quotaBurnFamilyOfDescription`. */
-export const burnTaskDescription = (familyId, label, appName) =>
- `${QUOTA_BURN_TASK_PREFIX}${familyId}] ${label} for ${appName}`;
-
/**
* The family id in a burn-task description, or null when it isn't one. Only the
* migration needs this — a live task carries `metadata.quotaBurnFamily` — so it
@@ -128,7 +125,8 @@ export const isUnlimitedDispatchCap = (cap) => Number(cap) < 0;
*
* `agent-prompt` was the original behavior (spawn a CoS agent in a managed app
* with a copied prompt); the other two are PROGRAMMATIC jobs PortOS performs
- * itself with no agent in the loop.
+ * itself with no agent in the loop. Migration 359 converts all three
+ * (`lib/quotaBurnLegacyConversion.js`); none of them has an executor any more.
*/
export const QUOTA_BURN_JOB_TYPE = Object.freeze({
AGENT_PROMPT: 'agent-prompt',
diff --git a/server/lib/quotaBurnLegacyConversion.js b/server/lib/quotaBurnLegacyConversion.js
new file mode 100644
index 0000000000..22e89ae355
--- /dev/null
+++ b/server/lib/quotaBurnLegacyConversion.js
@@ -0,0 +1,259 @@
+/**
+ * The ONE rule that turns a LEGACY quota-burn step into a scheduled-task
+ * reference — read by the migration that rewrites `data/cos/quota-burn.json`
+ * and by the runtime compat path that normalizes an old client's PUT before it
+ * reaches disk (`services/quotaBurnConversion.js`).
+ *
+ * A legacy step WAS its work: a copied prompt in a free-form `params` bag keyed
+ * by a quota-only `jobType`. A step now REFERENCES a scheduled task the user
+ * owns (`quotaBurnTaskRef.js`). Converting between the two is the one place in
+ * PortOS that has to guess what a stored prompt MEANT, so it is written once and
+ * shared — two conversions would disagree the first time either was tightened,
+ * and the disagreement would show up as a duplicated automation or a silently
+ * downgraded reference.
+ *
+ * Three outcomes, and the boundary between them is deliberately conservative:
+ *
+ * - a RECOGNIZED, unmodified shipped audit preset maps onto its scheduled
+ * counterpart (`auditCatalog.js`), with issues-only mode pinned explicitly;
+ * - the two PROGRAMMATIC types map onto the scheduled handler that already
+ * implements them, carrying their run params across;
+ * - anything else — a customized prompt, an unrecognized one, a preset with
+ * no target app — becomes a CUSTOM scheduled job holding the user's exact
+ * text and workflow settings, which the step then references.
+ *
+ * Recognition is `matchStoredAuditPreset` (`quotaBurnPresets.js`), i.e.
+ * migration 305's mission-half rule, NOT a byte match (migration 294's failure)
+ * and NOT a label or a partial match. A label is a display string the user may
+ * have renamed, and a partial mission match would map an edited prompt onto a
+ * shipped task — silently discarding the edit and running different work with
+ * the user's quota. When in doubt this module chooses the custom lane, because
+ * a preserved prompt is always recoverable and a discarded one is not.
+ *
+ * Pure: shape and decisions only. Job creation, file writes and catalog reads
+ * belong to the two adapters.
+ */
+
+import { AUDIT_DEFINITIONS } from './auditCatalog.js';
+import { ON_DEMAND_INTERVAL } from './autonomousJobIntervals.js';
+import { QUOTA_BURN_BOUNDS, QUOTA_BURN_JOB_TYPE } from './quotaBurnConfig.js';
+import { matchStoredAuditPreset } from './quotaBurnPresets.js';
+import { QUOTA_BURN_TASK_REF_KIND } from './quotaBurnTaskRef.js';
+import { isProgrammaticScheduledTaskType } from './taskTargetScope.js';
+
+/**
+ * `<preset id> → <scheduled audit task type>`, INVERTED from the catalog rather
+ * than restated. `auditCatalog.test.js` already fails when a burn preset ships
+ * without a scheduled counterpart, so deriving the map here means the conversion
+ * cannot drift from the pairing that guard enforces.
+ */
+export const AUDIT_TASK_TYPE_BY_PRESET_ID = Object.freeze(Object.fromEntries(
+ Object.entries(AUDIT_DEFINITIONS)
+ .filter(([, definition]) => typeof definition.quotaBurnId === 'string' && definition.quotaBurnId)
+ .map(([taskType, definition]) => [definition.quotaBurnId, taskType]),
+));
+
+/**
+ * The autonomy level a custom job needs for an UNATTENDED burn to run it
+ * (`quotaBurnInvoke.js#unattendedApprovalRefusal`). A legacy `agent-prompt` step
+ * ran with no approval at all, so a converted job that needed one would be a
+ * step that silently stopped burning — the conversion would have "preserved"
+ * the plan into something that never runs.
+ */
+const UNATTENDED_AUTONOMY_LEVEL = 'yolo';
+
+/**
+ * Workflow params a recognized preset step may legitimately have DIVERGED from
+ * its shipped defaults on, carried across as per-invocation overrides.
+ *
+ * Restricted to keys `sanitizeTaskMetadata` accepts (`lib/cosValidation.js`),
+ * because the generator sanitizes run overrides through exactly that allowlist —
+ * carrying a key it drops would be a promise the dispatch cannot keep.
+ */
+const MATERIAL_PRESET_PARAMS = Object.freeze(['useWorktree', 'openPR', 'simplify', 'discardWorktree']);
+
+/** Job-id alphabet, matching what `createJob` mints. */
+const idSafe = (value) => String(value || '').replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
+
+/**
+ * The custom job a converted step points at, keyed by the FAMILY and STEP it
+ * came from.
+ *
+ * Deterministic, and that is the whole idempotency story: re-running the
+ * migration (or resuming it after an interrupt) finds the job it created last
+ * time by id and reuses it instead of minting a second copy of the same
+ * automation. Step ids are preserved by the conversion, so the key is stable
+ * across runs.
+ */
+export const quotaBurnCustomJobId = (familyId, stepId) =>
+ `job-burn-${idSafe(familyId)}-${idSafe(stepId)}`.slice(0, QUOTA_BURN_BOUNDS.idLength.max);
+
+const boolParam = (params, key, fallback) => (typeof params?.[key] === 'boolean' ? params[key] : fallback);
+const trimmed = (value) => (typeof value === 'string' ? value.trim() : '');
+
+/**
+ * The task posture the retired `quotaBurnJobs/agentPrompt.js` executor derived
+ * at dispatch time, computed once here so a converted job keeps running exactly
+ * as it ran.
+ *
+ * The two "lands no code" postures are NOT the same and both had to be honored:
+ * `noCodeOutput` means the deliverable is something the agent DOES during the
+ * run (files an issue, calls an endpoint), so there is no branch; `discardWorktree`
+ * means it wants a scratch checkout but nothing in it may land. Either one
+ * forces `openPR`/`simplify` off — both presuppose a diff to ship — and makes a
+ * clean tree a SUCCESS rather than the `pr-missing` retry that would otherwise
+ * burn up to five agent runs of quota on a job that already did its work.
+ */
+export function legacyAgentTaskMetadata(params) {
+ const discardWorktree = params?.discardWorktree === true;
+ const landsNoCode = params?.noCodeOutput === true || discardWorktree;
+ return {
+ useWorktree: boolParam(params, 'useWorktree', true),
+ openPR: !landsNoCode && boolParam(params, 'openPR', true),
+ simplify: !landsNoCode && boolParam(params, 'simplify', true),
+ discardWorktree,
+ noCodeOutput: landsNoCode,
+ worktreeChangesExpected: !landsNoCode,
+ };
+}
+
+/**
+ * The full custom-job RECORD a converted step references — every field
+ * `createJob` writes, so the migration (which appends to
+ * `data/cos/autonomous-jobs.json` directly) and the runtime adapter (which calls
+ * `createJob`) produce the same job. `quotaBurnConversion.test.js` asserts the
+ * two agree.
+ *
+ * `interval: 'on-demand'` is the "disabled from the clock" part: the job never
+ * fires on a schedule (`getDueJobs` skips it), so converting a burn step does
+ * not silently add a second recurring automation. It is still `enabled`, which
+ * is what makes it INVOKABLE — a disabled job resolves the referencing step as
+ * unavailable. The exception is a step that could never have run anyway (no
+ * target app, or no prompt): that job ships disabled, so the step stays exactly
+ * as non-runnable as it was instead of becoming newly live against PortOS's own
+ * checkout.
+ */
+export function buildQuotaBurnCustomJob({ id, familyId, stepId, label, appId, prompt, params, now }) {
+ const timestamp = now || new Date().toISOString();
+ const runnable = Boolean(appId && prompt);
+ return {
+ id,
+ name: label || `Quota burn — ${familyId} ${stepId}`,
+ description: `Converted from the legacy quota-burn step ${familyId}/${stepId}.`,
+ category: 'custom',
+ appId: appId || null,
+ taskMetadata: legacyAgentTaskMetadata(params),
+ cronExpression: null,
+ cronSchedule: null,
+ type: 'agent',
+ interval: ON_DEMAND_INTERVAL,
+ intervalMs: null,
+ scheduledTime: null,
+ weekdaysOnly: false,
+ enabled: runnable,
+ priority: 'MEDIUM',
+ autonomyLevel: UNATTENDED_AUTONOMY_LEVEL,
+ promptTemplate: prompt,
+ dataInputs: [],
+ providerId: null,
+ model: null,
+ effort: null,
+ command: null,
+ triggerAction: null,
+ config: null,
+ lastRun: null,
+ runCount: 0,
+ createdAt: timestamp,
+ updatedAt: timestamp,
+ };
+}
+
+const refOutcome = (taskRef, params, step) => ({
+ taskRef,
+ overrides: {
+ // Provider / model / effort pins are the step's own and survive untouched —
+ // they name the subscription this burn is spending, not the work.
+ providerId: step?.overrides?.providerId ?? null,
+ model: step?.overrides?.model ?? null,
+ effort: step?.overrides?.effort ?? null,
+ params,
+ },
+ customJob: null,
+});
+
+/**
+ * Convert ONE normalized legacy step. Returns `null` for a step that already
+ * carries a reference (nothing to do — which is what makes a re-run a no-op),
+ * or `{ taskRef, overrides, customJob }` where `customJob` is the record the
+ * adapter must ensure exists before the reference resolves.
+ *
+ * An unrecognized `jobType` returns `null` too: there is no work to point at, and
+ * inventing one would spend real quota on something the user never configured.
+ * The step keeps its settings and stays unavailable with its migration reason.
+ */
+export function planQuotaBurnStepConversion(step, { familyId, now } = {}) {
+ if (!step || step.taskRef) return null;
+ const jobType = step.jobType;
+ const params = step.params || step.overrides?.params || {};
+
+ if (isProgrammaticScheduledTaskType(jobType)) {
+ // The legacy programmatic ids ARE the scheduled task types that implement
+ // them — #6376 moved the implementation and kept the name. Nothing is
+ // re-derived here; the params bag crosses as per-invocation overrides.
+ return refOutcome({ kind: QUOTA_BURN_TASK_REF_KIND.BUILTIN, taskType: jobType, appId: null }, { ...params }, step);
+ }
+ if (jobType !== QUOTA_BURN_JOB_TYPE.AGENT_PROMPT) return null;
+
+ const appId = trimmed(params.appId) || null;
+ const prompt = typeof params.prompt === 'string' ? params.prompt : '';
+ const preset = matchStoredAuditPreset(prompt);
+ const taskType = preset ? AUDIT_TASK_TYPE_BY_PRESET_ID[preset.id] : null;
+
+ // A recognized preset still needs a target: the built-in audit lane generates
+ // a MANAGED-APP task, and an app-less request would be routed to the
+ // install-wide self-improvement generator instead — different work. A step
+ // with no app could never run before either, so it takes the custom lane and
+ // stays as non-runnable as it was.
+ if (taskType && appId) {
+ return refOutcome({ kind: QUOTA_BURN_TASK_REF_KIND.BUILTIN, taskType, appId }, {
+ // Explicit, even where the shipped scheduled default is `false`: every
+ // burn preset is an issues-only audit, and a migration that let a
+ // catalog default flip it into code-writing work would spend the user's
+ // quota changing their repository without being asked.
+ fileIssues: true,
+ // Only a REAL divergence from the shipped default rides along. `?? false`
+ // supplies the default for a key the preset never set (`discardWorktree`),
+ // so a stored `false` there is recognized as agreement rather than
+ // written back as a no-op override on every converted step.
+ ...Object.fromEntries(MATERIAL_PRESET_PARAMS
+ .filter((key) => key in params && params[key] !== (preset.params[key] ?? false))
+ .map((key) => [key, params[key]])),
+ }, step);
+ }
+
+ const jobId = quotaBurnCustomJobId(familyId, step.id);
+ return {
+ ...refOutcome({ kind: QUOTA_BURN_TASK_REF_KIND.CUSTOM, jobId }, {}, step),
+ customJob: buildQuotaBurnCustomJob({
+ id: jobId,
+ familyId,
+ stepId: step.id,
+ label: trimmed(step.label) || (preset ? preset.label : ''),
+ appId,
+ prompt,
+ params,
+ now,
+ }),
+ };
+}
+
+/**
+ * The converted step, with its legacy identity dropped.
+ *
+ * Everything that is not the step's WORK is carried through untouched — id (the
+ * run-once ledger and every dispatch record key on it), label, enabled state and
+ * `runOnce` — so a conversion changes what a step points at and nothing else.
+ */
+export function applyQuotaBurnStepConversion(step, outcome) {
+ return { ...step, taskRef: outcome.taskRef, jobType: null, overrides: outcome.overrides, params: outcome.overrides.params, unavailable: null };
+}
diff --git a/server/lib/quotaBurnOrigin.js b/server/lib/quotaBurnOrigin.js
index 7a1f2f188c..2a16586c62 100644
--- a/server/lib/quotaBurnOrigin.js
+++ b/server/lib/quotaBurnOrigin.js
@@ -17,15 +17,16 @@
* (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 provenance keys are the SAME ones the legacy `quotaBurnJobs/agentPrompt.js`
- * executor stamps, on purpose: `cosTaskGenerator.js#isCooldownExemptTask`, the
+ * These are the same provenance keys the retired `quotaBurnJobs/agentPrompt.js`
+ * executor stamped, 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. `QUOTA_BURN_PROVENANCE_FIELDS` below is the one place they
+ * the finished agent, and they had to keep arriving unchanged when the burn's
+ * origin moved (#6381) or a burn would have stopped being cooldown-exempt and a
+ * refusal would have been credited to nobody. `QUOTA_BURN_PROVENANCE_FIELDS` below is the one place they
* are named.
*/
-import { isPlainObject } from './objects.js';
+import { isPlainObject, POLLUTING_KEYS } from './objects.js';
/**
* The `origin` a quota-burn on-demand request carries. Declared here rather
@@ -134,6 +135,17 @@ export const hasQuotaBurnProvenance = (taskMetadata) => Boolean(quotaBurnProvena
const trimmed = (value, max = MAX_FIELD) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
const nullable = (value, max = MAX_FIELD) => trimmed(value, max) || null;
+const scalarParams = (raw) => {
+ if (!isPlainObject(raw)) return {};
+ const clean = {};
+ for (const [key, value] of Object.entries(raw)) {
+ if (POLLUTING_KEYS.has(key)) continue;
+ if (typeof value === 'string' || typeof value === 'boolean' || value === null) clean[key] = value;
+ else if (typeof value === 'number' && Number.isFinite(value)) clean[key] = value;
+ }
+ return clean;
+};
+
/**
* 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
@@ -142,14 +154,26 @@ const nullable = (value, max = MAX_FIELD) => trimmed(value, max) || null;
* 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.
+ * `overrides` carries 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` — plus the step's run `params`.
+ *
+ * The params are here for a reason the other three are not: they have to reach
+ * the PROMPT, so they cannot ride the post-generation
+ * `onDemandRequestMetadata` stamp below. Both on-demand engines pull them off
+ * the request and hand them to `generateManagedAppImprovementTaskForType` as
+ * `runOverrides`, which layers them over the task's saved `taskMetadata` BEFORE
+ * the mode banner is chosen and the prompt is rendered. That is what lets a step
+ * migrated from an issues-only burn preset pin `fileIssues: true` explicitly and
+ * keep filing even against an audit type whose shipped scheduled default is
+ * `false` (#6381) — without it a migrated burn would silently run the task's
+ * saved mode and start writing code.
+ *
+ * Shallow scalars only, and validated for real one hop later: the generator
+ * sanitizes them through `sanitizeTaskMetadata`'s allowlist, the same door a
+ * stored override passes. Copied here rather than imported from
+ * `quotaBurnTaskRef.js` so this module keeps its one-import budget — it is
+ * reached by a large share of the server suite.
*/
export function normalizeQuotaBurnProvenance(raw) {
if (!isPlainObject(raw)) return null;
@@ -166,6 +190,7 @@ export function normalizeQuotaBurnProvenance(raw) {
providerId: nullable(overrides.providerId),
model: nullable(overrides.model),
effort: nullable(overrides.effort),
+ params: scalarParams(overrides.params),
},
};
}
diff --git a/server/lib/quotaBurnOrigin.test.js b/server/lib/quotaBurnOrigin.test.js
index dc27b22f52..aff79e7cc6 100644
--- a/server/lib/quotaBurnOrigin.test.js
+++ b/server/lib/quotaBurnOrigin.test.js
@@ -12,18 +12,26 @@ import {
const provenance = (overrides = {}) => ({ family: 'grok', stepId: 'step-1', ...overrides });
describe('normalizeQuotaBurnProvenance', () => {
- it('keeps the family, step, limiting reset and the three override pins', () => {
+ it('keeps the family, step, limiting reset, the three override pins and the run params', () => {
+ // The params ride here because they have to reach the PROMPT: the on-demand
+ // engines hand them to the generator as `runOverrides`, which is what lets a
+ // migrated issues-only burn pin `fileIssues: true` explicitly (#6381).
expect(normalizeQuotaBurnProvenance(provenance({
limitingResetAt: 1700000000000,
- overrides: { providerId: 'grok-tui', model: 'm', effort: 'high' },
+ overrides: { providerId: 'grok-tui', model: 'm', effort: 'high', params: { fileIssues: true, maxEntries: 5 } },
}))).toEqual({
family: 'grok',
stepId: 'step-1',
limitingResetAt: 1700000000000,
- overrides: { providerId: 'grok-tui', model: 'm', effort: 'high' },
+ overrides: { providerId: 'grok-tui', model: 'm', effort: 'high', params: { fileIssues: true, maxEntries: 5 } },
});
});
+ it('drops a non-scalar run param rather than carrying a blob into task metadata', () => {
+ const block = normalizeQuotaBurnProvenance(provenance({ overrides: { params: { fileIssues: true, nested: { a: 1 } } } }));
+ expect(block.overrides.params).toEqual({ fileIssues: true });
+ });
+
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.
diff --git a/server/lib/quotaBurnPresets.js b/server/lib/quotaBurnPresets.js
index 98e8a135fa..c53fec4613 100644
--- a/server/lib/quotaBurnPresets.js
+++ b/server/lib/quotaBurnPresets.js
@@ -27,7 +27,9 @@
* backlog arrived with no `model:`/`effort:` routing on it.
* - Migration 305 matches on the MISSION half instead (everything above
* `## How to run this audit`, the part that says WHAT to audit) and replaces
- * the contract half, which is the part this file owns and revises. Copy that
+ * the contract half, which is the part this file owns and revises. That rule
+ * is `matchStoredAuditPreset` below, shared with #6381's conversion so
+ * "still a shipped preset" means one thing. Copy that
* migration for the next contract edit rather than 294's.
*
* Pure module: strings only, no I/O. `routes/quotaBurn.js` serves the list in
@@ -709,35 +711,50 @@ const contractHeadings = (contract) =>
Array.from(contract.matchAll(/\*\*(.+?)\*\*/g), (match) => match[1]);
/**
- * The current render for a stored audit prompt that is still a shipped preset,
- * or `null` to leave the stored text exactly as it is.
+ * The shipped preset a stored audit prompt still IS, or `null` when the text is
+ * no longer purely ours.
*
- * Matching is on the MISSION half — everything above `AUDIT_CONTRACT_HEADING` —
- * rather than on the whole string. A job seeded N contract revisions ago matches
- * no reconstructed prior render byte-for-byte (that is why migration 294 skipped
+ * This is the recognition rule migration 305 settled on, extracted so the
+ * reference-model conversion (#6381) reuses it rather than inventing a second
+ * one: match the MISSION half — everything above `AUDIT_CONTRACT_HEADING` —
+ * rather than the whole string. A job seeded N contract revisions ago matches no
+ * reconstructed prior render byte-for-byte (that is why migration 294 skipped
* every real job as "user-edited"), but its mission half is unchanged, because
* revisions land in the contract. Two gates keep that looser rule from eating a
* user's own text: `SHIPPED_CONTRACT_ANCHORS` proves the shipped skeleton is
* still there (they did not replace the procedure), and
* `SHIPPED_CONTRACT_HEADINGS` proves nothing was ADDED to it (no step of their
* own that a wholesale replacement would delete). Either gate failing means
- * leave it alone.
- *
- * Returns `null` when the prompt is already current, so a caller can count real
- * upgrades without diffing.
+ * leave it alone — and, for the conversion, means the prompt is CUSTOMIZED and
+ * must become a custom task rather than be mapped onto a shipped one.
*/
-export function upgradeStoredAuditPrompt(stored) {
+export function matchStoredAuditPreset(stored) {
if (typeof stored !== 'string' || !stored.includes(AUDIT_CONTRACT_HEADING)) return null;
const index = stored.indexOf(AUDIT_CONTRACT_HEADING);
const storedMission = stored.slice(0, index);
const storedContract = stored.slice(index);
if (!SHIPPED_CONTRACT_ANCHORS.every((anchor) => storedContract.includes(anchor))) return null;
if (!contractHeadings(storedContract).every((heading) => SHIPPED_CONTRACT_HEADINGS.has(heading))) return null;
-
- for (const preset of QUOTA_BURN_PROMPT_PRESETS) {
+ return QUOTA_BURN_PROMPT_PRESETS.find((preset) => {
const current = preset.params.prompt;
- if (current.slice(0, current.indexOf(AUDIT_CONTRACT_HEADING)) !== storedMission) continue;
- return current === stored ? null : current;
- }
- return null;
+ return current.slice(0, current.indexOf(AUDIT_CONTRACT_HEADING)) === storedMission;
+ }) || null;
+}
+
+/**
+ * The current render for a stored audit prompt that is still a shipped preset,
+ * or `null` to leave the stored text exactly as it is.
+ *
+ * Recognition is `matchStoredAuditPreset` above — one rule, two readers, so a
+ * gate tightened for the migration cannot leave the conversion recognizing a
+ * prompt the refresh would refuse to touch.
+ *
+ * Returns `null` when the prompt is already current, so a caller can count real
+ * upgrades without diffing.
+ */
+export function upgradeStoredAuditPrompt(stored) {
+ const preset = matchStoredAuditPreset(stored);
+ if (!preset) return null;
+ const current = preset.params.prompt;
+ return current === stored ? null : current;
}
diff --git a/server/lib/quotaBurnPresets.test.js b/server/lib/quotaBurnPresets.test.js
index 82d8f94a5a..13e282e079 100644
--- a/server/lib/quotaBurnPresets.test.js
+++ b/server/lib/quotaBurnPresets.test.js
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
import {
AUDIT_CONTRACT_HEADING,
QUOTA_BURN_PROMPT_PRESETS,
+ matchStoredAuditPreset,
findQuotaBurnPreset,
upgradeStoredAuditPrompt,
} from './quotaBurnPresets.js';
@@ -200,6 +201,35 @@ describe('upgradeStoredAuditPrompt', () => {
});
});
+describe('matchStoredAuditPreset', () => {
+ // The recognition half of the refresh above, now also the input to #6381's
+ // conversion — the same rule decides whether a stored prompt may be replaced
+ // and whether it may be mapped onto a shipped scheduled task. A prompt the
+ // user edited must fail BOTH, or the conversion trades their text for a
+ // shipped audit that runs something else with their quota.
+ const preset = QUOTA_BURN_PROMPT_PRESETS[0];
+ const current = preset.params.prompt;
+ const mission = current.slice(0, current.indexOf(AUDIT_CONTRACT_HEADING));
+
+ it('names the preset a stored render still is, across contract revisions', () => {
+ expect(matchStoredAuditPreset(current)).toBe(preset);
+ const stale = `${mission}${AUDIT_CONTRACT_HEADING}
+1. **Pick a bounded slice and say so first.** Audit one area.
+2. \`gh issue create --title "..."\`. Suggested labels: \`ux\`, \`plan\`.
+3. **Change no code.**
+4. **Report at the end**: each issue number.
+`;
+ expect(matchStoredAuditPreset(stale)).toBe(preset);
+ });
+
+ it('refuses an edited mission, an edited contract, and a prompt of the user\'s own', () => {
+ expect(matchStoredAuditPreset(current.replace(mission, `${mission}Also check the billing module.\n\n`))).toBeNull();
+ expect(matchStoredAuditPreset(`${mission}${AUDIT_CONTRACT_HEADING}\n\nJust report findings in chat.\n`)).toBeNull();
+ expect(matchStoredAuditPreset('Refactor the billing module and open a PR.')).toBeNull();
+ expect(matchStoredAuditPreset(null)).toBeNull();
+ });
+});
+
describe('findQuotaBurnPreset', () => {
it('finds a known preset and returns null for anything else', () => {
expect(findQuotaBurnPreset(QUOTA_BURN_PROMPT_PRESETS[0].id)).toBe(QUOTA_BURN_PROMPT_PRESETS[0]);
diff --git a/server/lib/quotaBurnTaskRef.js b/server/lib/quotaBurnTaskRef.js
index 0bffb8aec6..27541b60e5 100644
--- a/server/lib/quotaBurnTaskRef.js
+++ b/server/lib/quotaBurnTaskRef.js
@@ -321,8 +321,9 @@ export function applyQuotaBurnAvailability(config, catalog = {}) {
*
* Three independent gates, deliberately spelled out rather than folded into
* `enabled`: the user switched it off, the catalog says it cannot run, or it
- * has no reference to run at all (an un-migrated legacy step — which the legacy
- * `JOB_MODULES` executor still handles until #6381 retires it).
+ * has no reference to run at all. The third is an un-migrated legacy step, and
+ * since #6381 retired the quota-only executor there is nothing else for it to
+ * run through — it stays visible and refused rather than dispatched.
*/
export function quotaBurnStepIsDispatchable(step) {
return step?.enabled !== false && !step?.unavailable && Boolean(step?.taskRef);
diff --git a/server/routes/quotaBurn.js b/server/routes/quotaBurn.js
index ca3cb24819..f6e00cd58c 100644
--- a/server/routes/quotaBurn.js
+++ b/server/routes/quotaBurn.js
@@ -7,14 +7,11 @@
import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest, quotaBurnConfigUpdateSchema, quotaBurnRearmSchema, quotaBurnRunSchema } from '../lib/validation.js';
-import { QUOTA_BURN_JOB_CATALOG } from '../lib/quotaBurnConfig.js';
-import { QUOTA_BURN_PROMPT_PRESETS } from '../lib/quotaBurnPresets.js';
-import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';
import { clearQuotaBurnJobCompletion } from '../services/quotaBurnCompletions.js';
+import { convertLegacyQuotaBurnPatch } from '../services/quotaBurnConversion.js';
import { saveQuotaBurnConfig } from '../services/quotaBurnStore.js';
import { getQuotaBurnStatus, runQuotaBurnCycle } from '../services/quotaBurnRunner.js';
import { getActiveApps } from '../services/apps.js';
-import { listUniverseNames } from '../services/universeBuilder.js';
import { listProviders } from '../services/providers.js';
const router = Router();
@@ -29,29 +26,21 @@ router.get('/', asyncHandler(async (req, res) => {
res.json(await getQuotaBurnStatus({ refresh }));
}));
-// GET /api/quota-burn/catalog — everything the config form needs to build its
-// pickers in one round trip: job types + their param descriptors, the family
-// list, and the app/universe/render-backend options those params select from.
+// GET /api/quota-burn/catalog — what the STEP editor still needs from this
+// route: the managed apps a reference may target and the providers a
+// per-invocation pin may name. The work itself is no longer here — a step
+// references a scheduled task, and those come from the shared schedule/custom-job
+// reads the CoS Schedule and System Tasks pages already make. The legacy job-type
+// catalog and the prompt presets are deliberately NOT served: they are frozen
+// compatibility-and-migration inputs (#6381), and offering them would invite a
+// client to author work that no longer has an executor.
router.get('/catalog', asyncHandler(async (_req, res) => {
- const [apps, universes, providers] = await Promise.all([
+ const [apps, providers] = await Promise.all([
getActiveApps(),
- // The `{ id, name }` projection, NOT listUniverses() — the picker needs a
- // label, not every bible on the install. A missing/empty universe store must
- // not 500 the config page either; the universe job just has nothing to pick.
- listUniverseNames().catch(() => []),
listProviders().catch(() => []),
]);
res.json({
- jobTypes: QUOTA_BURN_JOB_CATALOG,
- // Prompt templates for `agent-prompt` jobs. Served rather than bundled into
- // the client so the wording is one server-side edit — and so a job the user
- // has already tuned is never overwritten by a newer version of the text.
- presets: QUOTA_BURN_PROMPT_PRESETS,
apps: (apps || []).map((app) => ({ id: app.id, name: app.name })),
- universes,
- // Exactly the modes the media job queue can dispatch — the burn job enqueues
- // through it, so a backend added there appears in this picker for free.
- imageModes: QUEUEABLE_IMAGE_MODES,
providers: providers || [],
});
}));
@@ -60,7 +49,11 @@ router.get('/catalog', asyncHandler(async (_req, res) => {
// merge; a family's `jobs` array replaces.
router.put('/', asyncHandler(async (req, res) => {
const patch = validateRequest(quotaBurnConfigUpdateSchema, req.body);
- const config = await saveQuotaBurnConfig(patch);
+ // An old client may still PUT a legacy `jobType` step. It is converted through
+ // the SAME service the migration used before it reaches disk, so a stale body
+ // can neither downgrade a reference nor create a second automation beside one
+ // that already exists.
+ const config = await saveQuotaBurnConfig(await convertLegacyQuotaBurnPatch(patch));
res.json({ config });
}));
diff --git a/server/routes/quotaBurn.test.js b/server/routes/quotaBurn.test.js
index ddc1ac4970..7da5dec699 100644
--- a/server/routes/quotaBurn.test.js
+++ b/server/routes/quotaBurn.test.js
@@ -12,15 +12,15 @@ vi.mock('../services/quotaBurnRunner.js', () => ({
runQuotaBurnCycle: vi.fn(),
}));
vi.mock('../services/quotaBurnCompletions.js', () => ({ clearQuotaBurnJobCompletion: vi.fn() }));
+vi.mock('../services/quotaBurnConversion.js', () => ({ convertLegacyQuotaBurnPatch: vi.fn(async (patch) => patch) }));
vi.mock('../services/apps.js', () => ({ getActiveApps: vi.fn() }));
-vi.mock('../services/universeBuilder.js', () => ({ listUniverseNames: vi.fn() }));
vi.mock('../services/providers.js', () => ({ listProviders: vi.fn() }));
import { clearQuotaBurnJobCompletion } from '../services/quotaBurnCompletions.js';
+import { convertLegacyQuotaBurnPatch } from '../services/quotaBurnConversion.js';
import { getQuotaBurnConfig, saveQuotaBurnConfig } from '../services/quotaBurnStore.js';
import { getQuotaBurnStatus, runQuotaBurnCycle } from '../services/quotaBurnRunner.js';
import { getActiveApps } from '../services/apps.js';
-import { listUniverseNames } from '../services/universeBuilder.js';
import { listProviders } from '../services/providers.js';
import quotaBurnRoutes from './quotaBurn.js';
@@ -39,7 +39,6 @@ beforeEach(() => {
status: { running: false, families: [], runs: [] },
});
getActiveApps.mockResolvedValue([{ id: 'a1', name: 'App One', secret: 'do-not-leak' }]);
- listUniverseNames.mockResolvedValue([{ id: 'u1', name: 'Example Universe' }]);
listProviders.mockResolvedValue([{ id: 'claude-code', name: 'Claude Code', type: 'cli' }]);
});
@@ -63,34 +62,55 @@ describe('GET /api/quota-burn', () => {
});
describe('GET /api/quota-burn/catalog', () => {
- it('projects apps, universes, and providers', async () => {
+ it('projects apps and providers, and nothing an app record should not leak', async () => {
const res = await request(buildApp()).get('/api/quota-burn/catalog');
expect(res.status).toBe(200);
- expect(res.body.apps).toEqual([{ id: 'a1', name: 'App One' }]);
- expect(res.body.universes).toEqual([{ id: 'u1', name: 'Example Universe' }]);
- expect(res.body.providers).toEqual([{ id: 'claude-code', name: 'Claude Code', type: 'cli' }]);
- expect(res.body.jobTypes.map((type) => type.id)).toContain('universe-bible-images');
+ expect(res.body).toEqual({
+ apps: [{ id: 'a1', name: 'App One' }],
+ providers: [{ id: 'claude-code', name: 'Claude Code', type: 'cli' }],
+ });
+ });
+
+ it('no longer serves the legacy job catalog or the prompt presets', async () => {
+ // #6381 froze both as compatibility-and-migration inputs. Serving them would
+ // invite a client to author work that has no executor any more.
+ const res = await request(buildApp()).get('/api/quota-burn/catalog');
+ expect(res.body.jobTypes).toBeUndefined();
+ expect(res.body.presets).toBeUndefined();
});
- it('still renders when the universe store is unavailable', async () => {
- // The universe job simply has nothing to pick from — that must not 500 the
- // whole config page.
- listUniverseNames.mockRejectedValue(new Error('store down'));
+ it('still renders when the provider list is unavailable', async () => {
+ listProviders.mockRejectedValue(new Error('store down'));
const res = await request(buildApp()).get('/api/quota-burn/catalog');
expect(res.status).toBe(200);
- expect(res.body.universes).toEqual([]);
+ expect(res.body.providers).toEqual([]);
});
});
describe('PUT /api/quota-burn', () => {
it('saves a partial plan', async () => {
saveQuotaBurnConfig.mockResolvedValue({ enabled: true });
+ const jobs = [{ taskRef: { kind: 'builtin', taskType: 'ux', appId: 'a1' } }];
const res = await request(buildApp()).put('/api/quota-burn')
- .send({ families: { grok: { enabled: true, jobs: [{ jobType: 'agent-prompt', params: { appId: 'a1' } }] } } });
+ .send({ families: { grok: { enabled: true, jobs } } });
expect(res.status).toBe(200);
- expect(saveQuotaBurnConfig).toHaveBeenCalledWith({
- families: { grok: { enabled: true, jobs: [{ jobType: 'agent-prompt', params: { appId: 'a1' } }] } },
- });
+ expect(saveQuotaBurnConfig).toHaveBeenCalledWith({ families: { grok: { enabled: true, jobs } } });
+ });
+
+ it('runs a legacy body through the conversion service before it reaches disk', async () => {
+ // The compat door: an old client can still PUT a `jobType` step, and it must
+ // be converted through the SAME service the migration used rather than
+ // persisted as an un-migrated step the runner can only refuse.
+ saveQuotaBurnConfig.mockResolvedValue({ enabled: true });
+ const legacy = { families: { grok: { enabled: true, jobs: [{ jobType: 'agent-prompt', params: { appId: 'a1' } }] } } };
+ const converted = { families: { grok: { enabled: true, jobs: [{ taskRef: { kind: 'custom', jobId: 'job-burn-grok-job-1' } }] } } };
+ convertLegacyQuotaBurnPatch.mockResolvedValueOnce(converted);
+
+ const res = await request(buildApp()).put('/api/quota-burn').send(legacy);
+
+ expect(res.status).toBe(200);
+ expect(convertLegacyQuotaBurnPatch).toHaveBeenCalledWith(legacy);
+ expect(saveQuotaBurnConfig).toHaveBeenCalledWith(converted);
});
it('accepts the unlimited dispatch cap, which sits below the field\'s own minimum', async () => {
diff --git a/server/services/autonomousJobs/skillTemplates.js b/server/services/autonomousJobs/skillTemplates.js
index c57197d4fc..594523006b 100644
--- a/server/services/autonomousJobs/skillTemplates.js
+++ b/server/services/autonomousJobs/skillTemplates.js
@@ -178,6 +178,15 @@ async function generateTaskFromJob(job) {
// needed. This is only a completion marker; agentFinalization still
// requires verifyPrClaim to prove the branch is empty before honoring it.
...(meta.noChangeSuccess === true ? { noChangeSuccess: true } : {}),
+ // The "lands no code" posture a job converted from a legacy quota-burn
+ // step carries (#6381). Forwarded beside the git-workflow flags above
+ // because the legacy executor derived all of them together: either of
+ // these forces openPR/simplify off and makes a CLEAN worktree the success
+ // condition, so dropping one here would turn a report-shaped run into a
+ // `pr-missing` retry that burns agent quota on work already done.
+ ...(meta.noCodeOutput != null ? { noCodeOutput: meta.noCodeOutput } : {}),
+ ...(meta.discardWorktree != null ? { discardWorktree: meta.discardWorktree } : {}),
+ ...(meta.worktreeChangesExpected != null ? { worktreeChangesExpected: meta.worktreeChangesExpected } : {}),
// Optional per-job AI provider + model override. resolveAgentProviderAndModel
// reads metadata.provider to switch providers and selectModelForTask reads
// metadata.model as the highest-priority model choice. Absent = active
diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.js
index 2c06929d84..8e2cfa48ba 100644
--- a/server/services/quotaBurn.js
+++ b/server/services/quotaBurn.js
@@ -8,7 +8,7 @@
*
* This module owns the SELECTION half (which family, which window, is the
* window's dispatch cap spent) and nothing else. The plan lives in
- * `quotaBurnStore.js`, the jobs in `quotaBurnJobs/`, and the loop that ties
+ * `quotaBurnStore.js`, the shared invocation path in `quotaBurnInvoke.js`, and the loop that ties
* them together in `quotaBurnRunner.js`.
*
* Everything here fails CLOSED: an unknown reset time, an unsupported provider,
diff --git a/server/services/quotaBurnConversion.js b/server/services/quotaBurnConversion.js
new file mode 100644
index 0000000000..08481d3e48
--- /dev/null
+++ b/server/services/quotaBurnConversion.js
@@ -0,0 +1,105 @@
+/**
+ * Runtime adapter for the legacy → reference conversion — the compat door.
+ *
+ * The plan on disk is converted once, by migration 359. This is the OTHER door:
+ * a client (or a hand-edited file, or a body replayed from an older build) that
+ * still PUTs a legacy `jobType` step. Rather than persisting it as an
+ * un-migrated step the runner can only refuse, the save runs it through the SAME
+ * decision the migration used (`lib/quotaBurnLegacyConversion.js`) and stores the
+ * reference it produces.
+ *
+ * One rule, two doors, is the point. A second conversion written for the live
+ * path would drift from the migration the first time either was tightened, and
+ * the drift would land as the exact two failures the reference model exists to
+ * prevent: a reference silently downgraded back to a copied prompt, or a
+ * duplicate automation created beside one that already existed.
+ *
+ * Idempotency comes from the job id, not from bookkeeping: a custom conversion
+ * addresses its job as `job-burn-<family>-<step>`, so a step converted twice
+ * finds the job it made the first time and reuses it. Nothing here ever
+ * overwrites an existing job — the user may have edited it since.
+ *
+ * A step this module cannot convert is left EXACTLY as it was. It normalizes to
+ * unavailable with a migration reason (`QUOTA_BURN_UNAVAILABLE.LEGACY_UNMIGRATED`),
+ * which is the deliberate posture: unavailable, with its settings intact, rather
+ * than dispatched down a parallel legacy execution path that no longer exists.
+ */
+
+import {
+ applyQuotaBurnStepConversion,
+ planQuotaBurnStepConversion,
+} from '../lib/quotaBurnLegacyConversion.js';
+import { normalizeQuotaBurnJob } from '../lib/quotaBurnConfig.js';
+
+/**
+ * Ensure the custom job a conversion needs exists, and say whether it did.
+ * Returns false when the job could not be created — the caller then leaves the
+ * step legacy rather than pointing it at a job that is not there.
+ */
+async function ensureCustomJob(record) {
+ // Lazy: the route imports this module on every save, and only a LEGACY payload
+ // ever reaches here — a static import would pull the whole autonomous-jobs
+ // tree (script handlers, command security, skill templates) into the request
+ // path for every reference save that needs none of it.
+ const { createJob, getJob } = await import('./autonomousJobs.js');
+ const existing = await getJob(record.id).catch(() => null);
+ if (existing) return true;
+ const created = await createJob(record).catch((err) => {
+ console.error(`❌ Quota-burn conversion could not create custom job ${record.id}: ${err.message}`);
+ return null;
+ });
+ return Boolean(created?.id);
+}
+
+/**
+ * Convert every legacy step in one family's `jobs` array. Steps that already
+ * carry a reference pass through untouched, which is what makes a repeated save
+ * a no-op instead of a second automation.
+ */
+async function convertFamilyJobs(jobs, familyId) {
+ const converted = [];
+ let changed = 0;
+ for (const [index, raw] of jobs.entries()) {
+ // Normalized first so the conversion reads the same shape the migration
+ // does — including the `job-N` id a payload written without one falls back
+ // to, which is what the custom job's deterministic id is keyed on.
+ const step = normalizeQuotaBurnJob(raw, index);
+ if (!step) continue;
+ const outcome = planQuotaBurnStepConversion(step, { familyId });
+ if (!outcome) {
+ converted.push(raw);
+ continue;
+ }
+ if (outcome.customJob && !(await ensureCustomJob(outcome.customJob))) {
+ converted.push(raw);
+ continue;
+ }
+ converted.push(applyQuotaBurnStepConversion(step, outcome));
+ changed += 1;
+ console.log(`🔁 Quota-burn step ${familyId}/${step.id} converted to a scheduled-task reference`);
+ }
+ return { jobs: converted, changed };
+}
+
+/**
+ * Convert the legacy steps in a config PATCH before it is merged and saved.
+ *
+ * Takes and returns a patch (not a whole config): the PUT is partial, and a
+ * family the body did not mention must stay untouched.
+ */
+export async function convertLegacyQuotaBurnPatch(patch) {
+ const families = patch?.families;
+ if (!families) return patch;
+ const next = {};
+ let changed = 0;
+ for (const [familyId, family] of Object.entries(families)) {
+ if (!Array.isArray(family?.jobs)) {
+ next[familyId] = family;
+ continue;
+ }
+ const result = await convertFamilyJobs(family.jobs, familyId);
+ changed += result.changed;
+ next[familyId] = result.changed ? { ...family, jobs: result.jobs } : family;
+ }
+ return changed ? { ...patch, families: next } : patch;
+}
diff --git a/server/services/quotaBurnConversion.test.js b/server/services/quotaBurnConversion.test.js
new file mode 100644
index 0000000000..8096a66a9f
--- /dev/null
+++ b/server/services/quotaBurnConversion.test.js
@@ -0,0 +1,134 @@
+/**
+ * The runtime half of the legacy → reference conversion.
+ *
+ * Two things are proven here that the migration's own suite cannot: that the
+ * compat door behaves like the migration (same job, same id, no duplicate), and
+ * that the job the conversion mints actually RUNS with the posture the retired
+ * `quotaBurnJobs/agentPrompt.js` executor gave it. The second is where that
+ * module's behaviour tests moved to — the coercions are now a property of the
+ * converted job and the shared custom-job generator, not of a quota-only
+ * executor.
+ *
+ * Only the jobs FILE is doubled, so `createJob` / `getJob` / `generateTaskFromJob`
+ * are the real thing.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const store = { data: { version: 1, lastUpdated: '', jobs: [] } };
+
+vi.mock('./autonomousJobs/store.js', () => ({
+ loadJobs: vi.fn(async () => store.data),
+ saveJobs: vi.fn(async (data) => { store.data = data; }),
+ initJobs: vi.fn(async () => store.data),
+ syncSkillTemplatesFromSample: vi.fn(async () => {}),
+}));
+
+const { buildQuotaBurnCustomJob, planQuotaBurnStepConversion } = await import('../lib/quotaBurnLegacyConversion.js');
+const { generatedJobTaskFields } = await import('../lib/autonomousJobTask.js');
+const { convertLegacyQuotaBurnPatch } = await import('./quotaBurnConversion.js');
+const { createJob, generateTaskFromJob, getAllJobs } = await import('./autonomousJobs.js');
+
+const legacyStep = (overrides = {}) => ({
+ id: 'step-1', enabled: true, label: 'House style pass', jobType: 'agent-prompt',
+ params: { appId: 'app-example', prompt: 'Rewrite the onboarding copy.', ...overrides },
+});
+const patchWith = (...jobs) => ({ families: { grok: { enabled: true, jobs } } });
+const convertedStep = (patch) => patch.families.grok.jobs[0];
+
+beforeEach(() => {
+ store.data = { version: 1, lastUpdated: '', jobs: [] };
+});
+
+describe('convertLegacyQuotaBurnPatch', () => {
+ it('converts a legacy step an old client PUT and creates its task once', async () => {
+ const first = await convertLegacyQuotaBurnPatch(patchWith(legacyStep()));
+ expect(convertedStep(first).taskRef).toEqual({ kind: 'custom', jobId: 'job-burn-grok-step-1' });
+ expect(convertedStep(first).jobType).toBeNull();
+ expect((await getAllJobs()).map((job) => job.id)).toEqual(['job-burn-grok-step-1']);
+
+ // The same body replayed — the crash buffer the page restores from, or a
+ // second tab — must not mint a second automation.
+ const second = await convertLegacyQuotaBurnPatch(patchWith(legacyStep()));
+ expect(convertedStep(second).taskRef).toEqual({ kind: 'custom', jobId: 'job-burn-grok-step-1' });
+ expect((await getAllJobs())).toHaveLength(1);
+ });
+
+ it('cannot downgrade a step that already carries a reference', async () => {
+ const step = { id: 'step-1', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-example' } };
+ const patch = patchWith(step);
+ expect(await convertLegacyQuotaBurnPatch(patch)).toBe(patch);
+ expect(await getAllJobs()).toEqual([]);
+ });
+
+ it('leaves the step legacy when its task could not be created', async () => {
+ // Unavailable with a migration reason is the deliberate posture — better
+ // than a reference pointing at a job that is not there.
+ const { saveJobs } = await import('./autonomousJobs/store.js');
+ saveJobs.mockRejectedValueOnce(new Error('disk full'));
+ const patch = await convertLegacyQuotaBurnPatch(patchWith(legacyStep()));
+ expect(convertedStep(patch)).toMatchObject({ jobType: 'agent-prompt' });
+ expect(convertedStep(patch).taskRef).toBeUndefined();
+ });
+
+ it('passes through a family the body did not restate', async () => {
+ const patch = { enabled: true, families: { claude: { enabled: false } } };
+ expect(await convertLegacyQuotaBurnPatch(patch)).toBe(patch);
+ });
+});
+
+describe('the converted custom task', () => {
+ it('is the SAME record whichever adapter creates it', async () => {
+ // The migration appends the record to the jobs file directly; this door
+ // hands it to `createJob`. A divergence would mean an install migrating and
+ // an install PUTting an old body ended up with different automations.
+ const record = buildQuotaBurnCustomJob({
+ id: 'job-burn-grok-step-1', familyId: 'grok', stepId: 'step-1', label: 'House style pass',
+ appId: 'app-example', prompt: 'Rewrite the onboarding copy.', params: {},
+ });
+ const created = await createJob(record);
+ expect({ ...created, createdAt: null, updatedAt: null }).toEqual({ ...record, createdAt: null, updatedAt: null });
+ });
+
+ it('runs with the posture the retired executor derived, all the way onto the task', async () => {
+ // Was `quotaBurnJobs/agentPrompt.test.js`. `discardWorktree` means the job
+ // wants a scratch checkout that nothing may land from: leaving `openPR` on
+ // makes the spawner expect a PR that cannot exist, which downgrades the run
+ // to `pr-missing` and RETRIES it — up to five agent runs of subscription
+ // quota on a job that already did its work — while a clean tree must count
+ // as success rather than as the idle-complete failure.
+ const outcome = planQuotaBurnStepConversion(
+ { id: 'step-1', label: 'Reasoning pass', jobType: 'agent-prompt', params: { appId: 'app-example', prompt: 'Trace the failure paths.', discardWorktree: true, openPR: true, simplify: true } },
+ { familyId: 'grok' },
+ );
+ const generated = await generateTaskFromJob(outcome.customJob);
+ expect(generatedJobTaskFields(generated)).toMatchObject({
+ app: 'app-example',
+ prompt: 'Trace the failure paths.',
+ openPR: false,
+ simplify: false,
+ discardWorktree: true,
+ noCodeOutput: true,
+ worktreeChangesExpected: false,
+ });
+ });
+
+ it('keeps the auto-merge posture for a step that never asked to discard its worktree', async () => {
+ const outcome = planQuotaBurnStepConversion(
+ { id: 'step-1', jobType: 'agent-prompt', params: { appId: 'app-example', prompt: 'Ship the backlog.' } },
+ { familyId: 'grok' },
+ );
+ const generated = await generateTaskFromJob(outcome.customJob);
+ expect(generatedJobTaskFields(generated)).toMatchObject({
+ useWorktree: true, openPR: true, simplify: true, discardWorktree: false, noCodeOutput: false, worktreeChangesExpected: true,
+ });
+ });
+
+ it('is invokable by an unattended burn — approval was never something it could give', async () => {
+ const outcome = planQuotaBurnStepConversion(
+ { id: 'step-1', jobType: 'agent-prompt', params: { appId: 'app-example', prompt: 'x' } },
+ { familyId: 'grok' },
+ );
+ expect(outcome.customJob.autonomyLevel).toBe('yolo');
+ expect((await generateTaskFromJob(outcome.customJob)).autoApprove).toBe(true);
+ });
+});
diff --git a/server/services/quotaBurnDenials.js b/server/services/quotaBurnDenials.js
index 61d54218d5..798b57923f 100644
--- a/server/services/quotaBurnDenials.js
+++ b/server/services/quotaBurnDenials.js
@@ -225,7 +225,7 @@ export async function clearQuotaBurnBlock(familyId) {
* after it runs would arrive one wasted agent too late, every time.
*
* Only agents spawned BY a burn are considered — `quotaBurnFamily` is stamped on
- * the task by `quotaBurnJobs/agentPrompt.js` and projected onto the agent record
+ * the task by the burn dispatch (`quotaBurnInvoke.js`) and projected onto the agent record
* at registration. An unrelated agent that happens to hit a usage limit says
* nothing about whether the burn plan may spend; blocking on it would stall the
* feature over someone else's failed task.
diff --git a/server/services/quotaBurnInvoke.js b/server/services/quotaBurnInvoke.js
index df2b278256..ca3a5f18da 100644
--- a/server/services/quotaBurnInvoke.js
+++ b/server/services/quotaBurnInvoke.js
@@ -4,11 +4,12 @@
* 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.
+ * of the reference model: the retired `quotaBurnJobs/agentPrompt.js` executor
+ * called `cosTaskStore.addTask` directly with a synthesized free-form task,
+ * which walked past canonical task generation and every gate that lives in it.
+ * #6381 converted the plans that used it and removed it, so this is now the ONLY
+ * way a burn spends quota — a step still carrying a legacy `jobType` resolves to
+ * `LEGACY_UNMIGRATED` here and is refused, never executed.
*
* Three reference shapes, three canonical invocations — and no fourth:
*
@@ -455,6 +456,13 @@ async function runBuiltinTaskStep({ resolved, step, family, candidate }) {
providerId: picked.provider.id,
model: resolved.effective.model,
effort: resolved.effective.effort,
+ // The step's run params, which the on-demand engines hand to the
+ // generator as `runOverrides` — layered over the task's saved
+ // `taskMetadata` BEFORE the mode banner and the prompt are built. This
+ // is what carries a migrated issues-only burn's explicit
+ // `fileIssues: true` (#6381); without it the burn would run the
+ // referenced task's SAVED mode and start writing code.
+ params: resolved.effective.params,
},
},
});
diff --git a/server/services/quotaBurnInvoke.test.js b/server/services/quotaBurnInvoke.test.js
index 4009a5a039..90e62a573b 100644
--- a/server/services/quotaBurnInvoke.test.js
+++ b/server/services/quotaBurnInvoke.test.js
@@ -372,7 +372,10 @@ describe('built-in agent task invocation', () => {
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' },
+ // The step's effective run params ride along too: they have to reach
+ // the PROMPT, so the engines hand them to the generator as
+ // `runOverrides` before the mode banner is chosen (#6381).
+ overrides: { providerId: 'grok-tui', model: 'saved-model', effort: 'high', params: { fileIssues: true, depth: 'full' } },
},
},
}]);
diff --git a/server/services/quotaBurnJobs/agentPrompt.js b/server/services/quotaBurnJobs/agentPrompt.js
deleted file mode 100644
index 54282b65b4..0000000000
--- a/server/services/quotaBurnJobs/agentPrompt.js
+++ /dev/null
@@ -1,142 +0,0 @@
-/**
- * Burn job — queue a CoS agent in a managed app with a custom prompt.
- *
- * This is the original quota-burn behavior, now expressed as one job type among
- * several rather than as a per-app scheduled task type. The loop lives in
- * PortOS; only the WORK targets a managed app, named per job — so one install
- * can point its codex window at one repo and its claude window at another.
- *
- * The task is queued (not spawned directly) so the burn is visible in the CoS
- * queue and Active Agents like any other task, and inherits the daemon's
- * provider/worktree/PR handling instead of forking a second dispatch path.
- */
-
-import { addTask } from '../cosTaskStore.js';
-import { getAppById } from '../apps.js';
-import { noProviderReason, resolveBurnProvider } from '../scheduledHandlers/providerPick.js';
-import { burnTaskDescription, isUnlimitedDispatchCap } from '../../lib/quotaBurnConfig.js';
-import { windowLabelOf } from '../../lib/quotaWindows.js';
-
-async function resolve({ params, job, family }) {
- const appId = typeof params?.appId === 'string' ? params.appId.trim() : '';
- const prompt = typeof params?.prompt === 'string' ? params.prompt.trim() : '';
- if (!appId) return { error: 'no managed app selected' };
- if (!prompt) return { error: 'no work prompt configured' };
- const app = await getAppById(appId);
- if (!app) return { error: `managed app ${appId} no longer exists` };
- // Default `prefer: 'tui'` — an agent burn runs for minutes and should be
- // watchable in Active Agents.
- const provider = await resolveBurnProvider({ job, family });
- if (!provider) return { error: noProviderReason(family) };
- return { app, prompt, provider };
-}
-
-export async function countPending({ params, job, family } = {}) {
- const resolved = await resolve({ params, job, family });
- return resolved.error
- ? { count: 0, detail: resolved.error }
- // Handed back to run() by the runner so the app + provider lookups happen
- // once per dispatch instead of twice — see the registry's hook contract.
- : { count: 1, context: resolved, detail: `ready to queue an agent in ${resolved.app.name}` };
-}
-
-/**
- * The burn context the agent sees above the user's own prompt.
- *
- * Names the TARGET window (the weekly allowance this burn is racing) and, when
- * the family reports a separate short rolling window, that one too — a run that
- * is refused mid-way is nearly always the short window running out, and an agent
- * told only "the weekly window has 60% left" reads that refusal as a bug.
- */
-export function renderBurnPrompt({ family, candidate, prompt }) {
- const hours = Math.max(0, Math.ceil(candidate?.hoursUntilReset ?? 0));
- const target = windowLabelOf(candidate?.limit);
- const limiting = candidate?.limitingLimit;
- const showsLimiting = limiting && limiting !== candidate?.limit;
- return [
- `# ${family.id} quota-burn task`,
- '',
- `The ${family.id} ${target} quota window resets in about ${hours} hour${hours === 1 ? '' : 's'}.`,
- `Window: ${target}; remaining: ${candidate?.limit?.percentRemaining}%; reserve: ${family.reservePercent}%.`,
- ...(showsLimiting
- ? [`Shorter window in play: ${windowLabelOf(limiting)} at ${limiting.percentRemaining}% remaining — it is what will refuse this run if it empties.`]
- : []),
- `Dispatch cap: ${isUnlimitedDispatchCap(family.maxDispatchesPerWindow) ? 'unlimited' : family.maxDispatchesPerWindow} for this reset window.`,
- '',
- 'Carry out the configured work below. Do not use another provider family as a substitute.',
- '',
- prompt,
- ].join('\n');
-}
-
-export async function run({ params, job, family, candidate, context } = {}) {
- // Reuse the probe's lookups when the runner supplied them; the page's force
- // path calls run() with no probe, so fall back to resolving here.
- const resolved = context ?? await resolve({ params, job, family });
- if (resolved.error) return { dispatched: false, reason: resolved.error };
- const { app, prompt, provider } = resolved;
-
- const label = job?.label?.trim() || 'quota-burn work';
- // The two "lands no code" postures. `noCodeOutput` = the deliverable is an
- // action performed during the run (a filed issue, an endpoint call), so the
- // job needs no branch at all. `discardWorktree` = the job wants a scratch
- // checkout but nothing in it may land. Either one means there is no diff to
- // ship, which is what the coercions below rest on.
- const discardsWorktree = params?.discardWorktree === true;
- const landsNoCode = params?.noCodeOutput === true || discardsWorktree;
- const task = await addTask({
- description: burnTaskDescription(family.id, label, app.name),
- app: app.id,
- context: renderBurnPrompt({ family, candidate, prompt }),
- provider: provider.id,
- model: job?.model || undefined,
- effort: job?.effort || undefined,
- useWorktree: params?.useWorktree !== false,
- // A job that lands no code can never produce a PR. Leaving `openPR: true`
- // on it (the param's default, one checkbox away) makes the spawner expect a
- // PR that cannot exist: the run is downgraded to `pr-missing` and RETRIED,
- // burning up to five agent runs of subscription quota per misconfigured job.
- // `/simplify` reviews changed code ahead of a commit that never happens.
- // Coerced here rather than only in the UI so a hand-edited plan can't reach
- // that state.
- openPR: !landsNoCode && params?.openPR !== false,
- simplify: !landsNoCode && params?.simplify !== false,
- // Scratch-checkout posture. Without it, `useWorktree + !openPR` auto-merges
- // whatever the agent happened to commit onto the managed app's default
- // branch, unreviewed.
- discardWorktree: discardsWorktree,
- // Where the deliverable goes: the action the agent takes DURING the run, not
- // a commit and not the completion sentinel (which is only the done-signal).
- // Without this the prompt tells it "write your result to the sentinel" — so
- // an audit writes its findings into a file instead of filing anything — and,
- // on a no-worktree job, tells it to `/do:push` to the branch it is standing
- // on, which is the app's default branch.
- noCodeOutput: landsNoCode,
- // A run that correctly changed nothing must retain its report-shaped
- // deliverable posture instead of being treated like code work.
- worktreeChangesExpected: !landsNoCode,
- reviewLoop: false,
- // Burn provenance, read back after the task round-trips through
- // COS-TASKS.md by `isCooldownExemptTask` (cosTaskGenerator.js, which owns
- // the why), by the runner's completion continuation, and by the denial
- // ledger — a burn the provider REFUSES is the signal that this family's
- // short rolling window is spent, but only a run this plan dispatched says
- // anything about that. The limiting window's reset rides along so the block
- // can wait on the right clock instead of a bounded guess.
- quotaBurnFamily: family.id,
- quotaBurnLimitingResetAt: candidate?.limitingResetAt ?? null,
- }, 'internal');
-
- // A duplicate means an identical burn task for this app is still pending or
- // running. Report it as NOT dispatched so the window's cap isn't charged for
- // a task that already exists — otherwise a family whose burn keeps colliding
- // would exhaust its budget without ever adding work.
- if (task?.duplicate) return { dispatched: false, reason: `an identical burn task is already ${task.status}` };
-
- console.log(`🔥 Quota-burn queued agent task ${task.id} for ${app.name} via ${provider.id}`);
- return {
- dispatched: true,
- summary: `Queued "${label}" in ${app.name} via ${provider.id}`,
- detail: { taskId: task.id, appId: app.id, providerId: provider.id, model: job?.model || null, effort: job?.effort || null },
- };
-}
diff --git a/server/services/quotaBurnJobs/agentPrompt.test.js b/server/services/quotaBurnJobs/agentPrompt.test.js
deleted file mode 100644
index 20496195d1..0000000000
--- a/server/services/quotaBurnJobs/agentPrompt.test.js
+++ /dev/null
@@ -1,144 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
-
-const state = { apps: {}, providers: [], added: [], addResult: null };
-
-vi.mock('../cosTaskStore.js', () => ({
- addTask: vi.fn(async (task, type) => { state.added.push({ task, type }); return state.addResult ?? { id: 'sys-1', ...task }; }),
-}));
-vi.mock('../apps.js', () => ({ getAppById: vi.fn(async (id) => state.apps[id] || null) }));
-vi.mock('../providers.js', () => ({ getAllProviders: vi.fn(async () => state.providers) }));
-
-const { countPending, renderBurnPrompt, run } = await import('./agentPrompt.js');
-const { quotaBurnFamilyOfDescription } = await import('../../lib/quotaBurnConfig.js');
-
-const family = { id: 'grok', reservePercent: 10, maxDispatchesPerWindow: 3 };
-const candidate = { hoursUntilReset: 2.4, limit: { label: 'Weekly', percentRemaining: 62 } };
-
-beforeEach(() => {
- state.apps = { 'app-1': { id: 'app-1', name: 'Example App' } };
- state.providers = [
- { id: 'grok-cli', type: 'cli', enabled: true },
- { id: 'claude-code', type: 'cli', enabled: true },
- ];
- state.added = [];
- state.addResult = null;
-});
-
-describe('countPending', () => {
- it('is ready only when the app, the prompt, and a provider all resolve', async () => {
- await expect(countPending({ params: { appId: 'app-1', prompt: 'Do the thing' }, family }))
- .resolves.toMatchObject({ count: 1 });
- await expect(countPending({ params: { appId: 'app-1' }, family }))
- .resolves.toMatchObject({ count: 0, detail: 'no work prompt configured' });
- await expect(countPending({ params: { appId: 'gone', prompt: 'x' }, family }))
- .resolves.toMatchObject({ count: 0, detail: 'managed app gone no longer exists' });
- state.providers = [];
- await expect(countPending({ params: { appId: 'app-1', prompt: 'x' }, family }))
- .resolves.toMatchObject({ count: 0, detail: 'no enabled CLI/TUI provider in the grok family' });
- });
-});
-
-describe('run', () => {
- it('queues an internal task pinned to the family provider, model, and effort', async () => {
- const result = await run({ params: { appId: 'app-1', prompt: 'Do the thing' }, job: { id: 'j1', label: 'Nightly', model: 'grok-4', effort: 'high' }, family, candidate });
- expect(result.dispatched).toBe(true);
- expect(result.detail.effort).toBe('high');
- expect(state.added[0].type).toBe('internal');
- expect(state.added[0].task).toMatchObject({
- app: 'app-1', provider: 'grok-cli', model: 'grok-4', effort: 'high', useWorktree: true, openPR: true, simplify: true, reviewLoop: false,
- });
- expect(state.added[0].task.context).toContain('Do the thing');
- });
-
- it('stamps the burn provenance the cooldown exemption and the continuation read', async () => {
- // Without it the queued task is indistinguishable from any other system
- // task: it inherits the per-app review cooldown (which a busy app never lets
- // lapse, so the burn strands in Pending) and no completion continues the
- // family's plan to its next job.
- await run({ params: { appId: 'app-1', prompt: 'x' }, job: { id: 'j1' }, family, candidate });
- expect(state.added[0].task.quotaBurnFamily).toBe('grok');
- });
-
- it('names the task through the shared description builder', async () => {
- // Migration 225 parses this shape back to recover the family for tasks
- // queued before the metadata stamp existed, so the two must not drift.
- await run({ params: { appId: 'app-1', prompt: 'x' }, job: { id: 'j1', label: 'Nightly' }, family, candidate });
- expect(quotaBurnFamilyOfDescription(state.added[0].task.description)).toBe('grok');
- });
-
- it('reports a duplicate as NOT dispatched', async () => {
- // Charging the window's cap for a task that already exists would let a
- // repeatedly-colliding family exhaust its budget without adding any work.
- state.addResult = { duplicate: true, status: 'pending' };
- await expect(run({ params: { appId: 'app-1', prompt: 'x' }, job: { id: 'j1' }, family, candidate }))
- .resolves.toMatchObject({ dispatched: false, reason: 'an identical burn task is already pending' });
- });
-
- it('respects explicit false agent options', async () => {
- await run({ params: { appId: 'app-1', prompt: 'x', useWorktree: false, openPR: false, simplify: false }, job: { id: 'j1' }, family, candidate });
- expect(state.added[0].task).toMatchObject({ useWorktree: false, openPR: false, simplify: false });
- });
-
- it('keeps the auto-merge posture unless the job explicitly discards its worktree', async () => {
- // `useWorktree` + `openPR: false` merges the agent's branch onto the source
- // workspace's default branch. That is intended for a burn meant to land
- // code, so the default must not change — but a job that opts into
- // `discardWorktree` must get it, or an audit's stray commit lands unreviewed.
- await run({ params: { appId: 'app-1', prompt: 'x' }, job: { id: 'j1' }, family, candidate });
- expect(state.added[0].task).toMatchObject({ discardWorktree: false, worktreeChangesExpected: true });
-
- await run({ params: { appId: 'app-1', prompt: 'x', discardWorktree: true }, job: { id: 'j2' }, family, candidate });
- // A run that correctly changed nothing must also not be judged a failure by
- // the idle-complete gate, which otherwise requires a dirty tree.
- expect(state.added[1].task).toMatchObject({ discardWorktree: true, worktreeChangesExpected: false });
- });
-
- it('runs a no-code job in the app checkout with every commit path stripped', async () => {
- // The audit-preset posture: no worktree (it writes nothing, so there is
- // nothing to isolate — and worktree + no PR is the auto-merge posture), and
- // `noCodeOutput` so the prompt neither routes the deliverable to the
- // sentinel nor tells a no-worktree task to push to the branch it is on.
- await run({ params: { appId: 'app-1', prompt: 'x', useWorktree: false, noCodeOutput: true }, job: { id: 'j4' }, family, candidate });
- expect(state.added[0].task).toMatchObject({
- useWorktree: false, noCodeOutput: true, discardWorktree: false,
- openPR: false, simplify: false, worktreeChangesExpected: false,
- });
- });
-
- it('forces off the flags a discarded worktree makes impossible', async () => {
- // `openPR` defaults to true and sits one checkbox from `discardWorktree`.
- // The combination makes the spawner expect a PR that cannot exist (the
- // worktree is thrown away before any push), which downgrades the run to
- // `pr-missing` and RETRIES it — up to five agent runs of quota burned on a
- // job that already did its work. `noCodeOutput` rides along so the prompt
- // names the real output channel instead of the sentinel.
- await run({ params: { appId: 'app-1', prompt: 'x', discardWorktree: true, openPR: true, simplify: true }, job: { id: 'j3' }, family, candidate });
- expect(state.added[0].task).toMatchObject({ openPR: false, simplify: false, noCodeOutput: true });
- });
-});
-
-describe('renderBurnPrompt', () => {
- it('states the window it is spending and forbids substituting another family', () => {
- const prompt = renderBurnPrompt({ family, candidate, prompt: 'Ship the backlog' });
- expect(prompt).toContain('resets in about 3 hours');
- expect(prompt).toContain('remaining: 62%');
- expect(prompt).toContain('Do not use another provider family as a substitute.');
- expect(prompt.endsWith('Ship the backlog')).toBe(true);
- });
-});
-
-describe('probe → run passthrough', () => {
- it('reuses the probe\'s lookups instead of resolving twice', async () => {
- const { getAppById } = await import('../apps.js');
- const probe = await countPending({ params: { appId: 'app-1', prompt: 'x' }, family });
- getAppById.mockClear();
- await run({ params: { appId: 'app-1', prompt: 'x' }, job: { id: 'j1' }, family, candidate, context: probe.context });
- expect(getAppById).not.toHaveBeenCalled();
- expect(state.added).toHaveLength(1);
- });
-
- it('still resolves on its own when called with no probe (the force path)', async () => {
- await run({ params: { appId: 'app-1', prompt: 'x' }, job: { id: 'j1' }, family, candidate });
- expect(state.added).toHaveLength(1);
- });
-});
diff --git a/server/services/quotaBurnJobs/index.js b/server/services/quotaBurnJobs/index.js
deleted file mode 100644
index e25e80f7aa..0000000000
--- a/server/services/quotaBurnJobs/index.js
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * Quota-burn job registry.
- *
- * A burn job is one unit of work a provider family's plan can run when its
- * window is about to reset. Each module exports:
- *
- * countPending({ params, job, family }) → { count, detail, context? }
- * run({ params, job, family, candidate, context }) → { dispatched, summary?, reason?, detail? }
- *
- * `countPending` must be side-effect free — the config page calls it for every
- * configured job on every load, and the runner calls it to pick which job in the
- * ordered plan actually has work. It may return an opaque `context` (whatever it
- * already computed) which the runner hands straight back to `run`, so a probe
- * that scanned every universe bible to produce its count doesn't make `run`
- * repeat the scan. `run` must still work with `context: undefined` — the page's
- * force path calls it without a probe.
- *
- * `run` is the only thing that may spend quota, and reports `dispatched: false`
- * with a `reason` when it declines (nothing to do, misconfigured target) so the
- * caller does NOT charge the window's dispatch cap for a burn that never
- * happened.
- *
- * Modules are lazy-imported: `universeBibleImages` pulls the whole universe
- * store + media job queue, and `agentPrompt` the CoS task store, so a status
- * read for an install with no jobs configured should not load either.
- *
- * The two PROGRAMMATIC job types are no longer implemented here. They are
- * ordinary on-demand SCHEDULED TASKS (`services/scheduledHandlers/`) that the
- * user can also run from CoS → Schedule; this registry keeps their entries and
- * points them at that shared handler, passing the burning `family` so a burn
- * stays pinned to the subscription it is draining. There is one implementation,
- * not two. Retiring this registry in favour of scheduled-task references is
- * #6381's job.
- *
- * Adding a burn job type is three edits: a `QUOTA_BURN_JOB_TYPE` entry + catalog
- * row in `lib/quotaBurnConfig.js` (that's what the config page renders), a
- * module, and one line in `JOB_MODULES`. The client needs no change unless the
- * job introduces a param kind the form doesn't render yet.
- */
-
-import { QUOTA_BURN_JOB_TYPE } from '../../lib/quotaBurnConfig.js';
-import { SCHEDULED_HANDLER_MODULES } from '../scheduledHandlers/index.js';
-
-export const JOB_MODULES = {
- [QUOTA_BURN_JOB_TYPE.AGENT_PROMPT]: () => import('./agentPrompt.js'),
- [QUOTA_BURN_JOB_TYPE.UNIVERSE_BIBLE_DESCRIBE]: SCHEDULED_HANDLER_MODULES['universe-bible-describe'],
- [QUOTA_BURN_JOB_TYPE.UNIVERSE_BIBLE_IMAGES]: SCHEDULED_HANDLER_MODULES['universe-bible-images'],
-};
-
-// `Object.hasOwn`, not a truthiness check, so an inherited key like
-// 'constructor' can't resolve to a module.
-const load = async (jobType) =>
- (typeof jobType === 'string' && Object.hasOwn(JOB_MODULES, jobType) ? JOB_MODULES[jobType]() : null);
-
-/**
- * Pending-work probe for one configured job. Never throws: a job whose backing
- * store is unavailable reports zero pending with the error as its detail, so
- * one broken job can't wedge the family's whole plan or blank the status page.
- */
-export async function countJobPending({ job, family }) {
- const mod = await load(job?.jobType);
- if (!mod) return { count: 0, detail: `unknown job type: ${job?.jobType}` };
- return mod.countPending({ params: job.params, job, family })
- .catch((err) => ({ count: 0, detail: `probe failed: ${err.message}` }));
-}
-
-/**
- * Run one configured job. Throws are converted to a non-dispatch: the runner
- * treats it as "this job declined", moves on, and logs the reason — a burn that
- * failed to start must not charge the window's cap.
- */
-export async function runBurnJob({ job, family, candidate, context, force = false }) {
- const mod = await load(job?.jobType);
- if (!mod) return { dispatched: false, reason: `unknown job type: ${job?.jobType}` };
- return mod.run({ params: job.params, job, family, candidate, context, force })
- .catch((err) => ({ dispatched: false, reason: `job failed: ${err.message}` }));
-}
diff --git a/server/services/quotaBurnJobs/index.test.js b/server/services/quotaBurnJobs/index.test.js
deleted file mode 100644
index 9e3a8c1cc6..0000000000
--- a/server/services/quotaBurnJobs/index.test.js
+++ /dev/null
@@ -1,37 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { JOB_MODULES, countJobPending, runBurnJob } from './index.js';
-import { QUOTA_BURN_JOB_CATALOG, QUOTA_BURN_JOB_TYPES } from '../../lib/quotaBurnConfig.js';
-
-describe('burn job registry', () => {
- it('registers a module for every declared job type, and nothing else', () => {
- // A job type is declared in two places — the alphabet + catalog in
- // lib/quotaBurnConfig.js, and JOB_MODULES here. Without this guard, an
- // enum/catalog entry with no module gives a job type the config page happily
- // offers and that fails at dispatch with `unknown job type`, surfaced only in
- // the run log AFTER a burnable window was already selected and consumed.
- expect(Object.keys(JOB_MODULES).sort()).toEqual([...QUOTA_BURN_JOB_TYPES].sort());
- expect(QUOTA_BURN_JOB_CATALOG.map((entry) => entry.id).sort()).toEqual([...QUOTA_BURN_JOB_TYPES].sort());
- });
-
- it('every module exports the two hooks the runner calls', async () => {
- for (const load of Object.values(JOB_MODULES)) {
- const mod = await load();
- expect(typeof mod.countPending).toBe('function');
- expect(typeof mod.run).toBe('function');
- }
- });
-
- it('fails closed on an unknown job type rather than throwing', async () => {
- await expect(countJobPending({ job: { jobType: 'rm-rf' } }))
- .resolves.toEqual({ count: 0, detail: 'unknown job type: rm-rf' });
- await expect(runBurnJob({ job: { jobType: 'rm-rf' } }))
- .resolves.toEqual({ dispatched: false, reason: 'unknown job type: rm-rf' });
- });
-
- it('does not resolve an inherited Object.prototype key as a module', async () => {
- // `Object.hasOwn`, not a truthiness check — 'constructor' would otherwise
- // resolve to a function and be invoked as a lazy import.
- await expect(countJobPending({ job: { jobType: 'constructor' } }))
- .resolves.toMatchObject({ count: 0 });
- });
-});
diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.js
index 47deed2afc..65a8cf44d5 100644
--- a/server/services/quotaBurnRunner.js
+++ b/server/services/quotaBurnRunner.js
@@ -51,7 +51,6 @@ import { reconcileQuotaBurnReservations, reserveQuotaBurnDispatch } from './quot
import { getQuotaBurnCompletions, recordQuotaBurnJobCompletion } from './quotaBurnCompletions.js';
import { getActiveQuotaBurnBlocks, recordBurnAgentCompletion } from './quotaBurnDenials.js';
import { getQuotaBurnConfig, getQuotaBurnReservations, getQuotaBurnRuns, quotaBurnReservationKey, 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';
@@ -92,32 +91,31 @@ 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.
+ * references, or the legacy job type a plan that has not been converted yet is
+ * still carrying. `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 }));
+/**
+ * ONE invocation path, whatever the step names.
+ *
+ * There is no second lane any more: the quota-only `JOB_MODULES` registry and
+ * its direct `agentPrompt` executor are retired (#6381), so a step still
+ * carrying a legacy `jobType` has no reference to run and resolves to
+ * `LEGACY_UNMIGRATED` inside the shared path — reported as "nothing pending"
+ * with its migration reason rather than dispatched down an executor that no
+ * longer exists. Keeping the refusal INSIDE the shared path is deliberate: the
+ * page and the runner then say the same thing about the same step.
+ */
+const probeStep = ({ job, family, catalog }) => countQuotaBurnStepPending({ step: job, family, catalog });
-const runStep = ({ job, family, candidate, context, force, catalog }) => (job?.taskRef
- ? invokeQuotaBurnStep({ step: job, family, candidate, context, force, catalog })
- : runBurnJob({ job, family, candidate, context, force }));
+const runStep = ({ job, family, candidate, context, force, catalog }) =>
+ invokeQuotaBurnStep({ step: job, family, candidate, context, force, catalog });
/**
* The live task catalog, read at most once per cycle/status pass and only when a
diff --git a/server/services/quotaBurnRunner.test.js b/server/services/quotaBurnRunner.test.js
index 36faca3a14..72b8094745 100644
--- a/server/services/quotaBurnRunner.test.js
+++ b/server/services/quotaBurnRunner.test.js
@@ -3,14 +3,23 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const now = Date.now();
const resetsAt = new Date(now + 2 * 3600_000).toISOString();
+// Every task type and custom job the fixtures reference, so the availability
+// resolver stamps a runnable step rather than 'unknown task'.
+const taskCatalog = () => ({
+ builtin: {
+ ux: { enabled: true, eligible: true, appIds: ['app-1'] },
+ docs: { enabled: true, eligible: true, appIds: ['app-1'] },
+ 'universe-bible-images': { enabled: true, eligible: true, appIds: [] },
+ },
+ custom: { 'job-a': { enabled: true, eligible: true, appId: 'app-1' } },
+});
+
const state = {
config: null,
quotas: [],
runs: [],
dispatches: {},
recorded: [],
- pending: {},
- ran: [],
contexts: [],
blocks: {},
completions: {},
@@ -21,7 +30,7 @@ const state = {
invokePending: {},
invoked: [],
invokeResult: undefined,
- catalog: { builtin: {}, custom: {} },
+ catalog: taskCatalog(),
catalogReads: 0,
reservations: {},
reserved: [],
@@ -62,18 +71,10 @@ vi.mock('./quotaBurnAcceptance.js', () => ({
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 }) => {
+ invokeQuotaBurnStep: vi.fn(async ({ step, family, candidate, context, 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 }) => {
- state.ran.push({ jobId: job.id, familyId: family.id, charge: candidate.charge });
state.contexts.push(context);
- return state.jobResult ?? { dispatched: true, summary: `ran ${job.id}` };
+ return state.invokeResult ?? { dispatched: true, summary: `invoked ${step.id}` };
}),
}));
@@ -116,7 +117,7 @@ vi.mock('./quotaBurnCompletions.js', () => ({
}));
const { normalizeQuotaBurnConfig } = await import('../lib/quotaBurnConfig.js');
-const { countJobPending, runBurnJob } = await import('./quotaBurnJobs/index.js');
+const { countQuotaBurnStepPending, invokeQuotaBurnStep } = await import('./quotaBurnInvoke.js');
const { getQuotaBurnStatus, runQuotaBurnCycle, rotatePlanAfter, __tickQuotaBurn, __onBurnAgentCompleted, __resetQuotaBurnRunner } = await import('./quotaBurnRunner.js');
const card = (family, percentRemaining = 50) => ({
@@ -131,8 +132,8 @@ const plan = (overrides = {}) => normalizeQuotaBurnConfig({
enabled: true,
resetWithinHours: 24,
jobs: [
- { id: 'first', enabled: true, jobType: 'universe-bible-images', params: {} },
- { id: 'second', enabled: true, jobType: 'agent-prompt', params: {} },
+ { id: 'first', enabled: true, taskRef: { kind: 'builtin', taskType: 'universe-bible-images', appId: null } },
+ { id: 'second', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } },
],
},
},
@@ -143,8 +144,6 @@ beforeEach(() => {
state.config = plan();
state.quotas = [card('grok')];
state.runs = [];
- state.pending = {};
- state.ran = [];
state.contexts = [];
state.dispatches = {};
state.recorded = [];
@@ -154,7 +153,6 @@ beforeEach(() => {
state.completionsUnreadable = false;
state.settled = [];
state.settleError = null;
- state.jobResult = undefined;
state.invokePending = {};
state.invoked = [];
state.invokeResult = undefined;
@@ -162,7 +160,7 @@ beforeEach(() => {
state.reserved = [];
state.reserveOk = true;
state.settlement = { accepted: 0, refused: 0 };
- state.catalog = { builtin: {}, custom: {} };
+ state.catalog = taskCatalog();
state.catalogReads = 0;
__resetQuotaBurnRunner();
});
@@ -174,7 +172,7 @@ describe('runQuotaBurnCycle', () => {
state.config = plan({ enabled: false });
await expect(runQuotaBurnCycle()).resolves.toEqual({ skipped: 'disabled' });
expect(state.runs).toHaveLength(0);
- expect(state.ran).toHaveLength(0);
+ expect(state.invoked).toHaveLength(0);
});
it('never scrapes provider quota when no family could burn', async () => {
@@ -191,10 +189,10 @@ describe('runQuotaBurnCycle', () => {
it('runs the FIRST job in the plan that has pending work', async () => {
// Order is the whole point of the plan: "generate the missing bible images
// first, then fall through to agent work" must not be reordered by the runner.
- state.pending = { first: { count: 0, detail: 'all rendered' }, second: { count: 1, detail: 'ready' } };
+ state.invokePending = { first: { count: 0, detail: 'all rendered' }, second: { count: 1, detail: 'ready' } };
const result = await runQuotaBurnCycle();
expect(result.dispatched).toBe(true);
- expect(state.ran).toEqual([{ jobId: 'second', familyId: 'grok', charge: true }]);
+ expect(state.invoked).toEqual([{ stepId: 'second', familyId: 'grok', charge: true, force: false }]);
expect(state.recorded).toEqual([result.dispatchKey]);
});
@@ -203,19 +201,19 @@ describe('runQuotaBurnCycle', () => {
// run() needs the same scan to know what to render — without the passthrough
// that multi-megabyte read happened twice per dispatch.
const scan = { picked: ['batch'], total: 4 };
- state.pending = { first: { count: 4, context: scan } };
+ state.invokePending = { first: { count: 4, context: scan } };
await runQuotaBurnCycle();
expect(state.contexts).toEqual([scan]);
});
it('prefers an earlier job when both have work', async () => {
- state.pending = { first: { count: 3 }, second: { count: 9 } };
+ state.invokePending = { first: { count: 3 }, second: { count: 9 } };
await runQuotaBurnCycle();
- expect(state.ran.map((entry) => entry.jobId)).toEqual(['first']);
+ expect(state.invoked.map((entry) => entry.stepId)).toEqual(['first']);
});
it('logs why nothing burned instead of failing silently', async () => {
- state.pending = { first: { count: 0, detail: 'all rendered' }, second: { count: 0, detail: 'no app' } };
+ state.invokePending = { first: { count: 0, detail: 'all rendered' }, second: { count: 0, detail: 'no app' } };
const result = await runQuotaBurnCycle();
expect(result.dispatched).toBe(false);
// The per-job reasons are the actionable part — collapsing them to one
@@ -228,8 +226,8 @@ describe('runQuotaBurnCycle', () => {
it('does not charge the window when the job declines', async () => {
// A declined job spent no quota. Charging the cap for it would let a
// repeatedly-misconfigured family exhaust its budget without doing work.
- state.pending = { first: { count: 1 } };
- state.jobResult = { dispatched: false, reason: 'no managed app selected' };
+ state.invokePending = { first: { count: 1 } };
+ state.invokeResult = { dispatched: false, reason: 'no managed app selected' };
const result = await runQuotaBurnCycle();
expect(result.dispatched).toBe(false);
expect(state.recorded).toEqual([]);
@@ -237,30 +235,30 @@ describe('runQuotaBurnCycle', () => {
it('explains a closed window in the run log', async () => {
state.quotas = [card('grok', 100)];
- state.config = plan({ families: { grok: { enabled: true, resetWithinHours: 0, jobs: [{ id: 'first', enabled: true, jobType: 'agent-prompt' }] } } });
+ state.config = plan({ families: { grok: { enabled: true, resetWithinHours: 0, jobs: [{ id: 'first', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] } } });
const result = await runQuotaBurnCycle();
expect(result.dispatched).toBe(false);
expect(result.reason).toMatch(/no burnable window/);
});
it('force-runs one named job past the window gates without charging it', async () => {
- state.config = plan({ families: { grok: { enabled: true, resetWithinHours: 0, jobs: [{ id: 'second', enabled: true, jobType: 'agent-prompt' }] } } });
- state.pending = { second: { count: 1 } };
+ state.config = plan({ families: { grok: { enabled: true, resetWithinHours: 0, jobs: [{ id: 'second', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] } } });
+ state.invokePending = { second: { count: 1 } };
const result = await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', jobId: 'second', force: true });
expect(result.dispatched).toBe(true);
// A forced candidate still carries the family's REAL card and window — it is
// only marked uncharged, so the run log and the agent brief stay truthful.
- expect(state.ran).toEqual([{ jobId: 'second', familyId: 'grok', charge: false }]);
+ expect(state.invoked).toEqual([{ stepId: 'second', familyId: 'grok', charge: false, force: true }]);
expect(result.percentRemaining).toBe(50);
expect(state.recorded).toEqual([]);
});
it('force-runs a family plan after its automatic window closes', async () => {
- state.config = plan({ families: { grok: { enabled: true, resetWithinHours: 0, jobs: [{ id: 'second', enabled: true, jobType: 'agent-prompt' }] } } });
- state.pending = { second: { count: 1 } };
+ state.config = plan({ families: { grok: { enabled: true, resetWithinHours: 0, jobs: [{ id: 'second', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] } } });
+ state.invokePending = { second: { count: 1 } };
const result = await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', force: true });
expect(result.dispatched).toBe(true);
- expect(state.ran).toEqual([{ jobId: 'second', familyId: 'grok', charge: false }]);
+ expect(state.invoked).toEqual([{ stepId: 'second', familyId: 'grok', charge: false, force: true }]);
expect(state.recorded).toEqual([]);
});
@@ -272,19 +270,19 @@ describe('runQuotaBurnCycle', () => {
state.config = normalizeQuotaBurnConfig({
enabled: true,
families: {
- claude: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'soon', enabled: true, jobType: 'agent-prompt' }] },
- agy: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'later', enabled: true, jobType: 'agent-prompt' }] },
+ claude: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'soon', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] },
+ agy: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'later', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] },
},
});
state.quotas = [
{ family: 'claude', label: 'claude', supported: true, limits: [{ key: 'session', scope: 'session', resetsAt: new Date(now + 2 * 3600_000).toISOString(), percentRemaining: 90 }] },
{ family: 'agy', label: 'agy', supported: true, limits: [{ key: 'day', scope: 'day', resetsAt: new Date(now + 21 * 3600_000).toISOString(), percentRemaining: 93 }] },
];
- state.pending = { soon: { count: 1 }, later: { count: 1 } };
+ state.invokePending = { soon: { count: 1 }, later: { count: 1 } };
const result = await runQuotaBurnCycle();
expect(result.dispatched).toBe(true);
- expect(state.ran.map((entry) => entry.familyId)).toEqual(['claude', 'agy']);
+ expect(state.invoked.map((entry) => entry.familyId)).toEqual(['claude', 'agy']);
// Both windows charged — each against its OWN dispatch key.
expect(state.recorded).toHaveLength(2);
expect(new Set(state.recorded).size).toBe(2);
@@ -298,14 +296,13 @@ describe('runQuotaBurnCycle', () => {
state.config = normalizeQuotaBurnConfig({
enabled: true,
families: {
- claude: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'broken', enabled: true, jobType: 'agent-prompt' }] },
- agy: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'good', enabled: true, jobType: 'agent-prompt' }] },
+ claude: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'broken', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] },
+ agy: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'good', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] },
},
});
state.quotas = [card('claude'), card('agy')];
- state.pending = { broken: { count: 1 }, good: { count: 1 } };
- const { runBurnJob } = await import('./quotaBurnJobs/index.js');
- runBurnJob.mockImplementationOnce(async () => ({ dispatched: false, reason: 'no managed app selected' }));
+ state.invokePending = { broken: { count: 1 }, good: { count: 1 } };
+ invokeQuotaBurnStep.mockImplementationOnce(async () => ({ dispatched: false, reason: 'no managed app selected' }));
const result = await runQuotaBurnCycle();
expect(result.dispatched).toBe(true);
@@ -318,12 +315,12 @@ describe('runQuotaBurnCycle', () => {
state.config = normalizeQuotaBurnConfig({
enabled: true,
families: {
- claude: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'a', enabled: true, jobType: 'agent-prompt' }] },
- agy: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'b', enabled: true, jobType: 'agent-prompt' }] },
+ claude: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'a', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] },
+ agy: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'b', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] },
},
});
state.quotas = [card('claude'), card('agy')];
- state.pending = { a: { count: 0, detail: 'no app' }, b: { count: 0, detail: 'no app' } };
+ state.invokePending = { a: { count: 0, detail: 'no app' }, b: { count: 0, detail: 'no app' } };
const result = await runQuotaBurnCycle();
expect(result.reason).toMatch(/claude\/a: no app/);
expect(result.reason).toMatch(/agy\/b: no app/);
@@ -342,7 +339,7 @@ describe('runQuotaBurnCycle', () => {
});
it('refuses to run two cycles at once', async () => {
- state.pending = { first: { count: 1 } };
+ state.invokePending = { first: { count: 1 } };
const [first, second] = await Promise.all([runQuotaBurnCycle(), runQuotaBurnCycle()]);
expect([first.skipped, second.skipped].filter(Boolean)).toEqual(['already-running']);
});
@@ -358,7 +355,7 @@ describe('getQuotaBurnStatus', () => {
});
it('reports the live window and the reason a family would not burn', async () => {
- state.pending = { first: { count: 2, detail: '2 entries' }, second: { count: 0, detail: 'no app' } };
+ state.invokePending = { first: { count: 2, detail: '2 entries' }, second: { count: 0, detail: 'no app' } };
const { status } = await getQuotaBurnStatus();
const grok = status.families.find((family) => family.id === 'grok');
expect(grok.willBurn).toBe(true);
@@ -398,23 +395,23 @@ describe('getQuotaBurnStatus', () => {
*/
describe('denial blocks in a cycle', () => {
it('dispatches nothing while the family is blocked, and says why', async () => {
- state.pending = { first: { count: 1 } };
+ state.invokePending = { first: { count: 1 } };
state.blocks = { grok: { at: now - 1000, until: now + 3_600_000, reason: 'Usage limit exceeded' } };
const entry = await runQuotaBurnCycle({ trigger: 'scheduled' });
expect(entry.dispatched).toBe(false);
expect(entry.reason).toMatch(/provider refused the last burn/);
- expect(state.ran).toEqual([]);
+ expect(state.invoked).toEqual([]);
});
it('resumes once the block lapses', async () => {
- state.pending = { first: { count: 1 } };
+ state.invokePending = { first: { count: 1 } };
state.blocks = { grok: { at: now - 7_200_000, until: now - 1000, reason: 'Usage limit exceeded' } };
const entry = await runQuotaBurnCycle({ trigger: 'scheduled' });
expect(entry.dispatched).toBe(true);
});
it('lets a forced run retry through a block', async () => {
- state.pending = { first: { count: 1 } };
+ state.invokePending = { first: { count: 1 } };
state.blocks = { grok: { at: now - 1000, until: now + 3_600_000, reason: 'Usage limit exceeded' } };
const entry = await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', jobId: 'first', force: true });
expect(entry.dispatched).toBe(true);
@@ -426,19 +423,19 @@ describe('run-now targeting', () => {
// Clicking ▶ on a paused job is a more specific instruction than the
// checkbox set earlier; filtering it out made the click a silent no-op
// reported as "no pending work".
- state.config = plan({ families: { grok: { enabled: true, jobs: [{ id: 'paused', enabled: false, jobType: 'agent-prompt' }] } } });
- state.pending = { paused: { count: 1 } };
+ state.config = plan({ families: { grok: { enabled: true, jobs: [{ id: 'paused', enabled: false, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] } } });
+ state.invokePending = { paused: { count: 1 } };
const result = await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', jobId: 'paused', force: true });
expect(result.dispatched).toBe(true);
- expect(state.ran.map((entry) => entry.jobId)).toEqual(['paused']);
+ expect(state.invoked.map((entry) => entry.stepId)).toEqual(['paused']);
});
it('still skips a disabled job on an ordinary scheduled cycle', async () => {
- state.config = plan({ families: { grok: { enabled: true, jobs: [{ id: 'paused', enabled: false, jobType: 'agent-prompt' }] } } });
- state.pending = { paused: { count: 1 } };
+ state.config = plan({ families: { grok: { enabled: true, jobs: [{ id: 'paused', enabled: false, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] } } });
+ state.invokePending = { paused: { count: 1 } };
// Nothing enabled to run ⇒ not actionable ⇒ no quota scrape at all.
await expect(runQuotaBurnCycle()).resolves.toMatchObject({ dispatched: false });
- expect(state.ran).toEqual([]);
+ expect(state.invoked).toEqual([]);
});
it('force-runs a job in a family whose own checkbox is off', async () => {
@@ -446,9 +443,9 @@ describe('run-now targeting', () => {
// one row outranks them, exactly as it outranks the window/reserve/cap gates.
state.config = normalizeQuotaBurnConfig({
enabled: true,
- families: { grok: { enabled: false, jobs: [{ id: 'j', enabled: true, jobType: 'agent-prompt' }] } },
+ families: { grok: { enabled: false, jobs: [{ id: 'j', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] } },
});
- state.pending = { j: { count: 1 } };
+ state.invokePending = { j: { count: 1 } };
const result = await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', jobId: 'j', force: true });
expect(result.dispatched).toBe(true);
expect(state.recorded).toEqual([]);
@@ -460,8 +457,8 @@ describe('run-now targeting', () => {
state.config = normalizeQuotaBurnConfig({
enabled: true,
families: {
- grok: { enabled: true, jobs: [{ id: 'j', enabled: true, jobType: 'agent-prompt' }] },
- claude: { enabled: true, jobs: [{ id: 'k', enabled: true, jobType: 'agent-prompt' }] },
+ grok: { enabled: true, jobs: [{ id: 'j', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] },
+ claude: { enabled: true, jobs: [{ id: 'k', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] },
},
});
// grok has NO provider card — a fact about the world, so force can't pass it.
@@ -477,7 +474,7 @@ describe('interval clock', () => {
// finish() used to stamp lastRunAt for every trigger, so one "Evaluate now"
// pushed the automatic cycle a full interval out — on a 12-hour interval
// that can skip the reset the feature exists to spend.
- state.pending = { first: { count: 1 } };
+ state.invokePending = { first: { count: 1 } };
await runQuotaBurnCycle({ trigger: 'manual' });
const { getProviderQuotas } = await import('./providerUsage.js');
getProviderQuotas.mockClear();
@@ -499,7 +496,7 @@ describe('interval clock', () => {
// A run log whose newest SCHEDULED entry is older than the interval is due.
__resetQuotaBurnRunner();
state.runs = [{ at: new Date(Date.now() - 13 * 3600_000).toISOString(), trigger: 'scheduled', dispatched: false }];
- state.pending = { first: { count: 1 } };
+ state.invokePending = { first: { count: 1 } };
await __tickQuotaBurn();
expect(getProviderQuotas).toHaveBeenCalled();
});
@@ -510,7 +507,7 @@ describe('interval clock', () => {
const { getProviderQuotas } = await import('./providerUsage.js');
state.config = plan({ checkIntervalMinutes: 720 });
state.runs = [{ at: new Date().toISOString(), trigger: 'manual', dispatched: false }];
- state.pending = { first: { count: 1 } };
+ state.invokePending = { first: { count: 1 } };
await __tickQuotaBurn();
expect(getProviderQuotas).toHaveBeenCalled();
});
@@ -521,20 +518,20 @@ describe('plan rotation', () => {
// `agent-prompt` always probes as "1 pending" (its probe only checks that an
// app and a provider resolve), so an un-rotated walk re-ran job #1 on every
// cycle forever and jobs 2..N in an ordered plan never ran once.
- state.pending = { first: { count: 1 }, second: { count: 1 } };
+ state.invokePending = { first: { count: 1 }, second: { count: 1 } };
await runQuotaBurnCycle({ trigger: 'manual' });
await runQuotaBurnCycle({ trigger: 'manual' });
- expect(state.ran.map((entry) => entry.jobId)).toEqual(['first', 'second']);
+ expect(state.invoked.map((entry) => entry.stepId)).toEqual(['first', 'second']);
});
it('keeps walking to the next job with work when the resume point has none', async () => {
// Rotation moves where the walk STARTS; "first job with pending work wins"
// still holds, which is what a probing job like universe-bible-images needs.
- state.pending = { first: { count: 1 }, second: { count: 0, detail: 'all rendered' } };
+ state.invokePending = { first: { count: 1 }, second: { count: 0, detail: 'all rendered' } };
state.runs = [{ at: new Date().toISOString(), dispatched: true, familyId: 'grok', jobId: 'first' }];
const result = await runQuotaBurnCycle({ trigger: 'manual' });
expect(result.dispatched).toBe(true);
- expect(state.ran.map((entry) => entry.jobId)).toEqual(['first']);
+ expect(state.invoked.map((entry) => entry.stepId)).toEqual(['first']);
});
it('falls back to plan order for a cursor that is not in the plan', () => {
@@ -551,15 +548,15 @@ describe('plan rotation', () => {
state.config = normalizeQuotaBurnConfig({
enabled: true,
families: {
- claude: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'c1', enabled: true, jobType: 'agent-prompt' }, { id: 'c2', enabled: true, jobType: 'agent-prompt' }] },
- agy: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'a1', enabled: true, jobType: 'agent-prompt' }, { id: 'a2', enabled: true, jobType: 'agent-prompt' }] },
+ claude: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'c1', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }, { id: 'c2', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] },
+ agy: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'a1', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }, { id: 'a2', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] },
},
});
state.quotas = [card('claude'), card('agy')];
- state.pending = { c1: { count: 1 }, c2: { count: 1 }, a1: { count: 1 }, a2: { count: 1 } };
+ state.invokePending = { c1: { count: 1 }, c2: { count: 1 }, a1: { count: 1 }, a2: { count: 1 } };
state.runs = [{ at: new Date().toISOString(), dispatched: true, familyId: 'agy', jobId: 'a1' }];
await runQuotaBurnCycle({ trigger: 'manual' });
- expect(state.ran.map((entry) => entry.jobId)).toEqual(['c1', 'a2']);
+ expect(state.invoked.map((entry) => entry.stepId)).toEqual(['c1', 'a2']);
});
});
@@ -567,11 +564,11 @@ describe('completion continuation', () => {
it('evaluates the family again when one of its burn agents finishes', async () => {
// The interval only STARTS a burn — see the module header for why one
// dispatch per `checkIntervalMinutes` cannot spend the window.
- state.pending = { first: { count: 1 }, second: { count: 1 } };
+ state.invokePending = { first: { count: 1 }, second: { count: 1 } };
await runQuotaBurnCycle({ trigger: 'manual' });
await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });
// The continuation advances the plan and is charged like any unforced burn.
- expect(state.ran.map((entry) => entry.jobId)).toEqual(['first', 'second']);
+ expect(state.invoked.map((entry) => entry.stepId)).toEqual(['first', 'second']);
expect(state.recorded).toHaveLength(2);
expect(state.runs[0]).toMatchObject({ trigger: 'continuation', dispatched: true });
});
@@ -581,19 +578,19 @@ describe('completion continuation', () => {
// the moment a burn agent finishes, so a block recorded after it runs (or
// from a second `agent:completed` subscriber, whose ordering against this
// one is not guaranteed) arrives one wasted agent too late, every time.
- state.pending = { first: { count: 1 } };
+ state.invokePending = { first: { count: 1 } };
// Whatever the ledger just learned is what selection reads on this very tick.
state.blocks = { grok: { at: now - 1000, until: now + 3_600_000, reason: 'Usage limit exceeded' } };
const entry = await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });
expect(state.settled).toEqual(['grok']);
expect(entry.dispatched).toBe(false);
expect(entry.reason).toMatch(/provider refused the last burn/);
- expect(state.ran).toEqual([]);
+ expect(state.invoked).toEqual([]);
});
it('still continues when the denial ledger itself fails', async () => {
// Telemetry must never be able to stall the plan.
- state.pending = { first: { count: 1 } };
+ state.invokePending = { first: { count: 1 } };
state.settleError = 'ENOSPC';
const entry = await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });
expect(entry.dispatched).toBe(true);
@@ -604,7 +601,7 @@ describe('completion continuation', () => {
// multi-second PTY spawn — and every card but this family's is discarded.
// Unscoped, one burn chain would pay N scrapes per link instead of one.
const { getProviderQuotas } = await import('./providerUsage.js');
- state.pending = { first: { count: 1 } };
+ state.invokePending = { first: { count: 1 } };
await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });
expect(getProviderQuotas).toHaveBeenCalledWith(expect.objectContaining({ family: 'grok' }));
});
@@ -616,39 +613,38 @@ describe('completion continuation', () => {
state.config = normalizeQuotaBurnConfig({
enabled: true,
families: {
- claude: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'c1', enabled: true, jobType: 'agent-prompt' }] },
- agy: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'a1', enabled: true, jobType: 'agent-prompt' }] },
+ claude: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'c1', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] },
+ agy: { enabled: true, resetWithinHours: 24, jobs: [{ id: 'a1', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] },
},
});
state.quotas = [card('claude'), card('agy')];
- state.pending = { c1: { count: 1 }, a1: { count: 1 } };
+ state.invokePending = { c1: { count: 1 }, a1: { count: 1 } };
// agy's agent finishes while claude's cycle is still mid-dispatch.
- const { runBurnJob } = await import('./quotaBurnJobs/index.js');
- runBurnJob.mockImplementationOnce(async ({ job, family, candidate }) => {
- state.ran.push({ jobId: job.id, familyId: family.id, charge: candidate.charge });
+ invokeQuotaBurnStep.mockImplementationOnce(async ({ step, family, candidate }) => {
+ state.invoked.push({ stepId: step.id, familyId: family.id, charge: candidate.charge });
await expect(__onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'agy' } }))
.resolves.toEqual({ skipped: 'already-running' });
- return { dispatched: true, summary: `ran ${job.id}` };
+ return { dispatched: true, summary: `ran ${step.id}` };
});
await runQuotaBurnCycle({ trigger: 'manual', familyId: 'claude' });
- expect(state.ran.map((entry) => entry.familyId)).toEqual(['claude', 'agy']);
+ expect(state.invoked.map((entry) => entry.familyId)).toEqual(['claude', 'agy']);
});
it('ignores an agent that was not a quota burn', async () => {
- state.pending = { first: { count: 1 } };
+ state.invokePending = { first: { count: 1 } };
await __onBurnAgentCompleted({ metadata: { taskType: 'user' } });
await __onBurnAgentCompleted(null);
- expect(state.ran).toEqual([]);
+ expect(state.invoked).toEqual([]);
});
it('stops when the master switch is off', async () => {
// A continuation is unattended spending — switching the feature off must end
// the chain, not leave it running until the window cap happens to close it.
state.config = plan({ enabled: false });
- state.pending = { first: { count: 1 } };
+ state.invokePending = { first: { count: 1 } };
await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });
- expect(state.ran).toEqual([]);
+ expect(state.invoked).toEqual([]);
expect(state.runs).toEqual([]);
});
@@ -656,10 +652,10 @@ describe('completion continuation', () => {
// The chain is bounded by the same gate ladder every other cycle runs — here
// the reserve, which the run log records so the stop is auditable.
state.quotas = [card('grok', 10)];
- state.config = plan({ families: { grok: { enabled: true, resetWithinHours: 24, reservePercent: 40, jobs: [{ id: 'first', enabled: true, jobType: 'agent-prompt' }] } } });
- state.pending = { first: { count: 1 } };
+ state.config = plan({ families: { grok: { enabled: true, resetWithinHours: 24, reservePercent: 40, jobs: [{ id: 'first', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }] } } });
+ state.invokePending = { first: { count: 1 } };
await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });
- expect(state.ran).toEqual([]);
+ expect(state.invoked).toEqual([]);
expect(state.runs).toHaveLength(1);
expect(state.runs[0]).toMatchObject({ trigger: 'continuation', dispatched: false });
expect(state.runs[0].reason).toMatch(/reserve/);
@@ -672,19 +668,17 @@ describe('forced run bypasses the pending probe', () => {
// it veto reproduces the silent no-op the force path exists to fix, one
// gate later — it bites hardest on universe-bible-images, whose 6h
// in-flight cooldown reports zero for entries that are merely queued.
- const { countJobPending } = await import('./quotaBurnJobs/index.js');
- state.pending = { second: { count: 0, detail: 'already queued' } };
+ state.invokePending = { second: { count: 0, detail: 'already queued' } };
const result = await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', jobId: 'second', force: true });
- expect(countJobPending).not.toHaveBeenCalled();
+ expect(countQuotaBurnStepPending).not.toHaveBeenCalled();
expect(result.dispatched).toBe(true);
- expect(state.ran.map((entry) => entry.jobId)).toEqual(['second']);
+ expect(state.invoked.map((entry) => entry.stepId)).toEqual(['second']);
});
it('still probes on an unforced cycle', async () => {
- const { countJobPending } = await import('./quotaBurnJobs/index.js');
- state.pending = { first: { count: 1 } };
+ state.invokePending = { first: { count: 1 } };
await runQuotaBurnCycle();
- expect(countJobPending).toHaveBeenCalled();
+ expect(countQuotaBurnStepPending).toHaveBeenCalled();
});
});
@@ -702,28 +696,28 @@ describe('run-once jobs', () => {
it('marks a run-once job spent when it dispatches, and skips it next cycle', async () => {
state.config = oneShotPlan([
- { id: 'once', enabled: true, runOnce: true, jobType: 'agent-prompt', params: {} },
- { id: 'standing', enabled: true, jobType: 'agent-prompt', params: {} },
+ { id: 'once', enabled: true, runOnce: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } },
+ { id: 'standing', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } },
]);
- state.pending = { once: { count: 1 }, standing: { count: 1 } };
+ state.invokePending = { once: { count: 1 }, standing: { count: 1 } };
await runQuotaBurnCycle();
- expect(state.ran.map((entry) => entry.jobId)).toEqual(['once']);
+ expect(state.invoked.map((entry) => entry.stepId)).toEqual(['once']);
expect(state.completed).toEqual(['grok:once']);
// The plan's next lap must reach `standing` and never return to `once`.
await runQuotaBurnCycle();
await runQuotaBurnCycle();
- expect(state.ran.map((entry) => entry.jobId)).toEqual(['once', 'standing', 'standing']);
+ expect(state.invoked.map((entry) => entry.stepId)).toEqual(['once', 'standing', 'standing']);
});
it('leaves a repeating job in the rotation and records nothing', async () => {
- state.pending = { first: { count: 1 }, second: { count: 1 } };
+ state.invokePending = { first: { count: 1 }, second: { count: 1 } };
await runQuotaBurnCycle();
await runQuotaBurnCycle();
await runQuotaBurnCycle();
// Regression guard for the default: absent `runOnce` must keep repeating.
- expect(state.ran.map((entry) => entry.jobId)).toEqual(['first', 'second', 'first']);
+ expect(state.invoked.map((entry) => entry.stepId)).toEqual(['first', 'second', 'first']);
expect(state.completed).toEqual([]);
});
@@ -732,8 +726,8 @@ describe('run-once jobs', () => {
// finished plan would otherwise pay for a multi-second TUI scrape every
// interval, forever, to be told there is nothing to dispatch.
const { getProviderQuotas } = await import('./providerUsage.js');
- state.config = oneShotPlan([{ id: 'once', enabled: true, runOnce: true, jobType: 'agent-prompt', params: {} }]);
- state.pending = { once: { count: 1 } };
+ state.config = oneShotPlan([{ id: 'once', enabled: true, runOnce: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }]);
+ state.invokePending = { once: { count: 1 } };
await runQuotaBurnCycle();
getProviderQuotas.mockClear();
@@ -746,22 +740,22 @@ describe('run-once jobs', () => {
});
it('lets a forced run re-run a spent job, and re-stamps it', async () => {
- state.config = oneShotPlan([{ id: 'once', enabled: true, runOnce: true, jobType: 'agent-prompt', params: {} }]);
+ state.config = oneShotPlan([{ id: 'once', enabled: true, runOnce: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }]);
state.completions = { 'grok:once': new Date(now - 86_400_000).toISOString() };
const result = await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', jobId: 'once', force: true });
expect(result.dispatched).toBe(true);
// Uncharged against the window's automatic budget, but still recorded — the
// two ledgers answer different questions, and the work just happened.
- expect(state.ran).toEqual([{ jobId: 'once', familyId: 'grok', charge: false }]);
+ expect(state.invoked).toEqual([{ stepId: 'once', familyId: 'grok', charge: false, force: true }]);
expect(state.recorded).toEqual([]);
expect(state.completed).toEqual(['grok:once']);
});
it('does not record a completion for a job that declined to dispatch', async () => {
- state.config = oneShotPlan([{ id: 'once', enabled: true, runOnce: true, jobType: 'agent-prompt', params: {} }]);
- state.pending = { once: { count: 1 } };
- state.jobResult = { dispatched: false, reason: 'no managed app selected' };
+ state.config = oneShotPlan([{ id: 'once', enabled: true, runOnce: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }]);
+ state.invokePending = { once: { count: 1 } };
+ state.invokeResult = { dispatched: false, reason: 'no managed app selected' };
await runQuotaBurnCycle();
// A misconfigured step must stay retryable — burning its one run on a
// decline would strand it behind a Re-arm click for work that never ran.
@@ -774,54 +768,53 @@ describe('run-once jobs', () => {
state.completionsUnreadable = true;
const result = await runQuotaBurnCycle();
expect(result).toMatchObject({ dispatched: false, reason: 'run-once ledger unreadable' });
- expect(state.ran).toEqual([]);
+ expect(state.invoked).toEqual([]);
});
it('walks a whole one-shot series through the completion continuation', async () => {
// The "run the series once" case: each finished burn agent advances the
// plan, and the series stops of its own accord instead of looping.
state.config = oneShotPlan([
- { id: 's1', enabled: true, runOnce: true, jobType: 'agent-prompt', params: {} },
- { id: 's2', enabled: true, runOnce: true, jobType: 'agent-prompt', params: {} },
+ { id: 's1', enabled: true, runOnce: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } },
+ { id: 's2', enabled: true, runOnce: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } },
]);
- state.pending = { s1: { count: 1 }, s2: { count: 1 } };
+ state.invokePending = { s1: { count: 1 }, s2: { count: 1 } };
await runQuotaBurnCycle();
await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });
await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });
- expect(state.ran.map((entry) => entry.jobId)).toEqual(['s1', 's2']);
+ expect(state.invoked.map((entry) => entry.stepId)).toEqual(['s1', 's2']);
expect(state.completed).toEqual(['grok:s1', 'grok:s2']);
});
it('reports a spent step as ran rather than probing it', async () => {
- const { countJobPending } = await import('./quotaBurnJobs/index.js');
const ranAt = new Date(now - 3_600_000).toISOString();
- state.config = oneShotPlan([{ id: 'once', enabled: true, runOnce: true, jobType: 'agent-prompt', params: {} }]);
+ state.config = oneShotPlan([{ id: 'once', enabled: true, runOnce: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }]);
state.completions = { 'grok:once': ranAt };
const { status } = await getQuotaBurnStatus();
const grok = status.families.find((family) => family.id === 'grok');
expect(grok.jobs).toEqual([{ id: 'once', ranAt, pending: null }]);
- expect(countJobPending).not.toHaveBeenCalled();
+ expect(countQuotaBurnStepPending).not.toHaveBeenCalled();
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', () => {
+// #6381 retired the quota-only `JOB_MODULES` registry and its direct
+// `agentPrompt` executor, so there is now exactly ONE invocation path. These
+// cover what that leaves the runner responsible for: sending every step down the
+// shared path, reading the scheduled-task catalog once per cycle, and refusing —
+// not dispatching — a step that still carries a legacy `jobType` and therefore
+// has no reference to run.
+describe('every step routes through the shared invocation path', () => {
const refPlan = (jobs) => normalizeQuotaBurnConfig({
enabled: true,
families: { grok: { enabled: true, resetWithinHours: 24, jobs } },
});
+ const legacyPlan = () => refPlan([{ id: 'legacy', enabled: true, jobType: 'agent-prompt', params: { appId: 'app-1', prompt: 'x' } }]);
- it('probes and runs a taskRef step through quotaBurnInvoke, not the legacy registry', async () => {
+ it('probes and runs a taskRef step through quotaBurnInvoke', async () => {
state.config = refPlan([{ id: 'ref', enabled: true, taskRef: { kind: 'builtin', taskType: 'ux', appId: 'app-1' } }]);
state.invokePending = { ref: { count: 1, detail: 'ready' } };
@@ -829,30 +822,33 @@ describe('reference steps route through the shared invocation path', () => {
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']);
+ it('sends an un-migrated legacy step down the SAME path rather than a second lane', async () => {
+ // The registry that used to execute it is gone. The step is not dropped and
+ // not re-interpreted: it goes to the shared path, which resolves it as
+ // `legacy-unmigrated` and reports the migration reason. Dispatching it any
+ // other way would be the parallel execution path #6381 removed.
+ state.config = legacyPlan();
+ state.invokePending = { legacy: { count: 0, detail: 'legacy "agent-prompt" step is waiting to be migrated' } };
+
+ const result = await runQuotaBurnCycle();
+
+ expect(countQuotaBurnStepPending).toHaveBeenCalledWith(expect.objectContaining({ step: expect.objectContaining({ id: 'legacy', jobType: 'agent-prompt' }) }));
+ expect(result.dispatched).toBe(false);
expect(state.invoked).toHaveLength(0);
});
- it('preserves first-enabled-with-pending-work selection across both lanes', async () => {
+ it('walks past a step with no pending work to the next one', async () => {
state.config = refPlan([
- { id: 'legacy', enabled: true, jobType: 'agent-prompt', params: {} },
+ { id: 'idle', enabled: true, taskRef: { kind: 'builtin', taskType: 'docs', appId: 'app-1' } },
{ 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' } };
+ state.invokePending = { idle: { count: 0, detail: 'no pending work' }, ref: { count: 1, detail: 'ready' } };
const result = await runQuotaBurnCycle();
expect(result.jobId).toBe('ref');
- expect(state.ran).toHaveLength(0);
+ expect(state.invoked.map((entry) => entry.stepId)).toEqual(['ref']);
});
it('reads the scheduled-task catalog once per cycle, and not at all for a legacy-only plan', async () => {
@@ -864,7 +860,7 @@ describe('reference steps route through the shared invocation path', () => {
expect(state.catalogReads).toBe(1);
state.catalogReads = 0;
- state.config = plan();
+ state.config = legacyPlan();
await runQuotaBurnCycle();
expect(state.catalogReads).toBe(0);
});
@@ -896,7 +892,7 @@ describe('reference steps route through the shared invocation path', () => {
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();
+ expect(countQuotaBurnStepPending).toHaveBeenCalledWith(expect.objectContaining({ step: expect.objectContaining({ id: 'ref' }) }));
});
});
diff --git a/server/services/scheduledHandlers/index.js b/server/services/scheduledHandlers/index.js
index 0c31fcb092..588d253588 100644
--- a/server/services/scheduledHandlers/index.js
+++ b/server/services/scheduledHandlers/index.js
@@ -26,7 +26,7 @@
* an on-demand request for the task type and calls `runScheduledHandler`
* with the task's saved `taskMetadata` as its params and NO `family`.
* - Quota Burn's runner reaches the same modules through
- * `quotaBurnJobs/index.js`, passing the burning `family` so the work stays
+ * `quotaBurnInvoke.js`, passing the burning `family` so the work stays
* pinned to that subscription (see `providerPick.js` /
* `universeBibleImages.resolveRenderMode`).
*
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 0b35ef266f..2a0119f44c 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -2258,7 +2258,10 @@ describe('taskSchedule', () => {
// 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 } }
+ // `overrides.params` rides along because a migrated issues-only step pins
+ // `fileIssues` there, and the generator has to see it BEFORE it renders the
+ // prompt (#6381).
+ const burn = { family: 'grok', stepId: 'step-1', limitingResetAt: 1700000000000, overrides: { providerId: 'grok-tui', model: null, effort: null, params: { fileIssues: true } } }
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 () => {
diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.js
index 18622fb6fc..8a45d89954 100644
--- a/server/services/taskScheduleRegistry.js
+++ b/server/services/taskScheduleRegistry.js
@@ -138,7 +138,7 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [
// own buttons call. Install-wide (a universe is not a managed app's repo —
// see `requiresInstallWideTarget`) and ON_DEMAND with no interval, so they are
// never clock-due and a fresh install spends nothing until the user runs one.
- // Quota Burn reaches the SAME handlers through `quotaBurnJobs/index.js`; there
+ // Quota Burn reaches the SAME handlers through `quotaBurnInvoke.js`; there
// is one implementation, not two.
...PROGRAMMATIC_SCHEDULED_TASK_TYPES,
// NOTE: `quota-burn` used to live here as a per-app perpetual task type. It is
diff --git a/server/services/taskScheduleRegistry.programmatic.test.js b/server/services/taskScheduleRegistry.programmatic.test.js
index a5ce6dc7dc..a10d592a2c 100644
--- a/server/services/taskScheduleRegistry.programmatic.test.js
+++ b/server/services/taskScheduleRegistry.programmatic.test.js
@@ -6,7 +6,8 @@ import {
isProgrammaticScheduledTaskType,
} from './taskScheduleRegistry.js';
import { SCHEDULED_HANDLER_MODULES } from './scheduledHandlers/index.js';
-import { JOB_MODULES } from './quotaBurnJobs/index.js';
+import { QUOTA_BURN_JOB_TYPES } from '../lib/quotaBurnConfig.js';
+import { planQuotaBurnStepConversion } from '../lib/quotaBurnLegacyConversion.js';
import { QUOTA_BURN_JOB_CATALOG } from '../lib/quotaBurnConfig.js';
import { sanitizeTaskMetadata } from '../lib/cosValidation.js';
@@ -31,13 +32,25 @@ describe('programmatic scheduled handlers — registration parity', () => {
expect(isProgrammaticScheduledTaskType('constructor')).toBe(false);
});
- it('is the SAME module Quota Burn dispatches — one implementation, not two', () => {
- // #6376 moved these out of quotaBurnJobs/ and left the burn registry
- // pointing at the shared handler. A second copy would drift the moment one
- // door's behavior changed.
+ it('is what a legacy programmatic burn step converts INTO — one implementation, not two', () => {
+ // #6376 moved these out of quotaBurnJobs/ and #6381 retired that registry
+ // entirely: a legacy programmatic step now converts to a reference to the
+ // registered handler. A conversion naming anything else would resurrect the
+ // second implementation the move existed to remove.
for (const taskType of PROGRAMMATIC_SCHEDULED_TASK_TYPES) {
- expect(JOB_MODULES[taskType], taskType).toBe(SCHEDULED_HANDLER_MODULES[taskType]);
+ const outcome = planQuotaBurnStepConversion({ id: 's1', jobType: taskType, params: { maxEntries: 3 } }, { familyId: 'grok' });
+ expect(outcome.taskRef, taskType).toEqual({ kind: 'builtin', taskType, appId: null });
+ expect(outcome.customJob, taskType).toBeNull();
+ expect(SCHEDULED_HANDLER_MODULES[taskType], taskType).toBeTypeOf('function');
}
+ // Every legacy job type has a conversion rule — the guard the retired
+ // registry's own parity test used to provide. A type with none would leave a
+ // stored step permanently un-migrated and permanently unavailable.
+ for (const jobType of QUOTA_BURN_JOB_TYPES) {
+ expect(planQuotaBurnStepConversion({ id: 's1', jobType, params: { appId: 'a1', prompt: 'do the thing' } }, { familyId: 'grok' }), jobType)
+ .not.toBeNull();
+ }
+ expect(QUOTA_BURN_JOB_CATALOG.map((entry) => entry.id).sort()).toEqual([...QUOTA_BURN_JOB_TYPES].sort());
});
it('exports the countPending/run contract from every handler module', async () => {