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

move quota-burn off the per-app CoS task type onto one install-level loop with its own page

[._.]/ Adam Eivy8d5379583847
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 69bedd2d4b..e1a1a86f35 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,3 +1,9 @@
+## Added
+
+- **Quota Burn is now its own page (`Dev Tools → Quota Burn`) driven by one programmatic loop.** It used to be a `quota-burn` entry in each managed app's `taskTypeOverrides`, which meant the schedule, the provider windows, and the burn prompt were duplicated per app — and two enabled apps ran two independent loops racing for the same window budget, even though quota belongs to the machine, not to any one repo. There is now ONE install-level loop inside PortOS reading one machine-local plan (`data/cos/quota-burn.json`), with a full config surface: master switch, poll interval, and per-provider-family reset window / reserve / dispatch cap / priority.
+- **Each family runs an ORDERED list of burn jobs, each with its own type, model, and target** — so "have codex render every universe bible entry that has no image, and only then fall through to agent work" is expressible. Two job types ship: `agent-prompt` (the previous behavior — queue a CoS agent in a *named* managed app, so the work can still target any app) and `universe-bible-images`, a fully programmatic job that enqueues renders for bible entries whose `imageRefs[]` is empty, defaulting the render backend to the burning family's own image mode so a codex burn spends codex's image quota. A new job type is three server edits; the config form builds itself from the server's job catalog.
+- The page states, per family, whether it will burn on the next tick and — when it won't — the exact gate that closed (`resets in 40h — outside the 24h window`, `dispatch cap reached (2/2)`, `62% left is at or below the 70% reserve`), evaluated by the same predicate the runner uses. Per-job pending counts, a run log that records skips *with reasons*, and manual "Evaluate now" / "Burn now" / per-job force-run controls are all on the page.
+
## Fixed
- **A completed TUI agent could be recorded as failed by a duplicate finalize.** `cleanupOrphanedAgents` runs every 15 minutes and calls `syncRunnerAgents`, which only checked `runnerAgents` for "already tracked" — but a runner-backed TUI agent is owned by the live `spawnTuiAgent` closure, which registers in `activeAgents` and never in `runnerAgents`. Any TUI run outliving one health-check tick was therefore hoisted into `runnerAgents` mid-flight, so the `agent:completed` event the runner emits when the TUI spawner's own `finish()` kills the session slipped past the `if (!agent) return` guard and ran a *second* `finalizeAgent`. That overwrote a sentinel-signalled success with `success: false, exitCode: 143` plus a bogus `startup-failure` analysis (computed from an output buffer that path can't read — a TUI writes `output.txt` under the dated run dir, not `AGENTS_DIR/<id>`), which in turn flipped the agent card to Failed and requeued the already-finished task as `pending`. Observed on a 55-minute release-check run that had already published v2.37.0 and merged all three of its PRs.
@@ -5,6 +11,7 @@
## Changed
- **The chiptune preview loop now shows where it is.** `ChiptunePanel`'s Play/Stop row gained a thin progress bar and elapsed/total timecode for the 15–30s loop, driven by a requestAnimationFrame clock that reads the player's transport position and paints straight into the DOM (no per-frame React render). `createChiptunePlayer` exposes `position()` + `loopSec()` for it — the length of the schedule actually sounding, so a mid-preview regeneration can't re-scale the bar against a loop nobody is hearing yet.
+- **`quota-burn` is no longer a scheduled CoS task type.** The type, its perpetual work-detector, its programmatic-I/O hooks, and the cramped inline family editor in the CoS schedule tab are all gone. Migration 221 folds every app's existing override into the new global plan (each family's prompt becomes an `agent-prompt` job pointing back at the app it came from, and an install that never enabled the feature stays silent) and strips the dead task type from `data/apps.json`. Two apps that configured the same family keep BOTH prompts as ordered jobs — dropping one would silently lose configured work.
- **"Does this process own the agent?" is now one named predicate.** Ownership is split across `activeAgents` and `runnerAgents` by spawn mode, and which map an agent lands in isn't guessable from its `executionMode` — a `runner-tui` agent is driven locally and registers in `activeAgents` even though the runner owns its process and lists it. That implicit protocol was open-coded at two call sites, one of which had it wrong (above). `isAgentOwnedLocally` in `agentState.js` now owns the invariant, and `syncRunnerAgents` + `cleanupOrphanedAgents` both call it.
- `handleAgentCompletion` bails when the persisted record is already terminal — the same check its post-restart branch has always had — so any double-completion path is a no-op rather than a clobbering re-finalize.
- **The Music Video page is a composition, not a 1,492-line component.** Its seven co-located concerns are now six named hooks in `client/src/hooks/` (`useMusicVideoYoutubeImport`, `useMusicVideoMidiJob`, `useMusicVideoRenderJob`, `useMusicVideoModelSettings`, `useMusicVideoSceneMedia`, `useMusicVideoManualTempo`) plus seven presentational components in `client/src/components/musicVideo/`, leaving `MusicVideo.jsx` at 529 lines of project/scene CRUD and page shell. Behavior is unchanged — same polling flows, settings persistence, and render lifecycle. (#3386)
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 47fd0c1967..46c3f0c49d 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -38,6 +38,7 @@ const Goals = lazyWithReload(() => import('./pages/Goals'));
const OpenClawPage = lazyWithReload(() => import('./pages/OpenClaw'));
const Submodules = lazyWithReload(() => import('./pages/Submodules'));
const ImageClean = lazyWithReload(() => import('./pages/ImageClean'));
+const QuotaBurn = lazyWithReload(() => import('./pages/QuotaBurn'));
const VideoDownloaderPage = lazyWithReload(() => import('./pages/VideoDownloaderPage'));
const ChiefOfStaff = lazyWithReload(() => import('./pages/ChiefOfStaff'));
const Ask = lazyWithReload(() => import('./pages/Ask'));
@@ -251,6 +252,8 @@ export default function App() {
<Route path="devtools/github" element={<GitHub />} />
<Route path="devtools/history" element={<HistoryPage />} />
<Route path="devtools/image-clean" element={<ImageClean />} />
+ <Route path="devtools/quota-burn" element={<QuotaBurn />} />
+ <Route path="devtools/quota-burn/:familyId" element={<QuotaBurn />} />
<Route path="devtools/runs" element={<RunsHistoryPage />} />
<Route path="devtools/runner" element={<RunnerPage />} />
<Route path="devtools/submodules" element={<Submodules />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index c9c9fa32f4..1fc7e1a263 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -267,6 +267,7 @@ const navItems = [
{ to: '/devtools/jira/reports', label: 'JIRA Reports', icon: FileText },
{ to: '/loops', label: 'Loops', icon: RefreshCw },
{ to: '/devtools/processes', label: 'Processes', icon: Activity },
+ { to: '/devtools/quota-burn', label: 'Quota Burn', icon: Flame },
{ to: '/security', label: 'Security', icon: Camera },
{ to: '/shell', label: 'Shell', icon: SquareTerminal },
{ to: '/devtools/submodules', label: 'Submodules', icon: GitBranch },
diff --git a/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx b/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx
index 7810a90916..a4b2eee9a7 100644
--- a/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx
+++ b/client/src/components/cos/tabs/schedule/AppOverrideRow.jsx
@@ -5,7 +5,6 @@ import { AGENT_OPTIONS, ISSUE_AUTHOR_FILTER_OPTIONS, ISSUE_AUTHOR_FILTER_TASK_TY
import { isCronExpression, describeCron } from '../../../../utils/cronHelpers';
import ToggleSwitch from '../../../ToggleSwitch';
import { INTERVAL_LABELS } from './scheduleConstants';
-import QuotaBurnFamilyEditor from './QuotaBurnFamilyEditor';
const AppOverrideRow = memo(function AppOverrideRow({ app, taskType, globalIntervalType, globalTaskMetadata, managedAgentOptions, override, onUpdate }) {
const [updating, setUpdating] = useState(false);
@@ -192,17 +191,6 @@ const AppOverrideRow = memo(function AppOverrideRow({ app, taskType, globalInter
/>
</div>
- {taskType === 'quota-burn' && (
- <QuotaBurnFamilyEditor
- metadata={override?.taskMetadata}
- disabled={updating}
- onSave={async (taskMetadata) => {
- setUpdating(true);
- await onUpdate(app.id, taskType, { taskMetadata }).catch(() => {});
- setUpdating(false);
- }}
- />
- )}
</div>
</div>
);
diff --git a/client/src/components/cos/tabs/schedule/QuotaBurnFamilyEditor.jsx b/client/src/components/cos/tabs/schedule/QuotaBurnFamilyEditor.jsx
deleted file mode 100644
index e4ba70cc52..0000000000
--- a/client/src/components/cos/tabs/schedule/QuotaBurnFamilyEditor.jsx
+++ /dev/null
@@ -1,41 +0,0 @@
-import { useState } from 'react';
-
-const FAMILIES = ['claude', 'codex', 'agy', 'grok'];
-const defaults = { enabled: false, prompt: '', providerId: null, model: null, scope: null, resetWithinHours: 24, reservePercent: 0, maxDispatchesPerWindow: 5, priority: 0 };
-
-export default function QuotaBurnFamilyEditor({ metadata, onSave, disabled }) {
- const [expanded, setExpanded] = useState(null);
- const families = metadata?.families || {};
- const saveFamily = (id, patch) => {
- const next = { ...defaults, ...(families[id] || {}), ...patch };
- onSave({ ...(metadata || {}), families: { ...families, [id]: next } });
- };
-
- return (
- <div className="w-full mt-2 rounded border border-port-border bg-port-card/30 p-3 space-y-2">
- <p className="text-xs text-gray-300">Quota-burn families run only near reset, stay disabled until configured, and never dispatch on an unknown reset time.</p>
- {FAMILIES.map((id) => {
- const family = { ...defaults, ...(families[id] || {}) };
- const open = expanded === id;
- return (
- <div key={id} className="rounded border border-port-border/70 p-2">
- <div className="flex items-center gap-2">
- <input id={`quota-burn-${id}`} type="checkbox" checked={family.enabled} disabled={disabled} onChange={(event) => saveFamily(id, { enabled: event.target.checked })} />
- <label htmlFor={`quota-burn-${id}`} className="text-sm capitalize text-white flex-1">{id}</label>
- <button type="button" className="text-xs text-port-accent hover:underline" onClick={() => setExpanded(open ? null : id)}>{open ? 'Hide settings' : 'Configure'}</button>
- </div>
- {open && (
- <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 mt-3 text-xs">
- <label className="text-gray-400">Reset window (hours)<input className="w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white" type="number" min="0" value={family.resetWithinHours} disabled={disabled} onChange={(event) => saveFamily(id, { resetWithinHours: Number(event.target.value) })} /></label>
- <label className="text-gray-400">Reserve (%)<input className="w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white" type="number" min="0" max="100" value={family.reservePercent} disabled={disabled} onChange={(event) => saveFamily(id, { reservePercent: Number(event.target.value) })} /></label>
- <label className="text-gray-400">Dispatch cap<input className="w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white" type="number" min="1" value={family.maxDispatchesPerWindow} disabled={disabled} onChange={(event) => saveFamily(id, { maxDispatchesPerWindow: Number(event.target.value) })} /></label>
- <label className="text-gray-400">Provider ID (optional)<input className="w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white" value={family.providerId || ''} disabled={disabled} onChange={(event) => saveFamily(id, { providerId: event.target.value || null })} /></label>
- <label className="sm:col-span-2 text-gray-400">Work prompt<textarea className="w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white min-h-20" value={family.prompt} disabled={disabled} onChange={(event) => saveFamily(id, { prompt: event.target.value })} /></label>
- </div>
- )}
- </div>
- );
- })}
- </div>
- );
-}
diff --git a/client/src/components/quotaBurn/FamilyCard.jsx b/client/src/components/quotaBurn/FamilyCard.jsx
new file mode 100644
index 0000000000..04ce4682c6
--- /dev/null
+++ b/client/src/components/quotaBurn/FamilyCard.jsx
@@ -0,0 +1,167 @@
+/**
+ * One provider family's burn plan: the window gates that decide WHEN it burns,
+ * plus the ordered job list that decides WHAT it burns on.
+ *
+ * The header always states whether this family would burn on the next tick and,
+ * when it wouldn't, the exact reason the runner gave — the same predicate the
+ * runner evaluates, so the card can't disagree with what actually happens.
+ */
+
+import { ChevronDown, ChevronRight, Flame, Plus } from 'lucide-react';
+import JobRow from './JobRow';
+
+const numberField = (id, label, value, onChange, { min, max, step, hint }) => (
+ <label htmlFor={id} className="block text-xs text-gray-400">
+ {label}
+ <input
+ id={id}
+ type="number"
+ min={min}
+ max={max}
+ step={step}
+ className="w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white text-xs"
+ value={value}
+ onChange={(event) => onChange(Number(event.target.value))}
+ />
+ {hint && <span className="block mt-1 text-[11px] text-gray-500">{hint}</span>}
+ </label>
+);
+
+export default function FamilyCard({
+ familyId, config, status, catalog, expanded, actionsBusy,
+ onToggleExpand, onPatch, onRunFamily, onRunJob,
+}) {
+ const jobs = config.jobs || [];
+ // Pending counts arrive on the STATUS copy of each job (the config copy is
+ // what the form edits) — match by id so a reorder mid-save can't mis-pair them.
+ const withPending = jobs.map((job) => ({
+ ...job,
+ pending: (status?.jobs || []).find((row) => row.id === job.id)?.pending || null,
+ }));
+
+ // `pending` is a STATUS field grafted on for display below; the PUT schema is
+ // strict, so it has to come back off before a job is persisted.
+ const patchJobs = (next) => onPatch({ jobs: next.map(({ pending: _pending, ...job }) => job) });
+ const changeJob = (index, next) => patchJobs(jobs.map((job, i) => (i === index ? next : job)));
+ const moveJob = (index, delta) => {
+ const next = [...jobs];
+ const [moved] = next.splice(index, 1);
+ next.splice(index + delta, 0, moved);
+ patchJobs(next);
+ };
+ const addJob = () => patchJobs([...jobs, {
+ id: `job-${Date.now().toString(36)}`,
+ enabled: true,
+ label: '',
+ jobType: catalog.jobTypes[0]?.id,
+ model: null,
+ providerId: null,
+ params: {},
+ }]);
+
+ return (
+ <div className="rounded border border-port-border bg-port-card/40">
+ <div className="flex flex-wrap items-center gap-3 p-3">
+ <input
+ id={`burn-family-${familyId}`}
+ type="checkbox"
+ checked={config.enabled}
+ onChange={(event) => onPatch({ enabled: event.target.checked })}
+ />
+ <label htmlFor={`burn-family-${familyId}`} className="text-sm font-medium capitalize text-white">
+ {status?.label || familyId}
+ </label>
+
+ {status?.willBurn ? (
+ <span className="inline-flex items-center gap-1 text-xs text-emerald-400">
+ <Flame size={13} />
+ {status.percentRemaining}% left · resets in {status.hoursUntilReset}h · {status.dispatchesUsed}/{config.maxDispatchesPerWindow} used
+ </span>
+ ) : (
+ <span className="text-xs text-gray-500">{status?.skipReason || 'not evaluated yet'}</span>
+ )}
+
+ <div className="ml-auto flex items-center gap-2">
+ <button
+ type="button"
+ className="text-xs text-port-accent hover:underline disabled:opacity-40"
+ disabled={actionsBusy || !status?.willBurn}
+ onClick={() => onRunFamily(familyId)}
+ title={status?.willBurn ? 'Run this family\'s next job now' : 'This family has no burnable window right now'}
+ >
+ Burn now
+ </button>
+ <button
+ type="button"
+ className="inline-flex items-center gap-1 text-xs text-gray-300 hover:text-white"
+ onClick={() => onToggleExpand(familyId)}
+ >
+ {expanded ? <ChevronDown size={14} /> : <ChevronRight size={14} />}
+ {expanded ? 'Hide' : 'Configure'}
+ </button>
+ </div>
+ </div>
+
+ {expanded && (
+ <div className="border-t border-port-border/60 p-3 space-y-4">
+ <div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
+ {numberField(`burn-${familyId}-window`, 'Burn within (hours of reset)', config.resetWithinHours, (v) => onPatch({ resetWithinHours: v }), { min: 0, max: 168, hint: 'Only spend as the window is about to expire.' })}
+ {numberField(`burn-${familyId}-reserve`, 'Reserve (%)', config.reservePercent, (v) => onPatch({ reservePercent: v }), { min: 0, max: 100, hint: 'Never spend below this much headroom.' })}
+ {numberField(`burn-${familyId}-cap`, 'Dispatch cap per window', config.maxDispatchesPerWindow, (v) => onPatch({ maxDispatchesPerWindow: v }), { min: 1, max: 50, hint: 'Max automatic burns per reset window.' })}
+ {numberField(`burn-${familyId}-priority`, 'Priority', config.priority, (v) => onPatch({ priority: v }), { min: 0, max: 100, hint: 'Lower wins when two windows reset together.' })}
+ </div>
+
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <label htmlFor={`burn-${familyId}-provider`} className="block text-xs text-gray-400">
+ Provider ID (optional)
+ <input
+ id={`burn-${familyId}-provider`}
+ className="w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white text-xs"
+ value={config.providerId || ''}
+ placeholder="auto-match by family"
+ onChange={(event) => onPatch({ providerId: event.target.value || null })}
+ />
+ </label>
+ <label htmlFor={`burn-${familyId}-scope`} className="block text-xs text-gray-400">
+ Window scope (optional)
+ <input
+ id={`burn-${familyId}-scope`}
+ className="w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white text-xs"
+ value={config.scope || ''}
+ placeholder="e.g. week — blank watches every window"
+ onChange={(event) => onPatch({ scope: event.target.value || null })}
+ />
+ </label>
+ </div>
+
+ <div className="space-y-3">
+ <div className="flex items-center justify-between">
+ <h3 className="text-xs uppercase tracking-wide text-gray-400">Burn plan — runs in order</h3>
+ <button type="button" className="inline-flex items-center gap-1 text-xs text-port-accent hover:underline" onClick={addJob}>
+ <Plus size={13} /> Add job
+ </button>
+ </div>
+ {!withPending.length && (
+ <p className="text-xs text-gray-500">No jobs yet — this family will never burn until one is added.</p>
+ )}
+ {withPending.map((job, index) => (
+ <JobRow
+ key={job.id}
+ job={job}
+ index={index}
+ total={withPending.length}
+ jobTypes={catalog.jobTypes}
+ catalog={catalog}
+ actionsBusy={actionsBusy}
+ onChange={(next) => changeJob(index, next)}
+ onMove={moveJob}
+ onRemove={(i) => patchJobs(jobs.filter((_, x) => x !== i))}
+ onRun={(target) => onRunJob(familyId, target)}
+ />
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/quotaBurn/JobParamField.jsx b/client/src/components/quotaBurn/JobParamField.jsx
new file mode 100644
index 0000000000..0c91222688
--- /dev/null
+++ b/client/src/components/quotaBurn/JobParamField.jsx
@@ -0,0 +1,85 @@
+/**
+ * One burn-job parameter input, rendered from the server's param descriptor
+ * (`QUOTA_BURN_JOB_CATALOG[].params[]`). Keeping the descriptor server-side is
+ * what lets a new job type ship without a client change — this component only
+ * needs to know the param KINDS, not any particular job's fields.
+ */
+
+const inputClass = 'w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white text-xs';
+
+export default function JobParamField({ descriptor, value, onChange, options, idPrefix }) {
+ const id = `${idPrefix}-${descriptor.key}`;
+ const current = value ?? descriptor.default ?? '';
+
+ if (descriptor.kind === 'boolean') {
+ return (
+ <label htmlFor={id} className="flex items-center gap-2 text-xs text-gray-300">
+ <input
+ id={id}
+ type="checkbox"
+ checked={value ?? descriptor.default ?? false}
+ onChange={(event) => onChange(descriptor.key, event.target.checked)}
+ />
+ {descriptor.label}
+ </label>
+ );
+ }
+
+ if (descriptor.kind === 'text') {
+ return (
+ <label htmlFor={id} className="block sm:col-span-2 text-xs text-gray-400">
+ {descriptor.label}
+ <textarea
+ id={id}
+ className={`${inputClass} min-h-24 font-mono`}
+ value={current}
+ placeholder="What should this provider spend its remaining quota on?"
+ onChange={(event) => onChange(descriptor.key, event.target.value)}
+ />
+ </label>
+ );
+ }
+
+ if (descriptor.kind === 'number') {
+ return (
+ <label htmlFor={id} className="block text-xs text-gray-400">
+ {descriptor.label}
+ <input
+ id={id}
+ type="number"
+ min={descriptor.min}
+ max={descriptor.max}
+ className={inputClass}
+ value={current}
+ onChange={(event) => onChange(descriptor.key, Number(event.target.value))}
+ />
+ </label>
+ );
+ }
+
+ // Everything else is a select over a list the page supplied (apps, universes,
+ // image modes) or the descriptor's own enum. An `all`/`default` sentinel row
+ // is emitted for the kinds whose default is "no pin".
+ const rows = descriptor.kind === 'enum'
+ ? (descriptor.options || []).map((option) => ({ value: option, label: option }))
+ : (options || []).map((option) => ({ value: option.id ?? option, label: option.name ?? option }));
+ const sentinel = descriptor.kind === 'universe'
+ ? { value: 'all', label: 'All universes' }
+ : (descriptor.kind === 'imageMode' ? { value: '', label: 'Match the burning provider' } : null);
+
+ return (
+ <label htmlFor={id} className="block text-xs text-gray-400">
+ {descriptor.label}
+ <select
+ id={id}
+ className={inputClass}
+ value={current ?? ''}
+ onChange={(event) => onChange(descriptor.key, event.target.value || null)}
+ >
+ {sentinel && <option value={sentinel.value}>{sentinel.label}</option>}
+ {descriptor.required && !sentinel && <option value="">Select…</option>}
+ {rows.map((row) => <option key={row.value} value={row.value}>{row.label}</option>)}
+ </select>
+ </label>
+ );
+}
diff --git a/client/src/components/quotaBurn/JobRow.jsx b/client/src/components/quotaBurn/JobRow.jsx
new file mode 100644
index 0000000000..f1c5ba68eb
--- /dev/null
+++ b/client/src/components/quotaBurn/JobRow.jsx
@@ -0,0 +1,96 @@
+/**
+ * One burn job inside a family's ordered plan: its type, its per-job model, its
+ * type-specific params, and the controls that move/remove/run it.
+ *
+ * Order is meaningful — the runner takes the FIRST enabled job with pending
+ * work — so the move controls are part of the configuration, not a convenience.
+ */
+
+import { ArrowDown, ArrowUp, Play, Trash2 } from 'lucide-react';
+import JobParamField from './JobParamField';
+
+const inputClass = 'w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white text-xs';
+
+export default function JobRow({
+ job, index, total, jobTypes, catalog, actionsBusy,
+ onChange, onMove, onRemove, onRun,
+}) {
+ const spec = jobTypes.find((type) => type.id === job.jobType);
+ const idPrefix = `burn-job-${job.id}`;
+ const setParam = (key, value) => onChange({ ...job, params: { ...job.params, [key]: value } });
+ const optionsFor = (descriptor) => ({
+ app: catalog.apps,
+ universe: catalog.universes,
+ imageMode: catalog.imageModes,
+ })[descriptor.kind];
+
+ const pending = job.pending;
+
+ return (
+ <div className="rounded border border-port-border/70 bg-port-bg/40 p-3 space-y-3">
+ <div className="flex flex-wrap items-center gap-2">
+ <input
+ id={`${idPrefix}-enabled`}
+ type="checkbox"
+ checked={job.enabled !== false}
+ onChange={(event) => onChange({ ...job, enabled: event.target.checked })}
+ />
+ <label htmlFor={`${idPrefix}-enabled`} className="text-xs text-gray-400">Step {index + 1}</label>
+ <input
+ className="flex-1 min-w-40 bg-port-bg border border-port-border rounded p-2 text-white text-xs"
+ value={job.label || ''}
+ placeholder={spec?.label || 'Job name'}
+ aria-label={`Name for step ${index + 1}`}
+ onChange={(event) => onChange({ ...job, label: event.target.value })}
+ />
+ <div className="flex items-center gap-1">
+ <button type="button" className="p-1 text-gray-400 hover:text-white disabled:opacity-30" disabled={index === 0} onClick={() => onMove(index, -1)} aria-label={`Move step ${index + 1} earlier`}><ArrowUp size={14} /></button>
+ <button type="button" className="p-1 text-gray-400 hover:text-white disabled:opacity-30" disabled={index === total - 1} onClick={() => onMove(index, 1)} aria-label={`Move step ${index + 1} later`}><ArrowDown size={14} /></button>
+ <button type="button" className="p-1 text-port-accent hover:text-white disabled:opacity-30" disabled={actionsBusy} onClick={() => onRun(job)} aria-label={`Run step ${index + 1} now`} title="Run this job now, ignoring the reset window"><Play size={14} /></button>
+ <button type="button" className="p-1 text-red-400 hover:text-red-300 disabled:opacity-30" onClick={() => onRemove(index)} aria-label={`Remove step ${index + 1}`}><Trash2 size={14} /></button>
+ </div>
+ </div>
+
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <label htmlFor={`${idPrefix}-type`} className="block text-xs text-gray-400">
+ Job type
+ <select
+ id={`${idPrefix}-type`}
+ className={inputClass}
+ value={job.jobType}
+ onChange={(event) => onChange({ ...job, jobType: event.target.value, params: {} })}
+ >
+ {jobTypes.map((type) => <option key={type.id} value={type.id}>{type.label}</option>)}
+ </select>
+ </label>
+ <label htmlFor={`${idPrefix}-model`} className="block text-xs text-gray-400">
+ Model (optional)
+ <input
+ id={`${idPrefix}-model`}
+ className={inputClass}
+ value={job.model || ''}
+ placeholder="provider default"
+ onChange={(event) => onChange({ ...job, model: event.target.value || null })}
+ />
+ </label>
+ {(spec?.params || []).map((descriptor) => (
+ <JobParamField
+ key={descriptor.key}
+ descriptor={descriptor}
+ value={job.params?.[descriptor.key]}
+ options={optionsFor(descriptor)}
+ idPrefix={idPrefix}
+ onChange={setParam}
+ />
+ ))}
+ </div>
+
+ {spec?.description && <p className="text-[11px] text-gray-500">{spec.description}</p>}
+ {pending && (
+ <p className={`text-[11px] ${pending.count > 0 ? 'text-emerald-400' : 'text-gray-500'}`}>
+ {pending.count > 0 ? `Ready — ${pending.detail}` : `Idle — ${pending.detail}`}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 890e320614..fb3088c359 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -84,6 +84,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `boundedMap.js` | `evictOldest(map, max, onEvict?)` — evict oldest-first (`map.keys().next().value`) until a Map is within `max`, with an optional per-evicted-key teardown callback for a companion timer map; `ORPHAN_BUFFER_MAX` (64), the shared cap for the orphan-event race-buffers. The one home for the "stash an unmatched event in a `jobId → …` Map, evict the oldest on overflow" idiom shared by `useSceneRenderLifecycle`, `useImageGenQueue`, and `clientErrorReporter`. |
| `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup, dropping browser-extension errors (see `extensionErrors.js`) before either gate. Wired from `main.jsx`; never call directly from React components. |
| `clinicianReport.js` | Pure builders for the MeatSpace clinician-export view (`/meatspace/export`). `buildClinicianReport({ tests, config })` → structured report model (blood panels grouped by category with reference ranges + out-of-range flags, plus a lifestyle summary); `reportToMarkdown(report)` → copy-paste markdown. Reuses the Blood tab's `REFERENCE_RANGES` / `getBloodValueStatus` so printed flags match the UI. Also exports `buildBloodTestModel`, `buildLifestyleModel`, `getCategoryForKey`, `formatRange`. |
+| `quotaBurnPatch.js` | `mergeQuotaBurnPatch(base, patch)` — mirrors the server's quota-burn config merge (top-level + per-family keys merge, a family's `jobs` array replaces) so the Quota Burn page can apply an edit optimistically and accumulate debounced edits into one PUT body. |
| `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. |
| `compareHelpers.js` | `equalByKeys(a, b, keys)` / `equalListByKeys(a, b, keys)` — typed key-based equality for `useAutoRefetch`'s `compare`. Keys are property names, dotted paths (`'context.running'`), or `(item) => value` accessors. The typed alternative to `sameJsonShape` when a monotonic timestamp or unrendered field would break stringify-equality dedup. |
| `consoleFilters.js` | `installConsoleFilters()` — drops a small allow-list of known-noise console strings (THREE.js `Clock` deprecation, expected WebGL `Context Lost.`) from `console.{warn,log,debug}`. Idempotent; auto-installed on import. Imported for its side effect from `main.jsx`. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 724f37f604..4b61dc09a5 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -131,6 +131,7 @@ export * from './tabNotation.js';
export * from './terminalTheme.js';
export * from './threejsSculpt.js';
export * from './tribe.js';
+export * from './quotaBurnPatch.js';
export * from './tribeCadence.js';
export * from './universeBuilderExpand.js';
export * from './uuid.js';
diff --git a/client/src/lib/quotaBurnPatch.js b/client/src/lib/quotaBurnPatch.js
new file mode 100644
index 0000000000..34aa4edda2
--- /dev/null
+++ b/client/src/lib/quotaBurnPatch.js
@@ -0,0 +1,28 @@
+/**
+ * Merge a partial quota-burn config patch over a base, mirroring exactly what
+ * `saveQuotaBurnConfig` does on the server: top-level and per-family keys merge,
+ * and a family's `jobs` array REPLACES (it is an ordered list — a positional
+ * merge would make reordering and deletion inexpressible).
+ *
+ * Used twice on the page, both for the same reason: the config form must reflect
+ * a keystroke immediately while the PUT is debounced.
+ * 1. Optimistic local state — apply the patch to the rendered config now.
+ * 2. Pending-patch accumulation — fold successive edits into ONE body so the
+ * trailing PUT carries every change, not just the last field touched.
+ *
+ * Keeping it here (pure, shared) is what keeps the client's optimistic view from
+ * drifting from what the server will actually persist.
+ */
+export function mergeQuotaBurnPatch(base, patch) {
+ const families = { ...(base?.families || {}) };
+ for (const [id, familyPatch] of Object.entries(patch?.families || {})) {
+ families[id] = { ...(families[id] || {}), ...familyPatch };
+ }
+ const merged = { ...(base || {}), ...(patch || {}) };
+ // Omit an empty `families` rather than sending `families: {}` — a
+ // top-level-only edit (the master switch, the interval) should PUT exactly the
+ // key it changed, so the request reads as what the user did.
+ if (Object.keys(families).length) merged.families = families;
+ else delete merged.families;
+ return merged;
+}
diff --git a/client/src/lib/quotaBurnPatch.test.js b/client/src/lib/quotaBurnPatch.test.js
new file mode 100644
index 0000000000..17f0ba50b9
--- /dev/null
+++ b/client/src/lib/quotaBurnPatch.test.js
@@ -0,0 +1,40 @@
+import { describe, it, expect } from 'vitest';
+import { mergeQuotaBurnPatch } from './quotaBurnPatch';
+
+describe('mergeQuotaBurnPatch', () => {
+ it('merges top-level keys and leaves families untouched', () => {
+ expect(mergeQuotaBurnPatch({ enabled: false, checkIntervalMinutes: 30 }, { enabled: true }))
+ .toEqual({ enabled: true, checkIntervalMinutes: 30 });
+ });
+
+ it('merges per-family keys without dropping the rest of the plan', () => {
+ const base = { families: { grok: { enabled: true, reservePercent: 10 }, codex: { enabled: false } } };
+ expect(mergeQuotaBurnPatch(base, { families: { grok: { reservePercent: 40 } } })).toEqual({
+ families: { grok: { enabled: true, reservePercent: 40 }, codex: { enabled: false } },
+ });
+ });
+
+ it('REPLACES a family\'s jobs array', () => {
+ // Ordered list: a positional merge would make reordering and deletion
+ // inexpressible — the same rule the server's save applies.
+ const base = { families: { grok: { jobs: [{ id: 'a' }, { id: 'b' }] } } };
+ expect(mergeQuotaBurnPatch(base, { families: { grok: { jobs: [{ id: 'b' }] } } }))
+ .toEqual({ families: { grok: { jobs: [{ id: 'b' }] } } });
+ });
+
+ it('accumulates successive edits into one patch body', () => {
+ // The page folds debounced edits this way, so the trailing PUT carries every
+ // change rather than only the last field touched.
+ const first = mergeQuotaBurnPatch(null, { families: { grok: { reservePercent: 40 } } });
+ const second = mergeQuotaBurnPatch(first, { enabled: true });
+ const third = mergeQuotaBurnPatch(second, { families: { grok: { priority: 2 }, codex: { enabled: true } } });
+ expect(third).toEqual({
+ enabled: true,
+ families: { grok: { reservePercent: 40, priority: 2 }, codex: { enabled: true } },
+ });
+ });
+
+ it('omits families entirely for a top-level-only edit', () => {
+ expect(mergeQuotaBurnPatch(null, { enabled: true })).toEqual({ enabled: true });
+ });
+});
diff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsx
new file mode 100644
index 0000000000..da88829508
--- /dev/null
+++ b/client/src/pages/QuotaBurn.jsx
@@ -0,0 +1,206 @@
+/**
+ * Quota Burn — configure the ONE install-level loop that spends subscription
+ * quota which would otherwise expire unused.
+ *
+ * The loop lives in PortOS, not on any managed app: one schedule, one set of
+ * per-provider-family windows, and an ordered burn plan per family. Individual
+ * jobs decide what the quota goes to — an agent in a named managed app, or a
+ * programmatic PortOS job like rendering the universe bible entries that have
+ * no image yet.
+ *
+ * The master switch is the consent gate for the whole feature (CLAUDE.md's AI
+ * provider policy): with it off nothing here contacts a provider, and the page
+ * names the family, provider, model, and work before it can be turned on.
+ */
+
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useNavigate, useParams } from 'react-router';
+import { Flame, RefreshCw } from 'lucide-react';
+import toast from '../components/ui/Toast';
+import BrailleSpinner from '../components/BrailleSpinner';
+import FamilyCard from '../components/quotaBurn/FamilyCard';
+import * as api from '../services/api';
+import { mergeQuotaBurnPatch } from '../lib/quotaBurnPatch';
+import { coalesce } from '../utils/coalesce';
+import { timeAgo } from '../utils/formatters';
+
+// Trailing-edge window for the config PUT. A per-keystroke save would also
+// re-read the status, and a `universe-bible-images` job's pending probe walks
+// every universe bible — one full scan per character typed.
+const SAVE_DEBOUNCE_MS = 500;
+
+const EMPTY_CATALOG = { families: [], jobTypes: [], apps: [], universes: [], imageModes: [] };
+
+export default function QuotaBurn() {
+ // Which family is expanded lives in the URL, not local state, so a specific
+ // family's plan is linkable and survives a reload.
+ const { familyId: expanded } = useParams();
+ const navigate = useNavigate();
+
+ const [config, setConfig] = useState(null);
+ const [status, setStatus] = useState(null);
+ const [catalog, setCatalog] = useState(EMPTY_CATALOG);
+ const [loading, setLoading] = useState(true);
+ // `unsaved` covers BOTH the debounce window and the in-flight PUT. Every "run"
+ // control reads server-side config, so it must stay disabled until the edit
+ // has actually landed — otherwise the user changes a model, clicks Burn, and
+ // the server burns with the previous value.
+ const [unsaved, setUnsaved] = useState(false);
+ const [running, setRunning] = useState(false);
+ const pendingRef = useRef(null);
+
+ const load = useCallback(async (refresh = false) => {
+ const data = await api.getQuotaBurn(refresh, { silent: true }).catch(() => null);
+ if (!data) return;
+ setConfig(data.config);
+ setStatus(data.status);
+ }, []);
+
+ useEffect(() => {
+ Promise.all([
+ load(),
+ api.getQuotaBurnCatalog({ silent: true }).then(setCatalog).catch(() => {}),
+ ]).finally(() => setLoading(false));
+ }, [load]);
+
+ // There is no Save button: an edit lands in local state immediately and is
+ // persisted on a trailing edge. Successive edits fold into ONE patch body, so
+ // the PUT carries every change rather than just the last field touched.
+ const persist = useMemo(() => coalesce(async () => {
+ const patch = pendingRef.current;
+ pendingRef.current = null;
+ if (!patch) return;
+ const result = await api.saveQuotaBurn(patch, { silent: true })
+ .catch((err) => { toast.error(`Could not save: ${err.message}`); return null; });
+ // The server's normalization is authoritative — adopt what it stored, then
+ // re-read status so pending counts and skip reasons match the saved plan.
+ if (result) setConfig(result.config);
+ await load();
+ setUnsaved(false);
+ }, SAVE_DEBOUNCE_MS), [load]);
+
+ useEffect(() => () => persist.cancel(), [persist]);
+
+ const save = (patch) => {
+ setUnsaved(true);
+ setConfig((prev) => mergeQuotaBurnPatch(prev, patch));
+ pendingRef.current = mergeQuotaBurnPatch(pendingRef.current, patch);
+ persist();
+ };
+
+ const patchFamily = (familyId, patch) => save({ families: { [familyId]: patch } });
+
+ const run = async (body, label) => {
+ setRunning(true);
+ const response = await api.runQuotaBurn(body, { silent: true })
+ .catch((err) => { toast.error(`${label} failed: ${err.message}`); return null; });
+ if (response) {
+ const result = response.result || {};
+ if (result.dispatched) toast.success(result.summary || 'Dispatched');
+ else toast(result.reason || result.skipped || 'Nothing to burn right now');
+ await load();
+ }
+ setRunning(false);
+ };
+
+ if (loading) return <div className="p-6 text-gray-400"><BrailleSpinner /> Loading burn plan…</div>;
+ if (!config) return <div className="p-6 text-gray-400">Quota burn is unavailable — the server did not return a plan.</div>;
+
+ const lastRun = status?.runs?.[0];
+
+ return (
+ <div className="space-y-4">
+ <header className="flex flex-wrap items-center gap-3">
+ <h1 className="text-xl font-semibold text-white flex items-center gap-2"><Flame size={20} className="text-orange-400" /> Quota Burn</h1>
+ <button
+ type="button"
+ className="inline-flex items-center gap-1 text-xs text-gray-300 hover:text-white"
+ onClick={() => { setLoading(true); load(true).finally(() => setLoading(false)); }}
+ >
+ <RefreshCw size={13} /> Refresh quota
+ </button>
+ <button
+ type="button"
+ className="ml-auto text-xs px-3 py-1.5 rounded border border-port-border text-gray-200 hover:text-white disabled:opacity-40"
+ disabled={running || unsaved}
+ onClick={() => run({}, 'Run')}
+ title={unsaved ? 'Saving your changes…' : 'Run one evaluation now'}
+ >
+ {running ? 'Evaluating…' : 'Evaluate now'}
+ </button>
+ </header>
+
+ <section className="rounded border border-port-border bg-port-card/40 p-3 space-y-3">
+ <div className="flex flex-wrap items-center gap-3">
+ <input
+ id="quota-burn-enabled"
+ type="checkbox"
+ checked={config.enabled}
+ onChange={(event) => save({ enabled: event.target.checked })}
+ />
+ <label htmlFor="quota-burn-enabled" className="text-sm text-white">
+ Run the quota-burn loop automatically
+ </label>
+ <label htmlFor="quota-burn-interval" className="text-xs text-gray-400 ml-auto flex items-center gap-2">
+ Check every
+ <input
+ id="quota-burn-interval"
+ type="number"
+ min="5"
+ max="720"
+ className="w-20 bg-port-bg border border-port-border rounded p-1.5 text-white text-xs"
+ value={config.checkIntervalMinutes}
+ onChange={(event) => save({ checkIntervalMinutes: Number(event.target.value) })}
+ />
+ minutes
+ </label>
+ </div>
+ <p className="text-xs text-gray-400">
+ One loop for this install. Each provider family burns only inside its reset window, above its reserve, and within its
+ dispatch cap — running the first job in its plan that has work waiting. Turning this on is explicit consent to spend
+ those subscriptions on a schedule.
+ </p>
+ {lastRun && (
+ <p className="text-[11px] text-gray-500">
+ Last {lastRun.trigger} run {timeAgo(lastRun.at)} — {lastRun.dispatched ? lastRun.summary : lastRun.reason}
+ </p>
+ )}
+ </section>
+
+ <section className="space-y-3">
+ {Object.entries(config.families).map(([familyId, family]) => (
+ <FamilyCard
+ key={familyId}
+ familyId={familyId}
+ config={family}
+ status={(status?.families || []).find((row) => row.id === familyId)}
+ catalog={catalog}
+ expanded={expanded === familyId}
+ actionsBusy={unsaved || running}
+ running={running}
+ onToggleExpand={(id) => navigate(expanded === id ? '/devtools/quota-burn' : `/devtools/quota-burn/${id}`)}
+ onPatch={(patch) => patchFamily(familyId, patch)}
+ onRunFamily={(id) => run({ familyId: id }, 'Burn')}
+ onRunJob={(id, job) => run({ familyId: id, jobId: job.id, force: true }, 'Job run')}
+ />
+ ))}
+ </section>
+
+ {Boolean(status?.runs?.length) && (
+ <section className="rounded border border-port-border bg-port-card/40 p-3">
+ <h2 className="text-xs uppercase tracking-wide text-gray-400 mb-2">Recent runs</h2>
+ <ul className="space-y-1 text-xs">
+ {status.runs.slice(0, 15).map((entry, index) => (
+ <li key={`${entry.at}-${index}`} className="flex flex-wrap gap-2 text-gray-400">
+ <span className="text-gray-500 w-24 shrink-0">{timeAgo(entry.at)}</span>
+ <span className={entry.dispatched ? 'text-emerald-400' : 'text-gray-500'}>
+ {entry.dispatched ? `${entry.familyId} · ${entry.summary}` : entry.reason}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsx
new file mode 100644
index 0000000000..439e3b6d53
--- /dev/null
+++ b/client/src/pages/QuotaBurn.test.jsx
@@ -0,0 +1,131 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter, Route, Routes } from 'react-router';
+import QuotaBurn from './QuotaBurn';
+
+vi.mock('../services/api', () => ({
+ getQuotaBurn: vi.fn(),
+ getQuotaBurnCatalog: vi.fn(),
+ saveQuotaBurn: vi.fn(),
+ runQuotaBurn: vi.fn(),
+}));
+
+import * as api from '../services/api';
+
+const config = {
+ enabled: false,
+ checkIntervalMinutes: 30,
+ families: {
+ grok: {
+ enabled: true, providerId: null, scope: null, resetWithinHours: 24, reservePercent: 10,
+ maxDispatchesPerWindow: 5, priority: 0,
+ jobs: [{ id: 'j1', enabled: true, label: 'Bible images', jobType: 'universe-bible-images', model: null, providerId: null, params: {} }],
+ },
+ codex: { enabled: false, providerId: null, scope: null, resetWithinHours: 24, reservePercent: 0, maxDispatchesPerWindow: 5, priority: 0, jobs: [] },
+ },
+};
+
+const status = {
+ enabled: false, checkIntervalMinutes: 30, running: false, lastRunAt: null,
+ families: [
+ { id: 'grok', label: 'Grok', willBurn: true, percentRemaining: 62, hoursUntilReset: 2.4, dispatchesUsed: 1, skipReason: null, jobs: [{ id: 'j1', pending: { count: 4, detail: '4 bible entries have no image' } }] },
+ { id: 'codex', label: 'Codex', willBurn: false, skipReason: 'disabled', jobs: [] },
+ ],
+ runs: [{ at: new Date().toISOString(), trigger: 'scheduled', dispatched: false, reason: 'no burnable window' }],
+};
+
+const catalog = {
+ families: ['grok', 'codex'],
+ jobTypes: [
+ { id: 'universe-bible-images', label: 'Universe bible images', description: 'Render missing bible images.', params: [{ key: 'universeId', kind: 'universe', label: 'Universe', default: 'all' }] },
+ { id: 'agent-prompt', label: 'Agent prompt', description: 'Queue a CoS agent.', params: [{ key: 'appId', kind: 'app', label: 'Managed app', required: true }] },
+ ],
+ apps: [{ id: 'a1', name: 'App One' }],
+ universes: [{ id: 'u1', name: 'Example Universe' }],
+ imageModes: ['codex', 'grok'],
+};
+
+const renderPage = (path = '/devtools/quota-burn') => render(
+ <MemoryRouter initialEntries={[path]}>
+ <Routes>
+ <Route path="/devtools/quota-burn" element={<QuotaBurn />} />
+ <Route path="/devtools/quota-burn/:familyId" element={<QuotaBurn />} />
+ </Routes>
+ </MemoryRouter>,
+);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.getQuotaBurn.mockResolvedValue({ config, status });
+ api.getQuotaBurnCatalog.mockResolvedValue(catalog);
+ api.saveQuotaBurn.mockResolvedValue({ config });
+ api.runQuotaBurn.mockResolvedValue({ result: { dispatched: false, reason: 'nothing to burn' } });
+});
+
+describe('QuotaBurn page', () => {
+ it('shows each family\'s live window or the reason it will not burn', async () => {
+ renderPage();
+ expect(await screen.findByText(/62% left/)).toBeInTheDocument();
+ // A family that will not burn states WHY — the same predicate the runner
+ // evaluates, so the page can never disagree with what actually happens.
+ expect(screen.getByText('disabled')).toBeInTheDocument();
+ });
+
+ it('saves the master switch as a partial patch', async () => {
+ const user = userEvent.setup();
+ renderPage();
+ await user.click(await screen.findByLabelText(/Run the quota-burn loop automatically/));
+ await waitFor(() => expect(api.saveQuotaBurn).toHaveBeenCalledWith({ enabled: true }, { silent: true }));
+ });
+
+ it('drives the expanded family from the URL, not local state', async () => {
+ // Deep-linking rule: which plan is open must survive a reload and be shareable.
+ renderPage('/devtools/quota-burn/grok');
+ expect(await screen.findByLabelText(/Reserve \(%\)/)).toHaveValue(10);
+ expect(screen.getByDisplayValue('Bible images')).toBeInTheDocument();
+ expect(screen.getByText(/Ready — 4 bible entries have no image/)).toBeInTheDocument();
+ });
+
+ it('force-runs a single job from its row', async () => {
+ const user = userEvent.setup();
+ renderPage('/devtools/quota-burn/grok');
+ await user.click(await screen.findByLabelText('Run step 1 now'));
+ await waitFor(() => expect(api.runQuotaBurn).toHaveBeenCalledWith(
+ { familyId: 'grok', jobId: 'j1', force: true }, { silent: true },
+ ));
+ });
+
+ it('strips the display-only pending field before persisting a job edit', async () => {
+ // The PUT schema is strict — a grafted status field would 400 the save.
+ const user = userEvent.setup();
+ renderPage('/devtools/quota-burn/grok');
+ await user.click(await screen.findByLabelText('Name for step 1'));
+ await user.keyboard('!');
+ await waitFor(() => expect(api.saveQuotaBurn).toHaveBeenCalled());
+ const [patch] = api.saveQuotaBurn.mock.calls.at(-1);
+ expect(patch.families.grok.jobs[0]).not.toHaveProperty('pending');
+ });
+});
+
+describe('QuotaBurn save debounce', () => {
+ it('folds a burst of edits into ONE PUT and blocks runs until it lands', async () => {
+ // Per-keystroke saving also re-read the status, and a universe-bible-images
+ // pending probe walks every bible — one full scan per character typed.
+ const user = userEvent.setup();
+ renderPage('/devtools/quota-burn/grok');
+ const nameInput = await screen.findByLabelText('Name for step 1');
+ await user.click(nameInput);
+ await user.keyboard('abc');
+
+ // Mid-burst: nothing persisted yet, and every run control is disabled
+ // because the server still holds the pre-edit plan.
+ expect(api.saveQuotaBurn).not.toHaveBeenCalled();
+ expect(screen.getByRole('button', { name: /Evaluate now/ })).toBeDisabled();
+ expect(screen.getByLabelText('Run step 1 now')).toBeDisabled();
+
+ await waitFor(() => expect(api.saveQuotaBurn).toHaveBeenCalledTimes(1));
+ expect(api.saveQuotaBurn.mock.calls[0][0].families.grok.jobs[0].label).toBe('Bible imagesabc');
+ await waitFor(() => expect(screen.getByRole('button', { name: /Evaluate now/ })).not.toBeDisabled());
+ });
+});
diff --git a/client/src/services/README.md b/client/src/services/README.md
index fa819a0b17..35b0ec132d 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -58,6 +58,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiRuns.js` | Agent run history. |
| `apiScaffold.js` | App scaffolding templates. |
| `apiSchedules.js` | Automation schedules. |
+| `apiQuotaBurn.js` | Quota Burn plan + live status, the job-type catalog its config form renders, and manual runs (`getQuotaBurn`/`getQuotaBurnCatalog`/`saveQuotaBurn`/`runQuotaBurn`). |
| `apiSystem.js` | System info (CPU/memory/ports/alerts) + D&D-style character sheet getter, plus the usage cost report and explicit historical reconciliation (`getUsage`/`getUsageRaw`/`resetUsage`, `getProviderUsage`, `getUsageBackfillStatus`/`startUsageBackfill`). |
| `apiAuth.js` | Optional login password — status, login/logout, set/clear password. |
| `apiLoops.js` | Scheduled loops. |
diff --git a/client/src/services/api.js b/client/src/services/api.js
index b006003bea..11f68150e3 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -83,6 +83,7 @@ export * from './apiVoice.js';
export * from './apiAuth.js';
export * from './apiCity.js';
export * from './apiPrivacy.js';
+export * from './apiQuotaBurn.js';
// Default export for simplified imports (get/post/put/delete helpers)
export { default } from './apiCore.js';
diff --git a/client/src/services/apiQuotaBurn.js b/client/src/services/apiQuotaBurn.js
new file mode 100644
index 0000000000..2a0ecf6bfe
--- /dev/null
+++ b/client/src/services/apiQuotaBurn.js
@@ -0,0 +1,28 @@
+import { request } from './apiCore.js';
+
+// Quota Burn — the install-level burn plan (one loop in PortOS; jobs may target
+// managed apps). Every wrapper takes an optional `options` so callers with their
+// own error UI can pass `{ silent: true }` per the toasting convention.
+
+// Plan + live status (quota cards, per-job pending counts, recent runs).
+// `refresh` re-scrapes provider usage instead of reading the cache.
+export const getQuotaBurn = (refresh = false, options) =>
+ request(`/quota-burn${refresh ? '?refresh=1' : ''}`, options);
+
+// Job-type catalog + the app / universe / render-backend options its params pick from.
+export const getQuotaBurnCatalog = (options) => request('/quota-burn/catalog', options);
+
+// Partial merge: top-level and per-family keys merge, a family's `jobs` replaces.
+export const saveQuotaBurn = (patch, options) => request('/quota-burn', {
+ method: 'PUT',
+ body: JSON.stringify(patch),
+ ...options,
+});
+
+// Evaluate now. `{ familyId, jobId, force }` runs one named job past the
+// window/reserve/cap gates; no body behaves like a scheduled tick.
+export const runQuotaBurn = (body = {}, options) => request('/quota-burn/run', {
+ method: 'POST',
+ body: JSON.stringify(body),
+ ...options,
+});
diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.md
index 8d0c411b81..5127975063 100644
--- a/docs/QUOTA-BURN.md
+++ b/docs/QUOTA-BURN.md
@@ -1,17 +1,86 @@
# Quota-burn automation
-Quota-burn is an opt-in perpetual scheduled task for installations that use
-subscription-backed CLI providers. It first performs only the existing
-zero-token usage checks. It dispatches an agent only when an enabled provider
-family is inside its configured reset window and still has quota above its
-reserve percentage.
-
-Each provider family has its own prompt, optional CLI/TUI provider pin, reset
-window, reserve, and per-window dispatch cap. Unknown reset times, unsupported
-providers, quota-read errors, and missing agent-capable providers all skip a
-dispatch safely. The feature is disabled by default; enabling it is explicit
-consent to spend that provider's subscription quota on a schedule.
-
-The configuration and dispatch ledger are machine-local under `data/cos/`.
-They are intentionally not federated: quota belongs to a particular machine
-and provider account, not to an app record shared with peers.
+Quota-burn spends subscription-backed CLI quota that would otherwise expire
+unused. It is **one install-level loop inside PortOS** — not a per-managed-app
+scheduled task — configured at **Dev Tools → Quota Burn** (`/devtools/quota-burn`).
+
+It is disabled by default. Enabling it is explicit consent to spend those
+subscriptions on a schedule.
+
+## How a cycle works
+
+Every `checkIntervalMinutes` (default 30, bounded 5–720) the runner:
+
+1. Reads the plan from `data/cos/quota-burn.json`. If the master switch is off it
+ stops here — **no provider is contacted**.
+2. Takes a zero-token quota reading for every enabled provider family.
+3. Selects families whose soonest window is inside `resetWithinHours`, still has
+ headroom above `reservePercent`, and has not spent `maxDispatchesPerWindow`
+ for that window. Ties break on `priority` (lower wins).
+4. Runs the **first enabled job in that family's ordered plan that reports
+ pending work** — at most one dispatch per cycle.
+5. Charges the window in `data/cos/quota-burn-dispatches.json` and appends the
+ outcome (including skips, with reasons) to `data/cos/quota-burn-runs.json`.
+
+Everything fails closed: an unknown reset time, an unsupported provider, a
+quota-read error, a card that declares itself unburnable (`burnable: false`, e.g.
+the Image Gen card), or a family with no enabled jobs all mean "do not dispatch".
+
+## Burn jobs
+
+A family's plan is an **ordered list** — that ordering is the configuration ("do
+the missing bible images first, then fall through to agent work"). Each job has
+its own type, optional model/provider pin, and type-specific params.
+
+| Job type | What it does |
+| --- | --- |
+| `agent-prompt` | Queues a CoS agent in a named managed app with a custom prompt. Visible in the CoS queue and Active Agents like any other task. |
+| `universe-bible-images` | **Programmatic** — no agent. Enqueues renders for universe bible entries whose `imageRefs[]` is empty. Render backend defaults to the burning family's own image mode, so a codex burn spends codex's image quota. |
+
+Adding a job type is three edits: a `QUOTA_BURN_JOB_TYPE` entry + catalog row in
+`server/lib/quotaBurnConfig.js`, a module in `server/services/quotaBurnJobs/`, and
+one line in that directory's `JOB_MODULES`. The config page builds its form from
+the catalog, so no client change is needed unless the job introduces a param kind
+the form doesn't render yet.
+
+Each job module exports `countPending` (cheap, side-effect free — the page calls
+it on every load) and `run` (the only thing that may spend quota). A job that
+declines reports `dispatched: false` with a reason and is **not** charged against
+the window's cap.
+
+## Manual runs
+
+- **Evaluate now** runs a full cycle immediately, ignoring the master switch but
+ respecting every quota gate.
+- **Burn now** on a family card scopes that cycle to one family.
+- The ▶ on a job row **forces** that one job past the window/reserve/cap gates.
+ A forced run carries no window key and is deliberately not charged against the
+ family's automatic budget.
+
+## Storage
+
+The plan, the dispatch ledger, and the run log all live machine-locally under
+`data/cos/` and are intentionally **not federated**: quota belongs to a
+particular machine and provider account, and the "which managed app" targets
+differ per machine.
+
+## Migration from the per-app task type
+
+Before this, quota-burn was a `quota-burn` entry in each managed app's
+`taskTypeOverrides`, which meant two enabled apps ran two independent loops
+racing for the same window budget. Migration `221-quota-burn-global-config.js`
+folds those overrides into the single plan (each app's family prompt becomes an
+`agent-prompt` job pointing back at that app) and removes the dead task type from
+`data/apps.json`. Do not re-add `quota-burn` to `TASK_TYPES`.
+
+## Code map
+
+| File | Role |
+| --- | --- |
+| `server/lib/quotaBurnConfig.js` | Plan shape, job-type catalog, total normalization |
+| `server/services/quotaBurnStore.js` | `data/cos/quota-burn.json` + the run log |
+| `server/services/quotaBurn.js` | Candidate selection + the dispatch ledger |
+| `server/services/quotaBurnJobs/` | The job registry and its modules |
+| `server/services/quotaBurnRunner.js` | The loop, the cycle, and the status feed |
+| `server/routes/quotaBurn.js` | `/api/quota-burn` |
+| `client/src/pages/QuotaBurn.jsx` | The config page |
diff --git a/docs/STORAGE.md b/docs/STORAGE.md
index b9d8e8aa97..927b72ba1c 100644
--- a/docs/STORAGE.md
+++ b/docs/STORAGE.md
@@ -56,6 +56,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](
- MortalLoom / Health / Meatspace health data — `data/health`, `data/meatspace`, MortalLoom iCloud store. Kept file-backed to preserve iCloud/file sync and avoid routing sensitive health records through the app DB before that boundary is designed.
- App scaffolds / cloned repos / browser profiles — `data/repos`, `data/browser-profile` — inherently filesystem-oriented.
- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.
+- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + ordered job list. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and the plan's `agent-prompt` jobs name managed apps that only exist on this machine. No sync cursor, no tombstone. Its companion `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days) and `data/cos/quota-burn-runs.json` (capped run log) are `ephemeral-file` — regenerable telemetry. Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).
- LoRA training datasets — `data/lora-datasets/{id}/index.json` + `images/*.png` (collectionStore). The record is inseparable from the image bytes it organizes, has no cross-record queries beyond a small characterId scan, and is **machine-local** like `data/loras/` itself (training artifacts tied to this machine's GPU output — never federates, no sync cursor/tombstone). Backed up in full: uploads and hand-edited captions are not re-creatable. Training RUN records are `db-primary` (`lora_training_runs`); run artifacts (checkpoints/samples) live under `data/training-runs/{runId}/` with checkpoints/cache excluded from backup.
---
diff --git a/scripts/migrations/221-quota-burn-global-config.js b/scripts/migrations/221-quota-burn-global-config.js
new file mode 100644
index 0000000000..b4d71a915f
--- /dev/null
+++ b/scripts/migrations/221-quota-burn-global-config.js
@@ -0,0 +1,186 @@
+/**
+ * Migration 221 — move quota-burn from a per-app scheduled task type to ONE
+ * install-level burn plan.
+ *
+ * Background:
+ * Quota-burn used to be a `quota-burn` entry in each managed app's
+ * `taskTypeOverrides`, so its provider-family plan (prompt, reset window,
+ * reserve, dispatch cap) was duplicated per app even though the quota it
+ * spends belongs to the MACHINE, not to any one repo. Two enabled apps meant
+ * two independent loops racing for the same window budget.
+ *
+ * It is now one loop in PortOS (`server/services/quotaBurnRunner.js`) reading
+ * one machine-local plan at `data/cos/quota-burn.json`. The work can still
+ * target a managed app — that is now a per-JOB `appId` rather than the app
+ * owning the schedule.
+ *
+ * What it writes:
+ * - `data/cos/quota-burn.json` — one family entry per configured family,
+ * carrying the old window/reserve/cap/priority settings verbatim. Each
+ * family's old free-text `prompt` becomes a single `agent-prompt` job
+ * pointing at the app whose override it came from, so an install's existing
+ * burn keeps doing exactly what it did.
+ * - `data/apps.json` — the `quota-burn` key is removed from every app's
+ * `taskTypeOverrides`. The task type no longer exists; leaving it behind
+ * would show a dead row in the CoS schedule UI.
+ * - `data/cos/task-schedule.json` — the `quota-burn` entry is removed from
+ * `tasks`. `loadSchedule` deliberately PRESERVES persisted task types that
+ * are no longer in the defaults, so without this the install-wide schedule
+ * would keep offering a type with no detector, no prompt, and no hooks.
+ *
+ * Conflicts: when two apps configured the SAME family, the first app in file
+ * order supplies the family-level window settings and BOTH prompts survive as
+ * two ordered jobs. Dropping one would silently lose configured work; merging
+ * the windows would invent a setting the user never chose.
+ *
+ * `enabled` is deliberately carried over as-is: an install that had quota-burn
+ * running keeps running it (no surprise stop), and one that never enabled it
+ * stays silent. The migration itself makes NO provider calls.
+ *
+ * Idempotent: once no app carries a `quota-burn` override there is nothing to
+ * read, and an existing `quota-burn.json` is never overwritten.
+ */
+
+import { mkdir, readFile, writeFile, rename } from 'fs/promises';
+import { join } from 'path';
+
+const FAMILIES = ['claude', 'codex', 'agy', 'grok'];
+
+const readJson = async (abs) => {
+ const raw = await readFile(abs, 'utf-8').catch((err) => { if (err.code === 'ENOENT') return null; throw err; });
+ if (raw == null) return null;
+ try { return JSON.parse(raw); } catch { return null; }
+};
+
+const writeJsonAtomic = async (abs, value) => {
+ const tmp = `${abs}.tmp-221`;
+ await writeFile(tmp, JSON.stringify(value, null, 2) + '\n');
+ await rename(tmp, abs);
+};
+
+/**
+ * Fold every app's `taskTypeOverrides['quota-burn'].taskMetadata.families` into
+ * one plan. Pure — exported for the test.
+ *
+ * @param {Array<{id: string, name?: string, taskTypeOverrides?: object}>} apps
+ * @returns {{ config: object|null, touchedAppIds: string[] }} `config` is null
+ * when no app configured a family (nothing to migrate).
+ */
+export function buildGlobalPlan(apps) {
+ const families = {};
+ const touchedAppIds = [];
+ let jobSeq = 0;
+ for (const app of apps) {
+ const override = app?.taskTypeOverrides?.['quota-burn'];
+ if (!override) continue;
+ touchedAppIds.push(app.id);
+ const configured = override.taskMetadata?.families;
+ if (!configured || typeof configured !== 'object') continue;
+ for (const [familyId, value] of Object.entries(configured)) {
+ if (!FAMILIES.includes(familyId) || !value || typeof value !== 'object') continue;
+ const existing = families[familyId];
+ const jobs = existing?.jobs || [];
+ const prompt = typeof value.prompt === 'string' ? value.prompt.trim() : '';
+ if (prompt) {
+ jobSeq += 1;
+ jobs.push({
+ id: `migrated-${jobSeq}`,
+ enabled: true,
+ label: `${app.name || app.id} burn work`,
+ jobType: 'agent-prompt',
+ // The family-level `model` was the agent's model in the old shape;
+ // it becomes the job's, since model choice is now per job.
+ model: value.model || null,
+ providerId: null,
+ params: {
+ appId: app.id,
+ prompt,
+ useWorktree: override.taskMetadata?.useWorktree !== false,
+ openPR: override.taskMetadata?.openPR !== false,
+ simplify: override.taskMetadata?.simplify !== false,
+ },
+ });
+ }
+ // First app in file order owns the window settings — see the conflict
+ // note above. Later apps contribute only their jobs.
+ families[familyId] = existing ? { ...existing, jobs } : {
+ enabled: value.enabled === true,
+ providerId: value.providerId || null,
+ scope: typeof value.scope === 'string' ? value.scope : null,
+ resetWithinHours: Number.isFinite(Number(value.resetWithinHours)) ? Number(value.resetWithinHours) : 24,
+ reservePercent: Number.isFinite(Number(value.reservePercent)) ? Number(value.reservePercent) : 0,
+ maxDispatchesPerWindow: Number.isFinite(Number(value.maxDispatchesPerWindow)) ? Number(value.maxDispatchesPerWindow) : 5,
+ priority: Number.isFinite(Number(value.priority)) ? Number(value.priority) : 0,
+ jobs,
+ };
+ }
+ }
+ if (!Object.keys(families).length) return { config: null, touchedAppIds };
+ return {
+ config: {
+ // Master switch on only when at least one family was actually enabled —
+ // an install that configured but never enabled a family stays silent.
+ enabled: Object.values(families).some((family) => family.enabled === true),
+ checkIntervalMinutes: 30,
+ families,
+ },
+ touchedAppIds,
+ };
+}
+
+/**
+ * Drop the dead `quota-burn` entry from the install-wide schedule file. Runs
+ * even when no app carried an override — an install could have flipped the type
+ * on globally and never scoped it to an app.
+ */
+async function pruneScheduleFile(rootDir) {
+ const scheduleFile = join(rootDir, 'data', 'cos', 'task-schedule.json');
+ const schedule = await readJson(scheduleFile);
+ if (!schedule?.tasks || !Object.hasOwn(schedule.tasks, 'quota-burn')) return false;
+ const { 'quota-burn': _dropped, ...tasks } = schedule.tasks;
+ await writeJsonAtomic(scheduleFile, { ...schedule, tasks });
+ console.log('🔥 migration 221: removed the dead quota-burn entry from the CoS schedule');
+ return true;
+}
+
+export default {
+ async up({ rootDir }) {
+ const prunedSchedule = await pruneScheduleFile(rootDir);
+ const appsFile = join(rootDir, 'data', 'apps.json');
+ const data = await readJson(appsFile);
+ const appsMap = data?.apps && typeof data.apps === 'object' ? data.apps : null;
+ if (!appsMap) {
+ console.log('🔥 migration 221: no data/apps.json — fresh install, no-op');
+ return { ok: true, reason: 'no-apps', prunedSchedule };
+ }
+
+ const apps = Object.entries(appsMap).map(([id, app]) => ({ id, ...app }));
+ const { config, touchedAppIds } = buildGlobalPlan(apps);
+ if (!touchedAppIds.length) {
+ console.log('🔥 migration 221: no app carries a quota-burn override — nothing to migrate');
+ return { ok: true, reason: 'no-overrides', prunedSchedule };
+ }
+
+ const cosDir = join(rootDir, 'data', 'cos');
+ const configFile = join(cosDir, 'quota-burn.json');
+ if (config) {
+ const existing = await readJson(configFile);
+ if (existing) {
+ console.log('🔥 migration 221: data/cos/quota-burn.json already exists — leaving it as-is');
+ } else {
+ await mkdir(cosDir, { recursive: true });
+ await writeJsonAtomic(configFile, config);
+ const count = Object.keys(config.families).length;
+ console.log(`🔥 migration 221: wrote a global burn plan with ${count} famil${count === 1 ? 'y' : 'ies'}`);
+ }
+ }
+
+ for (const id of touchedAppIds) {
+ const { 'quota-burn': _dropped, ...rest } = appsMap[id].taskTypeOverrides || {};
+ appsMap[id] = { ...appsMap[id], taskTypeOverrides: rest };
+ }
+ await writeJsonAtomic(appsFile, { ...data, apps: appsMap });
+ console.log(`🔥 migration 221: removed the quota-burn task-type override from ${touchedAppIds.length} app(s)`);
+ return { ok: true, apps: touchedAppIds.length, prunedSchedule };
+ },
+};
diff --git a/scripts/migrations/221-quota-burn-global-config.test.js b/scripts/migrations/221-quota-burn-global-config.test.js
new file mode 100644
index 0000000000..517dc7d0ae
--- /dev/null
+++ b/scripts/migrations/221-quota-burn-global-config.test.js
@@ -0,0 +1,130 @@
+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, { buildGlobalPlan } from './221-quota-burn-global-config.js';
+
+const app = (id, families, extras = {}) => ({
+ id,
+ name: `App ${id}`,
+ taskTypeOverrides: { 'quota-burn': { taskMetadata: { families, ...extras } } },
+});
+
+describe('buildGlobalPlan', () => {
+ it('carries each family\'s window settings and turns its prompt into an agent job', () => {
+ const { config, touchedAppIds } = buildGlobalPlan([
+ app('a1', { grok: { enabled: true, prompt: 'Animate sprites.', reservePercent: 25, maxDispatchesPerWindow: 2, model: 'grok-4' } }),
+ ]);
+ expect(touchedAppIds).toEqual(['a1']);
+ expect(config.enabled).toBe(true);
+ expect(config.families.grok).toMatchObject({ enabled: true, reservePercent: 25, maxDispatchesPerWindow: 2 });
+ expect(config.families.grok.jobs).toEqual([{
+ id: 'migrated-1',
+ enabled: true,
+ label: 'App a1 burn work',
+ jobType: 'agent-prompt',
+ model: 'grok-4',
+ providerId: null,
+ params: { appId: 'a1', prompt: 'Animate sprites.', useWorktree: true, openPR: true, simplify: true },
+ }]);
+ });
+
+ it('keeps BOTH prompts when two apps configured the same family', () => {
+ // Dropping one would silently lose configured work; merging the window
+ // settings would invent a value the user never chose, so the first app in
+ // file order supplies those and both prompts survive as ordered jobs.
+ const { config } = buildGlobalPlan([
+ app('a1', { codex: { enabled: true, prompt: 'First', reservePercent: 10 } }),
+ app('a2', { codex: { enabled: true, prompt: 'Second', reservePercent: 90 } }),
+ ]);
+ expect(config.families.codex.reservePercent).toBe(10);
+ expect(config.families.codex.jobs.map((job) => job.params.prompt)).toEqual(['First', 'Second']);
+ expect(config.families.codex.jobs.map((job) => job.params.appId)).toEqual(['a1', 'a2']);
+ });
+
+ it('leaves the master switch off when no family was enabled', () => {
+ // An install that configured but never enabled quota-burn must not start
+ // spending after an upgrade.
+ const { config } = buildGlobalPlan([app('a1', { grok: { enabled: false, prompt: 'Someday' } })]);
+ expect(config.enabled).toBe(false);
+ });
+
+ it('mirrors the app\'s agent-option posture onto the job', () => {
+ const { config } = buildGlobalPlan([
+ app('a1', { grok: { enabled: true, prompt: 'x' } }, { useWorktree: false, openPR: false, simplify: false }),
+ ]);
+ expect(config.families.grok.jobs[0].params).toMatchObject({ useWorktree: false, openPR: false, simplify: false });
+ });
+
+ it('reports the app as touched but produces no plan when nothing was configured', () => {
+ // The dead task-type override still has to be removed from apps.json.
+ const { config, touchedAppIds } = buildGlobalPlan([app('a1', {})]);
+ expect(config).toBeNull();
+ expect(touchedAppIds).toEqual(['a1']);
+ });
+
+ it('ignores apps with no quota-burn override and unknown family keys', () => {
+ const { config, touchedAppIds } = buildGlobalPlan([
+ { id: 'a0', taskTypeOverrides: { security: { enabled: true } } },
+ app('a1', { nonsense: { enabled: true, prompt: 'x' } }),
+ ]);
+ expect(touchedAppIds).toEqual(['a1']);
+ expect(config).toBeNull();
+ });
+});
+
+describe('migration 221 up()', () => {
+ let rootDir;
+
+ const readJson = async (...parts) => JSON.parse(await readFile(join(rootDir, ...parts), 'utf-8'));
+
+ beforeEach(async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'portos-221-'));
+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });
+ });
+ afterEach(async () => { await rm(rootDir, { recursive: true, force: true }); });
+
+ it('no-ops on a fresh install', async () => {
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, reason: 'no-apps' });
+ });
+
+ it('writes the plan and strips the dead task type from both files', async () => {
+ await writeFile(join(rootDir, 'data', 'apps.json'), JSON.stringify({
+ apps: {
+ a1: {
+ name: 'App One',
+ taskTypeOverrides: {
+ security: { enabled: true },
+ 'quota-burn': { enabled: true, taskMetadata: { families: { grok: { enabled: true, prompt: 'Burn it' } } } },
+ },
+ },
+ },
+ }));
+ await writeFile(join(rootDir, 'data', 'cos', 'task-schedule.json'), JSON.stringify({
+ version: 2, tasks: { security: { enabled: true }, 'quota-burn': { enabled: true } },
+ }));
+
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, apps: 1, prunedSchedule: true });
+
+ const plan = await readJson('data', 'cos', 'quota-burn.json');
+ expect(plan.families.grok.jobs[0].params).toMatchObject({ appId: 'a1', prompt: 'Burn it' });
+
+ const apps = await readJson('data', 'apps.json');
+ // The unrelated override must survive — only the dead key is removed.
+ expect(Object.keys(apps.apps.a1.taskTypeOverrides)).toEqual(['security']);
+
+ const schedule = await readJson('data', 'cos', 'task-schedule.json');
+ expect(Object.keys(schedule.tasks)).toEqual(['security']);
+ });
+
+ it('never overwrites a plan the user already has', async () => {
+ await writeFile(join(rootDir, 'data', 'apps.json'), JSON.stringify({
+ apps: { a1: { taskTypeOverrides: { 'quota-burn': { taskMetadata: { families: { grok: { enabled: true, prompt: 'Old' } } } } } } },
+ }));
+ await writeFile(join(rootDir, 'data', 'cos', 'quota-burn.json'), JSON.stringify({ enabled: true, families: { grok: { enabled: true, jobs: [] } } }));
+
+ await migration.up({ rootDir });
+ const plan = await readJson('data', 'cos', 'quota-burn.json');
+ expect(plan.families.grok.jobs).toEqual([]);
+ });
+});
diff --git a/server/index.js b/server/index.js
index 617170c5a1..06117cac94 100644
--- a/server/index.js
+++ b/server/index.js
@@ -25,6 +25,7 @@ import historyRoutes from './routes/history.js';
import commandsRoutes from './routes/commands.js';
import gitRoutes from './routes/git.js';
import usageRoutes from './routes/usage.js';
+import quotaBurnRoutes from './routes/quotaBurn.js';
import screenshotsRoutes from './routes/screenshots.js';
import shellRoutes from './routes/shell.js';
import attachmentsRoutes from './routes/attachments.js';
@@ -249,6 +250,7 @@ app.use('/api/history', historyRoutes);
app.use('/api/commands', commandsRoutes);
app.use('/api/git', gitRoutes);
app.use('/api/usage', usageRoutes);
+app.use('/api/quota-burn', quotaBurnRoutes);
app.use('/api/screenshots', screenshotsRoutes);
app.use('/api/shell', shellRoutes);
app.use('/api/search', searchRoutes);
diff --git a/server/lib/README.md b/server/lib/README.md
index e8bdff55b7..29f2245d7c 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -27,6 +27,8 @@ 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, defaults, and total normalization (`normalizeQuotaBurnConfig`). Pure — no storage, no provider I/O. |
+| `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body). |
| `quotaReset.js` | Normalizes provider quota reset timestamps and computes time remaining without treating unknown values as imminent resets. |
| `appleHealthValidation.js` | Apple Health import payloads. |
| `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). |
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index e815870f5f..4567fc413d 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -943,31 +943,6 @@ export const ISSUE_AUTHOR_FILTERS = ['self', 'owner', 'any'];
export const SWARM_COUNT_MIN = 2;
export const SWARM_COUNT_MAX = 6;
-const QUOTA_BURN_FAMILIES = new Set(['claude', 'codex', 'agy', 'grok']);
-
-function sanitizeQuotaBurnFamilies(raw) {
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
- const clean = Object.create(null);
- for (const [id, value] of Object.entries(raw)) {
- if (!QUOTA_BURN_FAMILIES.has(id) || !value || typeof value !== 'object' || Array.isArray(value)) return null;
- const enabled = value.enabled === true;
- const prompt = typeof value.prompt === 'string' ? value.prompt.slice(0, 8000) : '';
- const resetWithinHours = Number(value.resetWithinHours ?? 24);
- const reservePercent = Number(value.reservePercent ?? 0);
- const maxDispatchesPerWindow = Number(value.maxDispatchesPerWindow ?? 5);
- const priority = Number(value.priority ?? 0);
- if (!Number.isFinite(resetWithinHours) || resetWithinHours < 0 || resetWithinHours > 168
- || !Number.isFinite(reservePercent) || reservePercent < 0 || reservePercent > 100
- || !Number.isInteger(maxDispatchesPerWindow) || maxDispatchesPerWindow < 1 || maxDispatchesPerWindow > 50
- || !Number.isInteger(priority) || priority < 0 || priority > 100
- || (value.providerId != null && typeof value.providerId !== 'string')
- || (value.model != null && typeof value.model !== 'string')) return null;
- clean[id] = { enabled, prompt, providerId: value.providerId || null, model: value.model || null,
- scope: typeof value.scope === 'string' ? value.scope : null, resetWithinHours, reservePercent, maxDispatchesPerWindow, priority };
- }
- return clean;
-}
-
// POST /api/cos/tasks/slashdo — a `/do:*` button click from an app's Agent
// Operations panel. The run-settings fields are PICKED from createCosTaskSchema
// rather than restated, so the drawer's provider/model/effort/simplify/reviewer
@@ -1007,12 +982,6 @@ export function sanitizeTaskMetadata(raw) {
hasKeys = true;
}
}
- if (Object.prototype.hasOwnProperty.call(raw, 'families')) {
- const families = sanitizeQuotaBurnFamilies(raw.families);
- if (!families) return null;
- clean.families = families;
- hasKeys = true;
- }
if (Object.prototype.hasOwnProperty.call(raw, 'prCompletion') && PR_COMPLETION_VALUES.includes(raw.prCompletion)) {
clean.prCompletion = raw.prCompletion;
hasKeys = true;
diff --git a/server/lib/index.js b/server/lib/index.js
index df528ba9e6..5412bfb2b1 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -110,6 +110,8 @@ export * from './promptSystemStages.js';
export * from './promptTemplate.js';
export * from './providerModels.js';
export * from './providerTranscriptUsage.js';
+export * from './quotaBurnConfig.js';
+export * from './quotaBurnValidation.js';
export * from './quotaReset.js';
export * from './opencodeConfig.js';
// `runners.js` re-defines `isFlux2`/`isZImage`/`isErnie` that also live in
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 4059077398..0798db3665 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -121,6 +121,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.devtools.image-clean', path: '/devtools/image-clean', label: 'Image Cleaner', section: 'Dev Tools', aliases: ['image-clean', 'image-cleaner'], keywords: ['metadata', 'c2pa', 'content-credentials', 'sharp', 'denoise'] },
{ id: 'nav.devtools.jira', path: '/devtools/jira', label: 'JIRA', section: 'Dev Tools', aliases: ['jira', 'devtools-jira'] },
{ id: 'nav.devtools.jira-reports', path: '/devtools/jira/reports', label: 'JIRA Reports', section: 'Dev Tools', aliases: ['jira-reports'] },
+ { id: 'nav.devtools.quota-burn', path: '/devtools/quota-burn', label: 'Quota Burn', section: 'Dev Tools', aliases: ['quota-burn', 'burn-quota', 'quota'], keywords: ['subscription', 'usage', 'reset window', 'spend quota', 'claude', 'codex', 'grok', 'agy', 'burn'] },
{ id: 'nav.shell', path: '/shell', label: 'Shell', section: 'Dev Tools', aliases: ['shell', 'terminal'] },
{ id: 'nav.devtools.submodules', path: '/devtools/submodules', label: 'Submodules', section: 'Dev Tools', aliases: ['devtools-submodules'] },
{ id: 'nav.devtools.usage', path: '/devtools/usage', label: 'Usage', section: 'Dev Tools', aliases: ['devtools-usage'] },
diff --git a/server/lib/quotaBurnConfig.js b/server/lib/quotaBurnConfig.js
new file mode 100644
index 0000000000..17b30b91c3
--- /dev/null
+++ b/server/lib/quotaBurnConfig.js
@@ -0,0 +1,206 @@
+/**
+ * Quota-burn configuration — shape, defaults, and normalization.
+ *
+ * Quota-burn is ONE machine-local loop that lives in PortOS itself, not a
+ * per-managed-app scheduled CoS task type (it used to be the latter; migration
+ * 221 moves installs over). The work it dispatches may still target a managed
+ * app — an `agent-prompt` burn job names the app it runs in — but the schedule,
+ * the provider-family windows, and the ordered job list are all install-level
+ * config held here.
+ *
+ * Pure module: shape + normalization only, no storage and no provider I/O, so
+ * the route validator, the store, the runner, and the client can all agree on
+ * one vocabulary. `server/services/quotaBurnStore.js` persists it;
+ * `server/services/quotaBurnRunner.js` executes it.
+ *
+ * Normalization is TOTAL and never throws: every read path (config file written
+ * by an older PortOS, a migrated per-app override, a PUT body) funnels through
+ * `normalizeQuotaBurnConfig`, which fills every family key and drops anything
+ * it cannot make sense of. Absent is never confused with "off" — a family the
+ * user has not configured materializes with `enabled: false`, and an unknown
+ * job type is DROPPED rather than silently coerced to a different one (running
+ * the wrong burn job spends real quota on work nobody asked for).
+ */
+
+/** 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']);
+
+/**
+ * Burn job types. `agent-prompt` is the original behavior (spawn a CoS agent in
+ * a managed app with a custom prompt); everything else is a PROGRAMMATIC job
+ * that PortOS performs itself with no agent in the loop.
+ */
+export const QUOTA_BURN_JOB_TYPE = Object.freeze({
+ AGENT_PROMPT: 'agent-prompt',
+ UNIVERSE_BIBLE_IMAGES: 'universe-bible-images',
+});
+export const QUOTA_BURN_JOB_TYPES = Object.freeze(Object.values(QUOTA_BURN_JOB_TYPE));
+
+/**
+ * Catalog rendered by the config page so the job picker can describe each type
+ * without the client re-encoding what a job does. `params` names the per-job
+ * fields the runner reads — the client builds its form from this list, so a new
+ * job type needs no client change beyond a field renderer for a novel kind.
+ */
+export const QUOTA_BURN_JOB_CATALOG = Object.freeze([
+ {
+ id: QUOTA_BURN_JOB_TYPE.AGENT_PROMPT,
+ label: 'Agent prompt',
+ description: 'Queue a CoS agent in a managed app with a custom prompt. Burns the family\'s agent quota.',
+ programmatic: false,
+ params: Object.freeze([
+ { key: 'appId', kind: 'app', label: 'Managed app', required: true },
+ { key: 'prompt', kind: 'text', label: 'Work prompt', required: true },
+ { key: 'useWorktree', kind: 'boolean', label: 'Run in a worktree', default: true },
+ { key: 'openPR', kind: 'boolean', label: 'Open a PR', default: true },
+ { key: 'simplify', kind: 'boolean', label: 'Run /simplify', default: true },
+ ]),
+ },
+ {
+ id: QUOTA_BURN_JOB_TYPE.UNIVERSE_BIBLE_IMAGES,
+ label: 'Universe bible images',
+ description: 'Render images for universe bible entries that have none yet. No agent — PortOS enqueues the renders itself.',
+ programmatic: true,
+ params: Object.freeze([
+ { key: 'universeId', kind: 'universe', label: 'Universe', default: 'all' },
+ { key: 'scope', kind: 'enum', label: 'Entries', options: ['all', 'variations', 'canon', 'sheets'], default: 'all' },
+ { key: 'maxEntries', kind: 'number', label: 'Max entries per run', min: 1, max: 50, default: 10 },
+ { key: 'mode', kind: 'imageMode', label: 'Render backend', default: null },
+ ]),
+ },
+]);
+
+export const DEFAULT_QUOTA_BURN_FAMILY = Object.freeze({
+ enabled: false,
+ providerId: null,
+ scope: null,
+ resetWithinHours: 24,
+ reservePercent: 0,
+ maxDispatchesPerWindow: 5,
+ priority: 0,
+ jobs: Object.freeze([]),
+});
+
+/** How often the runner re-reads quota. Bounded so a typo can't hammer the CLIs. */
+export const CHECK_INTERVAL_MINUTES_MIN = 5;
+export const CHECK_INTERVAL_MINUTES_MAX = 720;
+export const DEFAULT_CHECK_INTERVAL_MINUTES = 30;
+
+const clampNumber = (value, fallback, min, max) => {
+ const num = Number(value);
+ if (!Number.isFinite(num)) return fallback;
+ return Math.min(max, Math.max(min, num));
+};
+
+const clampInt = (value, fallback, min, max) =>
+ Math.round(clampNumber(value, fallback, min, max));
+
+const trimString = (value, max) =>
+ (typeof value === 'string' ? value.trim().slice(0, max) : '');
+
+const nullableString = (value, max) => {
+ const trimmed = trimString(value, max);
+ return trimmed || null;
+};
+
+/**
+ * A job's `params` bag stays free-form on purpose — each job type owns its own
+ * contract, and the runner's registry validates the keys it actually reads.
+ * What is enforced here is that it's a plain object of JSON-ish scalars, so a
+ * hand-edited config file can't smuggle a prototype or a nested blob into it.
+ */
+function normalizeParams(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return {};
+ const clean = {};
+ for (const [key, value] of Object.entries(raw)) {
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
+ if (typeof value === 'string') clean[key] = value.slice(0, 8000);
+ else if (typeof value === 'number' && Number.isFinite(value)) clean[key] = value;
+ else if (typeof value === 'boolean' || value === null) clean[key] = value;
+ }
+ return clean;
+}
+
+/**
+ * Normalize one burn job. Returns `null` for a job whose type is unknown — the
+ * caller DROPS it rather than substituting a default type: a job that runs the
+ * wrong work spends real subscription quota on something the user never asked
+ * for, which is strictly worse than the job disappearing from the list.
+ *
+ * `index` seeds a stable id for a job written before ids existed (or by a
+ * hand-edited file), so the client's list keys and the run ledger have
+ * something to key on.
+ */
+export function normalizeQuotaBurnJob(raw, index = 0) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ const jobType = typeof raw.jobType === 'string' ? raw.jobType : '';
+ if (!QUOTA_BURN_JOB_TYPES.includes(jobType)) return null;
+ return {
+ id: trimString(raw.id, 64) || `job-${index + 1}`,
+ enabled: raw.enabled !== false,
+ label: trimString(raw.label, 120),
+ jobType,
+ model: nullableString(raw.model, 120),
+ providerId: nullableString(raw.providerId, 120),
+ params: normalizeParams(raw.params),
+ };
+}
+
+/**
+ * Normalize one provider family's burn plan. Bounds mirror the pre-#3179
+ * per-app sanitizer so a migrated config keeps its meaning: reset window up to
+ * a week, reserve 0–100%, 1–50 dispatches per window.
+ */
+export function normalizeQuotaBurnFamily(raw) {
+ const value = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
+ const jobs = (Array.isArray(value.jobs) ? value.jobs : [])
+ .slice(0, 25)
+ .map((job, index) => normalizeQuotaBurnJob(job, index))
+ .filter(Boolean);
+ return {
+ enabled: value.enabled === true,
+ providerId: nullableString(value.providerId, 120),
+ scope: nullableString(value.scope, 60),
+ resetWithinHours: clampNumber(value.resetWithinHours, DEFAULT_QUOTA_BURN_FAMILY.resetWithinHours, 0, 168),
+ reservePercent: clampNumber(value.reservePercent, DEFAULT_QUOTA_BURN_FAMILY.reservePercent, 0, 100),
+ maxDispatchesPerWindow: clampInt(value.maxDispatchesPerWindow, DEFAULT_QUOTA_BURN_FAMILY.maxDispatchesPerWindow, 1, 50),
+ priority: clampInt(value.priority, 0, 0, 100),
+ jobs,
+ };
+}
+
+/**
+ * Normalize a whole config. Every known family key is materialized (disabled by
+ * default) so the page can render a complete card set and the runner never has
+ * to distinguish "absent" from "off" at read time. Unknown family keys are
+ * dropped — a card id the quota adapters don't produce could never be selected.
+ */
+export function normalizeQuotaBurnConfig(raw) {
+ const value = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};
+ const families = value.families && typeof value.families === 'object' && !Array.isArray(value.families)
+ ? value.families
+ : {};
+ return {
+ enabled: value.enabled === true,
+ checkIntervalMinutes: clampInt(
+ value.checkIntervalMinutes,
+ DEFAULT_CHECK_INTERVAL_MINUTES,
+ CHECK_INTERVAL_MINUTES_MIN,
+ CHECK_INTERVAL_MINUTES_MAX,
+ ),
+ families: Object.fromEntries(
+ QUOTA_BURN_FAMILIES.map((id) => [id, normalizeQuotaBurnFamily(families[id])]),
+ ),
+ };
+}
+
+/**
+ * Whether a family has anything the runner could dispatch: it must be enabled
+ * AND carry at least one enabled job. An enabled family with an empty job list
+ * is a half-finished setup, not a burn plan — treating it as actionable would
+ * spawn a candidate the runner then has to discard, which shows up as a
+ * confusing "selected, then skipped" cycle in the run log.
+ */
+export function familyIsActionable(family) {
+ return family?.enabled === true && (family.jobs || []).some((job) => job?.enabled !== false);
+}
diff --git a/server/lib/quotaBurnConfig.test.js b/server/lib/quotaBurnConfig.test.js
new file mode 100644
index 0000000000..4dcf812a77
--- /dev/null
+++ b/server/lib/quotaBurnConfig.test.js
@@ -0,0 +1,84 @@
+import { describe, expect, it } from 'vitest';
+import {
+ QUOTA_BURN_FAMILIES,
+ QUOTA_BURN_JOB_CATALOG,
+ QUOTA_BURN_JOB_TYPES,
+ familyIsActionable,
+ normalizeQuotaBurnConfig,
+ normalizeQuotaBurnJob,
+} from './quotaBurnConfig.js';
+
+describe('normalizeQuotaBurnConfig', () => {
+ it('materializes every family so absent is never confused with off', () => {
+ const config = normalizeQuotaBurnConfig(undefined);
+ expect(Object.keys(config.families).sort()).toEqual([...QUOTA_BURN_FAMILIES].sort());
+ expect(config.enabled).toBe(false);
+ expect(Object.values(config.families).every((family) => family.enabled === false)).toBe(true);
+ });
+
+ it('drops unknown family keys and clamps out-of-range window settings', () => {
+ const config = normalizeQuotaBurnConfig({
+ families: {
+ grok: { enabled: true, resetWithinHours: 999, reservePercent: -5, maxDispatchesPerWindow: 0, priority: 1e6 },
+ nonsense: { enabled: true },
+ },
+ });
+ expect(config.families.nonsense).toBeUndefined();
+ expect(config.families.grok).toMatchObject({
+ resetWithinHours: 168, reservePercent: 0, maxDispatchesPerWindow: 1, priority: 100,
+ });
+ });
+
+ it('clamps the check interval into the polling bounds', () => {
+ expect(normalizeQuotaBurnConfig({ checkIntervalMinutes: 1 }).checkIntervalMinutes).toBe(5);
+ expect(normalizeQuotaBurnConfig({ checkIntervalMinutes: 99999 }).checkIntervalMinutes).toBe(720);
+ expect(normalizeQuotaBurnConfig({ checkIntervalMinutes: 'nope' }).checkIntervalMinutes).toBe(30);
+ });
+});
+
+describe('normalizeQuotaBurnJob', () => {
+ it('drops a job whose type is unknown rather than substituting a default', () => {
+ // Substituting would run DIFFERENT work than configured and spend real
+ // subscription quota on it — strictly worse than the job disappearing.
+ expect(normalizeQuotaBurnJob({ jobType: 'delete-everything' })).toBeNull();
+ expect(normalizeQuotaBurnJob({ jobType: 'agent-prompt' })).toMatchObject({ jobType: 'agent-prompt', enabled: true });
+ });
+
+ it('mints a stable id for a job written before ids existed', () => {
+ expect(normalizeQuotaBurnJob({ jobType: 'agent-prompt' }, 2).id).toBe('job-3');
+ });
+
+ it('keeps scalar params and strips nested blobs and prototype keys', () => {
+ const job = normalizeQuotaBurnJob({
+ jobType: 'agent-prompt',
+ params: { appId: 'a1', maxEntries: 5, openPR: false, mode: null, nested: { a: 1 }, __proto__: { polluted: true } },
+ });
+ expect(job.params).toEqual({ appId: 'a1', maxEntries: 5, openPR: false, mode: null });
+ });
+});
+
+describe('familyIsActionable', () => {
+ it('requires an enabled family AND at least one enabled job', () => {
+ expect(familyIsActionable({ enabled: false, jobs: [{ enabled: true }] })).toBe(false);
+ expect(familyIsActionable({ enabled: true, jobs: [] })).toBe(false);
+ expect(familyIsActionable({ enabled: true, jobs: [{ enabled: false }] })).toBe(false);
+ expect(familyIsActionable({ enabled: true, jobs: [{ enabled: true }] })).toBe(true);
+ });
+});
+
+describe('QUOTA_BURN_JOB_CATALOG', () => {
+ it('describes exactly the registered job types', () => {
+ expect(QUOTA_BURN_JOB_CATALOG.map((entry) => entry.id).sort()).toEqual([...QUOTA_BURN_JOB_TYPES].sort());
+ });
+
+ it('gives every param a key and a renderable kind', () => {
+ // The client builds its form from these descriptors alone, so a param
+ // without a kind would render as nothing and silently stay unconfigurable.
+ for (const entry of QUOTA_BURN_JOB_CATALOG) {
+ for (const param of entry.params) {
+ expect(typeof param.key).toBe('string');
+ expect(['app', 'text', 'boolean', 'universe', 'enum', 'number', 'imageMode']).toContain(param.kind);
+ }
+ }
+ });
+});
diff --git a/server/lib/quotaBurnValidation.js b/server/lib/quotaBurnValidation.js
new file mode 100644
index 0000000000..8976afff49
--- /dev/null
+++ b/server/lib/quotaBurnValidation.js
@@ -0,0 +1,67 @@
+/**
+ * Zod schemas for the Quota Burn routes.
+ *
+ * Shape-only: the bounds here reject a malformed request, while
+ * `normalizeQuotaBurnConfig` (lib/quotaBurnConfig.js) is what the store applies
+ * on the way to disk. Both exist on purpose — a PUT gets a 400 instead of a
+ * silent clamp, and a config file written by an older PortOS still loads.
+ *
+ * Per the domain-validation convention this module must NOT import from
+ * `validation.js` (ESM hoisting would put that read in the TDZ); it re-exports
+ * from there instead.
+ */
+
+import { z } from 'zod';
+import {
+ CHECK_INTERVAL_MINUTES_MAX,
+ CHECK_INTERVAL_MINUTES_MIN,
+ QUOTA_BURN_FAMILIES,
+ QUOTA_BURN_JOB_TYPES,
+} from './quotaBurnConfig.js';
+
+// A job's params bag is per-job-type, so it stays a flat scalar map here — the
+// job module owns which keys it reads. Depth is what's rejected: a nested blob
+// in a config file is either a mistake or an attempt to smuggle state past the
+// normalizer.
+const paramValueSchema = z.union([z.string().max(8000), z.number().finite(), z.boolean(), z.null()]);
+
+export const quotaBurnJobSchema = z.object({
+ id: z.string().max(64).optional(),
+ enabled: z.boolean().optional(),
+ label: z.string().max(120).optional(),
+ jobType: z.enum(QUOTA_BURN_JOB_TYPES),
+ model: z.string().max(120).nullable().optional(),
+ providerId: z.string().max(120).nullable().optional(),
+ params: z.record(paramValueSchema).optional(),
+}).strict();
+
+export const quotaBurnFamilySchema = z.object({
+ enabled: z.boolean().optional(),
+ providerId: z.string().max(120).nullable().optional(),
+ scope: z.string().max(60).nullable().optional(),
+ resetWithinHours: z.number().min(0).max(168).optional(),
+ reservePercent: z.number().min(0).max(100).optional(),
+ maxDispatchesPerWindow: z.number().int().min(1).max(50).optional(),
+ priority: z.number().int().min(0).max(100).optional(),
+ // Replaced wholesale, never merged element-wise — it is an ordered list, and
+ // a positional merge would make reordering and deletion inexpressible.
+ jobs: z.array(quotaBurnJobSchema).max(25).optional(),
+}).strict();
+
+// Spelled out per family rather than z.record so an unknown family key is a 400
+// (a typo'd card id would otherwise round-trip and silently never burn).
+export const quotaBurnConfigUpdateSchema = z.object({
+ enabled: z.boolean().optional(),
+ checkIntervalMinutes: z.number().int().min(CHECK_INTERVAL_MINUTES_MIN).max(CHECK_INTERVAL_MINUTES_MAX).optional(),
+ families: z.object(
+ Object.fromEntries(QUOTA_BURN_FAMILIES.map((id) => [id, quotaBurnFamilySchema.optional()])),
+ ).strict().optional(),
+}).strict();
+
+export const quotaBurnRunSchema = z.object({
+ familyId: z.enum(QUOTA_BURN_FAMILIES).optional(),
+ jobId: z.string().max(64).optional(),
+ // Bypasses the reset-window / reserve / cap gates for ONE named job. Only
+ // meaningful with `familyId` — the route rejects it otherwise.
+ force: z.boolean().optional(),
+}).strict();
diff --git a/server/lib/validation.js b/server/lib/validation.js
index f2962a6522..4af1c5324d 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1695,3 +1695,4 @@ export * from './agentValidation.js';
export * from './cosValidation.js';
export * from './mediaValidation.js';
export * from './pipelineValidation.js';
+export * from './quotaBurnValidation.js';
diff --git a/server/routes/quotaBurn.js b/server/routes/quotaBurn.js
new file mode 100644
index 0000000000..b4947095e0
--- /dev/null
+++ b/server/routes/quotaBurn.js
@@ -0,0 +1,69 @@
+/**
+ * Quota Burn routes — the install-level burn plan, its live status, and manual
+ * runs. One loop for the whole install (see services/quotaBurnRunner.js); the
+ * work it dispatches may target any managed app, named per job.
+ */
+
+import { Router } from 'express';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest, quotaBurnConfigUpdateSchema, quotaBurnRunSchema } from '../lib/validation.js';
+import { QUOTA_BURN_FAMILIES, QUOTA_BURN_JOB_CATALOG } from '../lib/quotaBurnConfig.js';
+import { CLOUD_IMAGE_GEN_MODES, IMAGE_GEN_MODE } from '../services/imageGen/modes.js';
+import { getQuotaBurnConfig, saveQuotaBurnConfig } from '../services/quotaBurnStore.js';
+import { getQuotaBurnStatus, runQuotaBurnCycle } from '../services/quotaBurnRunner.js';
+import { getActiveApps } from '../services/apps.js';
+import { listUniverses } from '../services/universeBuilder.js';
+
+const router = Router();
+
+// GET /api/quota-burn — plan + live status (quota cards, per-job pending counts,
+// why each family would or wouldn't burn, recent runs). `?refresh=1` re-scrapes
+// provider usage; the default read is cached so opening the page is free.
+router.get('/', asyncHandler(async (req, res) => {
+ const refresh = req.query.refresh === '1' || req.query.refresh === 'true';
+ const [config, status] = await Promise.all([getQuotaBurnConfig(), getQuotaBurnStatus({ refresh })]);
+ res.json({ config, status });
+}));
+
+// 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.
+router.get('/catalog', asyncHandler(async (_req, res) => {
+ const [apps, universes] = await Promise.all([
+ getActiveApps(),
+ // A missing/empty universe store must not 500 the config page — the
+ // universe job simply has nothing to pick from.
+ listUniverses().catch(() => []),
+ ]);
+ res.json({
+ families: QUOTA_BURN_FAMILIES,
+ jobTypes: QUOTA_BURN_JOB_CATALOG,
+ apps: (apps || []).map((app) => ({ id: app.id, name: app.name })),
+ universes: universes.map((universe) => ({ id: universe.id, name: universe.name })),
+ imageModes: [...CLOUD_IMAGE_GEN_MODES, IMAGE_GEN_MODE.LOCAL],
+ });
+}));
+
+// PUT /api/quota-burn — merge a partial plan. Top-level and per-family keys
+// merge; a family's `jobs` array replaces.
+router.put('/', asyncHandler(async (req, res) => {
+ const patch = validateRequest(quotaBurnConfigUpdateSchema, req.body);
+ const config = await saveQuotaBurnConfig(patch);
+ res.json({ config });
+}));
+
+// POST /api/quota-burn/run — evaluate now. With no body it behaves like a
+// scheduled tick that ignores the master switch. `{ familyId, jobId, force }`
+// runs one named job immediately, past the window/reserve/cap gates.
+router.post('/run', asyncHandler(async (req, res) => {
+ const { familyId = null, jobId = null, force = false } = validateRequest(quotaBurnRunSchema, req.body || {});
+ if (force && !familyId) {
+ throw new ServerError('force requires a familyId — it bypasses that family\'s quota gates', {
+ status: 400, code: 'QUOTA_BURN_FORCE_NEEDS_FAMILY',
+ });
+ }
+ const result = await runQuotaBurnCycle({ trigger: 'manual', familyId, jobId, force });
+ res.json({ result });
+}));
+
+export default router;
diff --git a/server/routes/quotaBurn.test.js b/server/routes/quotaBurn.test.js
new file mode 100644
index 0000000000..6de58d6fc1
--- /dev/null
+++ b/server/routes/quotaBurn.test.js
@@ -0,0 +1,111 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+
+vi.mock('../services/quotaBurnStore.js', () => ({
+ getQuotaBurnConfig: vi.fn(),
+ saveQuotaBurnConfig: vi.fn(),
+}));
+vi.mock('../services/quotaBurnRunner.js', () => ({
+ getQuotaBurnStatus: vi.fn(),
+ runQuotaBurnCycle: vi.fn(),
+}));
+vi.mock('../services/apps.js', () => ({ getActiveApps: vi.fn() }));
+vi.mock('../services/universeBuilder.js', () => ({ listUniverses: vi.fn() }));
+
+import { getQuotaBurnConfig, saveQuotaBurnConfig } from '../services/quotaBurnStore.js';
+import { getQuotaBurnStatus, runQuotaBurnCycle } from '../services/quotaBurnRunner.js';
+import { getActiveApps } from '../services/apps.js';
+import { listUniverses } from '../services/universeBuilder.js';
+import quotaBurnRoutes from './quotaBurn.js';
+
+const buildApp = () => {
+ const app = express();
+ app.use(express.json());
+ app.use('/api/quota-burn', quotaBurnRoutes);
+ app.use(errorMiddleware);
+ return app;
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getQuotaBurnConfig.mockResolvedValue({ enabled: false, checkIntervalMinutes: 30, families: {} });
+ getQuotaBurnStatus.mockResolvedValue({ families: [], runs: [] });
+ getActiveApps.mockResolvedValue([{ id: 'a1', name: 'App One', secret: 'do-not-leak' }]);
+ listUniverses.mockResolvedValue([{ id: 'u1', name: 'Example Universe' }]);
+});
+
+describe('GET /api/quota-burn', () => {
+ it('returns the plan and its live status', async () => {
+ const res = await request(buildApp()).get('/api/quota-burn');
+ expect(res.status).toBe(200);
+ expect(res.body).toEqual({
+ config: { enabled: false, checkIntervalMinutes: 30, families: {} },
+ status: { families: [], runs: [] },
+ });
+ expect(getQuotaBurnStatus).toHaveBeenCalledWith({ refresh: false });
+ });
+
+ it('passes ?refresh through to the quota scrape', async () => {
+ await request(buildApp()).get('/api/quota-burn?refresh=1');
+ expect(getQuotaBurnStatus).toHaveBeenCalledWith({ refresh: true });
+ });
+});
+
+describe('GET /api/quota-burn/catalog', () => {
+ it('projects apps and universes down to id + name', 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.jobTypes.map((type) => type.id)).toContain('universe-bible-images');
+ });
+
+ 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.
+ listUniverses.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([]);
+ });
+});
+
+describe('PUT /api/quota-burn', () => {
+ it('saves a partial plan', async () => {
+ saveQuotaBurnConfig.mockResolvedValue({ enabled: true });
+ const res = await request(buildApp()).put('/api/quota-burn')
+ .send({ families: { grok: { enabled: true, jobs: [{ jobType: 'agent-prompt', params: { appId: 'a1' } }] } } });
+ expect(res.status).toBe(200);
+ expect(saveQuotaBurnConfig).toHaveBeenCalledWith({
+ families: { grok: { enabled: true, jobs: [{ jobType: 'agent-prompt', params: { appId: 'a1' } }] } },
+ });
+ });
+
+ it('rejects an unknown family, an unknown job type, and an out-of-range interval', async () => {
+ const app = buildApp();
+ expect((await request(app).put('/api/quota-burn').send({ families: { nope: { enabled: true } } })).status).toBe(400);
+ expect((await request(app).put('/api/quota-burn').send({ families: { grok: { jobs: [{ jobType: 'rm-rf' }] } } })).status).toBe(400);
+ expect((await request(app).put('/api/quota-burn').send({ checkIntervalMinutes: 1 })).status).toBe(400);
+ expect(saveQuotaBurnConfig).not.toHaveBeenCalled();
+ });
+});
+
+describe('POST /api/quota-burn/run', () => {
+ it('evaluates now with no body', async () => {
+ runQuotaBurnCycle.mockResolvedValue({ dispatched: false, reason: 'nothing' });
+ const res = await request(buildApp()).post('/api/quota-burn/run').send({});
+ expect(res.status).toBe(200);
+ expect(runQuotaBurnCycle).toHaveBeenCalledWith({ trigger: 'manual', familyId: null, jobId: null, force: false });
+ });
+
+ it('refuses force without a family', async () => {
+ // force bypasses a SPECIFIC family's quota gates; unscoped it would mean
+ // "ignore every gate on every family", which no button should be able to ask for.
+ const res = await request(buildApp()).post('/api/quota-burn/run').send({ force: true });
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('QUOTA_BURN_FORCE_NEEDS_FAMILY');
+ expect(runQuotaBurnCycle).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/autonomousJobs/quotaBurnHooks.js b/server/services/autonomousJobs/quotaBurnHooks.js
deleted file mode 100644
index 7e61416660..0000000000
--- a/server/services/autonomousJobs/quotaBurnHooks.js
+++ /dev/null
@@ -1,109 +0,0 @@
-import { getAllProviders } from '../providers.js';
-import { getProviderQuotas } from '../providerUsage.js';
-import { getEffectiveQuotaBurnDispatches, recordQuotaBurnDispatch, selectBurnCandidates, quotaBurnConfig, QUOTA_BURN_TASK_TYPE, QUOTA_BURN_DISPATCH_KEY_FIELD } from '../quotaBurn.js';
-
-function providerForFamily(providers, family) {
- const available = (providers || []).filter((provider) =>
- provider?.enabled && (provider.type === 'cli' || provider.type === 'tui'));
- if (family.providerId) return available.find((provider) => provider.id === family.providerId) || null;
- const familyName = family.id.toLowerCase();
- return available.find((provider) => String(provider.id || '').toLowerCase().includes(familyName)) || null;
-}
-
-function renderPrompt(candidate) {
- const { family, limit, hoursUntilReset } = candidate;
- return [
- `# ${family.id} quota-burn task`,
- '',
- `This configured ${family.id} quota window resets in about ${Math.max(0, Math.ceil(hoursUntilReset))} hours.`,
- `Window: ${limit.label || limit.scope || 'provider window'}; remaining: ${limit.percentRemaining}%; reserve: ${family.reservePercent}%.`,
- `Dispatch cap: ${family.maxDispatchesPerWindow} for this reset window.`,
- '',
- 'Carry out the configured work below. Do not use another provider family as a substitute.',
- '',
- family.prompt.trim(),
- ].join('\n');
-}
-
-/**
- * Programmatic pre-agent hook. It refreshes quota readings immediately before
- * dispatch, pins an agent-capable provider in the selected family, and returns
- * a skip instead of spawning when any prerequisite is missing.
- *
- * Deliberately does NOT write the dispatch ledger (#3179). Several gates in
- * `cosTaskGenerator.js#buildImprovementTask` run AFTER this hook returns —
- * claim-work routing, the perpetual-work gate, branch-/issue-reconcile,
- * reference-watch, the PLAN.md gate — and any of them can still `return null`
- * and skip creating the task, with no agent ever spawned. A ledger write here
- * therefore burned a slot of `family.maxDispatchesPerWindow` on a dispatch that
- * never happened. Instead the resolved `dispatchKey` is handed back as
- * `hookMetadata`, which the generator stamps onto the task only once every gate
- * has passed, and `processTaskOutput` below records it post-agent.
- */
-export async function buildTaskInput({ app, ignoreTaskId = null } = {}) {
- if (!app) return { skip: { reason: 'no-app' } };
- const config = quotaBurnConfig(app);
- // Ledger + in-flight, NOT the bare ledger: a quota-burn task already queued or
- // running holds its window slot even though its ledger write lands post-agent
- // (#3179). `ignoreTaskId` drops the run whose completion triggered this
- // generation — it recorded itself moments ago but still reads `in_progress`.
- const dispatches = await getEffectiveQuotaBurnDispatches({ ignoreTaskId });
- const quotas = await getProviderQuotas({ refresh: true });
- const candidates = selectBurnCandidates(quotas, config, { dispatches });
- const candidate = candidates[0];
- if (!candidate) return { skip: { reason: 'no-burnable-provider-quota' } };
-
- const providerResult = await getAllProviders();
- const provider = providerForFamily(
- Array.isArray(providerResult) ? providerResult : providerResult?.providers,
- candidate.family,
- );
- if (!provider) return { skip: { reason: 'no-enabled-agent-provider-in-family' } };
-
- return {
- prompt: renderPrompt(candidate),
- providerId: provider.id,
- model: candidate.family.model || null,
- hookMetadata: { [QUOTA_BURN_DISPATCH_KEY_FIELD]: candidate.dispatchKey },
- };
-}
-
-/**
- * Programmatic post-agent hook. Records the dispatch against the family's
- * reset-window ledger — the ONLY place that write happens (#3179). By the time
- * the finalize chokepoint runs this, an agent was actually spawned, which is the
- * real event `family.maxDispatchesPerWindow` is meant to bound.
- *
- * Runs regardless of `success`: the provider quota was consumed the moment the
- * agent ran, whether or not its run exited clean. A window's budget must count
- * failed burns too, otherwise a family that keeps erroring out would dispatch
- * without limit.
- *
- * Returns NO structured outcome, on purpose. `resolveProgrammaticIoVerdict`
- * (agentFinalization.js) reads an output hook's outcome as the task type's
- * success criterion, and quota-burn has none to offer: its agent does arbitrary
- * user-configured work with no `.agent-done` payload contract, so nothing here
- * evaluates the agent's output. Handing back no outcome keeps that verdict at
- * the "undeclared" null sentinel, leaving quota-burn exit-code-judged exactly as
- * it was before this hook existed. Do NOT return an object to make this "more
- * informative" — that would declare a criterion this hook never checked.
- *
- * For the same reason the ledger write must not throw. finalizeAgent turns a
- * thrown output hook into `{ ran: true, threw: true }`, which rejects the run's
- * success criterion AND records a `hook-error` against the per-type
- * consecutive-failure ledger that auto-parks a task type — so a transient
- * ENOSPC/EACCES writing one JSON file could park quota-burn entirely. A failed
- * write is environmental, not a bad run; log and move on, exactly as the
- * verdict's own docstring prescribes for a hook whose side effect couldn't land.
- */
-export async function processTaskOutput({ agentId, task } = {}) {
- const dispatchKey = task?.metadata?.[QUOTA_BURN_DISPATCH_KEY_FIELD];
- // Absent key = this task predates the metadata thread, or generation never
- // resolved a candidate. Nothing to record; never invent a ledger entry.
- if (typeof dispatchKey !== 'string' || !dispatchKey) return;
- await recordQuotaBurnDispatch(dispatchKey, { agentId })
- .then(() => console.log(`🔥 Recorded quota-burn dispatch for ${dispatchKey}`))
- .catch((err) => console.error(`❌ Failed to record quota-burn dispatch for ${dispatchKey}: ${err.message}`));
-}
-
-export const __test = { providerForFamily, renderPrompt, QUOTA_BURN_TASK_TYPE };
diff --git a/server/services/autonomousJobs/quotaBurnHooks.test.js b/server/services/autonomousJobs/quotaBurnHooks.test.js
deleted file mode 100644
index 33a1cfcfc3..0000000000
--- a/server/services/autonomousJobs/quotaBurnHooks.test.js
+++ /dev/null
@@ -1,155 +0,0 @@
-/**
- * Tests for the quota-burn programmatic-I/O hooks (#3179).
- *
- * The behavior under test is WHEN the dispatch ledger is written. It used to be
- * written inside `buildTaskInput`, before the task generator had finished
- * gating — so any downstream skip (perpetual-work, branch-/issue-reconcile,
- * reference-watch, PLAN.md) permanently consumed a slot of
- * `family.maxDispatchesPerWindow` for an agent that never ran. The write now
- * happens once, post-agent, in `processTaskOutput` — and because that leaves a
- * gap where a created burn isn't in the ledger yet, candidate selection counts
- * in-flight burns alongside it so the window cap still holds.
- */
-
-import { describe, it, expect, vi, beforeEach } from 'vitest';
-
-const recordQuotaBurnDispatch = vi.fn().mockResolvedValue({});
-const selectBurnCandidates = vi.fn();
-const getEffectiveQuotaBurnDispatches = vi.fn().mockResolvedValue({});
-const getProviderQuotas = vi.fn().mockResolvedValue([]);
-const getAllProviders = vi.fn();
-
-vi.mock('../quotaBurn.js', () => ({
- QUOTA_BURN_TASK_TYPE: 'quota-burn',
- QUOTA_BURN_DISPATCH_KEY_FIELD: 'quotaBurnDispatchKey',
- getEffectiveQuotaBurnDispatches: (...args) => getEffectiveQuotaBurnDispatches(...args),
- recordQuotaBurnDispatch: (...args) => recordQuotaBurnDispatch(...args),
- selectBurnCandidates: (...args) => selectBurnCandidates(...args),
- quotaBurnConfig: (app) => app?.taskTypeOverrides?.['quota-burn']?.taskMetadata || { families: {} },
-}));
-vi.mock('../providerUsage.js', () => ({ getProviderQuotas: (...args) => getProviderQuotas(...args) }));
-vi.mock('../providers.js', () => ({ getAllProviders: (...args) => getAllProviders(...args) }));
-
-const { buildTaskInput, processTaskOutput } = await import('./quotaBurnHooks.js');
-const { QUOTA_BURN_DISPATCH_KEY_FIELD } = await import('../quotaBurn.js');
-const { generateTasksMarkdown, parseTasksMarkdown } = await import('../../lib/taskParser.js');
-
-const DISPATCH_KEY = 'grok:1753574400000';
-const APP = { id: 'app-1', name: 'App One', taskTypeOverrides: { 'quota-burn': { taskMetadata: { families: { grok: { enabled: true, prompt: 'Burn it.' } } } } } };
-const CANDIDATE = {
- family: { id: 'grok', reservePercent: 20, maxDispatchesPerWindow: 2, prompt: 'Burn it.', model: 'grok-4' },
- limit: { label: 'Weekly', scope: 'week', percentRemaining: 50 },
- hoursUntilReset: 6,
- dispatchKey: DISPATCH_KEY,
-};
-
-beforeEach(() => {
- vi.clearAllMocks();
- selectBurnCandidates.mockReturnValue([CANDIDATE]);
- getAllProviders.mockResolvedValue([{ id: 'grok-cli', enabled: true, type: 'cli' }]);
-});
-
-describe('buildTaskInput (pre-agent)', () => {
- it('hands the dispatch key back as hookMetadata WITHOUT writing the ledger', async () => {
- const input = await buildTaskInput({ app: APP });
-
- expect(input.hookMetadata).toEqual({ [QUOTA_BURN_DISPATCH_KEY_FIELD]: DISPATCH_KEY });
- expect(input.providerId).toBe('grok-cli');
- expect(input.model).toBe('grok-4');
- expect(input.prompt).toContain('Burn it.');
- // The whole point of #3179: nothing is recorded until an agent actually runs.
- expect(recordQuotaBurnDispatch).not.toHaveBeenCalled();
- });
-
- it('records nothing on any skip path', async () => {
- await expect(buildTaskInput({})).resolves.toMatchObject({ skip: { reason: 'no-app' } });
-
- selectBurnCandidates.mockReturnValue([]);
- await expect(buildTaskInput({ app: APP })).resolves.toMatchObject({ skip: { reason: 'no-burnable-provider-quota' } });
-
- selectBurnCandidates.mockReturnValue([CANDIDATE]);
- getAllProviders.mockResolvedValue([{ id: 'other', enabled: true, type: 'cli' }]);
- await expect(buildTaskInput({ app: APP })).resolves.toMatchObject({ skip: { reason: 'no-enabled-agent-provider-in-family' } });
-
- expect(recordQuotaBurnDispatch).not.toHaveBeenCalled();
- });
-
- it('selects against the ledger PLUS in-flight tasks, not the bare ledger', async () => {
- // With the write deferred to processTaskOutput, an already-queued burn is
- // invisible to the raw ledger — so candidate selection has to consult the
- // effective count or a sibling app (or a second on-demand Run) would dispatch
- // straight past maxDispatchesPerWindow.
- getEffectiveQuotaBurnDispatches.mockResolvedValue({ [DISPATCH_KEY]: 1 });
-
- await buildTaskInput({ app: APP });
-
- expect(getEffectiveQuotaBurnDispatches).toHaveBeenCalled();
- expect(selectBurnCandidates).toHaveBeenCalledWith(expect.anything(), expect.anything(), { dispatches: { [DISPATCH_KEY]: 1 } });
- });
-
- it('forwards ignoreTaskId so the completing run is not counted against itself', async () => {
- await buildTaskInput({ app: APP, ignoreTaskId: 'sys-finishing' });
-
- expect(getEffectiveQuotaBurnDispatches).toHaveBeenCalledWith({ ignoreTaskId: 'sys-finishing' });
- });
-});
-
-describe('processTaskOutput (post-agent)', () => {
- const task = { metadata: { [QUOTA_BURN_DISPATCH_KEY_FIELD]: DISPATCH_KEY } };
-
- // The quota was consumed the moment the agent ran, so a failed run counts too.
- it.each([true, false])('records the dispatch exactly once on a run with success=%s', async (success) => {
- await processTaskOutput({ appId: 'app-1', agentId: 'agent-1', success, payload: null, task });
-
- expect(recordQuotaBurnDispatch).toHaveBeenCalledTimes(1);
- expect(recordQuotaBurnDispatch).toHaveBeenCalledWith(DISPATCH_KEY, { agentId: 'agent-1' });
- });
-
- it('swallows a ledger write failure instead of throwing', async () => {
- // A thrown output hook is read as `{ ran: true, threw: true }` — which
- // rejects the run's success criterion AND records a `hook-error` against the
- // per-type failure ledger that auto-parks a task type. A full disk must not
- // park quota-burn, so an environmental write failure stays a log line.
- recordQuotaBurnDispatch.mockRejectedValueOnce(new Error('ENOSPC'));
-
- await expect(processTaskOutput({ appId: 'app-1', success: true, task })).resolves.toBeUndefined();
- });
-
- it('no-ops when the task carries no dispatch key (task predating the metadata thread)', async () => {
- await processTaskOutput({ success: true, task: { metadata: {} } });
- await processTaskOutput({ success: true, task: {} });
- await processTaskOutput({ success: true });
- await processTaskOutput();
- // A non-string key must not be coerced into a ledger entry either.
- await processTaskOutput({ success: true, task: { metadata: { [QUOTA_BURN_DISPATCH_KEY_FIELD]: { id: 'grok' } } } });
- await processTaskOutput({ success: true, task: { metadata: { [QUOTA_BURN_DISPATCH_KEY_FIELD]: '' } } });
-
- expect(recordQuotaBurnDispatch).not.toHaveBeenCalled();
- });
-
- it('reads a dispatch key that survived the COS-TASKS.md round-trip', async () => {
- // The key only reaches this hook by riding in the task's PERSISTED metadata,
- // so the markdown format has to carry it intact. Two ways it could silently
- // fail: `parseMetadataLine` keys on `\w+` (fine for the camelCase field), and
- // it splits on the FIRST colon — while a dispatch key is `<family>:<epochMs>`
- // and so contains one. A greedy value capture is what makes that work; this
- // pins it, because a regression would look like a hook that just never fires.
- const built = await buildTaskInput({ app: APP });
- const persisted = { id: 'sys-abc', status: 'pending', priority: 'MEDIUM', description: 'quota burn', metadata: { app: 'app-1', analysisType: 'quota-burn', ...built.hookMetadata } };
- const [reparsed] = parseTasksMarkdown(generateTasksMarkdown([persisted], true));
-
- expect(reparsed.metadata[QUOTA_BURN_DISPATCH_KEY_FIELD]).toBe(DISPATCH_KEY);
-
- await processTaskOutput({ appId: 'app-1', agentId: 'agent-1', success: true, task: reparsed });
- expect(recordQuotaBurnDispatch).toHaveBeenCalledWith(DISPATCH_KEY, { agentId: 'agent-1' });
- });
-
- it('returns no structured outcome, so quota-burn stays exit-code-judged', async () => {
- // Registering an output hook must NOT start declaring a success criterion for
- // a task type whose agent has no `.agent-done` payload contract.
- // resolveProgrammaticIoVerdict maps a non-object outcome to the "undeclared"
- // null sentinel (pinned in agentFinalization.successCriteria.test.js), which
- // keeps task-learning falling back to the exit code exactly as before.
- expect(await processTaskOutput({ appId: 'app-1', success: true, task })).toBeUndefined();
- });
-});
diff --git a/server/services/bootstrap.js b/server/services/bootstrap.js
index 48b9e36453..a2ef065067 100644
--- a/server/services/bootstrap.js
+++ b/server/services/bootstrap.js
@@ -61,6 +61,7 @@ import { reconcile as reconcileVoice } from './voice/bootstrap.js';
import { initVoiceTimers } from './voice/timers.js';
import { startBackupScheduler } from './backupScheduler.js';
import { startPrivacyRecheckScheduler } from './privacyRecheckScheduler.js';
+import { startQuotaBurnScheduler } from './quotaBurnRunner.js';
import { startSeriesAutopilotScheduler } from './seriesAutopilotScheduler.js';
import { startCommissionScheduler } from './creativeCommissions/scheduler.js';
import { startCitySnapshotScheduler } from './citySnapshotScheduler.js';
@@ -343,6 +344,12 @@ const startBackgroundServices = ({ spawnerReady }) => {
// re-runs the broker scan + opt-out pass when the user opts in via
// Settings → Privacy (sanctioned scheduled-automation exception) (#2145).
startPrivacyRecheckScheduler().catch(err => console.error(`❌ Privacy recheck scheduler init failed: ${err.message}`));
+ // Quota-burn loop — ONE install-level loop that spends subscription quota that
+ // would otherwise expire. OFF by default: the tick returns before touching a
+ // provider unless the user enabled it on the Quota Burn page, where the
+ // family, provider, model, and work are all named first (sanctioned
+ // scheduled-automation exception).
+ startQuotaBurnScheduler();
// Initialize Series Autopilot scheduler — OFF by default; registers a cron per
// series only when the user configured + enabled one via Settings → Series
// Autopilot. Each scheduled run still passes through the cos autonomy gate +
diff --git a/server/services/perpetualWork.js b/server/services/perpetualWork.js
index e41b99b555..1c567493f2 100644
--- a/server/services/perpetualWork.js
+++ b/server/services/perpetualWork.js
@@ -488,14 +488,6 @@ export function hasWorkDetector(taskType) {
registerWorkDetector('claim-issue', detectGithubIssues);
registerWorkDetector('claim-issue-gitlab', detectGitlabIssues);
registerWorkDetector('plan-task', detectPlanTask);
-registerWorkDetector('quota-burn', async (app, opts) => {
- const { detectQuotaBurn } = await import('./quotaBurn.js');
- // Forward `ignoreTaskId`: on the drain-on-completion refill the just-finished
- // burn has already written its ledger entry but still reads `in_progress`, so
- // without this the detector counts it twice and parks a family that still has
- // window budget left (#3179).
- return detectQuotaBurn(app, { ignoreTaskId: opts?.ignoreTaskId || null });
-});
/**
* Probe whether `taskType` has actionable work for `app`. Always resolves to a
diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.js
index a8ba3bf736..4207883ff7 100644
--- a/server/services/quotaBurn.js
+++ b/server/services/quotaBurn.js
@@ -1,161 +1,103 @@
-import { getProviderQuotas } from './providerUsage.js';
+/**
+ * Quota-burn candidate selection + the per-window dispatch ledger.
+ *
+ * Quota-burn spends subscription-backed CLI quota that would otherwise expire
+ * unused: it watches each enabled provider family's reset clock and, only once
+ * a window is close to resetting and still has headroom above the family's
+ * reserve, runs the next job in that family's ordered burn plan.
+ *
+ * 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
+ * them together in `quotaBurnRunner.js`.
+ *
+ * Everything here fails CLOSED: an unknown reset time, an unsupported provider,
+ * a quota-read error, or a card that declares itself unburnable all mean "do not
+ * dispatch". Burning is opt-in spending of the user's own subscription — a
+ * guess in the permissive direction costs them real quota.
+ */
+
import { join } from 'path';
import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { familyIsActionable, normalizeQuotaBurnFamily } from '../lib/quotaBurnConfig.js';
import { hoursUntilReset, normalizeResetAt } from '../lib/quotaReset.js';
-export const QUOTA_BURN_TASK_TYPE = 'quota-burn';
-const LEDGER_FILE = join(PATHS.cos, 'quota-burn-dispatches.json');
-const AGENT_DISPATCH_LEDGER_KEY = '__agentDispatches';
-export const DEFAULT_QUOTA_BURN_FAMILY = {
- enabled: false,
- providerId: null,
- model: null,
- scope: null,
- resetWithinHours: 24,
- reservePercent: 0,
- maxDispatchesPerWindow: 5,
- priority: 0,
- prompt: '',
-};
+const LEDGER_FILE = () => join(PATHS.cos, 'quota-burn-dispatches.json');
-export function quotaBurnConfig(app) {
- const metadata = app?.taskTypeOverrides?.[QUOTA_BURN_TASK_TYPE]?.taskMetadata;
- return metadata && typeof metadata === 'object' ? metadata : { families: {} };
-}
+// Window keys older than this fall out of the ledger on the next write. A key is
+// `<family>:<resetEpochMs>`, so a passed window can never be selected again and
+// its count is dead weight; without a prune the file grows for the life of the
+// install.
+const LEDGER_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
async function readQuotaBurnLedger() {
- const loaded = await readJSONFile(LEDGER_FILE, {});
- return loaded && typeof loaded === 'object' ? loaded : {};
+ const loaded = await readJSONFile(LEDGER_FILE(), {});
+ return loaded && typeof loaded === 'object' && !Array.isArray(loaded) ? loaded : {};
}
+/** Dispatch counts per `<family>:<resetEpochMs>` window key. */
export async function getQuotaBurnDispatches() {
- const { [AGENT_DISPATCH_LEDGER_KEY]: _agentDispatches, ...counts } = await readQuotaBurnLedger();
- return counts;
+ return readQuotaBurnLedger();
}
-// Single-tail queue for the dispatch ledger's read-modify-write. Two quota-burn
-// agents (one per app) can finalize concurrently, and each finalization records a
-// dispatch — unserialized, both would read the same count and write the same
-// increment, losing one burn. An undercounted ledger then lets the window
-// dispatch past `maxDispatchesPerWindow`, which is real quota overspend. This is
-// the "serialize two write paths that mutate the same record" case, not a
-// defense against competing users. It only became reachable when the write moved
-// from generation (sequential, one app at a time) to finalize (#3179).
-//
-// `__agentDispatches` keeps the increment idempotent across a crash between the
-// hook side effect and finalizeAgent's separate agent-marker write (#3182). It
-// lives in this SAME atomic ledger write and leaves window counts as top-level
-// numbers, so an older PortOS version still reads and updates the file safely.
+const windowEpoch = (key) => Number(String(key).split(':').pop());
+
+function pruneLedger(ledger, now) {
+ return Object.fromEntries(Object.entries(ledger).filter(([key]) => {
+ const epoch = windowEpoch(key);
+ // Keep anything we can't date — an unparseable key is not evidence of age.
+ return !Number.isFinite(epoch) || now - epoch < LEDGER_RETENTION_MS;
+ }));
+}
+
+// Single tail for the ledger's read-modify-write. The scheduler tick and an
+// on-demand "Run now" can both land a dispatch at once; unserialized, both would
+// read the same count and write the same increment, losing one burn. An
+// undercounted ledger then lets the window dispatch past
+// `maxDispatchesPerWindow`, which is real quota overspend. This is the
+// "serialize two write paths that mutate the same record" case, not a defense
+// against competing users.
const ledgerWriteQueue = createFileWriteQueue();
-export async function recordQuotaBurnDispatch(key, { agentId = null } = {}) {
+export async function recordQuotaBurnDispatch(key, { now = Date.now() } = {}) {
return ledgerWriteQueue(async () => {
- const ledger = await readQuotaBurnLedger();
- const agentDispatches = ledger[AGENT_DISPATCH_LEDGER_KEY];
- const seenAgents = agentDispatches && typeof agentDispatches === 'object' ? agentDispatches : {};
- if (agentId && seenAgents[agentId]) return ledger;
- const next = {
- ...ledger,
- [key]: Number(ledger[key] || 0) + 1,
- ...(agentId ? {
- [AGENT_DISPATCH_LEDGER_KEY]: { ...seenAgents, [agentId]: key }
- } : {}),
- };
- await atomicWrite(LEDGER_FILE, next);
+ const ledger = pruneLedger(await readQuotaBurnLedger(), now);
+ const next = { ...ledger, [key]: Number(ledger[key] || 0) + 1 };
+ await atomicWrite(LEDGER_FILE(), next);
return next;
});
}
/**
- * The task-metadata key a resolved `dispatchKey` rides across on, from the
- * pre-agent `buildTaskInput` hook to the post-agent `processTaskOutput` that
- * writes the ledger (#3179). Lives here, beside the ledger it guards, so the
- * producer, the consumer, and the in-flight count below can't drift on spelling.
+ * The soonest-resetting limit on a card that is still in scope for the family,
+ * or null when none of them state a reset time we can read.
*/
-export const QUOTA_BURN_DISPATCH_KEY_FIELD = 'quotaBurnDispatchKey';
-
-/**
- * Dispatch counts to select the next burn candidate against: the persisted
- * ledger PLUS every quota-burn task already queued or running that carries a
- * dispatch key but has not reached its post-agent ledger write yet.
- *
- * Counting the in-flight tasks is what keeps the window cap honest now that the
- * ledger is written post-agent (#3179). The ledger write used to happen during
- * generation, which incidentally serialized sibling candidates — the next reader
- * always saw it. Deferring the write opens a gap between "task created" and
- * "dispatch recorded", and two paths generate inside that gap: the per-app
- * improvement loop runs once per managed app while `dispatchKey` is
- * `<family>:<resetEpoch>` (app-independent, one global ledger), and an on-demand
- * "Run" calls the generator directly, bypassing the per-app pending-task cap
- * entirely. Without this, either could dispatch past `maxDispatchesPerWindow` —
- * real quota overspend, the exact thing the cap exists to prevent, and a worse
- * failure than the over-counting #3179 fixed.
- *
- * `ignoreTaskId` excludes one task from the in-flight tally — the same exclusion
- * `buildImprovementDedupSets` takes, for the same reason. `agent:completed` fires
- * from `completeAgent`, which runs AFTER the output hook wrote this run's ledger
- * entry but BEFORE the completion flow's `updateTask` marks the task done. So
- * during the perpetual drain-on-completion refill the just-finished burn is
- * counted twice — once in the ledger, once as a still-`in_progress` task — and a
- * family with `maxDispatchesPerWindow: 2` would stop after one run and likely
- * miss its reset window. Callers on that path pass the completing task's id.
- *
- * An unreadable task file degrades to the ledger-only count rather than throwing:
- * COS-TASKS.md is the file the whole CoS queue reads, so if it is unavailable
- * nothing is dispatching anyway, and failing the probe closed would wedge
- * quota-burn until the next 12-hourly recheck.
- */
-export async function getEffectiveQuotaBurnDispatches({ ignoreTaskId = null } = {}) {
- const counts = { ...(await getQuotaBurnDispatches()) };
- // Lazy import: cosTaskStore pulls a heavy graph (state, code review, merge),
- // and quotaBurn.js is imported by the perpetual-work detector on a hot path.
- const { getCosTasks } = await import('./cosTaskStore.js');
- const cosTasks = await getCosTasks().catch((err) => {
- console.error(`❌ Quota-burn in-flight probe failed, falling back to the ledger alone: ${err.message}`);
- return null;
- });
- for (const task of cosTasks?.tasks || []) {
- if (ignoreTaskId && task?.id === ignoreTaskId) continue;
- if (task?.status !== 'pending' && task?.status !== 'in_progress') continue;
- const key = task?.metadata?.[QUOTA_BURN_DISPATCH_KEY_FIELD];
- if (typeof key !== 'string' || !key) continue;
- counts[key] = Number(counts[key] || 0) + 1;
- }
- return counts;
-}
-
-function normalizedFamily(id, value) {
- if (!value || typeof value !== 'object' || value.enabled !== true) return null;
- const config = { ...DEFAULT_QUOTA_BURN_FAMILY, ...value };
- return {
- id,
- ...config,
- resetWithinHours: Math.max(0, Number(config.resetWithinHours) || 24),
- reservePercent: Math.min(100, Math.max(0, Number(config.reservePercent) || 0)),
- maxDispatchesPerWindow: Math.max(1, Math.floor(Number(config.maxDispatchesPerWindow) || 5)),
- priority: Number(config.priority) || 0,
- };
-}
-
function selectLimit(card, family, now) {
const scoped = (card.limits || []).filter((limit) => !family.scope || limit.scope === family.scope);
return scoped
- .map((limit) => ({ limit, hours: hoursUntilReset(limit, { now, timeZone: family.timeZone }) }))
+ .map((limit) => ({ limit, hours: hoursUntilReset(limit, { now }) }))
.filter((entry) => entry.hours !== null)
.sort((a, b) => a.hours - b.hours)[0] || null;
}
+/** Headroom the family is willing to spend: what's left, minus its reserve. */
export function burnBudgetRemaining(limit, family) {
return Math.max(0, Number(limit?.percentRemaining) - family.reservePercent);
}
-/** Select only safely-known, still-burnable provider windows. */
+/**
+ * Select only safely-known, still-burnable provider windows, soonest reset
+ * first (ties broken by the family's `priority`).
+ *
+ * `config` is a normalized quota-burn config; `quotas` the provider cards from
+ * `providerUsage.getProviderQuotas()`.
+ */
export function selectBurnCandidates(quotas, config, { now = Date.now(), dispatches = {} } = {}) {
const cards = new Map((quotas || []).map((card) => [card.family, card]));
return Object.entries(config?.families || {})
- .map(([id, value]) => normalizedFamily(id, value))
- .filter(Boolean)
+ .map(([id, value]) => ({ id, ...normalizeQuotaBurnFamily(value) }))
+ .filter(familyIsActionable)
.map((family) => {
const card = cards.get(family.id);
if (!card || card.supported === false || card.error) return null;
@@ -166,28 +108,47 @@ export function selectBurnCandidates(quotas, config, { now = Date.now(), dispatc
if (card.burnable === false) return null;
const selected = selectLimit(card, family, now);
if (!selected || selected.hours < 0 || selected.hours > family.resetWithinHours) return null;
- const dispatchKey = `${family.id}:${normalizeResetAt(selected.limit, { now, timeZone: family.timeZone }).epochMs}`;
+ const dispatchKey = `${family.id}:${normalizeResetAt(selected.limit, { now }).epochMs}`;
if (Number(dispatches[dispatchKey] || 0) >= family.maxDispatchesPerWindow) return null;
if (burnBudgetRemaining(selected.limit, family) <= 0) return null;
- return { family, card, limit: selected.limit, hoursUntilReset: selected.hours, dispatchKey };
+ return {
+ family,
+ card,
+ limit: selected.limit,
+ hoursUntilReset: selected.hours,
+ dispatchKey,
+ dispatchesUsed: Number(dispatches[dispatchKey] || 0),
+ };
})
.filter(Boolean)
.sort((a, b) => a.hoursUntilReset - b.hoursUntilReset || a.family.priority - b.family.priority);
}
-export async function detectQuotaBurn(app, { getQuotas = getProviderQuotas, now = Date.now(), dispatches, ignoreTaskId = null } = {}) {
- const config = quotaBurnConfig(app);
- const configured = Object.entries(config.families || {})
- .filter(([, family]) => family?.enabled === true)
- .map(([id, family]) => ({ id, ...family }));
- if (!configured.length) return { actionable: false, count: 0, reason: 'no-enabled-families' };
- const quotas = await getQuotas({ refresh: false });
- const configuredCards = quotas.filter((card) => configured.some((family) => family?.id === card?.family));
- if (configuredCards.length && configuredCards.every((card) => card?.error)) {
- return { actionable: false, count: 0, transient: true, reason: 'all-provider-quota-checks-failed' };
+/**
+ * Why a configured family is NOT a candidate right now, for the status page.
+ * Mirrors `selectBurnCandidates`'s gates one-for-one so the page can never
+ * disagree with the runner about what would happen on the next tick.
+ */
+export function explainFamilySkip(familyId, rawFamily, quotas, { now = Date.now(), dispatches = {} } = {}) {
+ const family = { id: familyId, ...normalizeQuotaBurnFamily(rawFamily) };
+ if (!family.enabled) return 'disabled';
+ if (!familyIsActionable(family)) return 'no enabled jobs configured';
+ const card = (quotas || []).find((entry) => entry.family === familyId);
+ if (!card) return 'no enabled provider in this family';
+ if (card.supported === false) return 'provider has no queryable quota surface';
+ if (card.error) return `quota read failed: ${card.error}`;
+ if (card.burnable === false) return 'provider reports no spendable headroom';
+ const selected = selectLimit(card, family, now);
+ if (!selected) return 'no window states a reset time';
+ if (selected.hours < 0) return 'window already reset';
+ if (selected.hours > family.resetWithinHours) {
+ return `resets in ${Math.ceil(selected.hours)}h — outside the ${family.resetWithinHours}h window`;
+ }
+ const dispatchKey = `${family.id}:${normalizeResetAt(selected.limit, { now }).epochMs}`;
+ const used = Number(dispatches[dispatchKey] || 0);
+ if (used >= family.maxDispatchesPerWindow) return `dispatch cap reached (${used}/${family.maxDispatchesPerWindow})`;
+ if (burnBudgetRemaining(selected.limit, family) <= 0) {
+ return `${selected.limit.percentRemaining}% left is at or below the ${family.reservePercent}% reserve`;
}
- const candidates = selectBurnCandidates(quotas, config, { now, dispatches: dispatches || await getEffectiveQuotaBurnDispatches({ ignoreTaskId }) });
- return candidates.length
- ? { actionable: true, count: candidates.length, reason: `${candidates[0].family.id} resets in ${Math.ceil(candidates[0].hoursUntilReset)}h`, candidates }
- : { actionable: false, count: 0, reason: 'no-family-within-reset-window' };
+ return null;
}
diff --git a/server/services/quotaBurn.test.js b/server/services/quotaBurn.test.js
index a3ac9e270f..23d91355fd 100644
--- a/server/services/quotaBurn.test.js
+++ b/server/services/quotaBurn.test.js
@@ -1,14 +1,16 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { detectQuotaBurn, selectBurnCandidates } from './quotaBurn.js';
-import { sanitizeTaskMetadata } from '../lib/validation.js';
+import { burnBudgetRemaining, explainFamilySkip, selectBurnCandidates } from './quotaBurn.js';
+import { normalizeQuotaBurnConfig } from '../lib/quotaBurnConfig.js';
const NOW = Date.parse('2026-07-26T12:00:00.000Z');
-const config = {
+const job = (jobType = 'agent-prompt') => ({ id: 'j1', enabled: true, jobType, params: {} });
+const config = normalizeQuotaBurnConfig({
+ enabled: true,
families: {
- grok: { enabled: true, prompt: 'Animate eligible sprites.', resetWithinHours: 24, reservePercent: 20, maxDispatchesPerWindow: 2 },
- codex: { enabled: true, prompt: 'Prepare assets.', resetWithinHours: 24, reservePercent: 0, priority: 1 },
+ grok: { enabled: true, resetWithinHours: 24, reservePercent: 20, maxDispatchesPerWindow: 2, jobs: [job()] },
+ codex: { enabled: true, resetWithinHours: 24, reservePercent: 0, priority: 1, jobs: [job()] },
},
-};
+});
const quota = (family, resetsAt, percentRemaining = 50, extras = {}) => ({
family, supported: true, limits: [{ key: 'week', scope: 'week', label: 'Weekly', resetsAt, percentRemaining }], ...extras,
});
@@ -46,105 +48,66 @@ describe('selectBurnCandidates', () => {
now: NOW, dispatches: { [selected.dispatchKey]: 2 },
})).toEqual([]);
});
-});
-describe('detectQuotaBurn', () => {
- it('parks an empty configuration without reading provider usage', async () => {
- const getQuotas = vi.fn();
- await expect(detectQuotaBurn({ taskTypeOverrides: {} }, { getQuotas, now: NOW }))
- .resolves.toMatchObject({ actionable: false, reason: 'no-enabled-families' });
- expect(getQuotas).not.toHaveBeenCalled();
+ it('skips an enabled family whose plan has no enabled job', () => {
+ // An enabled family with nothing to run is a half-finished setup, not a burn
+ // plan — selecting it would surface as "chosen, then skipped" every cycle.
+ const empty = normalizeQuotaBurnConfig({ families: { grok: { enabled: true, jobs: [] } } });
+ expect(selectBurnCandidates([quota('grok', '2026-07-26T18:00:00.000Z')], empty, { now: NOW })).toEqual([]);
+ const disabledJob = normalizeQuotaBurnConfig({
+ families: { grok: { enabled: true, jobs: [{ ...job(), enabled: false }] } },
+ });
+ expect(selectBurnCandidates([quota('grok', '2026-07-26T18:00:00.000Z')], disabledJob, { now: NOW })).toEqual([]);
});
- it('reports a transient result when every configured quota probe failed', async () => {
- await expect(detectQuotaBurn({ taskTypeOverrides: { 'quota-burn': { taskMetadata: config } } }, {
- getQuotas: async () => [quota('grok', null, 0, { error: 'signed out' })], now: NOW,
- })).resolves.toMatchObject({ actionable: false, transient: true });
- });
-});
-
-describe('quota-burn metadata validation', () => {
- it('keeps valid family configuration and rejects unknown families or unsafe reserves', () => {
- expect(sanitizeTaskMetadata({ families: { grok: { enabled: true, reservePercent: 20 } } }))
- .toMatchObject({ families: { grok: { enabled: true, reservePercent: 20 } } });
- expect(sanitizeTaskMetadata({ families: { unknown: { enabled: true } } })).toBeNull();
- expect(sanitizeTaskMetadata({ families: { grok: { reservePercent: 101 } } })).toBeNull();
+ it('reports how much of the window the family is willing to spend', () => {
+ expect(burnBudgetRemaining({ percentRemaining: 50 }, { reservePercent: 20 })).toBe(30);
+ expect(burnBudgetRemaining({ percentRemaining: 10 }, { reservePercent: 20 })).toBe(0);
});
});
/**
- * The window cap is only honest if a burn that has been QUEUED but whose agent
- * has not finalized yet still holds its slot. The ledger write moved post-agent
- * (#3179), so the raw ledger no longer covers that gap on its own.
+ * The page renders `explainFamilySkip`'s answer verbatim, so it has to mirror
+ * `selectBurnCandidates`'s gates exactly — a card that says "ready" while the
+ * runner skips (or vice versa) is worse than no explanation at all.
*/
-describe('getEffectiveQuotaBurnDispatches', () => {
- const loadStore = async (tasks, { fail = false } = {}) => {
- vi.resetModules();
- vi.doMock('./cosTaskStore.js', () => ({
- getCosTasks: fail ? async () => { throw new Error('unreadable'); } : async () => ({ tasks }),
- }));
- vi.doMock('../lib/fileUtils.js', async (importActual) => ({
- ...(await importActual()),
- readJSONFile: async () => ({ 'grok:1': 1 }),
- }));
- return import('./quotaBurn.js');
- };
-
- const burnTask = (status, key) => ({ id: `sys-${status}`, status, metadata: { quotaBurnDispatchKey: key } });
-
- afterEach(() => { vi.doUnmock('./cosTaskStore.js'); vi.doUnmock('../lib/fileUtils.js'); vi.resetModules(); });
-
- it('adds pending and in_progress burns on top of the persisted ledger', async () => {
- const { getEffectiveQuotaBurnDispatches } = await loadStore([
- burnTask('pending', 'grok:1'),
- burnTask('in_progress', 'codex:2'),
- ]);
- // grok:1 = 1 persisted + 1 queued; codex:2 = 0 persisted + 1 running.
- await expect(getEffectiveQuotaBurnDispatches()).resolves.toEqual({ 'grok:1': 2, 'codex:2': 1 });
- });
+describe('explainFamilySkip', () => {
+ const family = { enabled: true, resetWithinHours: 24, reservePercent: 20, maxDispatchesPerWindow: 2, jobs: [job()] };
- it('ignores terminal tasks and tasks carrying no dispatch key', async () => {
- const { getEffectiveQuotaBurnDispatches } = await loadStore([
- burnTask('completed', 'grok:1'),
- burnTask('blocked', 'grok:1'),
- { id: 'sys-other', status: 'pending', metadata: { analysisType: 'performance' } },
- { id: 'sys-empty', status: 'pending', metadata: { quotaBurnDispatchKey: '' } },
- ]);
- // A completed burn already wrote its ledger entry — counting it would
- // double-charge the window; a blocked one never dispatched.
- await expect(getEffectiveQuotaBurnDispatches()).resolves.toEqual({ 'grok:1': 1 });
+ it('returns null exactly when the family is a candidate', () => {
+ const quotas = [quota('grok', '2026-07-26T18:00:00.000Z')];
+ expect(explainFamilySkip('grok', family, quotas, { now: NOW })).toBeNull();
+ expect(selectBurnCandidates(quotas, { families: { grok: family } }, { now: NOW })).toHaveLength(1);
});
- it('degrades to the ledger alone when the task file cannot be read', async () => {
- const { getEffectiveQuotaBurnDispatches } = await loadStore([], { fail: true });
- await expect(getEffectiveQuotaBurnDispatches()).resolves.toEqual({ 'grok:1': 1 });
- });
-
- it('excludes ignoreTaskId so a completing burn is not counted twice', async () => {
- // The drain-on-completion refill runs between the output hook's ledger write
- // and the completion flow's updateTask, so the finished burn is BOTH in the
- // ledger and still `in_progress`. Counting both would consume two slots for
- // one run — a family capped at 2 would stop after one and miss its window.
- const tasks = [{ id: 'sys-finishing', status: 'in_progress', metadata: { quotaBurnDispatchKey: 'grok:1' } }];
- const { getEffectiveQuotaBurnDispatches } = await loadStore(tasks);
-
- await expect(getEffectiveQuotaBurnDispatches()).resolves.toEqual({ 'grok:1': 2 });
- await expect(getEffectiveQuotaBurnDispatches({ ignoreTaskId: 'sys-finishing' })).resolves.toEqual({ 'grok:1': 1 });
+ it('names the specific gate that closed', () => {
+ expect(explainFamilySkip('grok', { ...family, enabled: false }, [], { now: NOW })).toBe('disabled');
+ expect(explainFamilySkip('grok', { ...family, jobs: [] }, [], { now: NOW })).toBe('no enabled jobs configured');
+ expect(explainFamilySkip('grok', family, [], { now: NOW })).toBe('no enabled provider in this family');
+ expect(explainFamilySkip('grok', family, [quota('grok', null)], { now: NOW })).toBe('no window states a reset time');
+ expect(explainFamilySkip('grok', family, [quota('grok', '2026-07-28T12:00:00.000Z')], { now: NOW }))
+ .toMatch(/outside the 24h window/);
+ expect(explainFamilySkip('grok', family, [quota('grok', '2026-07-26T18:00:00.000Z', 20)], { now: NOW }))
+ .toMatch(/20% left is at or below the 20% reserve/);
+ const selected = selectBurnCandidates([quota('grok', '2026-07-26T18:00:00.000Z')], { families: { grok: family } }, { now: NOW })[0];
+ expect(explainFamilySkip('grok', family, [quota('grok', '2026-07-26T18:00:00.000Z')], {
+ now: NOW, dispatches: { [selected.dispatchKey]: 2 },
+ })).toBe('dispatch cap reached (2/2)');
});
});
/**
- * Two quota-burn agents (one per app) can finalize concurrently, and each
- * finalization records a dispatch. The ledger update is a read-modify-write, so
- * without serialization both would read the same count and write the same
- * increment — losing a burn and letting the window overspend its cap.
+ * The scheduler tick and an on-demand "Run now" can both land a dispatch at
+ * once. The ledger update is a read-modify-write, so without serialization both
+ * would read the same count and write the same increment — losing a burn and
+ * letting the window overspend its cap.
*/
-describe('recordQuotaBurnDispatch serialization', () => {
+describe('recordQuotaBurnDispatch', () => {
afterEach(() => { vi.doUnmock('../lib/fileUtils.js'); vi.resetModules(); });
- it('does not lose an increment when two completions race', async () => {
+ const withLedger = async (initial = {}) => {
vi.resetModules();
- let stored = {};
+ let stored = { ...initial };
vi.doMock('../lib/fileUtils.js', async (importActual) => ({
...(await importActual()),
readJSONFile: async () => ({ ...stored }),
@@ -155,35 +118,29 @@ describe('recordQuotaBurnDispatch serialization', () => {
// and the test would pass even unserialized.)
atomicWrite: async (_file, data) => { await new Promise((r) => setTimeout(r, 5)); stored = { ...data }; },
}));
- const { recordQuotaBurnDispatch, getQuotaBurnDispatches } = await import('./quotaBurn.js');
+ return import('./quotaBurn.js');
+ };
+ it('does not lose an increment when two dispatches race', async () => {
+ const { recordQuotaBurnDispatch, getQuotaBurnDispatches } = await withLedger();
+ // Live window keys, not `grok:1` — the retention prune reads the epoch out
+ // of the key, and a 1970 epoch would be dropped by the very write under test.
+ const grok = `grok:${Date.now() + 3_600_000}`;
+ const codex = `codex:${Date.now() + 7_200_000}`;
await Promise.all([
- recordQuotaBurnDispatch('grok:1'),
- recordQuotaBurnDispatch('grok:1'),
- recordQuotaBurnDispatch('codex:2'),
+ recordQuotaBurnDispatch(grok),
+ recordQuotaBurnDispatch(grok),
+ recordQuotaBurnDispatch(codex),
]);
-
- await expect(getQuotaBurnDispatches()).resolves.toEqual({ 'grok:1': 2, 'codex:2': 1 });
+ await expect(getQuotaBurnDispatches()).resolves.toEqual({ [grok]: 2, [codex]: 1 });
});
- it('deduplicates an agent replay in the same atomic ledger write as the increment', async () => {
- vi.resetModules();
- let stored = {};
- vi.doMock('../lib/fileUtils.js', async (importActual) => ({
- ...(await importActual()),
- readJSONFile: async () => ({ ...stored }),
- atomicWrite: async (_file, data) => { stored = structuredClone(data); },
- }));
- const { recordQuotaBurnDispatch, getQuotaBurnDispatches } = await import('./quotaBurn.js');
-
- await recordQuotaBurnDispatch('grok:1', { agentId: 'agent-1' });
- await recordQuotaBurnDispatch('grok:1', { agentId: 'agent-1' });
- await recordQuotaBurnDispatch('grok:1', { agentId: 'agent-2' });
-
- await expect(getQuotaBurnDispatches()).resolves.toEqual({ 'grok:1': 2 });
- expect(stored.__agentDispatches).toEqual({
- 'agent-1': 'grok:1',
- 'agent-2': 'grok:1',
- });
+ it('prunes windows that reset over a month ago', async () => {
+ // A key is `<family>:<resetEpochMs>`; a passed window can never be selected
+ // again, so its count is dead weight that would grow the file forever.
+ const stale = NOW - 40 * 24 * 60 * 60 * 1000;
+ const { recordQuotaBurnDispatch } = await withLedger({ [`grok:${stale}`]: 3, 'grok:not-a-number': 1 });
+ const next = await recordQuotaBurnDispatch(`grok:${NOW}`, { now: NOW });
+ expect(next).toEqual({ 'grok:not-a-number': 1, [`grok:${NOW}`]: 1 });
});
});
diff --git a/server/services/quotaBurnJobs/agentPrompt.js b/server/services/quotaBurnJobs/agentPrompt.js
new file mode 100644
index 0000000000..194397a248
--- /dev/null
+++ b/server/services/quotaBurnJobs/agentPrompt.js
@@ -0,0 +1,102 @@
+/**
+ * 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 { getAllProviders } from '../providers.js';
+
+/**
+ * An agent-capable provider in the burning family. An explicit `providerId`
+ * (job first, then family) wins; otherwise match the family id against the
+ * enabled CLI/TUI providers. API-type providers are excluded on purpose — this
+ * job exists to spend a SUBSCRIPTION window, and an API provider bills per
+ * token instead.
+ */
+export function providerForFamily(providers, { familyId, providerId }) {
+ const available = (providers || []).filter((provider) =>
+ provider?.enabled && (provider.type === 'cli' || provider.type === 'tui'));
+ if (providerId) return available.find((provider) => provider.id === providerId) || null;
+ const needle = String(familyId || '').toLowerCase();
+ return available.find((provider) => String(provider.id || '').toLowerCase().includes(needle)) || null;
+}
+
+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` };
+ const result = await getAllProviders();
+ const provider = providerForFamily(
+ Array.isArray(result) ? result : result?.providers,
+ { familyId: family?.id, providerId: job?.providerId || family?.providerId || null },
+ );
+ if (!provider) return { error: `no enabled CLI/TUI provider in the ${family?.id} 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 }
+ : { count: 1, detail: `ready to queue an agent in ${resolved.app.name}` };
+}
+
+/** The burn context the agent sees above the user's own prompt. */
+export function renderBurnPrompt({ family, candidate, prompt }) {
+ const hours = Math.max(0, Math.ceil(candidate?.hoursUntilReset ?? 0));
+ return [
+ `# ${family.id} quota-burn task`,
+ '',
+ `This ${family.id} quota window resets in about ${hours} hour${hours === 1 ? '' : 's'}.`,
+ `Window: ${candidate?.limit?.label || candidate?.limit?.scope || 'provider window'}; remaining: ${candidate?.limit?.percentRemaining}%; reserve: ${family.reservePercent}%.`,
+ `Dispatch cap: ${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 } = {}) {
+ const resolved = 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';
+ const task = await addTask({
+ description: `[Quota burn: ${family.id}] ${label} for ${app.name}`,
+ app: app.id,
+ context: renderBurnPrompt({ family, candidate, prompt }),
+ provider: provider.id,
+ model: job?.model || undefined,
+ useWorktree: params?.useWorktree !== false,
+ openPR: params?.openPR !== false,
+ simplify: params?.simplify !== false,
+ reviewLoop: false,
+ }, '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 },
+ };
+}
diff --git a/server/services/quotaBurnJobs/agentPrompt.test.js b/server/services/quotaBurnJobs/agentPrompt.test.js
new file mode 100644
index 0000000000..2899fe5c21
--- /dev/null
+++ b/server/services/quotaBurnJobs/agentPrompt.test.js
@@ -0,0 +1,87 @@
+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, providerForFamily, renderBurnPrompt, run } = await import('./agentPrompt.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('providerForFamily', () => {
+ it('matches an enabled CLI/TUI provider by family name', () => {
+ expect(providerForFamily(state.providers, { familyId: 'grok' })?.id).toBe('grok-cli');
+ });
+
+ it('honors an explicit pin and ignores API-type providers', () => {
+ // The job exists to spend a SUBSCRIPTION window; an API provider bills per
+ // token instead, so burning through it would cost real money.
+ expect(providerForFamily(state.providers, { familyId: 'grok', providerId: 'claude-code' })?.id).toBe('claude-code');
+ expect(providerForFamily([{ id: 'grok-api', type: 'api', enabled: true }], { familyId: 'grok' })).toBeNull();
+ expect(providerForFamily([{ id: 'grok-cli', type: 'cli', enabled: false }], { familyId: 'grok' })).toBeNull();
+ });
+});
+
+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', async () => {
+ const result = await run({ params: { appId: 'app-1', prompt: 'Do the thing' }, job: { id: 'j1', label: 'Nightly', model: 'grok-4' }, family, candidate });
+ expect(result.dispatched).toBe(true);
+ expect(state.added[0].type).toBe('internal');
+ expect(state.added[0].task).toMatchObject({
+ app: 'app-1', provider: 'grok-cli', model: 'grok-4', useWorktree: true, openPR: true, simplify: true, reviewLoop: false,
+ });
+ expect(state.added[0].task.context).toContain('Do the thing');
+ });
+
+ 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 });
+ });
+});
+
+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);
+ });
+});
diff --git a/server/services/quotaBurnJobs/index.js b/server/services/quotaBurnJobs/index.js
new file mode 100644
index 0000000000..d1dc358d63
--- /dev/null
+++ b/server/services/quotaBurnJobs/index.js
@@ -0,0 +1,63 @@
+/**
+ * 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 }
+ * run({ params, job, family, candidate }) → { dispatched, summary?, reason?, detail? }
+ *
+ * `countPending` must be CHEAP and 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. `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.
+ *
+ * Adding a 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
+ * here, 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';
+
+const JOB_MODULES = {
+ [QUOTA_BURN_JOB_TYPE.AGENT_PROMPT]: () => import('./agentPrompt.js'),
+ [QUOTA_BURN_JOB_TYPE.UNIVERSE_BIBLE_IMAGES]: () => import('./universeBibleImages.js'),
+};
+
+export const isKnownBurnJobType = (jobType) =>
+ typeof jobType === 'string' && Object.hasOwn(JOB_MODULES, jobType);
+
+export async function loadBurnJob(jobType) {
+ return isKnownBurnJobType(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 loadBurnJob(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 }) {
+ const mod = await loadBurnJob(job?.jobType);
+ if (!mod) return { dispatched: false, reason: `unknown job type: ${job?.jobType}` };
+ return mod.run({ params: job.params, job, family, candidate })
+ .catch((err) => ({ dispatched: false, reason: `job failed: ${err.message}` }));
+}
diff --git a/server/services/quotaBurnJobs/universeBibleImages.js b/server/services/quotaBurnJobs/universeBibleImages.js
new file mode 100644
index 0000000000..3adc6e84c5
--- /dev/null
+++ b/server/services/quotaBurnJobs/universeBibleImages.js
@@ -0,0 +1,164 @@
+/**
+ * Burn job — render images for universe bible entries that have none.
+ *
+ * PROGRAMMATIC: no agent is spawned. PortOS compiles the missing entries' render
+ * prompts itself and enqueues them on the media job queue, exactly as the
+ * Universe Builder's "Render" button does. The quota it burns is the CLOUD IMAGE
+ * backend's (codex `image_gen`, grok `image_gen`, agy `generate_image`), which is
+ * why the job's render backend defaults to the burning family's own mode.
+ *
+ * "Has no image" means the entry's `imageRefs[]` is empty — the same array the
+ * collection hook appends a finished render's filename to. An entry that has
+ * ever rendered successfully is skipped forever after, so repeated runs walk
+ * down the backlog instead of re-rendering the same entries.
+ */
+
+import { getUniverse, listUniverses } from '../universeBuilder.js';
+import { getWorldCategoryKeys } from '../universeBuilder/sanitize.js';
+import { renderUniverseJobs } from '../universeBuilderRender.js';
+import { CLOUD_IMAGE_GEN_MODES } from '../imageGen/modes.js';
+
+const CANON_TRUNKS = ['characters', 'places', 'objects'];
+const DEFAULT_MAX_ENTRIES = 10;
+
+const hasNoImage = (entry) => !Array.isArray(entry?.imageRefs) || entry.imageRefs.length === 0;
+
+// The label `compilePrompts` matches a selection against, per entry kind. Canon
+// places may carry only a slugline, which is the identifier compile.js falls
+// back to — mirror that or those entries become unselectable.
+const canonLabel = (trunk, entry) =>
+ (typeof entry?.name === 'string' && entry.name.trim())
+ ? entry.name
+ : (trunk === 'places' && typeof entry?.slugline === 'string' ? entry.slugline : '');
+
+const wantsScope = (scope, kind) => scope === 'all' || !scope || scope === kind;
+
+/**
+ * Every image-less entry in one universe, as `{ kind, categoryKey, label }`
+ * rows in a stable order (variations → sheets → canon), so a capped run always
+ * chews through the same backlog front-to-back rather than sampling randomly.
+ */
+export function findMissingImageEntries(universe, { scope = 'all' } = {}) {
+ const rows = [];
+ if (wantsScope(scope, 'variations')) {
+ for (const categoryKey of getWorldCategoryKeys(universe?.categories)) {
+ for (const variation of universe?.categories?.[categoryKey]?.variations || []) {
+ if (!hasNoImage(variation) || !variation?.label) continue;
+ rows.push({ kind: 'variation', categoryKey, label: variation.label });
+ }
+ }
+ }
+ if (wantsScope(scope, 'sheets')) {
+ for (const sheet of universe?.compositeSheets || []) {
+ if (!hasNoImage(sheet) || !sheet?.label) continue;
+ rows.push({ kind: 'sheet', label: sheet.label });
+ }
+ }
+ if (wantsScope(scope, 'canon')) {
+ for (const trunk of CANON_TRUNKS) {
+ for (const entry of universe?.[trunk] || []) {
+ const label = canonLabel(trunk, entry);
+ if (!hasNoImage(entry) || !label) continue;
+ rows.push({ kind: 'canon', categoryKey: trunk, label });
+ }
+ }
+ }
+ return rows;
+}
+
+/** Turn capped rows back into the three selection shapes `compilePrompts` reads. */
+export function buildRenderSelection(rows) {
+ const selection = {};
+ const canonSelection = {};
+ const sheetSelection = [];
+ for (const row of rows) {
+ if (row.kind === 'variation') (selection[row.categoryKey] ||= []).push(row.label);
+ else if (row.kind === 'canon') (canonSelection[row.categoryKey] ||= []).push(row.label);
+ else sheetSelection.push(row.label);
+ }
+ return { selection, canonSelection, sheetSelection };
+}
+
+async function loadUniverses(params) {
+ const id = typeof params?.universeId === 'string' ? params.universeId.trim() : '';
+ if (!id || id === 'all') return listUniverses();
+ // A universe deleted since the job was configured must not wedge the family —
+ // report zero pending and let the next job in the plan take the window.
+ return getUniverse(id).then((universe) => [universe]).catch(() => []);
+}
+
+/**
+ * Rows this job would render next, capped to `maxEntries`, plus the total
+ * backlog so the page can show "10 of 143".
+ */
+async function collect(params) {
+ const max = Math.min(50, Math.max(1, Number(params?.maxEntries) || DEFAULT_MAX_ENTRIES));
+ const scope = typeof params?.scope === 'string' ? params.scope : 'all';
+ const universes = await loadUniverses(params);
+ const batches = [];
+ let total = 0;
+ for (const universe of universes) {
+ const rows = findMissingImageEntries(universe, { scope });
+ total += rows.length;
+ if (!rows.length) continue;
+ batches.push({ universe, rows });
+ }
+ // Cap ACROSS universes, taking whole universes in list order until the budget
+ // is spent: one render batch is one `renderUniverseJobs` call against one
+ // universe, so splitting the cap finer would mean several batches per run and
+ // several collections provisioned for a single burn.
+ const picked = [];
+ let budget = max;
+ for (const batch of batches) {
+ if (budget <= 0) break;
+ picked.push({ universe: batch.universe, rows: batch.rows.slice(0, budget) });
+ budget -= Math.min(budget, batch.rows.length);
+ }
+ return { picked, total, max };
+}
+
+export async function countPending({ params } = {}) {
+ const { picked, total } = await collect(params);
+ const universeCount = picked.length;
+ return {
+ count: total,
+ detail: total
+ ? `${total} bible ${total === 1 ? 'entry has' : 'entries have'} no image (${universeCount} universe${universeCount === 1 ? '' : 's'} queued next)`
+ : 'every bible entry already has an image',
+ };
+}
+
+/**
+ * Enqueue the next batch. The render backend resolves as
+ * `params.mode` → the burning family's own image mode (when it has one) →
+ * whatever the universe-bible render-target ladder decides. Pinning to the
+ * family by default is the point of the job: a `codex` burn should spend
+ * CODEX's image quota, not silently fall through to the install default and
+ * burn a different provider's.
+ */
+export async function run({ params, job, family } = {}) {
+ const { picked, total, max } = await collect(params);
+ if (!picked.length) return { dispatched: false, reason: 'no bible entries are missing images' };
+
+ const familyMode = CLOUD_IMAGE_GEN_MODES.includes(family?.id) ? family.id : undefined;
+ const mode = (typeof params?.mode === 'string' && params.mode) || familyMode;
+ const batch = picked[0];
+ const { selection, canonSelection, sheetSelection } = buildRenderSelection(batch.rows);
+
+ const result = await renderUniverseJobs(batch.universe.id, {
+ promptMode: 'all',
+ selection,
+ canonSelection,
+ sheetSelection,
+ batchPerVariation: 1,
+ mode,
+ cloudModel: job?.model || undefined,
+ }, (err) => err);
+
+ console.log(`🔥 Quota-burn rendered ${result.promptCount} bible image(s) for "${batch.universe.name}" via ${result.mode}`);
+ return {
+ dispatched: true,
+ summary: `Queued ${result.promptCount} image render${result.promptCount === 1 ? '' : 's'} for "${batch.universe.name}" via ${result.mode}`,
+ detail: { universeId: batch.universe.id, runId: result.runId, jobIds: result.jobIds, mode: result.mode, backlog: total, cap: max },
+ };
+}
diff --git a/server/services/quotaBurnJobs/universeBibleImages.test.js b/server/services/quotaBurnJobs/universeBibleImages.test.js
new file mode 100644
index 0000000000..ac4f609857
--- /dev/null
+++ b/server/services/quotaBurnJobs/universeBibleImages.test.js
@@ -0,0 +1,57 @@
+import { describe, expect, it } from 'vitest';
+import { buildRenderSelection, findMissingImageEntries } from './universeBibleImages.js';
+
+const universe = {
+ id: 'u1',
+ name: 'Example Universe',
+ categories: {
+ landscapes: {
+ variations: [
+ { id: 'v1', label: 'Salt Flats', imageRefs: [] },
+ { id: 'v2', label: 'Rendered Ridge', imageRefs: ['ridge.png'] },
+ ],
+ },
+ },
+ compositeSheets: [{ id: 's1', label: 'Cast Sheet' }],
+ characters: [
+ { id: 'c1', name: 'Alice', imageRefs: [] },
+ { id: 'c2', name: 'Bob', imageRefs: ['bob.png'] },
+ ],
+ places: [{ id: 'p1', slugline: 'EXT. FOUNDRY — DAY' }],
+ objects: [],
+};
+
+describe('findMissingImageEntries', () => {
+ it('returns only entries whose imageRefs are empty', () => {
+ const rows = findMissingImageEntries(universe);
+ expect(rows.map((row) => row.label)).toEqual(['Salt Flats', 'Cast Sheet', 'Alice', 'EXT. FOUNDRY — DAY']);
+ });
+
+ it('falls back to a place\'s slugline, matching what compilePrompts selects on', () => {
+ // A canon place may carry ONLY a slugline. Keying on `name` alone would make
+ // those entries permanently unselectable — they would show as pending
+ // forever and never render.
+ const rows = findMissingImageEntries(universe, { scope: 'canon' });
+ expect(rows.some((row) => row.label === 'EXT. FOUNDRY — DAY')).toBe(true);
+ });
+
+ it('honors a narrowed scope', () => {
+ expect(findMissingImageEntries(universe, { scope: 'variations' }).map((r) => r.label)).toEqual(['Salt Flats']);
+ expect(findMissingImageEntries(universe, { scope: 'sheets' }).map((r) => r.label)).toEqual(['Cast Sheet']);
+ });
+
+ it('tolerates an empty or malformed universe', () => {
+ expect(findMissingImageEntries(null)).toEqual([]);
+ expect(findMissingImageEntries({})).toEqual([]);
+ });
+});
+
+describe('buildRenderSelection', () => {
+ it('splits rows back into the three shapes compilePrompts reads', () => {
+ expect(buildRenderSelection(findMissingImageEntries(universe))).toEqual({
+ selection: { landscapes: ['Salt Flats'] },
+ canonSelection: { characters: ['Alice'], places: ['EXT. FOUNDRY — DAY'] },
+ sheetSelection: ['Cast Sheet'],
+ });
+ });
+});
diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.js
new file mode 100644
index 0000000000..6b38199743
--- /dev/null
+++ b/server/services/quotaBurnRunner.js
@@ -0,0 +1,242 @@
+/**
+ * Quota-burn runner — the single install-level loop.
+ *
+ * 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
+ * family's ordered plan that reports pending work. At most ONE dispatch per
+ * cycle, so a cycle can never blow through several windows' budgets at once.
+ *
+ * AI-policy posture (CLAUDE.md): this is a sanctioned scheduled automation —
+ * disabled by default, armed only by an explicit opt-in on the Quota Burn page,
+ * where the family, provider, model, and work are all named before anything
+ * runs. Boot ARMS the interval; it never dispatches. With `enabled: false` the
+ * tick returns before reading quota, so a fresh install is silent.
+ *
+ * Everything fails CLOSED and nothing here throws into the timer: a probe that
+ * errors, a job that declines, or an unreadable config all end the cycle with a
+ * logged reason instead of charging a dispatch or crashing the process.
+ */
+
+import { getProviderQuotas } from './providerUsage.js';
+import { getQuotaBurnDispatches, explainFamilySkip, recordQuotaBurnDispatch, selectBurnCandidates } from './quotaBurn.js';
+import { getQuotaBurnConfig, getQuotaBurnRuns, recordQuotaBurnRun } from './quotaBurnStore.js';
+import { countJobPending, runBurnJob } from './quotaBurnJobs/index.js';
+import { normalizeQuotaBurnFamily } from '../lib/quotaBurnConfig.js';
+
+const TICK_MS = 60_000;
+
+let tickTimer = null;
+let running = false;
+let lastRunAt = null;
+
+const enabledJobs = (family, jobId = null) =>
+ (family.jobs || []).filter((job) => job?.enabled !== false && (!jobId || job.id === jobId));
+
+/**
+ * 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.
+ */
+async function dispatchFromCandidate(candidate, { jobId = null } = {}) {
+ const attempts = [];
+ for (const job of enabledJobs(candidate.family, jobId)) {
+ const pending = await countJobPending({ job, family: candidate.family });
+ if (!(pending.count > 0)) {
+ attempts.push({ jobId: job.id, jobType: job.jobType, skipped: pending.detail || 'no pending work' });
+ continue;
+ }
+ const result = await runBurnJob({ job, family: candidate.family, candidate });
+ if (!result.dispatched) {
+ attempts.push({ jobId: job.id, jobType: job.jobType, skipped: result.reason || 'declined' });
+ continue;
+ }
+ return { dispatched: true, job, result, attempts };
+ }
+ return { dispatched: false, attempts };
+}
+
+/**
+ * One evaluation. `trigger` is recorded in the run log so the page can tell a
+ * scheduled tick from a "Run now". A manual trigger ignores the master
+ * `enabled` switch (the user just clicked the button) but respects every quota
+ * gate — the reset window, the reserve, and the per-window dispatch cap.
+ */
+export async function runQuotaBurnCycle(options = {}) {
+ if (running) return { skipped: 'already-running' };
+ running = true;
+ // try/finally, not try/catch: this runs from a timer and from a route, and a
+ // throw anywhere below (an ENOSPC on the ledger write, say) would otherwise
+ // leave `running` stuck true and wedge the loop for the life of the process.
+ // The error itself is deliberately NOT swallowed — the timer logs it and the
+ // route surfaces it.
+ try {
+ return await evaluate(options);
+ } finally {
+ running = false;
+ }
+}
+
+async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null, force = false }) {
+ const finish = async (entry) => {
+ lastRunAt = Date.now();
+ await recordQuotaBurnRun({ trigger, ...entry });
+ return entry;
+ };
+
+ const config = await getQuotaBurnConfig().catch((err) => {
+ console.error(`❌ Quota-burn could not read its config: ${err.message}`);
+ return 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' };
+
+ const quotas = await getProviderQuotas({ refresh: true }).catch((err) => {
+ console.error(`❌ Quota-burn could not read provider quota: ${err.message}`);
+ return null;
+ });
+ if (!quotas) return finish({ dispatched: false, reason: 'provider quota read failed' });
+
+ const dispatches = await getQuotaBurnDispatches();
+ let candidates = selectBurnCandidates(quotas, config, { dispatches })
+ .filter((candidate) => !familyId || candidate.family.id === familyId);
+
+ // `force` is the page's per-job "Run now": the user named a family and a job
+ // and clicked, which is a direct instruction to spend that quota now — so the
+ // reset-window / reserve / cap gates (which exist to bound UNATTENDED burns)
+ // don't apply. It carries NO dispatchKey, so the run is also not charged
+ // against the window's automatic budget.
+ if (force && familyId && !candidates.length) {
+ const family = { id: familyId, ...normalizeQuotaBurnFamily(config.families[familyId]) };
+ candidates = [{ family, card: quotas.find((entry) => entry.family === familyId) || null, limit: null, hoursUntilReset: 0, dispatchKey: null }];
+ }
+
+ if (!candidates.length) {
+ const reasons = Object.entries(config.families)
+ .filter(([, family]) => family.enabled)
+ .map(([id, family]) => `${id}: ${explainFamilySkip(id, family, quotas, { dispatches }) || 'ready'}`);
+ return finish({
+ dispatched: false,
+ reason: reasons.length ? `no burnable window — ${reasons.join('; ')}` : 'no families enabled',
+ });
+ }
+
+ for (const candidate of candidates) {
+ const outcome = await dispatchFromCandidate(candidate, { jobId });
+ if (!outcome.dispatched) continue;
+ // Charge the window only once work actually started. `runBurnJob` reports a
+ // decline rather than throwing, and a declined job never reaches here — so
+ // the cap bounds real burns, not attempts. A forced run has no window key
+ // and is deliberately not charged (see the `force` block above).
+ if (candidate.dispatchKey) await recordQuotaBurnDispatch(candidate.dispatchKey);
+ return finish({
+ dispatched: true,
+ familyId: candidate.family.id,
+ jobId: outcome.job.id,
+ jobType: outcome.job.jobType,
+ dispatchKey: candidate.dispatchKey,
+ hoursUntilReset: Math.round(candidate.hoursUntilReset * 10) / 10,
+ percentRemaining: candidate.limit?.percentRemaining ?? null,
+ summary: outcome.result.summary || 'dispatched',
+ detail: outcome.result.detail || null,
+ });
+ }
+
+ return finish({
+ dispatched: false,
+ familyId: candidates[0].family.id,
+ reason: `no job in the ${candidates[0].family.id} plan had pending work`,
+ });
+}
+
+/**
+ * Per-family view for the config page: the live quota card, whether the family
+ * would burn on the next tick (and if not, exactly why), and each job's pending
+ * count. Reads quota from cache by default — the page's explicit Refresh passes
+ * `refresh: true` — so opening the page doesn't spawn a TUI scrape per family.
+ */
+export async function getQuotaBurnStatus({ refresh = false } = {}) {
+ const config = await getQuotaBurnConfig();
+ const quotas = await getProviderQuotas({ refresh }).catch((err) => {
+ console.error(`❌ Quota-burn status could not read provider quota: ${err.message}`);
+ return [];
+ });
+ const dispatches = await getQuotaBurnDispatches();
+ const candidates = selectBurnCandidates(quotas, config, { dispatches });
+ const byFamily = new Map(candidates.map((candidate) => [candidate.family.id, candidate]));
+
+ const families = await Promise.all(Object.entries(config.families).map(async ([id, raw]) => {
+ const family = { id, ...normalizeQuotaBurnFamily(raw) };
+ const card = quotas.find((entry) => entry.family === id) || null;
+ const candidate = byFamily.get(id) || null;
+ // Probe pending work only for families the user actually enabled — a probe
+ // is cheap but not free (the universe job reads every bible), and a disabled
+ // family's counts are never acted on.
+ const jobs = family.enabled
+ ? await Promise.all(family.jobs.map(async (job) => ({ ...job, pending: await countJobPending({ job, family }) })))
+ : family.jobs.map((job) => ({ ...job, pending: null }));
+ return {
+ id,
+ label: card?.label || id,
+ supported: card ? card.supported !== false : null,
+ error: card?.error || null,
+ percentRemaining: candidate?.limit?.percentRemaining ?? null,
+ limitLabel: candidate?.limit?.label || candidate?.limit?.scope || null,
+ hoursUntilReset: candidate ? Math.round(candidate.hoursUntilReset * 10) / 10 : null,
+ dispatchesUsed: candidate?.dispatchesUsed ?? null,
+ willBurn: Boolean(candidate),
+ skipReason: candidate ? null : explainFamilySkip(id, raw, quotas, { dispatches }),
+ jobs,
+ };
+ }));
+
+ return {
+ enabled: config.enabled,
+ checkIntervalMinutes: config.checkIntervalMinutes,
+ running,
+ lastRunAt: lastRunAt ? new Date(lastRunAt).toISOString() : null,
+ families,
+ runs: await getQuotaBurnRuns(),
+ };
+}
+
+async function tick() {
+ const config = await getQuotaBurnConfig().catch(() => null);
+ if (!config?.enabled) return;
+ const dueAt = (lastRunAt || 0) + config.checkIntervalMinutes * 60_000;
+ if (Date.now() < dueAt) return;
+ await runQuotaBurnCycle({ trigger: 'scheduled' });
+}
+
+/**
+ * Arm the loop. Called once at boot. The interval itself is unconditional and
+ * cheap (a config read per minute); the SPEND is gated inside `tick`, so
+ * toggling the feature on the page takes effect without a restart.
+ */
+export function startQuotaBurnScheduler() {
+ if (tickTimer) return;
+ // Every timer callback runs outside the request lifecycle — an uncaught throw
+ // here would take down the process, so the whole tick is caught and logged.
+ tickTimer = setInterval(() => {
+ // `running` is already released by runQuotaBurnCycle's finally — this only
+ // has to keep the throw from reaching the timer and killing the process.
+ tick().catch((err) => console.error(`❌ Quota-burn tick failed: ${err.message}`));
+ }, TICK_MS);
+ tickTimer.unref?.();
+ console.log('🔥 Quota-burn loop armed (off unless enabled in Quota Burn settings)');
+}
+
+export function stopQuotaBurnScheduler() {
+ if (tickTimer) clearInterval(tickTimer);
+ tickTimer = null;
+}
+
+/** Test seam — clears the in-process cycle state between cases. */
+export function __resetQuotaBurnRunner() {
+ stopQuotaBurnScheduler();
+ running = false;
+ lastRunAt = null;
+}
diff --git a/server/services/quotaBurnRunner.test.js b/server/services/quotaBurnRunner.test.js
new file mode 100644
index 0000000000..2acbec819a
--- /dev/null
+++ b/server/services/quotaBurnRunner.test.js
@@ -0,0 +1,175 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const now = Date.now();
+const resetsAt = new Date(now + 2 * 3600_000).toISOString();
+
+const state = {
+ config: null,
+ quotas: [],
+ runs: [],
+ dispatches: {},
+ recorded: [],
+ pending: {},
+ ran: [],
+};
+
+vi.mock('./providerUsage.js', () => ({
+ getProviderQuotas: vi.fn(async () => state.quotas),
+}));
+
+vi.mock('./quotaBurnStore.js', () => ({
+ getQuotaBurnConfig: vi.fn(async () => state.config),
+ getQuotaBurnRuns: vi.fn(async () => state.runs),
+ recordQuotaBurnRun: vi.fn(async (entry) => { state.runs.unshift(entry); }),
+}));
+
+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 }) => {
+ state.ran.push({ jobId: job.id, familyId: family.id, hasWindow: Boolean(candidate.dispatchKey) });
+ return state.jobResult ?? { dispatched: true, summary: `ran ${job.id}` };
+ }),
+}));
+
+// Only the two ledger functions are stubbed — `selectBurnCandidates` and
+// `explainFamilySkip` stay REAL so this suite exercises the actual gates rather
+// than a second copy of them. Stubbing the ledger keeps the suite off the
+// install's real `data/cos/` files.
+vi.mock('./quotaBurn.js', async (importActual) => ({
+ ...(await importActual()),
+ getQuotaBurnDispatches: vi.fn(async () => state.dispatches),
+ recordQuotaBurnDispatch: vi.fn(async (key) => { state.recorded.push(key); }),
+}));
+
+const { normalizeQuotaBurnConfig } = await import('../lib/quotaBurnConfig.js');
+const { getQuotaBurnStatus, runQuotaBurnCycle, __resetQuotaBurnRunner } = await import('./quotaBurnRunner.js');
+
+const card = (family, percentRemaining = 50) => ({
+ family, label: family, supported: true,
+ limits: [{ key: 'week', scope: 'week', label: 'Weekly', resetsAt, percentRemaining }],
+});
+
+const plan = (overrides = {}) => normalizeQuotaBurnConfig({
+ enabled: true,
+ families: {
+ grok: {
+ enabled: true,
+ resetWithinHours: 24,
+ jobs: [
+ { id: 'first', enabled: true, jobType: 'universe-bible-images', params: {} },
+ { id: 'second', enabled: true, jobType: 'agent-prompt', params: {} },
+ ],
+ },
+ },
+ ...overrides,
+});
+
+beforeEach(() => {
+ state.config = plan();
+ state.quotas = [card('grok')];
+ state.runs = [];
+ state.pending = {};
+ state.ran = [];
+ state.dispatches = {};
+ state.recorded = [];
+ state.jobResult = undefined;
+ __resetQuotaBurnRunner();
+});
+
+afterEach(() => { vi.clearAllMocks(); });
+
+describe('runQuotaBurnCycle', () => {
+ it('stays silent when the master switch is off and the trigger is scheduled', async () => {
+ state.config = plan({ enabled: false });
+ await expect(runQuotaBurnCycle()).resolves.toEqual({ skipped: 'disabled' });
+ expect(state.runs).toHaveLength(0);
+ expect(state.ran).toHaveLength(0);
+ });
+
+ 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' } };
+ const result = await runQuotaBurnCycle();
+ expect(result.dispatched).toBe(true);
+ expect(state.ran).toEqual([{ jobId: 'second', familyId: 'grok', hasWindow: true }]);
+ expect(state.recorded).toEqual([result.dispatchKey]);
+ });
+
+ it('prefers an earlier job when both have work', async () => {
+ state.pending = { first: { count: 3 }, second: { count: 9 } };
+ await runQuotaBurnCycle();
+ expect(state.ran.map((entry) => entry.jobId)).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' } };
+ const result = await runQuotaBurnCycle();
+ expect(result.dispatched).toBe(false);
+ expect(result.reason).toMatch(/no job in the grok plan had pending work/);
+ expect(state.runs[0]).toMatchObject({ trigger: 'scheduled', dispatched: false });
+ });
+
+ 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' };
+ const result = await runQuotaBurnCycle();
+ expect(result.dispatched).toBe(false);
+ expect(state.recorded).toEqual([]);
+ });
+
+ 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' }] } } });
+ 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 } };
+ const result = await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', jobId: 'second', force: true });
+ expect(result.dispatched).toBe(true);
+ expect(state.ran).toEqual([{ jobId: 'second', familyId: 'grok', hasWindow: false }]);
+ // A forced run carries no window key, so it never eats the automatic budget.
+ expect(state.recorded).toEqual([]);
+ });
+
+ it('releases the re-entrancy guard even when a cycle throws', async () => {
+ // Without the finally, an ENOSPC on the ledger write (or any other throw)
+ // would leave `running` stuck true and wedge the loop for the life of the
+ // process — every later tick returning `already-running` forever.
+ const { recordQuotaBurnRun } = await import('./quotaBurnStore.js');
+ recordQuotaBurnRun.mockRejectedValueOnce(new Error('ENOSPC'));
+ await expect(runQuotaBurnCycle()).rejects.toThrow('ENOSPC');
+
+ recordQuotaBurnRun.mockImplementationOnce(async (entry) => { state.runs.unshift(entry); });
+ await expect(runQuotaBurnCycle()).resolves.toMatchObject({ dispatched: false });
+ });
+
+ it('refuses to run two cycles at once', async () => {
+ state.pending = { first: { count: 1 } };
+ const [first, second] = await Promise.all([runQuotaBurnCycle(), runQuotaBurnCycle()]);
+ expect([first.skipped, second.skipped].filter(Boolean)).toEqual(['already-running']);
+ });
+});
+
+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' } };
+ const status = await getQuotaBurnStatus();
+ const grok = status.families.find((family) => family.id === 'grok');
+ expect(grok.willBurn).toBe(true);
+ expect(grok.skipReason).toBeNull();
+ expect(grok.jobs.map((job) => job.pending.count)).toEqual([2, 0]);
+
+ const codex = status.families.find((family) => family.id === 'codex');
+ expect(codex.willBurn).toBe(false);
+ expect(codex.skipReason).toBe('disabled');
+ // A disabled family's jobs are not probed — the counts would never be acted on.
+ expect(codex.jobs.every((job) => job.pending === null)).toBe(true);
+ });
+});
diff --git a/server/services/quotaBurnStore.js b/server/services/quotaBurnStore.js
new file mode 100644
index 0000000000..c333155be8
--- /dev/null
+++ b/server/services/quotaBurnStore.js
@@ -0,0 +1,87 @@
+/**
+ * Quota-burn config + run-log storage (machine-local).
+ *
+ * Two files under `data/cos/`:
+ * - `quota-burn.json` — the install's burn plan (see lib/quotaBurnConfig.js)
+ * - `quota-burn-runs.json` — a capped log of what the runner did, for the page
+ *
+ * Deliberately NOT federated, for the same reason the dispatch ledger isn't:
+ * quota belongs to a particular machine and provider account. Two peers sharing
+ * a burn plan would each think they owned the other's window budget, and the
+ * "which managed app" targets differ per machine anyway.
+ *
+ * Every read normalizes, so a config file written by an older PortOS (or by
+ * hand) loads without a migration step — `normalizeQuotaBurnConfig` fills the
+ * family set and drops what it can't interpret.
+ */
+
+import { join } from 'path';
+import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { normalizeQuotaBurnConfig } from '../lib/quotaBurnConfig.js';
+
+const configFile = () => join(PATHS.cos, 'quota-burn.json');
+const runLogFile = () => join(PATHS.cos, 'quota-burn-runs.json');
+
+/** Keep the run log skimmable and bounded — it is a UI feed, not an audit trail. */
+export const QUOTA_BURN_RUN_LOG_LIMIT = 50;
+
+// One tail per file. The config's read-modify-write races with itself when the
+// page saves twice quickly; the run log's races between the scheduler tick and
+// an on-demand "Run now". Same "serialize two write paths that mutate the same
+// record" case the dispatch ledger documents — not a multi-user defense.
+const configWriteQueue = createFileWriteQueue();
+const runLogWriteQueue = createFileWriteQueue();
+
+export async function getQuotaBurnConfig() {
+ return normalizeQuotaBurnConfig(await readJSONFile(configFile(), null));
+}
+
+/**
+ * Merge `patch` over the stored config and persist the normalized result.
+ * Shallow at the top level and per family, so the page can PUT a single family
+ * (or just `{ enabled }`) without restating the whole plan. A family's `jobs`
+ * array is REPLACED wholesale when present — it is an ordered list, and
+ * element-wise merging would make reordering and deletion inexpressible.
+ */
+export async function saveQuotaBurnConfig(patch) {
+ return configWriteQueue(async () => {
+ const current = normalizeQuotaBurnConfig(await readJSONFile(configFile(), null));
+ const patchFamilies = patch?.families && typeof patch.families === 'object' ? patch.families : {};
+ const merged = {
+ ...current,
+ ...patch,
+ families: Object.fromEntries(
+ Object.entries(current.families).map(([id, family]) => [
+ id,
+ Object.prototype.hasOwnProperty.call(patchFamilies, id)
+ ? { ...family, ...patchFamilies[id] }
+ : family,
+ ]),
+ ),
+ };
+ const next = normalizeQuotaBurnConfig(merged);
+ await atomicWrite(configFile(), next);
+ return next;
+ });
+}
+
+export async function getQuotaBurnRuns() {
+ const loaded = await readJSONFile(runLogFile(), null);
+ return Array.isArray(loaded?.runs) ? loaded.runs : [];
+}
+
+/**
+ * Append one run-log entry (newest first). Records SKIPS as well as dispatches:
+ * "why did nothing burn last night" is the question the page exists to answer,
+ * and a log that only shows successful dispatches cannot answer it.
+ */
+export async function recordQuotaBurnRun(entry) {
+ return runLogWriteQueue(async () => {
+ const loaded = await readJSONFile(runLogFile(), null);
+ const runs = Array.isArray(loaded?.runs) ? loaded.runs : [];
+ const next = [{ at: new Date().toISOString(), ...entry }, ...runs].slice(0, QUOTA_BURN_RUN_LOG_LIMIT);
+ await atomicWrite(runLogFile(), { runs: next });
+ return next;
+ });
+}
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index c2e72d8f08..46d7786a51 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -223,9 +223,11 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [
// buildTaskInput hook renders the prompt. See taskTypeHooks.js +
// autonomousJobs/layeredIntelligenceHooks.js.
'layered-intelligence',
- // An opt-in perpetual task that runs a zero-token quota probe before it
- // ever dispatches an agent. The hook owns its provider-specific prompt.
- 'quota-burn'
+ // NOTE: `quota-burn` used to live here as a per-app perpetual task type. It is
+ // now ONE install-level loop (services/quotaBurnRunner.js) configured on the
+ // Quota Burn page — the burn plan is machine-local, and its jobs name which
+ // managed app (if any) the work targets. Migration 221 moves existing per-app
+ // overrides across; do not re-add it as a scheduled type.
];
// Shared config for code-reviewer-a and code-reviewer-b (two instances for independent provider/model configuration)
@@ -369,8 +371,7 @@ export const DEFAULT_TASK_INTERVALS = {
// agent runs in a worktree that is discarded without a commit/merge/PR
// (discardWorktree), so it can't land code — its `.agent-done` payload is the
// only sanctioned output (consumed by the processTaskOutput hook).
- 'layered-intelligence': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: false, discardWorktree: true } },
- 'quota-burn': { type: INTERVAL_TYPES.PERPETUAL, enabled: false, providerId: null, model: null, prompt: null, recheckCron: '0 */12 * * *', taskMetadata: { useWorktree: true, openPR: true, simplify: true, families: {} } }
+ 'layered-intelligence': { type: INTERVAL_TYPES.DAILY, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { useWorktree: true, openPR: false, discardWorktree: true } }
};
// Agent-options that a task manages internally — UI locks the toggle, and
@@ -1894,8 +1895,7 @@ export const TASK_TYPE_DESCRIPTIONS = {
'reference-watch': 'Watch reference repos and append PLAN.md items for new upstream work',
'ux': 'UX/design audit — files issues, no code changes',
'refresh-local-llm-catalog': "Refresh PortOS's bundled suggested local-model catalog + editorial ranking (PortOS repo only)",
- 'layered-intelligence': "Read this app's goals + telemetry, ask a reasoning model for one improvement, and file one deduplicated tracker issue — no code, no agent",
- 'quota-burn': 'When enabled, spend configured provider subscription quota only near its reset window using that provider family\'s prompt'
+ 'layered-intelligence': "Read this app's goals + telemetry, ask a reasoning model for one improvement, and file one deduplicated tracker issue — no code, no agent"
};
function getTaskTypeDescription(taskType) {
diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.js
index 27ea00b367..5177fc6661 100644
--- a/server/services/taskTypeHooks.js
+++ b/server/services/taskTypeHooks.js
@@ -10,14 +10,14 @@
* issues, …) and returns `{ prompt?, providerId?, model?, hookMetadata?, skip? }`.
* `ignoreTaskId` is set on the drain-on-completion refill and names the task
* that just finished but is still `in_progress` on disk — a hook that counts
- * in-flight work must exclude it (see quotaBurnHooks.js):
+ * in-flight work must exclude it:
* • `prompt` — a fully-rendered prompt that REPLACES the template.
* • `providerId` / `model` — pin the agent's provider/model (per-app choice).
* • `hookMetadata` — a free-form bag merged into the task's persisted
* `metadata`, so a value resolved pre-agent survives to `processTaskOutput`.
* The generator applies it only AFTER every gate that can still skip task
* creation has passed, so a hook can safely defer a side effect until the
- * task really exists (quota-burn's dispatch ledger, #3179) instead of
+ * task really exists (a spend ledger, say — #3179) instead of
* performing it speculatively here. Untyped by design — a passthrough, not
* a schema; keep the keys namespaced to the task type. A key that collides
* with generator-computed metadata is DROPPED with a warning, so the bag
@@ -49,9 +49,8 @@ import { TRACKER_FILING_TASK_TYPES } from '../lib/workTracker.js';
// or both hooks; a missing export means "no hook of that kind for this type".
const HOOK_MODULES = {
'layered-intelligence': () => import('./autonomousJobs/layeredIntelligenceHooks.js'),
- 'quota-burn': () => import('./autonomousJobs/quotaBurnHooks.js'),
};
-const PAYLOAD_OPTIONAL_OUTPUT_HOOKS = new Set(['quota-burn']);
+const PAYLOAD_OPTIONAL_OUTPUT_HOOKS = new Set();
async function loadHookModule(taskType) {
if (!isProgrammaticIoTaskType(taskType)) return null;
diff --git a/server/services/taskTypeHooks.test.js b/server/services/taskTypeHooks.test.js
index 8eff9a5096..59ffc9e018 100644
--- a/server/services/taskTypeHooks.test.js
+++ b/server/services/taskTypeHooks.test.js
@@ -17,7 +17,9 @@ describe('taskTypeHooks registry', () => {
});
it('declares only payload-independent hooks safe for sentinel-less recovery', () => {
- expect(canRunTaskOutputHookWithoutPayload('quota-burn')).toBe(true);
+ // No registered type is payload-independent today (quota-burn was, until it
+ // stopped being a scheduled task type entirely — see quotaBurnRunner.js).
+ // The predicate must still fail CLOSED for everything else.
expect(canRunTaskOutputHookWithoutPayload('layered-intelligence')).toBe(false);
expect(canRunTaskOutputHookWithoutPayload('does-not-exist')).toBe(false);
});