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

collapse the quota-burn gate ladder into one evaluation and share its bounds table

[._.]/ Adam Eivyf83c46fe4e2e
diff --git a/client/src/components/quotaBurn/FamilyCard.jsx b/client/src/components/quotaBurn/FamilyCard.jsx
index 04ce4682c6..383623237d 100644
--- a/client/src/components/quotaBurn/FamilyCard.jsx
+++ b/client/src/components/quotaBurn/FamilyCard.jsx
@@ -9,39 +9,20 @@
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>
-);
+import { NumberField, TextField } from './fields';
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 counts stay on the STATUS side and are passed to JobRow as their own
+ // prop — merging them into the job objects would mean stripping them back off
+ // before every save (the PUT schema is strict). Matched by id so a reorder
+ // mid-save can't mis-pair them.
+ const pendingFor = (id) => (status?.jobs || []).find((row) => row.id === 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 patchJobs = (next) => onPatch({ jobs: next });
const changeJob = (index, next) => patchJobs(jobs.map((job, i) => (i === index ? next : job)));
const moveJob = (index, delta) => {
const next = [...jobs];
@@ -105,33 +86,15 @@ export default function FamilyCard({
{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.' })}
+ <NumberField id={`burn-${familyId}-window`} label="Burn within (hours of reset)" value={config.resetWithinHours} onChange={(v) => onPatch({ resetWithinHours: v })} min={0} max={168} hint="Only spend as the window is about to expire." />
+ <NumberField id={`burn-${familyId}-reserve`} label="Reserve (%)" value={config.reservePercent} onChange={(v) => onPatch({ reservePercent: v })} min={0} max={100} hint="Never spend below this much headroom." />
+ <NumberField id={`burn-${familyId}-cap`} label="Dispatch cap per window" value={config.maxDispatchesPerWindow} onChange={(v) => onPatch({ maxDispatchesPerWindow: v })} min={1} max={50} hint="Max automatic burns per reset window." />
+ <NumberField id={`burn-${familyId}-priority`} label="Priority" value={config.priority} onChange={(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>
+ <TextField id={`burn-${familyId}-provider`} label="Provider ID (optional)" value={config.providerId} onChange={(v) => onPatch({ providerId: v })} placeholder="auto-match by family" />
+ <TextField id={`burn-${familyId}-scope`} label="Window scope (optional)" value={config.scope} onChange={(v) => onPatch({ scope: v })} placeholder="e.g. week — blank watches every window" />
</div>
<div className="space-y-3">
@@ -141,17 +104,17 @@ export default function FamilyCard({
<Plus size={13} /> Add job
</button>
</div>
- {!withPending.length && (
+ {!jobs.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) => (
+ {jobs.map((job, index) => (
<JobRow
key={job.id}
job={job}
index={index}
- total={withPending.length}
- jobTypes={catalog.jobTypes}
+ total={jobs.length}
catalog={catalog}
+ pending={pendingFor(job.id)}
actionsBusy={actionsBusy}
onChange={(next) => changeJob(index, next)}
onMove={moveJob}
diff --git a/client/src/components/quotaBurn/JobParamField.jsx b/client/src/components/quotaBurn/JobParamField.jsx
index 0c91222688..c98baa6f1c 100644
--- a/client/src/components/quotaBurn/JobParamField.jsx
+++ b/client/src/components/quotaBurn/JobParamField.jsx
@@ -5,7 +5,7 @@
* 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';
+import { inputClass } from './fields';
export default function JobParamField({ descriptor, value, onChange, options, idPrefix }) {
const id = `${idPrefix}-${descriptor.key}`;
@@ -58,14 +58,17 @@ export default function JobParamField({ descriptor, value, onChange, options, id
}
// 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".
+ // image modes) or the descriptor's own enum. The "no pin" row, when a kind has
+ // one, is DESCRIBED BY THE SERVER (`emptyLabel`/`emptyValue`) rather than
+ // switched on `kind` here — otherwise every new job type with an optional
+ // param would need a client change, which is the thing the catalog exists to
+ // avoid.
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);
+ const sentinel = descriptor.emptyLabel
+ ? { value: descriptor.emptyValue ?? '', label: descriptor.emptyLabel }
+ : null;
return (
<label htmlFor={id} className="block text-xs text-gray-400">
diff --git a/client/src/components/quotaBurn/JobRow.jsx b/client/src/components/quotaBurn/JobRow.jsx
index f1c5ba68eb..9cf39b2f08 100644
--- a/client/src/components/quotaBurn/JobRow.jsx
+++ b/client/src/components/quotaBurn/JobRow.jsx
@@ -8,14 +8,13 @@
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';
+import { inputClass } from './fields';
export default function JobRow({
- job, index, total, jobTypes, catalog, actionsBusy,
+ job, index, total, catalog, pending, actionsBusy,
onChange, onMove, onRemove, onRun,
}) {
- const spec = jobTypes.find((type) => type.id === job.jobType);
+ const spec = catalog.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) => ({
@@ -24,8 +23,6 @@ export default function JobRow({
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">
@@ -37,7 +34,7 @@ export default function JobRow({
/>
<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"
+ className={`${inputClass} flex-1 min-w-40 mt-0`}
value={job.label || ''}
placeholder={spec?.label || 'Job name'}
aria-label={`Name for step ${index + 1}`}
@@ -60,7 +57,7 @@ export default function JobRow({
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>)}
+ {catalog.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">
diff --git a/client/src/components/quotaBurn/fields.jsx b/client/src/components/quotaBurn/fields.jsx
new file mode 100644
index 0000000000..a14bedca92
--- /dev/null
+++ b/client/src/components/quotaBurn/fields.jsx
@@ -0,0 +1,46 @@
+/**
+ * Shared field primitives for the Quota Burn config surface.
+ *
+ * The three components here (`FamilyCard`, `JobRow`, `JobParamField`) all render
+ * the same dark label+control pair. Keeping the class string and the number
+ * field in one place means a styling change is one edit rather than four —
+ * before this, the identical Tailwind string was declared or inlined at four
+ * sites and had already started to drift.
+ */
+
+export const inputClass = 'w-full mt-1 bg-port-bg border border-port-border rounded p-2 text-white text-xs';
+
+/** A labeled number input with an optional hint line beneath it. */
+export function NumberField({ id, label, value, onChange, min, max, hint }) {
+ return (
+ <label htmlFor={id} className="block text-xs text-gray-400">
+ {label}
+ <input
+ id={id}
+ type="number"
+ min={min}
+ max={max}
+ className={inputClass}
+ value={value}
+ onChange={(event) => onChange(Number(event.target.value))}
+ />
+ {hint && <span className="block mt-1 text-[11px] text-gray-500">{hint}</span>}
+ </label>
+ );
+}
+
+/** A labeled text input. `value` is always controlled; `null` renders as empty. */
+export function TextField({ id, label, value, onChange, placeholder }) {
+ return (
+ <label htmlFor={id} className="block text-xs text-gray-400">
+ {label}
+ <input
+ id={id}
+ className={inputClass}
+ value={value || ''}
+ placeholder={placeholder}
+ onChange={(event) => onChange(event.target.value || null)}
+ />
+ </label>
+ );
+}
diff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsx
index da88829508..ec6832523f 100644
--- a/client/src/pages/QuotaBurn.jsx
+++ b/client/src/pages/QuotaBurn.jsx
@@ -29,7 +29,7 @@ import { timeAgo } from '../utils/formatters';
// every universe bible — one full scan per character typed.
const SAVE_DEBOUNCE_MS = 500;
-const EMPTY_CATALOG = { families: [], jobTypes: [], apps: [], universes: [], imageModes: [] };
+const EMPTY_CATALOG = { jobTypes: [], apps: [], universes: [], imageModes: [] };
export default function QuotaBurn() {
// Which family is expanded lives in the URL, not local state, so a specific
@@ -177,7 +177,6 @@ export default function QuotaBurn() {
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')}
diff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsx
index 439e3b6d53..4370191776 100644
--- a/client/src/pages/QuotaBurn.test.jsx
+++ b/client/src/pages/QuotaBurn.test.jsx
@@ -96,8 +96,10 @@ describe('QuotaBurn page', () => {
));
});
- 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.
+ it('never persists a status field alongside the job config', async () => {
+ // Pending counts live on the STATUS side and reach JobRow as their own prop.
+ // If they were merged into the job objects they would have to be stripped
+ // back off before every save — the PUT schema is strict and would 400.
const user = userEvent.setup();
renderPage('/devtools/quota-burn/grok');
await user.click(await screen.findByLabelText('Name for step 1'));
diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.md
index 5127975063..39935f933d 100644
--- a/docs/QUOTA-BURN.md
+++ b/docs/QUOTA-BURN.md
@@ -43,10 +43,18 @@ 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.
+Each job module exports `countPending` (side-effect free — the page calls it on
+every load) and `run` (the only thing that may spend quota). `countPending` may
+return an opaque `context` that the runner hands straight to `run`, so a probe
+that scanned every universe bible to produce its count doesn't make `run` repeat
+the scan; `run` must still work without it, because the force path calls it with
+no probe. A job that declines reports `dispatched: false` with a reason and is
+**not** charged against the window's cap.
+
+Every numeric bound (windows, reserve, caps, entry limits) lives in
+`QUOTA_BURN_BOUNDS` in `server/lib/quotaBurnConfig.js`, read by the normalizer
+(which clamps an older on-disk plan), the Zod schemas (which reject a bad
+request), and the catalog descriptors the client renders as `min`/`max`.
## Manual runs
@@ -54,8 +62,9 @@ the window's cap.
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.
+ It goes through the same selection, so the run still reports the family's real
+ remaining percentage and reset time — it is only marked `charge: false`, so it
+ never eats the family's automatic budget.
## Storage
@@ -79,7 +88,7 @@ folds those overrides into the single plan (each app's family prompt becomes an
| --- | --- |
| `server/lib/quotaBurnConfig.js` | Plan shape, job-type catalog, total normalization |
| `server/services/quotaBurnStore.js` | `data/cos/quota-burn.json` + the run log |
-| `server/services/quotaBurn.js` | Candidate selection + the dispatch ledger |
+| `server/services/quotaBurn.js` | `evaluateFamily` — the one gate ladder both selection and the page's skip reasons read — plus 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` |
diff --git a/server/lib/README.md b/server/lib/README.md
index 29f2245d7c..76aa1cf25e 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -27,7 +27,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). |
| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. |
| `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |
-| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders, defaults, and total normalization (`normalizeQuotaBurnConfig`). Pure — no storage, no provider I/O. |
+| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). 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. |
diff --git a/server/lib/quotaBurnConfig.js b/server/lib/quotaBurnConfig.js
index 17b30b91c3..5952c4f9ea 100644
--- a/server/lib/quotaBurnConfig.js
+++ b/server/lib/quotaBurnConfig.js
@@ -22,9 +22,37 @@
* the wrong burn job spends real quota on work nobody asked for).
*/
+import { isPlainObject, POLLUTING_KEYS } from './objects.js';
+
/** Provider quota families a burn plan may target. Mirrors `providerUsage.js`'s card ids. */
export const QUOTA_BURN_FAMILIES = Object.freeze(['claude', 'codex', 'agy', 'grok']);
+/**
+ * Every numeric/length bound in the plan, in ONE place.
+ *
+ * Three consumers read these and must agree: the normalizer below (which
+ * CLAMPS, so an older on-disk plan still loads), `quotaBurnValidation.js`
+ * (which REJECTS with a 400, so a bad request is not silently reshaped), and
+ * the job catalog's param descriptors (which the client renders as `min`/`max`
+ * on the input). When they were three sets of literals, raising a cap in one
+ * meant the PUT 400'd on a plan the normalizer would happily have accepted —
+ * a split-brain invisible from inside any single file.
+ */
+export const QUOTA_BURN_BOUNDS = Object.freeze({
+ checkIntervalMinutes: { min: 5, max: 720, default: 30 },
+ resetWithinHours: { min: 0, max: 168, default: 24 },
+ reservePercent: { min: 0, max: 100, default: 0 },
+ maxDispatchesPerWindow: { min: 1, max: 50, default: 5 },
+ priority: { min: 0, max: 100, default: 0 },
+ maxEntries: { min: 1, max: 50, default: 10 },
+ jobsPerFamily: { max: 25 },
+ idLength: { max: 64 },
+ labelLength: { max: 120 },
+ scopeLength: { max: 60 },
+ paramLength: { max: 8000 },
+});
+const BOUNDS = QUOTA_BURN_BOUNDS;
+
/**
* 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
@@ -62,38 +90,34 @@ export const QUOTA_BURN_JOB_CATALOG = Object.freeze([
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: 'universeId', kind: 'universe', label: 'Universe', default: 'all', emptyLabel: 'All universes', emptyValue: '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 },
+ { key: 'maxEntries', kind: 'number', label: 'Max entries per run', min: BOUNDS.maxEntries.min, max: BOUNDS.maxEntries.max, default: BOUNDS.maxEntries.default },
+ { key: 'mode', kind: 'imageMode', label: 'Render backend', default: null, emptyLabel: 'Match the burning provider', emptyValue: '' },
]),
},
]);
-export const DEFAULT_QUOTA_BURN_FAMILY = Object.freeze({
+const DEFAULT_QUOTA_BURN_FAMILY = Object.freeze({
enabled: false,
providerId: null,
scope: null,
- resetWithinHours: 24,
- reservePercent: 0,
- maxDispatchesPerWindow: 5,
- priority: 0,
+ resetWithinHours: BOUNDS.resetWithinHours.default,
+ reservePercent: BOUNDS.reservePercent.default,
+ maxDispatchesPerWindow: BOUNDS.maxDispatchesPerWindow.default,
+ priority: BOUNDS.priority.default,
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) => {
+// Clamp against one QUOTA_BURN_BOUNDS entry, falling back to its documented
+// default when the value is missing or non-numeric.
+const clamp = ({ min, max, default: fallback }, value) => {
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 clampInt = (bounds, value) => Math.round(clamp(bounds, value));
const trimString = (value, max) =>
(typeof value === 'string' ? value.trim().slice(0, max) : '');
@@ -110,11 +134,11 @@ const nullableString = (value, max) => {
* 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 {};
+ if (!isPlainObject(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);
+ if (POLLUTING_KEYS.has(key)) continue;
+ if (typeof value === 'string') clean[key] = value.slice(0, BOUNDS.paramLength.max);
else if (typeof value === 'number' && Number.isFinite(value)) clean[key] = value;
else if (typeof value === 'boolean' || value === null) clean[key] = value;
}
@@ -132,16 +156,16 @@ function normalizeParams(raw) {
* something to key on.
*/
export function normalizeQuotaBurnJob(raw, index = 0) {
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+ if (!isPlainObject(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}`,
+ id: trimString(raw.id, BOUNDS.idLength.max) || `job-${index + 1}`,
enabled: raw.enabled !== false,
- label: trimString(raw.label, 120),
+ label: trimString(raw.label, BOUNDS.labelLength.max),
jobType,
- model: nullableString(raw.model, 120),
- providerId: nullableString(raw.providerId, 120),
+ model: nullableString(raw.model, BOUNDS.labelLength.max),
+ providerId: nullableString(raw.providerId, BOUNDS.labelLength.max),
params: normalizeParams(raw.params),
};
}
@@ -152,19 +176,19 @@ export function normalizeQuotaBurnJob(raw, index = 0) {
* 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 value = isPlainObject(raw) ? raw : {};
const jobs = (Array.isArray(value.jobs) ? value.jobs : [])
- .slice(0, 25)
+ .slice(0, BOUNDS.jobsPerFamily.max)
.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),
+ providerId: nullableString(value.providerId, BOUNDS.labelLength.max),
+ scope: nullableString(value.scope, BOUNDS.scopeLength.max),
+ resetWithinHours: clamp(BOUNDS.resetWithinHours, value.resetWithinHours),
+ reservePercent: clamp(BOUNDS.reservePercent, value.reservePercent),
+ maxDispatchesPerWindow: clampInt(BOUNDS.maxDispatchesPerWindow, value.maxDispatchesPerWindow),
+ priority: clampInt(BOUNDS.priority, value.priority),
jobs,
};
}
@@ -176,20 +200,17 @@ export function normalizeQuotaBurnFamily(raw) {
* 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
- : {};
+ const value = isPlainObject(raw) ? raw : {};
+ const families = isPlainObject(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,
- ),
+ checkIntervalMinutes: clampInt(BOUNDS.checkIntervalMinutes, value.checkIntervalMinutes),
+ // Each family carries its own `id`. Every consumer needs it (selection sorts
+ // and keys on it, the runner logs it, a job pins its render backend to it),
+ // and stamping it here is what lets them read `config.families[x]` straight
+ // instead of re-attaching `{ id, ...normalize(...) }` at four call sites.
families: Object.fromEntries(
- QUOTA_BURN_FAMILIES.map((id) => [id, normalizeQuotaBurnFamily(families[id])]),
+ QUOTA_BURN_FAMILIES.map((id) => [id, { id, ...normalizeQuotaBurnFamily(families[id]) }]),
),
};
}
diff --git a/server/lib/quotaBurnValidation.js b/server/lib/quotaBurnValidation.js
index 8976afff49..43f8515770 100644
--- a/server/lib/quotaBurnValidation.js
+++ b/server/lib/quotaBurnValidation.js
@@ -1,10 +1,12 @@
/**
* 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.
+ * Two layers on purpose: these schemas REJECT a malformed request with a 400,
+ * while `normalizeQuotaBurnConfig` (lib/quotaBurnConfig.js) CLAMPS on the way to
+ * disk so a plan written by an older PortOS still loads. Both read their numbers
+ * from the one `QUOTA_BURN_BOUNDS` table — when the bounds were literals in both
+ * files, raising a cap in one meant the PUT 400'd on a plan the normalizer would
+ * happily have accepted.
*
* 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
@@ -12,47 +14,44 @@
*/
import { z } from 'zod';
-import {
- CHECK_INTERVAL_MINUTES_MAX,
- CHECK_INTERVAL_MINUTES_MIN,
- QUOTA_BURN_FAMILIES,
- QUOTA_BURN_JOB_TYPES,
-} from './quotaBurnConfig.js';
+import { QUOTA_BURN_BOUNDS, QUOTA_BURN_FAMILIES, QUOTA_BURN_JOB_TYPES } from './quotaBurnConfig.js';
+
+const B = QUOTA_BURN_BOUNDS;
// 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()]);
+const paramValueSchema = z.union([z.string().max(B.paramLength.max), z.number().finite(), z.boolean(), z.null()]);
-export const quotaBurnJobSchema = z.object({
- id: z.string().max(64).optional(),
+const quotaBurnJobSchema = z.object({
+ id: z.string().max(B.idLength.max).optional(),
enabled: z.boolean().optional(),
- label: z.string().max(120).optional(),
+ label: z.string().max(B.labelLength.max).optional(),
jobType: z.enum(QUOTA_BURN_JOB_TYPES),
- model: z.string().max(120).nullable().optional(),
- providerId: z.string().max(120).nullable().optional(),
+ model: z.string().max(B.labelLength.max).nullable().optional(),
+ providerId: z.string().max(B.labelLength.max).nullable().optional(),
params: z.record(paramValueSchema).optional(),
}).strict();
-export const quotaBurnFamilySchema = z.object({
+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(),
+ providerId: z.string().max(B.labelLength.max).nullable().optional(),
+ scope: z.string().max(B.scopeLength.max).nullable().optional(),
+ resetWithinHours: z.number().min(B.resetWithinHours.min).max(B.resetWithinHours.max).optional(),
+ reservePercent: z.number().min(B.reservePercent.min).max(B.reservePercent.max).optional(),
+ maxDispatchesPerWindow: z.number().int().min(B.maxDispatchesPerWindow.min).max(B.maxDispatchesPerWindow.max).optional(),
+ priority: z.number().int().min(B.priority.min).max(B.priority.max).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(),
+ jobs: z.array(quotaBurnJobSchema).max(B.jobsPerFamily.max).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(),
+ checkIntervalMinutes: z.number().int().min(B.checkIntervalMinutes.min).max(B.checkIntervalMinutes.max).optional(),
families: z.object(
Object.fromEntries(QUOTA_BURN_FAMILIES.map((id) => [id, quotaBurnFamilySchema.optional()])),
).strict().optional(),
@@ -60,7 +59,7 @@ export const quotaBurnConfigUpdateSchema = z.object({
export const quotaBurnRunSchema = z.object({
familyId: z.enum(QUOTA_BURN_FAMILIES).optional(),
- jobId: z.string().max(64).optional(),
+ jobId: z.string().max(B.idLength.max).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(),
diff --git a/server/routes/quotaBurn.js b/server/routes/quotaBurn.js
index b4947095e0..2f1f774d5d 100644
--- a/server/routes/quotaBurn.js
+++ b/server/routes/quotaBurn.js
@@ -7,12 +7,12 @@
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 { QUOTA_BURN_JOB_CATALOG } from '../lib/quotaBurnConfig.js';
+import { QUEUEABLE_IMAGE_MODES } from '../services/imageGen/modes.js';
+import { 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 { listUniverseNames } from '../services/universeBuilder.js';
const router = Router();
@@ -21,8 +21,9 @@ const router = Router();
// 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 });
+ // getQuotaBurnStatus returns the config it already loaded — reading the file a
+ // second time here would just normalize the same bytes twice per page load.
+ res.json(await getQuotaBurnStatus({ refresh }));
}));
// GET /api/quota-burn/catalog — everything the config form needs to build its
@@ -31,16 +32,18 @@ router.get('/', asyncHandler(async (req, res) => {
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(() => []),
+ // The `{ id, name }` projection, NOT listUniverses() — the picker needs a
+ // label, not every bible on the install. A missing/empty universe store must
+ // not 500 the config page either; the universe job just has nothing to pick.
+ listUniverseNames().catch(() => []),
]);
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],
+ universes,
+ // Exactly the modes the media job queue can dispatch — the burn job enqueues
+ // through it, so a backend added there appears in this picker for free.
+ imageModes: QUEUEABLE_IMAGE_MODES,
});
}));
diff --git a/server/routes/quotaBurn.test.js b/server/routes/quotaBurn.test.js
index 6de58d6fc1..8c3ddfdf6a 100644
--- a/server/routes/quotaBurn.test.js
+++ b/server/routes/quotaBurn.test.js
@@ -12,12 +12,12 @@ vi.mock('../services/quotaBurnRunner.js', () => ({
runQuotaBurnCycle: vi.fn(),
}));
vi.mock('../services/apps.js', () => ({ getActiveApps: vi.fn() }));
-vi.mock('../services/universeBuilder.js', () => ({ listUniverses: vi.fn() }));
+vi.mock('../services/universeBuilder.js', () => ({ listUniverseNames: 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 { listUniverseNames } from '../services/universeBuilder.js';
import quotaBurnRoutes from './quotaBurn.js';
const buildApp = () => {
@@ -30,10 +30,12 @@ const buildApp = () => {
beforeEach(() => {
vi.clearAllMocks();
- getQuotaBurnConfig.mockResolvedValue({ enabled: false, checkIntervalMinutes: 30, families: {} });
- getQuotaBurnStatus.mockResolvedValue({ families: [], runs: [] });
+ getQuotaBurnStatus.mockResolvedValue({
+ config: { enabled: false, checkIntervalMinutes: 30, families: {} },
+ status: { running: false, families: [], runs: [] },
+ });
getActiveApps.mockResolvedValue([{ id: 'a1', name: 'App One', secret: 'do-not-leak' }]);
- listUniverses.mockResolvedValue([{ id: 'u1', name: 'Example Universe' }]);
+ listUniverseNames.mockResolvedValue([{ id: 'u1', name: 'Example Universe' }]);
});
describe('GET /api/quota-burn', () => {
@@ -42,8 +44,10 @@ describe('GET /api/quota-burn', () => {
expect(res.status).toBe(200);
expect(res.body).toEqual({
config: { enabled: false, checkIntervalMinutes: 30, families: {} },
- status: { families: [], runs: [] },
+ status: { running: false, families: [], runs: [] },
});
+ // The status read carries the config, so the route must NOT read the file again.
+ expect(getQuotaBurnConfig).not.toHaveBeenCalled();
expect(getQuotaBurnStatus).toHaveBeenCalledWith({ refresh: false });
});
@@ -65,7 +69,7 @@ describe('GET /api/quota-burn/catalog', () => {
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'));
+ listUniverseNames.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([]);
diff --git a/server/services/cos.js b/server/services/cos.js
index ae239861e0..f258a9e5b7 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -1083,7 +1083,7 @@ async function spawnDequeuePriority4IdleReview(ctx) {
* `ignoreTaskId` names a task that just completed but may still read
* `pending`/`in_progress` on disk — `agent:completed` fires from `completeAgent`,
* before the completion flow's `updateTask` settles it. Generators that count
- * in-flight work (quota-burn's dispatch tally, #3179) must exclude it or they
+ * in-flight work against a spend budget (#3179) must exclude it or they
* charge the finished run twice. Only the completion continuation passes it; every
* other caller runs outside that window and correctly leaves it null.
*/
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index f745258dde..d027f15743 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1862,8 +1862,8 @@ export async function emitOnDemandEmpty({ taskScheduleMod, request, targetApp, t
// blocked by an outbound firewall fails EVERY tick forever, so that advice sends
// the user in circles. Ask the CLI the detector actually ran (recorded by the
// work gate moments ago — the task-type NAME can't answer this: `claim-work`
- // resolves its forge internally, and branch-reconcile/quota-burn go transient
- // over git/provider faults with no forge involved) whether it is broken in a
+ // resolves its forge internally, and branch-reconcile goes transient over
+ // git/provider faults with no forge involved) whether it is broken in a
// way that won't self-clear, and pass the remedy through. No verdict, an
// unprobeable CLI, or a healthy one all leave `forge` null and keep the
// generic copy — the failure really was a blip, or at least not one we can name.
@@ -2441,7 +2441,7 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
// provider/model block below, so the per-app choice wins.
// `ignoreTaskId` reaches the hook because a drain-on-completion refill runs
// while the completing task is still `in_progress` on disk — a hook that
- // counts in-flight tasks (quota-burn) must not count the run that just
+ // counts in-flight tasks against a budget must not count the run that just
// finished and already recorded itself (#3179).
const inputHook = await resolveTaskInputHook(app, taskType, taskSchedule, { ignoreTaskId });
if (inputHook.skip) return null;
@@ -2554,8 +2554,10 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
// intentionally leaves all three untouched.
//
// The hook bag lands HERE, below the last gate, precisely so a hook can defer a
- // side effect keyed on it until the task is certain to exist (rationale in
- // autonomousJobs/quotaBurnHooks.js#buildTaskInput, #3179).
+ // side effect keyed on it until the task is certain to exist. Several gates
+ // below `resolveTaskInputHook` can still `return null` with no agent ever
+ // spawned, so a hook that charged a spend ledger from `buildTaskInput` would
+ // burn budget on a dispatch that never happened (#3179).
//
// Generator-computed keys always win. Stamping last would otherwise let a hook
// silently clobber a decision made a few lines earlier — `analysisType` is the
diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.js
index 4207883ff7..f2386252b5 100644
--- a/server/services/quotaBurn.js
+++ b/server/services/quotaBurn.js
@@ -21,6 +21,7 @@ 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 { isPlainObject } from '../lib/objects.js';
import { hoursUntilReset, normalizeResetAt } from '../lib/quotaReset.js';
const LEDGER_FILE = () => join(PATHS.cos, 'quota-burn-dispatches.json');
@@ -31,14 +32,10 @@ const LEDGER_FILE = () => join(PATHS.cos, 'quota-burn-dispatches.json');
// install.
const LEDGER_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;
-async function readQuotaBurnLedger() {
- 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() {
- return readQuotaBurnLedger();
+ const loaded = await readJSONFile(LEDGER_FILE(), {});
+ return isPlainObject(loaded) ? loaded : {};
}
const windowEpoch = (key) => Number(String(key).split(':').pop());
@@ -62,7 +59,7 @@ const ledgerWriteQueue = createFileWriteQueue();
export async function recordQuotaBurnDispatch(key, { now = Date.now() } = {}) {
return ledgerWriteQueue(async () => {
- const ledger = pruneLedger(await readQuotaBurnLedger(), now);
+ const ledger = pruneLedger(await getQuotaBurnDispatches(), now);
const next = { ...ledger, [key]: Number(ledger[key] || 0) + 1 };
await atomicWrite(LEDGER_FILE(), next);
return next;
@@ -86,69 +83,104 @@ export function burnBudgetRemaining(limit, family) {
return Math.max(0, Number(limit?.percentRemaining) - family.reservePercent);
}
+/**
+ * THE gate ladder. Evaluates one family against its live quota card and returns
+ * either a burn candidate or the reason it isn't one — never both, never
+ * neither.
+ *
+ * Deliberately one function rather than a selector plus a matching explainer.
+ * Those were written twice, and the status page renders the explanation
+ * verbatim: a gate added to one and not the other makes the page confidently
+ * report "will burn" for a family the runner then skips forever, which is
+ * exactly the question the page exists to answer.
+ *
+ * `bypassGates` is the page's per-job "Run now": the user named a family and
+ * clicked, which is a direct instruction to spend that quota. The window /
+ * reserve / cap gates bound UNATTENDED burns, so they are skipped — but the card
+ * and limit are still read, so a forced run reports its real remaining
+ * percentage and reset time instead of a fabricated one. It comes back
+ * `charge: false` so it never eats the automatic budget.
+ */
+export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}, bypassGates = false } = {}) {
+ if (!family.enabled) return { skipReason: 'disabled' };
+ if (!familyIsActionable(family)) return { skipReason: 'no enabled jobs configured' };
+ if (!card) return { skipReason: 'no enabled provider in this family' };
+ if (card.supported === false) return { skipReason: 'provider has no queryable quota surface' };
+ if (card.error) return { skipReason: `quota read failed: ${card.error}` };
+ // A card can declare it carries no spendable headroom (`burnable: false`) —
+ // e.g. the Image Gen card, whose 0%-left meter is an OBSERVED refusal, not a
+ // measured allowance. Burning against it would dispatch work to a backend that
+ // just refused. Opt-out only: absent means burnable.
+ if (card.burnable === false) return { skipReason: 'provider reports no spendable headroom' };
+
+ const selected = selectLimit(card, family, now);
+ // A window with no readable reset time is unknowable, not merely closed — a
+ // forced run can't invent one either, so this gate holds even under bypass.
+ if (!selected) return { skipReason: 'no window states a reset time' };
+
+ const dispatchKey = `${family.id}:${normalizeResetAt(selected.limit, { now }).epochMs}`;
+ const dispatchesUsed = Number(dispatches[dispatchKey] || 0);
+
+ // The three gates a forced run is allowed past. Evaluated regardless so the
+ // ordering (and the wording) stays in one place; only the return is skipped.
+ if (!bypassGates) {
+ if (selected.hours < 0) return { skipReason: 'window already reset' };
+ if (selected.hours > family.resetWithinHours) {
+ return { skipReason: `resets in ${Math.ceil(selected.hours)}h — outside the ${family.resetWithinHours}h window` };
+ }
+ if (dispatchesUsed >= family.maxDispatchesPerWindow) {
+ return { skipReason: `dispatch cap reached (${dispatchesUsed}/${family.maxDispatchesPerWindow})` };
+ }
+ if (burnBudgetRemaining(selected.limit, family) <= 0) {
+ return { skipReason: `${selected.limit.percentRemaining}% left is at or below the ${family.reservePercent}% reserve` };
+ }
+ }
+
+ return {
+ candidate: {
+ family,
+ card,
+ limit: selected.limit,
+ hoursUntilReset: selected.hours,
+ dispatchKey,
+ dispatchesUsed,
+ // Only an unforced burn is charged against the window's automatic budget.
+ charge: !bypassGates,
+ },
+ };
+}
+
+/** The family entries of a config, normalized and id-stamped. */
+const familiesOf = (config) => Object.entries(config?.families || {})
+ .map(([id, value]) => ({ id, ...normalizeQuotaBurnFamily(value) }));
+
/**
* 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()`.
+ * `providerUsage.getProviderQuotas()`. `bypassGatesFor` names one family whose
+ * window/reserve/cap gates are skipped (see `evaluateFamily`).
*/
-export function selectBurnCandidates(quotas, config, { now = Date.now(), dispatches = {} } = {}) {
+export function selectBurnCandidates(quotas, config, { now = Date.now(), dispatches = {}, bypassGatesFor = null } = {}) {
const cards = new Map((quotas || []).map((card) => [card.family, card]));
- return Object.entries(config?.families || {})
- .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;
- // A card can declare it carries no spendable headroom (`burnable: false`)
- // — e.g. the Image Gen card, whose 0%-left meter is an OBSERVED refusal,
- // not a measured allowance. Burning against it would dispatch work to a
- // backend that just refused. Opt-out only: absent means burnable.
- 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 }).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,
- dispatchesUsed: Number(dispatches[dispatchKey] || 0),
- };
- })
+ return familiesOf(config)
+ .map((family) => evaluateFamily(family, cards.get(family.id), {
+ now, dispatches, bypassGates: bypassGatesFor === family.id,
+ }).candidate)
.filter(Boolean)
.sort((a, b) => a.hoursUntilReset - b.hoursUntilReset || a.family.priority - b.family.priority);
}
/**
- * 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.
+ * Per-family verdicts for the status page: the candidate when the family would
+ * burn on the next tick, otherwise the exact gate that closed. One pass over the
+ * SAME ladder the runner uses, so the two can't disagree.
*/
-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`;
- }
- return null;
+export function evaluateFamilies(quotas, config, { now = Date.now(), dispatches = {} } = {}) {
+ const cards = new Map((quotas || []).map((card) => [card.family, card]));
+ return familiesOf(config).map((family) => ({
+ family,
+ ...evaluateFamily(family, cards.get(family.id), { now, dispatches }),
+ }));
}
diff --git a/server/services/quotaBurn.test.js b/server/services/quotaBurn.test.js
index 23d91355fd..e63b662022 100644
--- a/server/services/quotaBurn.test.js
+++ b/server/services/quotaBurn.test.js
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { burnBudgetRemaining, explainFamilySkip, selectBurnCandidates } from './quotaBurn.js';
+import { burnBudgetRemaining, evaluateFamilies, selectBurnCandidates } from './quotaBurn.js';
import { normalizeQuotaBurnConfig } from '../lib/quotaBurnConfig.js';
const NOW = Date.parse('2026-07-26T12:00:00.000Z');
@@ -67,32 +67,72 @@ describe('selectBurnCandidates', () => {
});
/**
- * 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.
+ * The page renders `evaluateFamilies`' answer verbatim, and the runner selects
+ * from the SAME ladder — a card that says "ready" while the runner skips (or
+ * vice versa) is worse than no explanation at all, so the two must be one
+ * function, not two that mirror each other.
*/
-describe('explainFamilySkip', () => {
+describe('evaluateFamilies', () => {
const family = { enabled: true, resetWithinHours: 24, reservePercent: 20, maxDispatchesPerWindow: 2, jobs: [job()] };
+ const reasonFor = (rawFamily, quotas, opts = {}) =>
+ evaluateFamilies(quotas, { families: { grok: rawFamily } }, { now: NOW, ...opts })[0].skipReason;
- it('returns null exactly when the family is a candidate', () => {
+ it('yields a candidate exactly when selectBurnCandidates does', () => {
const quotas = [quota('grok', '2026-07-26T18:00:00.000Z')];
- expect(explainFamilySkip('grok', family, quotas, { now: NOW })).toBeNull();
+ const [verdict] = evaluateFamilies(quotas, { families: { grok: family } }, { now: NOW });
+ expect(verdict.skipReason).toBeUndefined();
+ expect(verdict.candidate).toBeTruthy();
expect(selectBurnCandidates(quotas, { families: { grok: family } }, { now: NOW })).toHaveLength(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 }))
+ expect(reasonFor({ ...family, enabled: false }, [])).toBe('disabled');
+ expect(reasonFor({ ...family, jobs: [] }, [])).toBe('no enabled jobs configured');
+ expect(reasonFor(family, [])).toBe('no enabled provider in this family');
+ expect(reasonFor(family, [quota('grok', null)])).toBe('no window states a reset time');
+ expect(reasonFor(family, [quota('grok', '2026-07-28T12:00:00.000Z')])).toMatch(/outside the 24h window/);
+ expect(reasonFor(family, [quota('grok', '2026-07-26T18:00:00.000Z', 20)]))
.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)');
+ expect(reasonFor(family, [quota('grok', '2026-07-26T18:00:00.000Z')], { dispatches: { [selected.dispatchKey]: 2 } }))
+ .toBe('dispatch cap reached (2/2)');
+ });
+});
+
+describe('selectBurnCandidates bypassGatesFor', () => {
+ const closed = normalizeQuotaBurnConfig({
+ families: { grok: { enabled: true, resetWithinHours: 0, reservePercent: 99, maxDispatchesPerWindow: 1, jobs: [job()] } },
+ });
+ const quotas = [quota('grok', '2026-07-27T18:00:00.000Z', 10)];
+
+ it('still reports the family\'s REAL window when the gates are bypassed', () => {
+ // The forced candidate must not be a fabricated stand-in: the agent prompt
+ // renders `percentRemaining` and the reset hours into its brief, and the run
+ // log records them, so a synthesized zero would lie in both places.
+ expect(selectBurnCandidates(quotas, closed, { now: NOW })).toEqual([]);
+ const [forced] = selectBurnCandidates(quotas, closed, { now: NOW, bypassGatesFor: 'grok' });
+ expect(forced.limit.percentRemaining).toBe(10);
+ expect(forced.hoursUntilReset).toBeCloseTo(30, 0);
+ expect(forced.dispatchKey).toMatch(/^grok:/);
+ });
+
+ it('marks a forced candidate uncharged and an ordinary one charged', () => {
+ // `charge`, not a null dispatchKey: keyed on WHY it ran, so a force whose
+ // gates happen to pass is still uncharged instead of silently billing the
+ // window.
+ expect(selectBurnCandidates(quotas, closed, { now: NOW, bypassGatesFor: 'grok' })[0].charge).toBe(false);
+ const open = normalizeQuotaBurnConfig({ families: { grok: { enabled: true, jobs: [job()] } } });
+ expect(selectBurnCandidates([quota('grok', '2026-07-26T18:00:00.000Z')], open, { now: NOW })[0].charge).toBe(true);
+ expect(selectBurnCandidates([quota('grok', '2026-07-26T18:00:00.000Z')], open, { now: NOW, bypassGatesFor: 'grok' })[0].charge).toBe(false);
+ });
+
+ it('does not bypass gates for a family it was not named for', () => {
+ expect(selectBurnCandidates(quotas, closed, { now: NOW, bypassGatesFor: 'codex' })).toEqual([]);
+ });
+
+ it('still refuses a window with no readable reset time', () => {
+ // Unknowable, not merely closed — a forced run can't invent a reset either.
+ expect(selectBurnCandidates([quota('grok', null)], closed, { now: NOW, bypassGatesFor: 'grok' })).toEqual([]);
});
});
diff --git a/server/services/quotaBurnJobs/agentPrompt.js b/server/services/quotaBurnJobs/agentPrompt.js
index 194397a248..3cc6a38273 100644
--- a/server/services/quotaBurnJobs/agentPrompt.js
+++ b/server/services/quotaBurnJobs/agentPrompt.js
@@ -50,7 +50,9 @@ 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}` };
+ // Handed back to run() by the runner so the app + provider lookups happen
+ // once per dispatch instead of twice — see the registry's hook contract.
+ : { count: 1, context: resolved, detail: `ready to queue an agent in ${resolved.app.name}` };
}
/** The burn context the agent sees above the user's own prompt. */
@@ -69,8 +71,10 @@ export function renderBurnPrompt({ family, candidate, prompt }) {
].join('\n');
}
-export async function run({ params, job, family, candidate } = {}) {
- const resolved = await resolve({ params, job, family });
+export async function run({ params, job, family, candidate, context } = {}) {
+ // Reuse the probe's lookups when the runner supplied them; the page's force
+ // path calls run() with no probe, so fall back to resolving here.
+ const resolved = context ?? await resolve({ params, job, family });
if (resolved.error) return { dispatched: false, reason: resolved.error };
const { app, prompt, provider } = resolved;
diff --git a/server/services/quotaBurnJobs/agentPrompt.test.js b/server/services/quotaBurnJobs/agentPrompt.test.js
index 2899fe5c21..f53462bfea 100644
--- a/server/services/quotaBurnJobs/agentPrompt.test.js
+++ b/server/services/quotaBurnJobs/agentPrompt.test.js
@@ -85,3 +85,19 @@ describe('renderBurnPrompt', () => {
expect(prompt.endsWith('Ship the backlog')).toBe(true);
});
});
+
+describe('probe → run passthrough', () => {
+ it('reuses the probe\'s lookups instead of resolving twice', async () => {
+ const { getAppById } = await import('../apps.js');
+ const probe = await countPending({ params: { appId: 'app-1', prompt: 'x' }, family });
+ getAppById.mockClear();
+ await run({ params: { appId: 'app-1', prompt: 'x' }, job: { id: 'j1' }, family, candidate, context: probe.context });
+ expect(getAppById).not.toHaveBeenCalled();
+ expect(state.added).toHaveLength(1);
+ });
+
+ it('still resolves on its own when called with no probe (the force path)', async () => {
+ await run({ params: { appId: 'app-1', prompt: 'x' }, job: { id: 'j1' }, family, candidate });
+ expect(state.added).toHaveLength(1);
+ });
+});
diff --git a/server/services/quotaBurnJobs/index.js b/server/services/quotaBurnJobs/index.js
index d1dc358d63..381df6bf7a 100644
--- a/server/services/quotaBurnJobs/index.js
+++ b/server/services/quotaBurnJobs/index.js
@@ -4,15 +4,21 @@
* 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({ params, job, family }) → { count, detail, context? }
+ * run({ params, job, family, candidate, context }) → { 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.
+ * `countPending` must be side-effect free — the config page calls it for every
+ * configured job on every load, and the runner calls it to pick which job in the
+ * ordered plan actually has work. It may return an opaque `context` (whatever it
+ * already computed) which the runner hands straight back to `run`, so a probe
+ * that scanned every universe bible to produce its count doesn't make `run`
+ * repeat the scan. `run` must still work with `context: undefined` — the page's
+ * force path calls it without a probe.
+ *
+ * `run` is the only thing that may spend quota, and reports `dispatched: false`
+ * with a `reason` when it declines (nothing to do, misconfigured target) so the
+ * caller does NOT charge the window's dispatch cap for a burn that never
+ * happened.
*
* Modules are lazy-imported: `universeBibleImages` pulls the whole universe
* store + media job queue, and `agentPrompt` the CoS task store, so a status
@@ -26,17 +32,15 @@
import { QUOTA_BURN_JOB_TYPE } from '../../lib/quotaBurnConfig.js';
-const JOB_MODULES = {
+export 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;
-}
+// `Object.hasOwn`, not a truthiness check, so an inherited key like
+// 'constructor' can't resolve to a module.
+const load = async (jobType) =>
+ (typeof jobType === 'string' && Object.hasOwn(JOB_MODULES, jobType) ? JOB_MODULES[jobType]() : null);
/**
* Pending-work probe for one configured job. Never throws: a job whose backing
@@ -44,7 +48,7 @@ export async function loadBurnJob(jobType) {
* 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);
+ const mod = await load(job?.jobType);
if (!mod) return { count: 0, detail: `unknown job type: ${job?.jobType}` };
return mod.countPending({ params: job.params, job, family })
.catch((err) => ({ count: 0, detail: `probe failed: ${err.message}` }));
@@ -55,9 +59,9 @@ export async function countJobPending({ job, family }) {
* 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);
+export async function runBurnJob({ job, family, candidate, context }) {
+ const mod = await load(job?.jobType);
if (!mod) return { dispatched: false, reason: `unknown job type: ${job?.jobType}` };
- return mod.run({ params: job.params, job, family, candidate })
+ return mod.run({ params: job.params, job, family, candidate, context })
.catch((err) => ({ dispatched: false, reason: `job failed: ${err.message}` }));
}
diff --git a/server/services/quotaBurnJobs/index.test.js b/server/services/quotaBurnJobs/index.test.js
new file mode 100644
index 0000000000..9e3a8c1cc6
--- /dev/null
+++ b/server/services/quotaBurnJobs/index.test.js
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+import { JOB_MODULES, countJobPending, runBurnJob } from './index.js';
+import { QUOTA_BURN_JOB_CATALOG, QUOTA_BURN_JOB_TYPES } from '../../lib/quotaBurnConfig.js';
+
+describe('burn job registry', () => {
+ it('registers a module for every declared job type, and nothing else', () => {
+ // A job type is declared in two places — the alphabet + catalog in
+ // lib/quotaBurnConfig.js, and JOB_MODULES here. Without this guard, an
+ // enum/catalog entry with no module gives a job type the config page happily
+ // offers and that fails at dispatch with `unknown job type`, surfaced only in
+ // the run log AFTER a burnable window was already selected and consumed.
+ expect(Object.keys(JOB_MODULES).sort()).toEqual([...QUOTA_BURN_JOB_TYPES].sort());
+ expect(QUOTA_BURN_JOB_CATALOG.map((entry) => entry.id).sort()).toEqual([...QUOTA_BURN_JOB_TYPES].sort());
+ });
+
+ it('every module exports the two hooks the runner calls', async () => {
+ for (const load of Object.values(JOB_MODULES)) {
+ const mod = await load();
+ expect(typeof mod.countPending).toBe('function');
+ expect(typeof mod.run).toBe('function');
+ }
+ });
+
+ it('fails closed on an unknown job type rather than throwing', async () => {
+ await expect(countJobPending({ job: { jobType: 'rm-rf' } }))
+ .resolves.toEqual({ count: 0, detail: 'unknown job type: rm-rf' });
+ await expect(runBurnJob({ job: { jobType: 'rm-rf' } }))
+ .resolves.toEqual({ dispatched: false, reason: 'unknown job type: rm-rf' });
+ });
+
+ it('does not resolve an inherited Object.prototype key as a module', async () => {
+ // `Object.hasOwn`, not a truthiness check — 'constructor' would otherwise
+ // resolve to a function and be invoked as a lazy import.
+ await expect(countJobPending({ job: { jobType: 'constructor' } }))
+ .resolves.toMatchObject({ count: 0 });
+ });
+});
diff --git a/server/services/quotaBurnJobs/universeBibleImages.js b/server/services/quotaBurnJobs/universeBibleImages.js
index 3adc6e84c5..31b6cba690 100644
--- a/server/services/quotaBurnJobs/universeBibleImages.js
+++ b/server/services/quotaBurnJobs/universeBibleImages.js
@@ -17,9 +17,13 @@ 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';
+import { QUOTA_BURN_BOUNDS } from '../../lib/quotaBurnConfig.js';
const CANON_TRUNKS = ['characters', 'places', 'objects'];
-const DEFAULT_MAX_ENTRIES = 10;
+// Bounds come from the catalog descriptor the client renders its min/max from —
+// hardcoding them here would let a raised cap change the accepted range in the
+// form without changing what the job actually runs.
+const ENTRY_BOUNDS = QUOTA_BURN_BOUNDS.maxEntries;
const hasNoImage = (entry) => !Array.isArray(entry?.imageRefs) || entry.imageRefs.length === 0;
@@ -92,7 +96,7 @@ async function loadUniverses(params) {
* 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 max = Math.min(ENTRY_BOUNDS.max, Math.max(ENTRY_BOUNDS.min, Number(params?.maxEntries) || ENTRY_BOUNDS.default));
const scope = typeof params?.scope === 'string' ? params.scope : 'all';
const universes = await loadUniverses(params);
const batches = [];
@@ -118,10 +122,14 @@ async function collect(params) {
}
export async function countPending({ params } = {}) {
- const { picked, total } = await collect(params);
+ const collected = await collect(params);
+ const { picked, total } = collected;
const universeCount = picked.length;
return {
count: total,
+ // Handed back to run() by the runner so the bible scan happens once per
+ // dispatch instead of twice — see the registry's hook contract.
+ context: collected,
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',
@@ -136,8 +144,10 @@ export async function countPending({ params } = {}) {
* 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);
+export async function run({ params, job, family, context } = {}) {
+ // Reuse the probe's scan when the runner supplied it; the page's force path
+ // calls run() with no probe, so fall back to scanning here.
+ const { picked, total, max } = context ?? 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;
diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.js
index 6b38199743..092eefb7ec 100644
--- a/server/services/quotaBurnRunner.js
+++ b/server/services/quotaBurnRunner.js
@@ -20,10 +20,10 @@
*/
import { getProviderQuotas } from './providerUsage.js';
-import { getQuotaBurnDispatches, explainFamilySkip, recordQuotaBurnDispatch, selectBurnCandidates } from './quotaBurn.js';
+import { getQuotaBurnDispatches, evaluateFamilies, 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';
+import { familyIsActionable } from '../lib/quotaBurnConfig.js';
const TICK_MS = 60_000;
@@ -38,6 +38,11 @@ const enabledJobs = (family, jobId = null) =>
* Walk a candidate's plan in order and run the first job with pending work.
* Returns the dispatch outcome plus the per-job reasons, so a cycle that
* dispatched nothing still explains itself in the run log.
+ *
+ * The probe's `context` is handed to `run` rather than thrown away: a
+ * `universe-bible-images` probe reads every universe bible to count the backlog,
+ * and `run` needs the very same scan to know what to render. Without the
+ * passthrough that multi-megabyte read happened twice per dispatch.
*/
async function dispatchFromCandidate(candidate, { jobId = null } = {}) {
const attempts = [];
@@ -47,7 +52,7 @@ async function dispatchFromCandidate(candidate, { jobId = null } = {}) {
attempts.push({ jobId: job.id, jobType: job.jobType, skipped: pending.detail || 'no pending work' });
continue;
}
- const result = await runBurnJob({ job, family: candidate.family, candidate });
+ const result = await runBurnJob({ job, family: candidate.family, candidate, context: pending.context });
if (!result.dispatched) {
attempts.push({ jobId: job.id, jobType: job.jobType, skipped: result.reason || 'declined' });
continue;
@@ -94,6 +99,14 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
// the log with "disabled" rows and bury the last real run.
if (!config.enabled && trigger === 'scheduled') return { skipped: 'disabled' };
+ // Check the plan BEFORE the quota read. `getProviderQuotas({ refresh: true })`
+ // spawns a multi-second TUI scrape per enabled family; with no actionable
+ // family configured that scrape could never produce a dispatch, and it would
+ // otherwise run every `checkIntervalMinutes` forever.
+ if (!Object.values(config.families).some(familyIsActionable)) {
+ return finish({ dispatched: false, reason: 'no families enabled' });
+ }
+
const quotas = await getProviderQuotas({ refresh: true }).catch((err) => {
console.error(`❌ Quota-burn could not read provider quota: ${err.message}`);
return null;
@@ -101,23 +114,18 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = 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 }];
- }
+ // `force` is the page's per-job "Run now" — the window/reserve/cap gates that
+ // bound UNATTENDED burns don't apply to a run the user just asked for. It goes
+ // through the same selection, so the candidate still carries the family's real
+ // card and limit; it only comes back `charge: false`.
+ const candidates = selectBurnCandidates(quotas, config, {
+ dispatches, bypassGatesFor: force ? familyId : null,
+ }).filter((candidate) => !familyId || candidate.family.id === familyId);
if (!candidates.length) {
- const reasons = Object.entries(config.families)
- .filter(([, family]) => family.enabled)
- .map(([id, family]) => `${id}: ${explainFamilySkip(id, family, quotas, { dispatches }) || 'ready'}`);
+ const reasons = evaluateFamilies(quotas, config, { dispatches })
+ .filter(({ family }) => family.enabled)
+ .map(({ family, skipReason }) => `${family.id}: ${skipReason || 'ready'}`);
return finish({
dispatched: false,
reason: reasons.length ? `no burnable window — ${reasons.join('; ')}` : 'no families enabled',
@@ -129,15 +137,16 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
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);
+ // the cap bounds real burns, not attempts. `charge` is false for a forced
+ // run, which the user asked for outside the automatic budget.
+ if (candidate.charge) await recordQuotaBurnDispatch(candidate.dispatchKey);
return finish({
dispatched: true,
familyId: candidate.family.id,
jobId: outcome.job.id,
jobType: outcome.job.jobType,
dispatchKey: candidate.dispatchKey,
+ charged: candidate.charge,
hoursUntilReset: Math.round(candidate.hoursUntilReset * 10) / 10,
percentRemaining: candidate.limit?.percentRemaining ?? null,
summary: outcome.result.summary || 'dispatched',
@@ -153,54 +162,47 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,
}
/**
- * 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.
+ * The config page's whole payload: the plan plus, per family, whether it would
+ * burn on the next tick (and if not, exactly why) and each job's pending count.
+ *
+ * Returns the config it loaded so the route doesn't read and normalize the same
+ * file a second time. 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,
+ // Independent reads: only `quotas` is slow (a PTY scrape on the Refresh path),
+ // and nothing else waits on it.
+ const [config, quotas, dispatches, runs] = await Promise.all([
+ getQuotaBurnConfig(),
+ getProviderQuotas({ refresh }).catch((err) => {
+ console.error(`❌ Quota-burn status could not read provider quota: ${err.message}`);
+ return [];
+ }),
+ getQuotaBurnDispatches(),
+ getQuotaBurnRuns(),
+ ]);
+
+ // ONE pass over the gate ladder the runner uses — the page's "will burn" and
+ // its reason come from the same verdict, so they can't contradict each other.
+ const families = await Promise.all(evaluateFamilies(quotas, config, { dispatches })
+ .map(async ({ family, candidate, skipReason }) => ({
+ id: family.id,
+ label: candidate?.card?.label || quotas.find((entry) => entry.family === family.id)?.label || family.id,
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(),
- };
+ skipReason: skipReason || null,
+ // Probe pending work only for families the user actually enabled — a probe
+ // is not free (the universe job reads every bible), and a disabled
+ // family's counts are never acted on.
+ jobs: family.enabled
+ ? await Promise.all(family.jobs.map(async (job) => ({ id: job.id, pending: await countJobPending({ job, family }) })))
+ : family.jobs.map((job) => ({ id: job.id, pending: null })),
+ })));
+
+ return { config, status: { running, families, runs } };
}
async function tick() {
@@ -229,14 +231,10 @@ export function startQuotaBurnScheduler() {
console.log('🔥 Quota-burn loop armed (off unless enabled in Quota Burn settings)');
}
-export function stopQuotaBurnScheduler() {
+/** Test seam — disarms the timer and clears the in-process cycle state. */
+export function __resetQuotaBurnRunner() {
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
index 2acbec819a..8e10dd1eb8 100644
--- a/server/services/quotaBurnRunner.test.js
+++ b/server/services/quotaBurnRunner.test.js
@@ -11,6 +11,7 @@ const state = {
recorded: [],
pending: {},
ran: [],
+ contexts: [],
};
vi.mock('./providerUsage.js', () => ({
@@ -25,15 +26,16 @@ vi.mock('./quotaBurnStore.js', () => ({
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) });
+ runBurnJob: vi.fn(async ({ job, family, candidate, context }) => {
+ state.ran.push({ jobId: job.id, familyId: family.id, charge: candidate.charge });
+ state.contexts.push(context);
return state.jobResult ?? { dispatched: true, summary: `ran ${job.id}` };
}),
}));
// 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
+// `evaluateFamilies` stay REAL so this suite exercises the actual gate ladder
+// rather than a second copy of it. Stubbing the ledger keeps the suite off the
// install's real `data/cos/` files.
vi.mock('./quotaBurn.js', async (importActual) => ({
...(await importActual()),
@@ -70,6 +72,7 @@ beforeEach(() => {
state.runs = [];
state.pending = {};
state.ran = [];
+ state.contexts = [];
state.dispatches = {};
state.recorded = [];
state.jobResult = undefined;
@@ -86,16 +89,37 @@ describe('runQuotaBurnCycle', () => {
expect(state.ran).toHaveLength(0);
});
+ it('never scrapes provider quota when no family could burn', async () => {
+ // getProviderQuotas({ refresh: true }) spawns a multi-second TUI scrape per
+ // enabled family. With nothing actionable configured it could not produce a
+ // dispatch, and it would otherwise run on every tick forever.
+ const { getProviderQuotas } = await import('./providerUsage.js');
+ state.config = plan({ families: { grok: { enabled: true, jobs: [] } } });
+ const result = await runQuotaBurnCycle();
+ expect(getProviderQuotas).not.toHaveBeenCalled();
+ expect(result).toMatchObject({ dispatched: false, reason: 'no families enabled' });
+ });
+
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.ran).toEqual([{ jobId: 'second', familyId: 'grok', charge: true }]);
expect(state.recorded).toEqual([result.dispatchKey]);
});
+ it('hands the probe\'s work to run() instead of making it recompute', async () => {
+ // A universe-bible-images probe reads every bible to produce its count, and
+ // run() needs the same scan to know what to render — without the passthrough
+ // that multi-megabyte read happened twice per dispatch.
+ const scan = { picked: ['batch'], total: 4 };
+ state.pending = { first: { count: 4, context: scan } };
+ await runQuotaBurnCycle();
+ expect(state.contexts).toEqual([scan]);
+ });
+
it('prefers an earlier job when both have work', async () => {
state.pending = { first: { count: 3 }, second: { count: 9 } };
await runQuotaBurnCycle();
@@ -133,8 +157,10 @@ describe('runQuotaBurnCycle', () => {
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.
+ // A forced candidate still carries the family's REAL card and window — it is
+ // only marked uncharged, so the run log and the agent brief stay truthful.
+ expect(state.ran).toEqual([{ jobId: 'second', familyId: 'grok', charge: false }]);
+ expect(result.percentRemaining).toBe(50);
expect(state.recorded).toEqual([]);
});
@@ -158,9 +184,14 @@ describe('runQuotaBurnCycle', () => {
});
describe('getQuotaBurnStatus', () => {
+ it('returns the config it loaded so the route need not re-read it', async () => {
+ const { config } = await getQuotaBurnStatus();
+ expect(config).toBe(state.config);
+ });
+
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 { status } = await getQuotaBurnStatus();
const grok = status.families.find((family) => family.id === 'grok');
expect(grok.willBurn).toBe(true);
expect(grok.skipReason).toBeNull();
diff --git a/server/services/quotaBurnStore.js b/server/services/quotaBurnStore.js
index c333155be8..706c0e02df 100644
--- a/server/services/quotaBurnStore.js
+++ b/server/services/quotaBurnStore.js
@@ -18,13 +18,14 @@
import { join } from 'path';
import { atomicWrite, PATHS, readJSONFile } from '../lib/fileUtils.js';
import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { isPlainObject } from '../lib/objects.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;
+const 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
@@ -47,20 +48,15 @@ export async function getQuotaBurnConfig() {
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);
+ // Written to match `client/src/lib/quotaBurnPatch.js#mergeQuotaBurnPatch`
+ // line for line — the client applies the same merge optimistically while the
+ // PUT is debounced, and the two only stay honest if the claim is checkable
+ // at a glance. `normalizeQuotaBurnConfig` below drops any unknown family id.
+ const families = { ...current.families };
+ for (const [id, familyPatch] of Object.entries(isPlainObject(patch?.families) ? patch.families : {})) {
+ families[id] = { ...(families[id] || {}), ...familyPatch };
+ }
+ const next = normalizeQuotaBurnConfig({ ...current, ...patch, families });
await atomicWrite(configFile(), next);
return next;
});
@@ -80,7 +76,7 @@ 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);
+ const next = [{ at: new Date().toISOString(), ...entry }, ...runs].slice(0, RUN_LOG_LIMIT);
await atomicWrite(runLogFile(), { runs: next });
return next;
});
diff --git a/server/services/universeBuilder/crud.js b/server/services/universeBuilder/crud.js
index 5eeb077651..2e85dff80a 100644
--- a/server/services/universeBuilder/crud.js
+++ b/server/services/universeBuilder/crud.js
@@ -79,6 +79,31 @@ export async function listUniverses({ includeDeleted = false } = {}) {
return [...filtered].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));
}
+/**
+ * Every live universe as `{ id, name }` — a label and nothing else.
+ *
+ * Backs pickers that only need to name a universe (the Quota Burn job form).
+ * Same motivation as `listUniverseStyles` below: the PG backend projects in SQL,
+ * so this never ships the bibles / categories / composite sheets / run history
+ * that make `listUniverses()` a multi-megabyte read. Reach for this instead of
+ * `(await listUniverses()).map(u => ({ id: u.id, name: u.name }))`.
+ *
+ * Nameless records are dropped — an unlabeled row in a picker is unselectable.
+ * Newest-first, matching `listUniverses()`; ordering lives here rather than in
+ * either backend so the two can't drift.
+ */
+export async function listUniverseNames() {
+ const rows = await store().listNames();
+ return rows
+ .flatMap((r) => {
+ const name = trimTo(r?.name, NAME_MAX_LENGTH);
+ if (!isStr(r?.id) || !r.id || !name) return [];
+ return [{ id: r.id, name, createdAt: r.createdAt || '' }];
+ })
+ .sort((a, b) => b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id))
+ .map((r) => ({ id: r.id, name: r.name }));
+}
+
/**
* Every live universe as `{ id, name, influences: { embrace[], avoid[] } }` —
* the style tokens and nothing else.
diff --git a/server/services/universeBuilder/db.js b/server/services/universeBuilder/db.js
index 122d571794..7fcdcf27e7 100644
--- a/server/services/universeBuilder/db.js
+++ b/server/services/universeBuilder/db.js
@@ -50,6 +50,24 @@ export async function listRaw() {
return rows.map((r) => r.data);
}
+/**
+ * Live universes projected down to `{ id, name }`, unordered — the rows behind
+ * `listUniverseNames`, for pickers that need a label and nothing else.
+ *
+ * Same reasoning as `listStyles` below and `countUniverses` further down: both
+ * columns are exact mirrors of the JSONB (every `writeRaw` binds them from the
+ * same record), and `deleted = FALSE` hits the `idx_universes_live` partial
+ * index. Skips the bibles, the composite sheets, the whole `universe_runs`
+ * table, and the per-record sanitize that make `listUniverses()` a
+ * multi-megabyte read.
+ */
+export async function listNames() {
+ const { rows } = await query(
+ `SELECT id, name, data->>'createdAt' AS "createdAt" FROM universes WHERE deleted = FALSE`,
+ );
+ return rows;
+}
+
/**
* Live universes projected down to the style-bearing fields, unordered — the
* raw input `listUniverseStyles` derives its token lists from. See that
diff --git a/server/services/universeBuilder/store.js b/server/services/universeBuilder/store.js
index 11f4fe4737..95e7ba5e4d 100644
--- a/server/services/universeBuilder/store.js
+++ b/server/services/universeBuilder/store.js
@@ -101,6 +101,15 @@ function makeFileBackend(dir) {
const records = await listRaw();
return includeDeleted ? records.length : records.filter((r) => r?.deleted !== true).length;
},
+ // The file layout can't actually project — same constraint as countUniverses
+ // above. The `.map` is shape parity with db.listNames, not a saving.
+ // Unordered — the service sorts.
+ listNames: async () => {
+ const records = await listRaw();
+ return records
+ .filter((r) => r && r.deleted !== true)
+ .map((r) => ({ id: r.id, name: r.name, createdAt: r.createdAt }));
+ },
// The file layout can't actually project — `deleted` and the style fields
// both live inside each record, so knowing which rows are live means
// reading them all (same constraint as countUniverses above). The `.map`
@@ -157,6 +166,7 @@ function makePgBackend(db) {
listIds: db.listIds,
listRaw: db.listRaw,
countUniverses: db.countUniverses,
+ listNames: db.listNames,
listStyles: db.listStyles,
writeRaw: db.writeRaw,
deleteRaw: db.deleteRaw,
@@ -215,6 +225,7 @@ function createFacade({ dir, sanitizeRecord }) {
listIds: async () => (await getBackend()).listIds(),
listRaw: async () => (await getBackend()).listRaw(),
countUniverses: async (opts) => (await getBackend()).countUniverses(opts),
+ listNames: async () => (await getBackend()).listNames(),
listStyles: async () => (await getBackend()).listStyles(),
loadOneRaw: async (id) => (await getBackend()).readRaw(id),
loadOne: async (id) => {