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

stop quota-burn tasks stranding in Pending, and walk the whole burn plan

[._.]/ Adam Eivydf05a7c9af96
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 994d784b75..e059bbf440 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -26,6 +26,8 @@
## Fixed
+- **Quota-burn tasks were queued and then never picked up, so the window they were meant to spend expired unspent anyway.** Three separate faults, each of which alone was enough to strand a burn. First, a queued burn inherited the per-app *review cooldown* — a 30-minute throttle re-stamped by every task that completes on that app. On an app that carries any other recurring CoS work (a perpetual claim-issue drain, which is itself exempt from the cooldown and therefore keeps completing) the cooldown never lapses, so the burn task sat in Pending indefinitely while agents ran past it. The cooldown was never this task's throttle: the burn plan's own gate ladder — the reset horizon, the family's reserve, and `maxDispatchesPerWindow` — is checked before the task is queued at all, so burns now bypass it, as pipeline continuations and perpetual drains already did. Tasks already queued carry no marker, so migration 225 back-fills it onto them rather than leaving them stranded — and a stranded burn is worse than late, because `addTask` dedupes on description + app, so a pending twin makes the runner report "an identical burn task is already pending" and that job in the plan is permanently unreachable. Second, the runner always walked the family's job plan from the top, and an `agent-prompt` job always probes as "work pending" (its probe only checks that an app and a provider resolve) — so job #1 won every dispatch forever and the other seven audits in an eight-job plan never ran once. The walk now resumes after the family's last dispatch, read from the run log rather than a second cursor file, and still runs the first job with pending work from there, so a probing job like `universe-bible-images` keeps its ordering. Third, the plan only advanced once per `checkIntervalMinutes` — at the 12-hour default, two dispatches a day against an allowance of five on a five-hour window. Each finished burn agent now re-evaluates its own family, so the plan is walked one agent at a time until a gate actually closes; the chain is bounded by the same ledger every other cycle charges, and switching the feature off ends it immediately. That re-evaluation reads only the burning family's quota card rather than respawning every enabled provider's TUI for numbers it then discards — a per-family scrape the usage page already asked for this way.
+
- **Two agents working a swarm run could overwrite each other's pull-request descriptions.** Every agent in a swarm shares one scratch directory and — by design — runs byte-identical instructions, so when two of them reached the "write the PR description to a file" step they independently picked the same obvious filename and the second quietly overwrote the first. The failure was invisible: nothing errored, the text was well-formed, and it only surfaced minutes later when the first agent re-published its now-replaced description onto its own PR. Swarm runs now hand each agent its own scratch subdirectory named for the issue it's working, so no two agents can collide on a filename, and each agent re-reads its published description after creating or editing it to confirm the right one landed. Single-issue runs are unchanged.
- **Quota burn stopped after the first family it dispatched, so a longer-windowed provider never burned at all.** A cycle selected every family whose window was inside its reset horizon, sorted them soonest-reset-first — and then returned after the first successful dispatch. Families do not share a budget: each draws down its own subscription window, against its own reserve and its own `maxDispatchesPerWindow`, so stopping early protected nothing. It just meant the soonest-resetting family took every cycle. A `claude` window resetting in 2h beat an `agy` window resetting in 21h on every tick, and the Antigravity plan sat at "93% left · 0/5 used" indefinitely while its eight configured audits never ran. A cycle now dispatches one job per *family*, records a run-log row per dispatch (so no family is hidden from the audit list), charges each window against its own key, and continues past a family whose job declines. When several plans are walked, every skip reason is prefixed with the family it came from.
diff --git a/scripts/migrations/225-quota-burn-task-provenance.js b/scripts/migrations/225-quota-burn-task-provenance.js
new file mode 100644
index 0000000000..c0d015ca19
--- /dev/null
+++ b/scripts/migrations/225-quota-burn-task-provenance.js
@@ -0,0 +1,113 @@
+/**
+ * Migration 225 — stamp `quotaBurnFamily` onto burn tasks queued before it existed.
+ *
+ * Background:
+ * A quota-burn dispatch queues an ordinary CoS task (`quotaBurnJobs/agentPrompt.js`),
+ * and the spawn scheduler used to apply the per-app REVIEW COOLDOWN to it —
+ * a 30-minute throttle re-stamped by every task that completes on that app.
+ * On an app carrying any other recurring CoS work (a perpetual claim-issue
+ * drain, which is itself cooldown-exempt and therefore keeps completing) the
+ * cooldown never lapses, so the burn task sat in Pending until its window
+ * reset unspent — the exact outcome quota burn exists to prevent.
+ *
+ * Burn tasks are now exempt (`isCooldownExemptTask` in
+ * `server/services/cosTaskGenerator.js`), and the completion continuation in
+ * `quotaBurnRunner.js` advances the family's plan when one finishes. Both
+ * recognise a burn by `metadata.quotaBurnFamily`, which the dispatcher now
+ * stamps at queue time — but nothing rewrites a task already on disk, and
+ * every install that had the feature on has one or more sitting there.
+ *
+ * Leaving them unstamped is not merely "they stay stuck". A stranded burn
+ * also REJECTS its own re-dispatch: `addTask` dedupes on first-line
+ * description + app, and a pending twin makes the runner report "an identical
+ * burn task is already pending" — so that job in the family's plan is
+ * permanently unreachable, not just late.
+ *
+ * What it writes:
+ * `data/COS-TASKS.md` — one ` - quotaBurnFamily: <id>` metadata line
+ * inserted directly under each `[Quota burn: <family>] …` task that lacks it.
+ * Every section is stamped, not just Pending: the marker is provenance and a
+ * completed task carrying it is correct, while tracking sections would mean
+ * parsing structure this rewrite deliberately does not need.
+ *
+ * A text-level insert rather than a parse/regenerate round-trip (the same
+ * choice migration 146 made for this file): regenerating would reorder,
+ * re-escape and re-sort every task in the queue, so a bug in an unrelated
+ * metadata value would be written back over the user's live task list.
+ *
+ * Idempotent: a task that already carries the key is skipped, so a second run
+ * changes nothing and the file is left untouched when there is nothing to do.
+ */
+
+import { readFile, writeFile, rename } from 'fs/promises';
+import { join } from 'path';
+import { quotaBurnFamilyOfDescription } from '../../server/lib/quotaBurnConfig.js';
+
+// The task header line, per `server/lib/taskParser.js`. Both spellings — with
+// and without the AUTO/APPROVAL flag — since internal tasks carry it and the
+// legacy shape does not.
+const TASK_LINE = /^-\s*\[([ x~!?])\]\s*#([\w-]+)\s*\|\s*(?:CRITICAL|HIGH|MEDIUM|LOW)\s*\|\s*(?:(?:AUTO|APPROVAL)\s*\|\s*)?(.+)$/i;
+const METADATA_LINE = /^\s+-\s*(\w+):/;
+
+/**
+ * Insert the missing `quotaBurnFamily` metadata line under every burn task.
+ * Pure — exported for the test.
+ *
+ * @param {string} markdown raw COS-TASKS.md
+ * @returns {{ markdown: string, stamped: string[] }} stamped task ids
+ */
+export function stampBurnTaskProvenance(markdown) {
+ const lines = markdown.split('\n');
+ const out = [];
+ const stamped = [];
+
+ for (let i = 0; i < lines.length; i++) {
+ out.push(lines[i]);
+ const header = lines[i].match(TASK_LINE);
+ if (!header) continue;
+ const family = quotaBurnFamilyOfDescription(header[3].trim());
+ if (!family) continue;
+
+ // Look ahead over this task's own metadata block only — it ends at the next
+ // line that is not an indented `- key: value`, which is the next task, a
+ // section heading, or a blank line.
+ let hasKey = false;
+ for (let j = i + 1; j < lines.length; j++) {
+ const meta = lines[j].match(METADATA_LINE);
+ if (!meta) break;
+ if (meta[1] === 'quotaBurnFamily') { hasKey = true; break; }
+ }
+ if (hasKey) continue;
+
+ out.push(` - quotaBurnFamily: ${family}`);
+ stamped.push(header[2]);
+ }
+
+ return { markdown: out.join('\n'), stamped };
+}
+
+export default {
+ async up({ rootDir }) {
+ const file = join(rootDir, 'data', 'COS-TASKS.md');
+ const raw = await readFile(file, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) {
+ console.log('🔥 migration 225: no data/COS-TASKS.md — nothing to stamp');
+ return { ok: true, reason: 'no-task-file' };
+ }
+
+ const { markdown, stamped } = stampBurnTaskProvenance(raw);
+ if (!stamped.length) {
+ console.log('🔥 migration 225: no unstamped quota-burn tasks');
+ return { ok: true, reason: 'already-stamped', stamped: 0 };
+ }
+
+ const tmp = `${file}.tmp-225`;
+ await writeFile(tmp, markdown);
+ await rename(tmp, file);
+ console.log(`🔥 migration 225: stamped quotaBurnFamily on ${stamped.length} quota-burn task(s)`);
+ return { ok: true, stamped: stamped.length };
+ },
+};
diff --git a/scripts/migrations/225-quota-burn-task-provenance.test.js b/scripts/migrations/225-quota-burn-task-provenance.test.js
new file mode 100644
index 0000000000..88c15b6921
--- /dev/null
+++ b/scripts/migrations/225-quota-burn-task-provenance.test.js
@@ -0,0 +1,88 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration, { stampBurnTaskProvenance } from './225-quota-burn-task-provenance.js';
+import { parseTasksMarkdown } from '../../server/lib/taskParser.js';
+
+const burnTask = (id, family = 'agy') => [
+ `- [ ] #${id} | MEDIUM | AUTO | [Quota burn: ${family}] Performance issues for PortOS`,
+ ' - provider: antigravity-tui',
+ ' - app: portos-default',
+].join('\n');
+
+const queue = (...tasks) => ['# Tasks', '', '## Pending', ...tasks, ''].join('\n');
+
+describe('stampBurnTaskProvenance', () => {
+ it('inserts the family the description names, directly under the task line', () => {
+ const { markdown, stamped } = stampBurnTaskProvenance(queue(burnTask('sys-1')));
+ expect(stamped).toEqual(['sys-1']);
+ // Parsed back through the REAL parser — a metadata line the queue's own
+ // reader cannot see would be no better than not writing it.
+ const [task] = parseTasksMarkdown(markdown);
+ expect(task.metadata.quotaBurnFamily).toBe('agy');
+ // The rest of the task survives verbatim.
+ expect(task.metadata.provider).toBe('antigravity-tui');
+ expect(task.metadata.app).toBe('portos-default');
+ });
+
+ it('leaves every other task untouched', () => {
+ const other = ['- [ ] #sys-2 | HIGH | AUTO | Ordinary system work', ' - app: portos-default'].join('\n');
+ const { markdown, stamped } = stampBurnTaskProvenance(queue(burnTask('sys-1'), other));
+ expect(stamped).toEqual(['sys-1']);
+ const parsed = parseTasksMarkdown(markdown);
+ expect(parsed.find((t) => t.id === 'sys-2').metadata.quotaBurnFamily).toBeUndefined();
+ });
+
+ it('skips a task that already carries the key', () => {
+ const already = [burnTask('sys-1'), ' - quotaBurnFamily: agy'].join('\n');
+ const input = queue(already);
+ expect(stampBurnTaskProvenance(input)).toEqual({ markdown: input, stamped: [] });
+ });
+
+ it('ignores a description that merely mentions a burn, and an unknown family', () => {
+ const prose = '- [ ] #sys-3 | LOW | AUTO | Quota burn: agy should be investigated';
+ const bogus = '- [ ] #sys-4 | LOW | AUTO | [Quota burn: notafamily] whatever for App';
+ expect(stampBurnTaskProvenance(queue(prose, bogus)).stamped).toEqual([]);
+ });
+
+ it('stamps tasks in every section, including completed ones', () => {
+ const md = [
+ '# Tasks', '', '## Pending', burnTask('sys-1', 'claude'), '',
+ '## Completed', burnTask('sys-2', 'grok').replace('- [ ]', '- [x]'), '',
+ ].join('\n');
+ expect(stampBurnTaskProvenance(md).stamped).toEqual(['sys-1', 'sys-2']);
+ });
+});
+
+describe('migration 225 up()', () => {
+ let rootDir;
+ const tasksPath = () => join(rootDir, 'data', 'COS-TASKS.md');
+ beforeEach(async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'portos-225-'));
+ await mkdir(join(rootDir, 'data'), { recursive: true });
+ });
+ afterEach(async () => { await rm(rootDir, { recursive: true, force: true }); });
+
+ it('no-ops when the install has no CoS task queue', async () => {
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, reason: 'no-task-file' });
+ });
+
+ it('unsticks a burn task that was queued before the stamp existed', async () => {
+ // Without the stamp this task inherits the per-app review cooldown, never
+ // spawns, and blocks its own re-dispatch as a duplicate — so that job in the
+ // family's plan is permanently unreachable, not merely late.
+ await writeFile(tasksPath(), queue(burnTask('sys-msfm89zj')));
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, stamped: 1 });
+ const [task] = parseTasksMarkdown(await readFile(tasksPath(), 'utf-8'));
+ expect(task.metadata.quotaBurnFamily).toBe('agy');
+ });
+
+ it('is idempotent — a second run leaves the file byte-identical', async () => {
+ await writeFile(tasksPath(), queue(burnTask('sys-1')));
+ await migration.up({ rootDir });
+ const first = await readFile(tasksPath(), 'utf-8');
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ reason: 'already-stamped' });
+ expect(await readFile(tasksPath(), 'utf-8')).toBe(first);
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 4360015c58..4c1f9d9bf8 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -27,7 +27,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). |
| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. |
| `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |
-| `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`). 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`). Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225. Pure — no storage, no provider I/O. |
| `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)`. |
| `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body). |
| `quotaReset.js` | `parseHumanReset` turns a provider CLI's human reset string into ISO 8601 (call it from the adapter); `normalizeResetAt`/`hoursUntilReset` compute time remaining without treating unknown values as imminent resets. |
diff --git a/server/lib/quotaBurnConfig.js b/server/lib/quotaBurnConfig.js
index 53ac899425..2241b50e51 100644
--- a/server/lib/quotaBurnConfig.js
+++ b/server/lib/quotaBurnConfig.js
@@ -27,6 +27,32 @@ import { isPlainObject, POLLUTING_KEYS } from './objects.js';
/** Provider quota families a burn plan may target. Mirrors `providerUsage.js`'s card ids. */
export const QUOTA_BURN_FAMILIES = Object.freeze(['claude', 'codex', 'agy', 'grok']);
+/**
+ * How a queued burn task's description opens: `[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.
+ */
+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
+ * deliberately requires the exact minted shape rather than sniffing loosely.
+ */
+export function quotaBurnFamilyOfDescription(description) {
+ if (typeof description !== 'string' || !description.startsWith(QUOTA_BURN_TASK_PREFIX)) return null;
+ const family = description.slice(QUOTA_BURN_TASK_PREFIX.length).split(']')[0].trim();
+ return QUOTA_BURN_FAMILIES.includes(family) ? family : null;
+}
+
/**
* Every numeric/length bound in the plan, in ONE place.
*
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 821f0c2b4a..adac1c1c82 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -465,6 +465,12 @@ async function runAgentSpawn(task) {
// the proposal's domain. agent.metadata is a hand-picked projection of
// task.metadata (not a full spread), so this must be listed explicitly.
taskLiProposal: task.metadata?.liProposal || null,
+ // Quota-burn provenance. Same hand-picked-projection reason as
+ // `taskLiProposal`: the runner listens for `agent:completed` and dispatches
+ // the NEXT job in this family's burn plan when the previous one finishes,
+ // so it must be able to tell a burn run from any other agent from the
+ // agent record alone.
+ taskQuotaBurnFamily: task.metadata?.quotaBurnFamily || null,
// Same reason as taskLiProposal — a hand-picked projection, so this must be
// listed explicitly. `declaresNoCommitCriterion` (taskTypeHooks.js) reads it
// to decide whether a run declared a `[task-<id>]` commit criterion at all,
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index bbe247b352..1a0868fdf9 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -70,8 +70,8 @@ export function exceedsMaxSpawns(task) {
}
/**
- * A task that must BYPASS the per-app review cooldown at spawn time. Two classes
- * qualify, for the same reason — the cooldown is not their throttle:
+ * A task that must BYPASS the per-app review cooldown at spawn time. Three
+ * classes qualify, for the same reason — the cooldown is not their throttle:
* - **Pipeline continuations** (`metadata.pipeline.currentStage > 0`) — a
* multi-stage pipeline's own stage gating sequences the work.
* - **Perpetual drains** (`metadata.perpetual`) — the work-detector park is the
@@ -80,6 +80,15 @@ export function exceedsMaxSpawns(task) {
* the queue-path cooldown) would still be skipped here at the spawn gate,
* because the on-demand "Run" path stamped `lastReviewedAt` and these gates
* read it — so a manually-triggered perpetual drain stalls one item in.
+ * - **Quota burns** (`metadata.quotaBurnFamily`) — the throttle is the burn
+ * plan's own gate ladder: the reset-window horizon, the family's reserve, and
+ * `maxDispatchesPerWindow`, all checked before the task is ever queued. The
+ * app cooldown is re-stamped by EVERY completed task on that app, so on an app
+ * carrying any other recurring CoS work (a perpetual drain, which is itself
+ * exempt and therefore keeps completing) it never lapses — and the burn task
+ * sits in Pending until its window resets unspent, which is the exact outcome
+ * quota burn exists to prevent. (Tasks queued before this stamp existed are
+ * back-filled by migration 225, so the predicate reads metadata only.)
*
* `metadata.perpetual` is a bare boolean set upstream, but it round-trips through
* COS-TASKS.md as the STRING `"true"` (taskParser serializes non-string/-object
@@ -94,7 +103,9 @@ export function exceedsMaxSpawns(task) {
export function isCooldownExemptTask(task) {
const meta = task?.metadata;
if (!meta) return false;
- return meta.pipeline?.currentStage > 0 || meta.perpetual === true || meta.perpetual === 'true';
+ return meta.pipeline?.currentStage > 0
+ || meta.perpetual === true || meta.perpetual === 'true'
+ || Boolean(meta.quotaBurnFamily);
}
/**
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 1ed8d566e2..536fb5f7ed 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -171,6 +171,21 @@ describe('isCooldownExemptTask', () => {
it('does NOT exempt an ordinary app task', () => {
expect(isCooldownExemptTask({ metadata: { app: 'app-1', analysisType: 'security-audit' } })).toBe(false);
});
+ // A burn task's throttle is its family's gate ladder (reset horizon, reserve,
+ // maxDispatchesPerWindow), all checked before it is queued. The app cooldown is
+ // re-stamped by EVERY task that completes on that app, so on an app carrying a
+ // perpetual drain — itself exempt, so it keeps completing — the cooldown never
+ // lapses and the burn sits in Pending until its window expires unspent.
+ it('exempts a quota-burn task so a busy app cannot starve it', () => {
+ expect(isCooldownExemptTask({ metadata: { app: 'app-1', quotaBurnFamily: 'agy' } })).toBe(true);
+ });
+ // Deliberately metadata-only — a task queued before the stamp existed is
+ // back-filled by scripts/migrations/225-quota-burn-task-provenance.js, not
+ // recognised here by sniffing its description. That keeps a user-visible
+ // display string from becoming load-bearing for a scheduling gate.
+ it('does NOT exempt a burn-shaped description with no marker', () => {
+ expect(isCooldownExemptTask({ description: '[Quota burn: agy] Perf', metadata: { app: 'app-1' } })).toBe(false);
+ });
it('is null-safe for a task with no metadata', () => {
expect(isCooldownExemptTask(null)).toBe(false);
expect(isCooldownExemptTask({})).toBe(false);
diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.js
index 7560dab15d..cedef415dc 100644
--- a/server/services/cosTaskStore.js
+++ b/server/services/cosTaskStore.js
@@ -431,6 +431,10 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore
if (taskData.liProposal && typeof taskData.liProposal === 'object' && !Array.isArray(taskData.liProposal)) {
metadata.liProposal = taskData.liProposal;
}
+ // Which provider family's window this burn task is spending. Read by
+ // `isCooldownExemptTask` (cosTaskGenerator.js, which owns the why) and by
+ // quotaBurnRunner's completion continuation.
+ if (taskData.quotaBurnFamily) metadata.quotaBurnFamily = taskData.quotaBurnFamily;
// Content-edit timestamp for cross-peer newest-edit-wins LWW (#1714). Stamped
// at creation so a freshly-added task always carries a stamp; the merge treats
// an absent stamp as oldest, so this also keeps a stamped task from losing a
diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.js
index f577f75f73..167e3ca8e6 100644
--- a/server/services/cosTaskStore.test.js
+++ b/server/services/cosTaskStore.test.js
@@ -400,6 +400,19 @@ describe('cosTaskStore.addTask', () => {
expect(created.metadata.investigationFingerprint).toBeUndefined();
});
+ it('persists quota-burn provenance and omits it for every other task', async () => {
+ // `metadata` is an allowlist, so an unlisted key is silently dropped — and a
+ // dropped `quotaBurnFamily` makes the queued burn indistinguishable from any
+ // other system task at the cooldown gate and the completion continuation.
+ const burn = await addTask(
+ { description: '[Quota burn: agy] Perf', app: 'portos', quotaBurnFamily: 'agy' },
+ 'internal',
+ );
+ expect(burn.metadata.quotaBurnFamily).toBe('agy');
+ const ordinary = await addTask({ description: 'not a burn' }, 'user');
+ expect(ordinary.metadata.quotaBurnFamily).toBeUndefined();
+ });
+
it('omits diagnostics metadata when none is supplied and ignores a non-object / array value', async () => {
const created = await addTask({ description: 'no diagnostics here' }, 'user');
expect(created.metadata.diagnostics).toBeUndefined();
diff --git a/server/services/quotaBurnJobs/agentPrompt.js b/server/services/quotaBurnJobs/agentPrompt.js
index 2df27ad2e6..06bf947f35 100644
--- a/server/services/quotaBurnJobs/agentPrompt.js
+++ b/server/services/quotaBurnJobs/agentPrompt.js
@@ -15,6 +15,7 @@ import { addTask } from '../cosTaskStore.js';
import { getAppById } from '../apps.js';
import { getAllProviders } from '../providers.js';
import { commandBasename } from '../../lib/providerModels.js';
+import { burnTaskDescription } from '../../lib/quotaBurnConfig.js';
/**
* An agent-capable provider in the burning family. An explicit `providerId`
@@ -124,7 +125,7 @@ export async function run({ params, job, family, candidate, context } = {}) {
const discardsWorktree = params?.discardWorktree === true;
const landsNoCode = params?.noCodeOutput === true || discardsWorktree;
const task = await addTask({
- description: `[Quota burn: ${family.id}] ${label} for ${app.name}`,
+ description: burnTaskDescription(family.id, label, app.name),
app: app.id,
context: renderBurnPrompt({ family, candidate, prompt }),
provider: provider.id,
@@ -154,6 +155,10 @@ export async function run({ params, job, family, candidate, context } = {}) {
// idle-complete gate, which otherwise requires a dirty tree.
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) and by the runner's completion continuation.
+ quotaBurnFamily: family.id,
}, 'internal');
// A duplicate means an identical burn task for this app is still pending or
diff --git a/server/services/quotaBurnJobs/agentPrompt.test.js b/server/services/quotaBurnJobs/agentPrompt.test.js
index 7a7e0ef0c3..76d50f752d 100644
--- a/server/services/quotaBurnJobs/agentPrompt.test.js
+++ b/server/services/quotaBurnJobs/agentPrompt.test.js
@@ -9,6 +9,7 @@ vi.mock('../apps.js', () => ({ getAppById: vi.fn(async (id) => state.apps[id] ||
vi.mock('../providers.js', () => ({ getAllProviders: vi.fn(async () => state.providers) }));
const { countPending, providerForFamily, 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 } };
@@ -115,6 +116,22 @@ describe('run', () => {
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.
diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.js
index 5942ca1148..87389dcca1 100644
--- a/server/services/quotaBurnRunner.js
+++ b/server/services/quotaBurnRunner.js
@@ -4,9 +4,18 @@
* ONE loop lives in PortOS (not one scheduled task per managed app, which is
* what this replaced): every `checkIntervalMinutes` it reads the burn plan,
* takes a zero-token quota reading, and — only when a family's window is inside
- * its reset horizon with headroom above its reserve — runs the first job in that
+ * its reset horizon with headroom above its reserve — runs the next job in that
* family's ordered plan that reports pending work.
*
+ * The interval only STARTS a family's burn. Once a job is out, each finished burn
+ * agent triggers a fresh evaluation of that family (`onBurnAgentCompleted`), so
+ * the plan is walked one agent at a time until a gate closes — the window's
+ * dispatch cap, the reserve, or the reset horizon.
+ *
+ * "Next job" is literal — the walk resumes after the family's last dispatch
+ * rather than restarting at the top (`rotatePlanAfter`), so an N-job plan cycles
+ * through all N instead of re-running job #1 every time.
+ *
* At most one dispatch per FAMILY per cycle. Families do not share a budget:
* each one draws down its own subscription window, against its own reserve and
* its own `maxDispatchesPerWindow`. Stopping the whole cycle after the first
@@ -33,6 +42,7 @@ import { getQuotaBurnConfig, getQuotaBurnRuns, recordQuotaBurnRun } from './quot
import { countJobPending, runBurnJob } from './quotaBurnJobs/index.js';
import { familyIsActionable } from '../lib/quotaBurnConfig.js';
import { WAIT } from '../lib/staleWhileRevalidate.js';
+import { cosEvents } from './cosEvents.js';
const TICK_MS = 60_000;
@@ -54,16 +64,52 @@ const selectJobs = (family, { jobId = null, force = false } = {}) =>
(!jobId || job.id === jobId) && (job?.enabled !== false || (jobId && force)));
/**
- * Walk a candidate's plan in order and run the first job with pending work.
- * Returns the dispatch outcome plus the per-job reasons, so a cycle that
- * dispatched nothing still explains itself in the run log.
+ * The plan, re-anchored to start just AFTER the job this family last dispatched.
+ *
+ * A burn plan is an ordered ROTATION, not a priority list. Without this the walk
+ * restarts at index 0 every cycle, and since `agent-prompt` always reports work
+ * pending (its probe only checks that an app and a provider resolve), the first
+ * job in the plan won every dispatch forever — an eight-job agy plan spent its
+ * entire window re-running "Performance issues" and the other seven never ran
+ * once. Rotating preserves the "first job with pending work wins" semantics that
+ * matter for probing jobs like `universe-bible-images`; it only moves where the
+ * walk begins.
+ *
+ * An unknown cursor (first ever dispatch, a job since deleted from the plan, or
+ * one aged out of the capped run log) falls back to plan order.
+ */
+export function rotatePlanAfter(jobs, afterJobId) {
+ const at = afterJobId ? jobs.findIndex((job) => job.id === afterJobId) : -1;
+ return at < 0 ? jobs : [...jobs.slice(at + 1), ...jobs.slice(0, at + 1)];
+}
+
+/**
+ * Each family's most recently dispatched job id, read from the run log rather
+ * than a second persisted cursor file — `recordQuotaBurnRun` already stamps
+ * `familyId` + `jobId` on every dispatch, newest first, so the log IS the cursor.
+ */
+async function lastDispatchedJobByFamily() {
+ const runs = await getQuotaBurnRuns().catch(() => []);
+ const cursors = new Map();
+ for (const entry of runs) {
+ if (!entry?.dispatched || !entry.familyId || !entry.jobId) continue;
+ if (!cursors.has(entry.familyId)) cursors.set(entry.familyId, entry.jobId);
+ }
+ return cursors;
+}
+
+/**
+ * Walk a candidate's plan — starting after the family's last dispatch — and run
+ * the first job with pending work. Returns the dispatch outcome plus the per-job
+ * reasons, so a cycle that dispatched nothing still explains itself in the run
+ * log.
*
* The probe's `context` is handed to `run` rather than thrown away: a
* `universe-bible-images` probe reads every universe bible to count the backlog,
* and `run` needs the very same scan to know what to render. Without the
* passthrough that multi-megabyte read happened twice per dispatch.
*/
-async function dispatchFromCandidate(candidate, { jobId = null, force = false } = {}) {
+async function dispatchFromCandidate(candidate, { jobId = null, force = false, afterJobId = null } = {}) {
const attempts = [];
// A forced run of a NAMED job skips the pending probe entirely and calls the
// job directly. The probe exists to pick which job in the plan to run; when
@@ -74,7 +120,7 @@ async function dispatchFromCandidate(candidate, { jobId = null, force = false }
// override it from the page. `force` is threaded into the job so it can relax
// its own cooldown too.
const targeted = force && jobId;
- for (const job of selectJobs(candidate.family, { jobId, force })) {
+ for (const job of rotatePlanAfter(selectJobs(candidate.family, { jobId, force }), afterJobId)) {
const pending = targeted ? null : await countJobPending({ job, family: candidate.family });
if (pending && !(pending.count > 0)) {
attempts.push({ jobId: job.id, jobType: job.jobType, skipped: pending.detail || 'no pending work' });
@@ -135,8 +181,12 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
});
if (!config) return finish({ dispatched: false, reason: 'config unreadable' });
// A disabled tick writes NO run-log entry: a silent loop would otherwise fill
- // the log with "disabled" rows and bury the last real run.
- if (!config.enabled && trigger === 'scheduled') return { skipped: 'disabled' };
+ // the log with "disabled" rows and bury the last real run. Only a `manual`
+ // trigger — the user asking for this cycle by name — runs while the master
+ // switch is off; everything unattended (the interval tick AND the completion
+ // continuation it hands off to) stops. Phrased as "not manual" rather than an
+ // allowlist of automatic triggers so a trigger added later fails CLOSED.
+ if (!config.enabled && trigger !== 'manual') return { skipped: 'disabled' };
// Check the plan BEFORE the quota read. `getProviderQuotas({ wait: WAIT.FRESH })`
// spawns a multi-second TUI scrape per enabled family; with no actionable
@@ -152,7 +202,13 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
return finish({ dispatched: false, reason: 'no families enabled' });
}
- const quotas = await getProviderQuotas({ wait: WAIT.FRESH }).catch((err) => {
+ // Scoped to the one family when the caller named it — a per-family "Run now",
+ // or a completion continuation. Every card this read returns for another family
+ // is discarded by the `familyId` filter below, and each one costs its own
+ // multi-second PTY scrape (WAIT.FRESH bypasses the cache by design). Unscoped
+ // that was two wasted scrapes a day; with the continuation it would be N per
+ // finished burn agent, on every link of the chain.
+ const quotas = await getProviderQuotas({ wait: WAIT.FRESH, family: familyId }).catch((err) => {
console.error(`❌ Quota-burn could not read provider quota: ${err.message}`);
return null;
});
@@ -184,12 +240,18 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
const attempts = [];
const dispatched = [];
+ // Where each family's plan walk resumes (see `rotatePlanAfter`). Read once per
+ // cycle, before any dispatch, so two families in the same cycle can't see each
+ // other's fresh run-log entries.
+ const cursors = await lastDispatchedJobByFamily();
// Every eligible family gets its own dispatch — see the module header. The
// loop does NOT break on the first success: `candidates` is already the set
// that passed the full gate ladder, and each entry spends a different
// provider's window.
for (const candidate of candidates) {
- const outcome = await dispatchFromCandidate(candidate, { jobId, force });
+ const outcome = await dispatchFromCandidate(candidate, {
+ jobId, force, afterJobId: cursors.get(candidate.family.id) || null,
+ });
attempts.push(...outcome.attempts.map((entry) => ({ familyId: candidate.family.id, ...entry })));
if (!outcome.dispatched) continue;
// Charge the window only once work actually started. `runBurnJob` reports a
@@ -325,6 +387,31 @@ async function lastScheduledRunAt() {
return lastRunAt;
}
+/**
+ * Continuation: when a burn agent finishes, evaluate its family again so the
+ * NEXT job in the plan goes out.
+ *
+ * Without this the plan advances only once per `checkIntervalMinutes` — at the
+ * 12-hour default, two dispatches a day against a `maxDispatchesPerWindow` of 5
+ * on a window that resets every 5 hours, so most of the allowance the feature
+ * exists to spend expired unspent. Completion is the right pacing signal: it
+ * runs the plan strictly one agent at a time and asks the gate ladder, every
+ * time, whether there is still quota to spend.
+ *
+ * It cannot run away. Every continuation dispatch is charged to the window's
+ * ledger, so `maxDispatchesPerWindow` bounds the chain, and the reserve /
+ * reset-horizon gates close it earlier when the quota actually runs out.
+ */
+function onBurnAgentCompleted(agent) {
+ const familyId = agent?.metadata?.taskQuotaBurnFamily;
+ if (!familyId) return null;
+ // Returned so tests can await the cycle. The emitter ignores it — this is a
+ // fire-and-forget listener, and the `.catch` is what keeps a rejection from
+ // reaching the emitter as an unhandled one.
+ return runQuotaBurnCycle({ trigger: 'continuation', familyId })
+ .catch((err) => console.error(`❌ Quota-burn continuation for ${familyId} failed: ${err.message}`));
+}
+
async function tick() {
const config = await getQuotaBurnConfig().catch(() => null);
if (!config?.enabled) return;
@@ -348,16 +435,24 @@ export function startQuotaBurnScheduler() {
tick().catch((err) => console.error(`❌ Quota-burn tick failed: ${err.message}`));
}, TICK_MS);
tickTimer.unref?.();
+ // Same "outside the request lifecycle" posture as the timer: an emitter
+ // callback that throws would take the process down, so `onBurnAgentCompleted`
+ // never awaits and never rethrows.
+ cosEvents.on('agent:completed', onBurnAgentCompleted);
console.log('🔥 Quota-burn loop armed (off unless enabled in Quota Burn settings)');
}
/** Test seam — one interval tick, without waiting on the timer. */
export const __tickQuotaBurn = tick;
-/** Test seam — disarms the timer and clears the in-process cycle state. */
+/** Test seam — the completion continuation, without going through cosEvents. */
+export const __onBurnAgentCompleted = onBurnAgentCompleted;
+
+/** Test seam — disarms the timer/listener and clears the in-process cycle state. */
export function __resetQuotaBurnRunner() {
if (tickTimer) clearInterval(tickTimer);
tickTimer = null;
+ cosEvents.off('agent:completed', onBurnAgentCompleted);
running = false;
lastRunAt = null;
}
diff --git a/server/services/quotaBurnRunner.test.js b/server/services/quotaBurnRunner.test.js
index a099d4028d..27429841b2 100644
--- a/server/services/quotaBurnRunner.test.js
+++ b/server/services/quotaBurnRunner.test.js
@@ -44,7 +44,7 @@ vi.mock('./quotaBurn.js', async (importActual) => ({
}));
const { normalizeQuotaBurnConfig } = await import('../lib/quotaBurnConfig.js');
-const { getQuotaBurnStatus, runQuotaBurnCycle, __tickQuotaBurn, __resetQuotaBurnRunner } = await import('./quotaBurnRunner.js');
+const { getQuotaBurnStatus, runQuotaBurnCycle, rotatePlanAfter, __tickQuotaBurn, __onBurnAgentCompleted, __resetQuotaBurnRunner } = await import('./quotaBurnRunner.js');
const card = (family, percentRemaining = 50) => ({
family, label: family, supported: true,
@@ -368,6 +368,107 @@ describe('interval clock', () => {
});
});
+describe('plan rotation', () => {
+ it('resumes after the job the family last dispatched instead of restarting at the top', async () => {
+ // `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 } };
+ await runQuotaBurnCycle({ trigger: 'manual' });
+ await runQuotaBurnCycle({ trigger: 'manual' });
+ expect(state.ran.map((entry) => entry.jobId)).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.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']);
+ });
+
+ it('falls back to plan order for a cursor that is not in the plan', () => {
+ // A job deleted from the plan, or one aged out of the capped run log.
+ const jobs = [{ id: 'a' }, { id: 'b' }, { id: 'c' }];
+ expect(rotatePlanAfter(jobs, 'gone').map((job) => job.id)).toEqual(['a', 'b', 'c']);
+ expect(rotatePlanAfter(jobs, null).map((job) => job.id)).toEqual(['a', 'b', 'c']);
+ expect(rotatePlanAfter(jobs, 'a').map((job) => job.id)).toEqual(['b', 'c', 'a']);
+ expect(rotatePlanAfter(jobs, 'c').map((job) => job.id)).toEqual(['a', 'b', 'c']);
+ });
+
+ it('reads every family\'s cursor before any dispatch writes a new one', async () => {
+ // Two families in one cycle must not see each other's fresh run-log rows.
+ 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' }] },
+ },
+ });
+ state.quotas = [card('claude'), card('agy')];
+ state.pending = { 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']);
+ });
+});
+
+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 } };
+ 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.recorded).toHaveLength(2);
+ expect(state.runs[0]).toMatchObject({ trigger: 'continuation', dispatched: true });
+ });
+
+ it('scrapes only the burning family\'s quota, not every enabled provider\'s', async () => {
+ // WAIT.FRESH bypasses the cache by design, so each card costs its own
+ // 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 } };
+ await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });
+ expect(getProviderQuotas).toHaveBeenCalledWith(expect.objectContaining({ family: 'grok' }));
+ });
+
+ it('ignores an agent that was not a quota burn', async () => {
+ state.pending = { first: { count: 1 } };
+ await __onBurnAgentCompleted({ metadata: { taskType: 'user' } });
+ await __onBurnAgentCompleted(null);
+ expect(state.ran).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 } };
+ await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });
+ expect(state.ran).toEqual([]);
+ expect(state.runs).toEqual([]);
+ });
+
+ it('stops once the window has no quota left to spend', async () => {
+ // 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 } };
+ await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });
+ expect(state.ran).toEqual([]);
+ expect(state.runs).toHaveLength(1);
+ expect(state.runs[0]).toMatchObject({ trigger: 'continuation', dispatched: false });
+ expect(state.runs[0].reason).toMatch(/reserve/);
+ });
+});
+
describe('forced run bypasses the pending probe', () => {
it('calls the job directly instead of letting its own probe veto the click', async () => {
// The probe exists to PICK a job. When the user already picked one, letting