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

default quota burn's dispatch cap to unlimited so a plan stops on quota, not on a tally

[._.]/ Adam Eivya486e003d2a3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9da8782152..af90bcabc8 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -4,6 +4,8 @@
- **Quota Burn's per-family "Provider ID" and "Window scope" boxes are gone.** Both were free-text overrides for decisions the page already makes correctly on its own: the family match already prefers the watchable TUI provider over the headless CLI (a hand-typed id could only ever pick a worse one), and window targeting already reads *every* window on the card — the broadest one as the target the reset horizon and dispatch cap key on, the narrowest as the one that will refuse first, the tightest as the one the reserve guards. Scope was a free-text filter over that, so its realistic uses were "type the same thing the classifier already picked" or "type a word this provider doesn't publish and silently never burn." A job still carries its own optional `providerId`, which is the level where naming a specific provider actually means something. Configs written before this load unchanged — the normalizer drops both keys on the next save — and migration 221 no longer carries them over from the retired per-app shape.
+- **Quota burn's dispatch cap is now opt-in — `-1` (unlimited) is the default, so a plan stops when the *quota* says so rather than when a tally runs out.** `maxDispatchesPerWindow` counted how many burns one target window could spend, and at its old default of 5 it was routinely the first gate to close: a weekly window with days left and headroom above the reserve would sit idle at "dispatch cap reached (5/5)" — the exact "allowance expires unused" outcome the feature exists to prevent. It read as a safety property, but the gates that actually bound spend all measure live numbers: the reset horizon (`resetWithinHours`), the reserve (`reservePercent`, checked against the *tightest* window on the card), and the provider's own refusal, which blocks the family outright when the short window empties underneath a weekly plan. A count stacked on top of those adds no protection they don't already give. A hard ceiling is still available — set 1–50 on the family card — and the window is charged either way, so the card still shows how many burns it has spent (with no denominator when uncapped). `0` is deliberately not accepted: "never burn" is what switching the family off means, and the client's number field collapses anything below 1 to the sentinel so stepping the spinner down can't 400. Migration 226 lifts an existing plan that still carries the old default of 5 — a changed default reaches nobody otherwise, since the normalizer has written that 5 into every install's `quota-burn.json` — while any other stored value is a number the user chose and is left alone.
+
- **The `cosAgents.js` barrel is gone, so an agent function no longer arrives from a specifier that says nothing about which layer it lives in.** The #2530 decomposition split a ~1090-line module into four focused siblings — `cosAgentIndex.js` (date-bucket index + on-disk archive layout), `cosAgentLifecycle.js` (register / update / complete / output / terminate), `cosAgentFeedback.js` (capture + classifier), `cosAgentArchive.js` (state-eviction sweeps) — then put an `export *` wall back in front of all four so no import path had to change. Three years of imports later, `updateAgent` and `getAgentsByDate` came from the same specifier despite sitting in different layers, and the wall is what made `cos.js` a *two*-hop forwarder of a lifecycle transition, which is the shape #3450's guard exists to delete. All ~20 production importers and ~14 `vi.mock` targets now name the module that declares what they asked for — several of which turn out to want only the index (`cosReports.js`, the peer cos-history merge) or only the lifecycle layer (the runner sync, the TUI output spooler, the completion cleanup), so the graph gets narrower as well as flatter. The four leaf modules are unchanged; the two test files that only ever exercised one of them are renamed to sit beside it (`cosAgentLifecycle.test.js`, `cosAgentIndex.merge.test.js`). The forwarder guard in `agentImportCycles.test.js` — which walks re-export edges rather than naming barrels, so a new one is covered the day it is written — now asserts `cos.js` is the *only* module forwarding a transition, and was bypass-probed both ways: planting a fresh `export *` barrel turns it red, and so does routing a production import of `completeAgent` back through `cos.js`. Its two module-loading assertions also take an explicit timeout: they transform `cos.js`'s whole service graph, which lands at 5–10s and straddles Vitest's 10s default, so the guard was one busy machine away from failing for a reason that had nothing to do with the invariant (#3450).
- **The agent lifecycle has a named entry point instead of seven mutually-recursive modules.** The `cos.js → cosAgents.js → cosAgentLifecycle.js → agentManagement.js → agents.js → subAgentSpawner.js → agentLifecycle.js` cluster has no owner, so reasoning about one transition — pause, kill, complete, spawn — means holding all seven files in mind, and several of the back-edges are `await import(...)` calls that exist only to dodge a load-time cycle. `server/services/agentOrchestrator.js` is the facade above that cluster: it imports the transition owners one-directionally, carries the transition-vs-leaf classification in its header so later passes start from it, and renames apart the two different functions both called `terminateAgent` — `requestAgentTermination` only emits the event and returns, while `terminateAgent` keeps the name for the real SIGTERM/SIGKILL sequence. The four agent routes (terminate, pause, kill, stats) now go through it, one hop instead of three. `agentImportCycles.test.js` gains a guard that fails if anything reachable from the facade imports it back, statically *or* via `import(...)` — the dynamic form matters because reaching across a blocked layer that way is exactly this cluster's habit, and the forbidden set is derived from the graph rather than listed so it can't fall behind. Widening that suite's graph builder to walk subdirectories closed a hole in the pre-existing cycle guard too: it read only top-level `server/services/*.js`, so a cycle routed through one subdirectory hop (`agentTuiSpawning/outputSpooler.js` already imports back up to `../cosAgents.js`) was invisible to it. The remaining call sites and the dynamic-import workarounds follow in later PRs (#3450).
diff --git a/client/src/components/quotaBurn/FamilyCard.jsx b/client/src/components/quotaBurn/FamilyCard.jsx
index 76cbc9ae17..2c2bded228 100644
--- a/client/src/components/quotaBurn/FamilyCard.jsx
+++ b/client/src/components/quotaBurn/FamilyCard.jsx
@@ -11,7 +11,7 @@ import { Ban, ChevronDown, ChevronRight, Flame, Plus } from 'lucide-react';
import BrailleSpinner from '../BrailleSpinner';
import JobRow from './JobRow';
import PresetPicker from './PresetPicker';
-import { jobFromPreset } from '../../lib/quotaBurnPatch';
+import { dispatchCapInput, isUnlimitedDispatchCap, jobFromPreset, UNLIMITED_DISPATCHES } from '../../lib/quotaBurnPatch';
import { formatDateTime } from '../../utils/formatters';
import { NumberField } from './fields';
@@ -102,7 +102,7 @@ export default function FamilyCard({
unreadable without knowing which allowance it describes. */
<span className="inline-flex items-center gap-1 text-xs text-emerald-400">
<Flame size={13} />
- {status.windowLabel ? `${status.windowLabel}: ` : ''}{status.percentRemaining}% left · resets in {status.hoursUntilReset}h · {status.dispatchesUsed}/{config.maxDispatchesPerWindow} used
+ {status.windowLabel ? `${status.windowLabel}: ` : ''}{status.percentRemaining}% left · resets in {status.hoursUntilReset}h · {status.dispatchesUsed}{isUnlimitedDispatchCap(config.maxDispatchesPerWindow) ? '' : `/${config.maxDispatchesPerWindow}`} used
</span>
) : (
<span className="text-xs text-gray-500">{status?.skipReason || 'not evaluated yet'}</span>
@@ -155,7 +155,7 @@ export default function FamilyCard({
<div className="grid grid-cols-2 lg:grid-cols-4 gap-3">
<NumberField id={`burn-${familyId}-window`} label="Burn within (hours of reset)" value={config.resetWithinHours} onChange={(v) => onPatch({ resetWithinHours: v })} min={0} max={168} hint="Measured against the broadest window (the weekly one) — the allowance that expires unused." />
<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}-cap`} label="Dispatch cap per window" value={config.maxDispatchesPerWindow} onChange={(v) => onPatch({ maxDispatchesPerWindow: dispatchCapInput(v) })} min={UNLIMITED_DISPATCHES} max={50} hint="Max automatic burns per reset window. -1 = unlimited (the default) — the reset window, the reserve, and provider refusals still bound it." />
<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>
diff --git a/client/src/components/quotaBurn/fields.jsx b/client/src/components/quotaBurn/fields.jsx
index 6ea2dd905e..af29a9f7ae 100644
--- a/client/src/components/quotaBurn/fields.jsx
+++ b/client/src/components/quotaBurn/fields.jsx
@@ -16,10 +16,11 @@ export const inputClass = 'w-full mt-1 bg-port-bg border border-port-border roun
* A labeled number input with an optional hint line beneath it.
*
* Holds a local draft string so the box can be EMPTY mid-edit without
- * committing a value. `Number('') === 0`, and 0 is below the server minimum for
- * `checkIntervalMinutes` (5) and `maxDispatchesPerWindow` (1) — so a user who
- * clears the box to retype it, and pauses past the save debounce, would 400 the
- * request and take every other edit coalesced into that body down with it.
+ * committing a value. `Number('') === 0`, and 0 is not an accepted value for
+ * `checkIntervalMinutes` (minimum 5) or `maxDispatchesPerWindow` (1–50, or the
+ * -1 "unlimited" sentinel) — so a user who clears the box to retype it, and
+ * pauses past the save debounce, would 400 the request and take every other
+ * edit coalesced into that body down with it.
* Committing only on a parseable number avoids the whole class. The draft is
* released on blur so the field snaps back to whatever the server stored.
*/
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 82c32c16e2..f0f9aaa912 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -84,7 +84,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `boundedMap.js` | `evictOldest(map, max, onEvict?)` — evict oldest-first (`map.keys().next().value`) until a Map is within `max`, with an optional per-evicted-key teardown callback for a companion timer map; `ORPHAN_BUFFER_MAX` (64), the shared cap for the orphan-event race-buffers. The one home for the "stash an unmatched event in a `jobId → …` Map, evict the oldest on overflow" idiom shared by `useSceneRenderLifecycle`, `useImageGenQueue`, and `clientErrorReporter`. |
| `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup, dropping browser-extension errors (see `extensionErrors.js`) before either gate. Wired from `main.jsx`; never call directly from React components. |
| `clinicianReport.js` | Pure builders for the MeatSpace clinician-export view (`/meatspace/export`). `buildClinicianReport({ tests, config })` → structured report model (blood panels grouped by category with reference ranges + out-of-range flags, plus a lifestyle summary); `reportToMarkdown(report)` → copy-paste markdown. Reuses the Blood tab's `REFERENCE_RANGES` / `getBloodValueStatus` so printed flags match the UI. Also exports `buildBloodTestModel`, `buildLifestyleModel`, `getCategoryForKey`, `formatRange`. |
-| `quotaBurnPatch.js` | `mergeQuotaBurnPatch(base, patch)` — mirrors the server's quota-burn config merge (top-level + per-family keys merge, a family's `jobs` array replaces) so the Quota Burn page can apply an edit optimistically and accumulate debounced edits into one PUT body. `applyQuotaBurnPreset(job, preset)` / `jobFromPreset(preset, { id, appId })` — copy a catalog prompt preset into a job, preserving the user's own step name and app choice. |
+| `quotaBurnPatch.js` | `mergeQuotaBurnPatch(base, patch)` — mirrors the server's quota-burn config merge (top-level + per-family keys merge, a family's `jobs` array replaces) so the Quota Burn page can apply an edit optimistically and accumulate debounced edits into one PUT body. `applyQuotaBurnPreset(job, preset)` / `jobFromPreset(preset, { id, appId })` — copy a catalog prompt preset into a job, preserving the user's own step name and app choice. `UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap(cap)` / `dispatchCapInput(value)` — the -1 "no dispatch cap" sentinel (the default), mirrored from the server. |
| `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. |
| `compareHelpers.js` | `equalByKeys(a, b, keys)` / `equalListByKeys(a, b, keys)` — typed key-based equality for `useAutoRefetch`'s `compare`. Keys are property names, dotted paths (`'context.running'`), or `(item) => value` accessors. The typed alternative to `sameJsonShape` when a monotonic timestamp or unrendered field would break stringify-equality dedup. |
| `consoleFilters.js` | `installConsoleFilters()` — drops a small allow-list of known-noise console strings (THREE.js `Clock` deprecation, expected WebGL `Context Lost.`) from `console.{warn,log,debug}`. Idempotent; auto-installed on import. Imported for its side effect from `main.jsx`. |
diff --git a/client/src/lib/quotaBurnPatch.js b/client/src/lib/quotaBurnPatch.js
index 49f36ab214..fc7a8eb246 100644
--- a/client/src/lib/quotaBurnPatch.js
+++ b/client/src/lib/quotaBurnPatch.js
@@ -61,3 +61,25 @@ export function jobFromPreset(preset, { id, appId = null } = {}) {
params: appId ? { appId } : {},
}, preset);
}
+
+/**
+ * `QUOTA_BURN_UNLIMITED_DISPATCHES` in `server/lib/quotaBurnConfig.js`: the
+ * `maxDispatchesPerWindow` value that means the window is not counted at all,
+ * and the default. Mirrored (not imported) for the same reason the merge above
+ * is — the client cannot reach into `server/`.
+ */
+export const UNLIMITED_DISPATCHES = -1;
+
+/** Mirrors the server's `isUnlimitedDispatchCap`: any negative cap means no cap. */
+export const isUnlimitedDispatchCap = (cap) => Number(cap) < 0;
+
+/**
+ * What to PUT for a dispatch cap the user just typed.
+ *
+ * Anything below the real minimum of 1 collapses to the sentinel rather than
+ * being sent as-is: 0 is not a value the PUT schema accepts (it would read as
+ * "never burn", which the family switch already expresses), so stepping the
+ * spinner down past 1 would otherwise 400 — taking every edit coalesced into
+ * that body with it. -1 is the natural continuation of "fewer restrictions".
+ */
+export const dispatchCapInput = (value) => (value < 1 ? UNLIMITED_DISPATCHES : value);
diff --git a/client/src/lib/quotaBurnPatch.test.js b/client/src/lib/quotaBurnPatch.test.js
index 93dc279988..bf5e3d8119 100644
--- a/client/src/lib/quotaBurnPatch.test.js
+++ b/client/src/lib/quotaBurnPatch.test.js
@@ -1,5 +1,12 @@
import { describe, it, expect } from 'vitest';
-import { applyQuotaBurnPreset, jobFromPreset, mergeQuotaBurnPatch } from './quotaBurnPatch';
+import {
+ applyQuotaBurnPreset,
+ dispatchCapInput,
+ isUnlimitedDispatchCap,
+ jobFromPreset,
+ mergeQuotaBurnPatch,
+ UNLIMITED_DISPATCHES,
+} from './quotaBurnPatch';
describe('mergeQuotaBurnPatch', () => {
it('merges top-level keys and leaves families untouched', () => {
@@ -89,3 +96,20 @@ describe('jobFromPreset', () => {
expect(jobFromPreset(preset, { id: 'job-x' }).params).not.toHaveProperty('appId');
});
});
+
+describe('dispatch cap helpers', () => {
+ it('reads any negative cap as unlimited and a real cap as bounded', () => {
+ expect(isUnlimitedDispatchCap(UNLIMITED_DISPATCHES)).toBe(true);
+ expect(isUnlimitedDispatchCap(1)).toBe(false);
+ expect(isUnlimitedDispatchCap(50)).toBe(false);
+ });
+
+ it('collapses anything below the real minimum to the sentinel the PUT accepts', () => {
+ // 0 is what a spinner step down from 1 produces, and the schema rejects it —
+ // sending it would 400 and take every co-pending edit with it.
+ expect(dispatchCapInput(0)).toBe(UNLIMITED_DISPATCHES);
+ expect(dispatchCapInput(-4)).toBe(UNLIMITED_DISPATCHES);
+ expect(dispatchCapInput(1)).toBe(1);
+ expect(dispatchCapInput(50)).toBe(50);
+ });
+});
diff --git a/client/src/pages/QuotaBurn.jsx b/client/src/pages/QuotaBurn.jsx
index db48e7456f..fb67e1c108 100644
--- a/client/src/pages/QuotaBurn.jsx
+++ b/client/src/pages/QuotaBurn.jsx
@@ -259,7 +259,7 @@ export default function QuotaBurn() {
</div>
<p className="text-xs text-gray-400">
One loop for this install, but each provider family burns independently: every family whose window is inside its reset
- horizon, above its reserve, and under its dispatch cap runs the first job in its plan that has work waiting — one job
+ horizon, above its reserve, and under its dispatch cap (unlimited by default) runs the first job in its plan that has work waiting — one job
per family per cycle. Turning this on is explicit consent to spend those subscriptions on a schedule.
</p>
{lastRun && (
diff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsx
index 25f0770368..4c28214507 100644
--- a/client/src/pages/QuotaBurn.test.jsx
+++ b/client/src/pages/QuotaBurn.test.jsx
@@ -121,6 +121,31 @@ describe('QuotaBurn page', () => {
expect(await screen.findByText(/Weekly: 62% left/)).toBeInTheDocument();
});
+ it('drops the denominator when the dispatch cap is unlimited', async () => {
+ // -1 is the default: the window is still CHARGED (so "1 used" stays useful)
+ // but nothing is counting down to a limit, and "1/-1 used" would read as a
+ // bug in the ledger.
+ api.getQuotaBurn.mockResolvedValue({
+ config: { ...config, families: { ...config.families, grok: { ...config.families.grok, maxDispatchesPerWindow: -1 } } },
+ status,
+ });
+ renderPage();
+ expect(await screen.findByText(/· 1 used/)).toBeInTheDocument();
+ expect(screen.queryByText(/1\/-1 used/)).not.toBeInTheDocument();
+ });
+
+ it('sends the unlimited sentinel rather than a 0 the server would reject', async () => {
+ // Stepping the cap below 1 is "fewer restrictions", and 0 is not a value the
+ // PUT accepts — collapsing it to -1 keeps the spinner from 400ing the save.
+ const user = userEvent.setup();
+ renderPage('/devtools/quota-burn/grok');
+ const cap = await screen.findByLabelText(/Dispatch cap per window/);
+ await user.clear(cap);
+ await user.type(cap, '0');
+ await waitFor(() => expect(api.saveQuotaBurn).toHaveBeenCalled());
+ expect(api.saveQuotaBurn.mock.calls[0][0].families.grok.maxDispatchesPerWindow).toBe(-1);
+ });
+
it('shows an observed provider refusal, not just the gate that closed', async () => {
// "The provider said no" is the actionable fact, and it is what explains a
// family that looks healthy on paper but never burns.
diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.md
index 28ce758389..ce31606b93 100644
--- a/docs/QUOTA-BURN.md
+++ b/docs/QUOTA-BURN.md
@@ -17,8 +17,8 @@ Every `checkIntervalMinutes` (default 30, bounded 5–720) the runner:
3. Selects families whose **target window** (see below) is inside
`resetWithinHours`, that no provider refusal is currently blocking, that still
have headroom above `reservePercent` in *every* window on the card, and that have
- not spent `maxDispatchesPerWindow` for that window. Ties break on `priority`
- (lower wins).
+ not spent `maxDispatchesPerWindow` for that window (`-1`, the default, means
+ no cap — see below). Ties break on `priority` (lower wins).
4. Runs the **first enabled job in that family's ordered plan that reports
pending work** — at most one dispatch per cycle.
5. Charges the window in `data/cos/quota-burn-dispatches.json` and appends the
@@ -51,6 +51,23 @@ words the adapters emit, or from an exact `periodHours` when a provider states
one (codex's telemetry carries `window_minutes`). A family whose windows can't be
classified at all falls back to soonest-reset ordering.
+## The dispatch cap is opt-in
+
+`maxDispatchesPerWindow` defaults to **-1 (unlimited)**: the tally is not
+consulted at all, and the window's spend is bounded by the gates that read live
+numbers — `resetWithinHours`, `reservePercent`, and the provider's own refusal
+(below). A count-based ceiling stacked on top of those read like a safety
+property but mostly stopped a plan mid-window with quota still on the table,
+which is the outcome quota-burn exists to prevent.
+
+Set 1–50 for a hard ceiling per target window. **0 is not a value** — "never
+burn" is what switching the family off means. The window is charged in
+`quota-burn-dispatches.json` either way, so the family card still shows how many
+burns the current window has spent (without a denominator when uncapped).
+
+Migration 226 lifts an existing plan that still carries the old default of 5;
+any other stored value is a number the user chose and is left alone.
+
## Stop condition: an observed refusal
Reported numbers are stale by design (scraped every few minutes, rounded to whole
diff --git a/scripts/migrations/226-quota-burn-unlimited-dispatch-cap.js b/scripts/migrations/226-quota-burn-unlimited-dispatch-cap.js
new file mode 100644
index 0000000000..bc1569ad97
--- /dev/null
+++ b/scripts/migrations/226-quota-burn-unlimited-dispatch-cap.js
@@ -0,0 +1,72 @@
+/**
+ * Migration 226 — carry the old `maxDispatchesPerWindow: 5` default over to
+ * "unlimited" (-1), the new default.
+ *
+ * Background:
+ * The dispatch cap is now opt-in — see "The dispatch cap is opt-in" in
+ * `docs/QUOTA-BURN.md` for why a count-based ceiling protected nothing the
+ * live-number gates don't already.
+ *
+ * Changing the default alone would not reach an existing install. Every
+ * install that has ever SAVED a burn plan has the number 5 written into
+ * `data/cos/quota-burn.json` — the normalizer materializes every family key,
+ * caps included, before the store writes it, and migration 221 wrote 5
+ * explicitly for each per-app plan it folded in — so without this pass the new
+ * default reaches only installs that have never opened the page.
+ *
+ * What it writes:
+ * `data/cos/quota-burn.json`, with `maxDispatchesPerWindow: 5` rewritten to -1
+ * on each family that still carries exactly the old default. Any other value
+ * is a number the user chose over the default and is left alone; so is a
+ * family that already reads -1.
+ *
+ * Idempotent: a plan with no remaining 5s is left untouched on a second run.
+ */
+
+import { join } from 'path';
+import { atomicWrite, readJSONFile } from '../../server/lib/fileUtils.js';
+import { QUOTA_BURN_UNLIMITED_DISPATCHES } from '../../server/lib/quotaBurnConfig.js';
+
+/** The default this release replaces. Only this exact value is rewritten. */
+const PREVIOUS_DEFAULT_CAP = 5;
+
+/**
+ * Rewrite every family still on the old default cap. Pure — exported for the test.
+ *
+ * @param {object} config raw parsed quota-burn config
+ * @returns {{ config: object, lifted: string[] }} the family ids that changed
+ */
+export function liftDispatchCaps(config) {
+ const source = config?.families;
+ if (!source || typeof source !== 'object' || Array.isArray(source)) return { config, lifted: [] };
+
+ const families = { ...source };
+ const lifted = Object.keys(families).filter((id) => families[id]?.maxDispatchesPerWindow === PREVIOUS_DEFAULT_CAP);
+ for (const id of lifted) {
+ families[id] = { ...families[id], maxDispatchesPerWindow: QUOTA_BURN_UNLIMITED_DISPATCHES };
+ }
+ return { config: { ...config, families }, lifted };
+}
+
+export default {
+ async up({ rootDir }) {
+ // Read and write exactly as `quotaBurnStore.js` does, so an install that
+ // never opens the page again is left with a byte-identical file shape.
+ const configFile = join(rootDir, 'data', 'cos', 'quota-burn.json');
+ const config = await readJSONFile(configFile, null, { allowArray: false });
+ if (!config) {
+ console.log('🔥 migration 226: no quota-burn config — the new unlimited default applies as-is');
+ return { ok: true, reason: 'no-config' };
+ }
+
+ const { config: next, lifted } = liftDispatchCaps(config);
+ if (!lifted.length) {
+ console.log('🔥 migration 226: no family still carries the old dispatch cap of 5 — nothing to lift');
+ return { ok: true, reason: 'already-lifted' };
+ }
+
+ await atomicWrite(configFile, next);
+ console.log(`🔥 migration 226: lifted the dispatch cap to unlimited for ${lifted.length} quota-burn famil${lifted.length === 1 ? 'y' : 'ies'} (${lifted.join(', ')})`);
+ return { ok: true, lifted };
+ },
+};
diff --git a/scripts/migrations/226-quota-burn-unlimited-dispatch-cap.test.js b/scripts/migrations/226-quota-burn-unlimited-dispatch-cap.test.js
new file mode 100644
index 0000000000..3828c7f2f1
--- /dev/null
+++ b/scripts/migrations/226-quota-burn-unlimited-dispatch-cap.test.js
@@ -0,0 +1,96 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration, { liftDispatchCaps } from './226-quota-burn-unlimited-dispatch-cap.js';
+import { normalizeQuotaBurnConfig, QUOTA_BURN_UNLIMITED_DISPATCHES } from '../../server/lib/quotaBurnConfig.js';
+
+const family = (overrides = {}) => ({
+ enabled: true,
+ providerId: null,
+ scope: null,
+ resetWithinHours: 24,
+ reservePercent: 0,
+ maxDispatchesPerWindow: 5,
+ priority: 0,
+ jobs: [],
+ ...overrides,
+});
+
+describe('liftDispatchCaps', () => {
+ it('rewrites the old default of 5 to the unlimited sentinel', () => {
+ const { config, lifted } = liftDispatchCaps({ enabled: true, families: { grok: family() } });
+ expect(lifted).toEqual(['grok']);
+ expect(config.families.grok.maxDispatchesPerWindow).toBe(QUOTA_BURN_UNLIMITED_DISPATCHES);
+ // Everything else about the family survives verbatim.
+ expect(config.families.grok).toMatchObject({ enabled: true, resetWithinHours: 24, priority: 0 });
+ });
+
+ it('leaves a cap the user chose over the default alone', () => {
+ const { config, lifted } = liftDispatchCaps({
+ families: { claude: family({ maxDispatchesPerWindow: 2 }), codex: family({ maxDispatchesPerWindow: 50 }) },
+ });
+ expect(lifted).toEqual([]);
+ expect(config.families.claude.maxDispatchesPerWindow).toBe(2);
+ expect(config.families.codex.maxDispatchesPerWindow).toBe(50);
+ });
+
+ it('lifts only the families still on the default, in a mixed plan', () => {
+ const { config, lifted } = liftDispatchCaps({
+ families: { claude: family(), codex: family({ maxDispatchesPerWindow: 3 }), agy: family() },
+ });
+ expect(lifted).toEqual(['claude', 'agy']);
+ expect(config.families.codex.maxDispatchesPerWindow).toBe(3);
+ });
+
+ it('reports no change on a config with no families block', () => {
+ const config = { enabled: false };
+ expect(liftDispatchCaps(config)).toEqual({ config, lifted: [] });
+ });
+
+ it('produces a config the normalizer keeps as unlimited', () => {
+ // The sentinel sits below the field's own minimum, so a generic clamp would
+ // fold it back up to 1 and silently reinstate a cap — guard against that
+ // regression from the migration's side too.
+ const { config } = liftDispatchCaps({ enabled: true, families: { grok: family() } });
+ expect(normalizeQuotaBurnConfig(config).families.grok.maxDispatchesPerWindow)
+ .toBe(QUOTA_BURN_UNLIMITED_DISPATCHES);
+ });
+});
+
+describe('migration 226 up()', () => {
+ let rootDir;
+ const configPath = () => join(rootDir, 'data', 'cos', 'quota-burn.json');
+ beforeEach(async () => {
+ rootDir = await mkdtemp(join(tmpdir(), 'portos-226-'));
+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });
+ });
+ afterEach(async () => { await rm(rootDir, { recursive: true, force: true }); });
+
+ it('no-ops when the install has never written a burn plan', async () => {
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, reason: 'no-config' });
+ });
+
+ it('no-ops on an unparseable config rather than throwing the boot migration run', async () => {
+ await writeFile(configPath(), 'not json');
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, reason: 'no-config' });
+ });
+
+ it('lifts a stored plan that still carries the old default', async () => {
+ await writeFile(configPath(), JSON.stringify({ enabled: true, families: { grok: family() } }));
+
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, lifted: ['grok'] });
+
+ const after = JSON.parse(await readFile(configPath(), 'utf-8'));
+ expect(after.families.grok.maxDispatchesPerWindow).toBe(QUOTA_BURN_UNLIMITED_DISPATCHES);
+ });
+
+ it('is idempotent — a second run leaves the file byte-identical', async () => {
+ await writeFile(configPath(), JSON.stringify({ enabled: true, families: { grok: family() } }));
+
+ await migration.up({ rootDir });
+ const first = await readFile(configPath(), 'utf-8');
+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ reason: 'already-lifted' });
+ expect(await readFile(configPath(), 'utf-8')).toBe(first);
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 6ab954c41f..238f9f8a4f 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -27,7 +27,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentOutputMarkers.js` | Status lines PortOS itself appends to an agent's output buffer: `SENTINEL_COMPLETION_MARKER` (the line `ingestDoneSentinel` writes just before the agent's `.agent-done` summary) plus `isAgentLifecycleLine(line)`/`stripLifecycleLines(lines)`, which match PortOS's telemetry on its actual message shapes rather than on a leading emoji (an agent's own summary may well start a line with `✅`). Pure — shared by the emitter (`services/agentTuiSpawning.js`) and by readers that must show only the agent's own words (notably the generated PR description). |
| `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME` + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. |
| `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. |
-| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225. Pure — no storage, no provider I/O. |
+| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Owns the dispatch-cap sentinel too (`QUOTA_BURN_UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap`) — -1 means the window is not counted, and is the default. Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225. Pure — no storage, no provider I/O. |
| `quotaBurnPresets.js` | `QUOTA_BURN_PROMPT_PRESETS` — ready-made single-focus audit prompts for `agent-prompt` burn jobs (UX, a11y, mobile, failure paths, perf, test gaps, dead code, data safety, docs, security), each filing GitHub issues and changing no code. Templates: picking one COPIES its prompt into the job, so editing them never rewrites a configured job. `findQuotaBurnPreset(id)`. |
| `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body). |
| `quotaReset.js` | `parseHumanReset` turns a provider CLI's human reset string into ISO 8601 (call it from the adapter); `normalizeResetAt`/`hoursUntilReset` compute time remaining without treating unknown values as imminent resets; `parseObservedReset` pulls the reset a provider stated in its own refusal text, and `isObservedBlockActive` is the shared "is that refusal still holding?" predicate every observed-refusal ledger uses. |
diff --git a/server/lib/quotaBurnConfig.js b/server/lib/quotaBurnConfig.js
index 3efc529f1c..5c9f5bc7b3 100644
--- a/server/lib/quotaBurnConfig.js
+++ b/server/lib/quotaBurnConfig.js
@@ -53,6 +53,18 @@ export function quotaBurnFamilyOfDescription(description) {
return QUOTA_BURN_FAMILIES.includes(family) ? family : null;
}
+/**
+ * `maxDispatchesPerWindow` sentinel for "no cap on how many burns this window
+ * may spend" — and the default. Why the cap is opt-in rather than a safety
+ * property is argued once, in `docs/QUOTA-BURN.md`.
+ *
+ * -1 rather than 0/null: it stays a number for the client's `<input
+ * type="number">` and the run log, and it can never be confused with "0 burns
+ * allowed" (which is what disabling the family already means). It sits BELOW
+ * the field's own minimum, which is what `clampDispatchCap` exists to handle.
+ */
+export const QUOTA_BURN_UNLIMITED_DISPATCHES = -1;
+
/**
* Every numeric/length bound in the plan, in ONE place.
*
@@ -68,7 +80,8 @@ 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 },
+ // `min` is the smallest REAL cap; the default opts out of capping entirely.
+ maxDispatchesPerWindow: { min: 1, max: 50, default: QUOTA_BURN_UNLIMITED_DISPATCHES },
priority: { min: 0, max: 100, default: 0 },
maxEntries: { min: 1, max: 50, default: 10 },
jobsPerFamily: { max: 25 },
@@ -78,6 +91,9 @@ export const QUOTA_BURN_BOUNDS = Object.freeze({
});
const BOUNDS = QUOTA_BURN_BOUNDS;
+/** Whether a family's dispatch cap means "no cap". Any negative value reads as unlimited. */
+export const isUnlimitedDispatchCap = (cap) => Number(cap) < 0;
+
/**
* 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
@@ -148,6 +164,20 @@ const clamp = ({ min, max, default: fallback }, value) => {
const clampInt = (bounds, value) => Math.round(clamp(bounds, value));
+/**
+ * The dispatch cap can't go straight through `clampInt`: its sentinel sits
+ * BELOW its own minimum, so the generic clamp would fold -1 back up to 1 and
+ * silently reinstate a cap of one burn per window. Any negative reads as
+ * unlimited; a real cap still clamps into 1–50 (so a legacy 0 keeps landing on
+ * 1 rather than meaning "never burn", which is what disabling the family is
+ * for).
+ */
+const clampDispatchCap = (value) => {
+ const num = Number(value);
+ if (!Number.isFinite(num)) return BOUNDS.maxDispatchesPerWindow.default;
+ return num < 0 ? QUOTA_BURN_UNLIMITED_DISPATCHES : clampInt(BOUNDS.maxDispatchesPerWindow, num);
+};
+
const trimString = (value, max) =>
(typeof value === 'string' ? value.trim().slice(0, max) : '');
@@ -202,7 +232,8 @@ export function normalizeQuotaBurnJob(raw, index = 0) {
/**
* Normalize one provider family's burn plan. Bounds mirror the pre-#3179
* per-app sanitizer so a migrated config keeps its meaning: reset window up to
- * a week, reserve 0–100%, 1–50 dispatches per window.
+ * a week, reserve 0–100%, and 1–50 dispatches per window (or -1 for no cap,
+ * which is the default).
*/
export function normalizeQuotaBurnFamily(raw) {
const value = isPlainObject(raw) ? raw : {};
@@ -214,7 +245,7 @@ export function normalizeQuotaBurnFamily(raw) {
enabled: value.enabled === true,
resetWithinHours: clamp(BOUNDS.resetWithinHours, value.resetWithinHours),
reservePercent: clamp(BOUNDS.reservePercent, value.reservePercent),
- maxDispatchesPerWindow: clampInt(BOUNDS.maxDispatchesPerWindow, value.maxDispatchesPerWindow),
+ maxDispatchesPerWindow: clampDispatchCap(value.maxDispatchesPerWindow),
priority: clampInt(BOUNDS.priority, value.priority),
jobs,
};
diff --git a/server/lib/quotaBurnConfig.test.js b/server/lib/quotaBurnConfig.test.js
index 473714a59f..56b70860cc 100644
--- a/server/lib/quotaBurnConfig.test.js
+++ b/server/lib/quotaBurnConfig.test.js
@@ -3,7 +3,9 @@ import {
QUOTA_BURN_FAMILIES,
QUOTA_BURN_JOB_CATALOG,
QUOTA_BURN_JOB_TYPES,
+ QUOTA_BURN_UNLIMITED_DISPATCHES,
familyIsActionable,
+ isUnlimitedDispatchCap,
normalizeQuotaBurnConfig,
normalizeQuotaBurnJob,
} from './quotaBurnConfig.js';
@@ -40,6 +42,28 @@ describe('normalizeQuotaBurnConfig', () => {
expect(family).not.toHaveProperty('scope');
});
+ it('defaults the dispatch cap to unlimited', () => {
+ const config = normalizeQuotaBurnConfig({ families: { grok: { enabled: true } } });
+ expect(config.families.grok.maxDispatchesPerWindow).toBe(QUOTA_BURN_UNLIMITED_DISPATCHES);
+ expect(normalizeQuotaBurnConfig(undefined).families.claude.maxDispatchesPerWindow)
+ .toBe(QUOTA_BURN_UNLIMITED_DISPATCHES);
+ });
+
+ it('preserves the unlimited sentinel instead of clamping it up to the minimum', () => {
+ // The sentinel sits BELOW the field's own minimum, so the generic clamp
+ // would fold -1 to 1 and silently reinstate a cap of one burn per window.
+ const config = normalizeQuotaBurnConfig({
+ families: { grok: { enabled: true, maxDispatchesPerWindow: -1 }, codex: { maxDispatchesPerWindow: -99 } },
+ });
+ expect(config.families.grok.maxDispatchesPerWindow).toBe(-1);
+ expect(config.families.codex.maxDispatchesPerWindow).toBe(-1);
+ });
+
+ it('keeps a real cap the user set', () => {
+ const config = normalizeQuotaBurnConfig({ families: { grok: { maxDispatchesPerWindow: 3 } } });
+ expect(config.families.grok.maxDispatchesPerWindow).toBe(3);
+ });
+
it('clamps the check interval into the polling bounds', () => {
expect(normalizeQuotaBurnConfig({ checkIntervalMinutes: 1 }).checkIntervalMinutes).toBe(5);
expect(normalizeQuotaBurnConfig({ checkIntervalMinutes: 99999 }).checkIntervalMinutes).toBe(720);
@@ -80,6 +104,15 @@ describe('familyIsActionable', () => {
});
});
+describe('isUnlimitedDispatchCap', () => {
+ it('reads any negative cap as unlimited and a real cap as bounded', () => {
+ expect(isUnlimitedDispatchCap(QUOTA_BURN_UNLIMITED_DISPATCHES)).toBe(true);
+ expect(isUnlimitedDispatchCap(-5)).toBe(true);
+ expect(isUnlimitedDispatchCap(1)).toBe(false);
+ expect(isUnlimitedDispatchCap(50)).toBe(false);
+ });
+});
+
describe('QUOTA_BURN_JOB_CATALOG', () => {
it('describes exactly the registered job types', () => {
expect(QUOTA_BURN_JOB_CATALOG.map((entry) => entry.id).sort()).toEqual([...QUOTA_BURN_JOB_TYPES].sort());
diff --git a/server/lib/quotaBurnValidation.js b/server/lib/quotaBurnValidation.js
index 16fe539056..c853c437c2 100644
--- a/server/lib/quotaBurnValidation.js
+++ b/server/lib/quotaBurnValidation.js
@@ -14,7 +14,12 @@
*/
import { z } from 'zod';
-import { QUOTA_BURN_BOUNDS, QUOTA_BURN_FAMILIES, QUOTA_BURN_JOB_TYPES } from './quotaBurnConfig.js';
+import {
+ QUOTA_BURN_BOUNDS,
+ QUOTA_BURN_FAMILIES,
+ QUOTA_BURN_JOB_TYPES,
+ QUOTA_BURN_UNLIMITED_DISPATCHES,
+} from './quotaBurnConfig.js';
const B = QUOTA_BURN_BOUNDS;
@@ -38,7 +43,13 @@ const quotaBurnFamilySchema = z.object({
enabled: z.boolean().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(),
+ // The unlimited sentinel sits below the field's own minimum, so it is spelled
+ // as its own branch rather than by widening `min` — which would also let 0
+ // through, and 0 would read as "never burn" where the family switch belongs.
+ maxDispatchesPerWindow: z.union([
+ z.literal(QUOTA_BURN_UNLIMITED_DISPATCHES),
+ 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.
diff --git a/server/routes/quotaBurn.test.js b/server/routes/quotaBurn.test.js
index 8c3ddfdf6a..4865da97fa 100644
--- a/server/routes/quotaBurn.test.js
+++ b/server/routes/quotaBurn.test.js
@@ -87,6 +87,20 @@ describe('PUT /api/quota-burn', () => {
});
});
+ it('accepts the unlimited dispatch cap, which sits below the field\'s own minimum', async () => {
+ saveQuotaBurnConfig.mockResolvedValue({ enabled: true });
+ const res = await request(buildApp()).put('/api/quota-burn')
+ .send({ families: { grok: { maxDispatchesPerWindow: -1 } } });
+ expect(res.status).toBe(200);
+ });
+
+ it('rejects a dispatch cap of 0 — "never burn" is the family switch, not a cap', async () => {
+ const res = await request(buildApp()).put('/api/quota-burn')
+ .send({ families: { grok: { maxDispatchesPerWindow: 0 } } });
+ expect(res.status).toBe(400);
+ expect(saveQuotaBurnConfig).not.toHaveBeenCalled();
+ });
+
it('rejects an unknown family, an unknown job type, and an out-of-range interval', async () => {
const app = buildApp();
expect((await request(app).put('/api/quota-burn').send({ families: { nope: { enabled: true } } })).status).toBe(400);
diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.js
index f04ffeadc7..edd2a5ab81 100644
--- a/server/services/quotaBurn.js
+++ b/server/services/quotaBurn.js
@@ -20,7 +20,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 { familyIsActionable, isUnlimitedDispatchCap, normalizeQuotaBurnFamily } from '../lib/quotaBurnConfig.js';
import { isPlainObject } from '../lib/objects.js';
import { hoursUntilReset, normalizeResetAt } from '../lib/quotaReset.js';
import { classifyWindows, windowLabelOf } from '../lib/quotaWindows.js';
@@ -201,7 +201,10 @@ export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}
if (target.hours > family.resetWithinHours) {
return { skipReason: `resets in ${Math.ceil(target.hours)}h — outside the ${family.resetWithinHours}h window` };
}
- if (dispatchesUsed >= family.maxDispatchesPerWindow) {
+ // A cap of -1 (the default) opts out of counting entirely — the window is
+ // still bounded by `resetWithinHours`, the reserve, and provider refusals,
+ // all of which read live numbers rather than a tally.
+ if (!isUnlimitedDispatchCap(family.maxDispatchesPerWindow) && dispatchesUsed >= family.maxDispatchesPerWindow) {
return { skipReason: `dispatch cap reached (${dispatchesUsed}/${family.maxDispatchesPerWindow})` };
}
if (burnBudgetRemaining(tightest, family) <= 0) {
diff --git a/server/services/quotaBurn.test.js b/server/services/quotaBurn.test.js
index da29cc2a91..26b1259c1b 100644
--- a/server/services/quotaBurn.test.js
+++ b/server/services/quotaBurn.test.js
@@ -112,6 +112,18 @@ describe('evaluateFamilies', () => {
expect(reasonFor(family, [quota('grok', '2026-07-26T18:00:00.000Z')], { dispatches: { [selected.dispatchKey]: 2 } }))
.toBe('dispatch cap reached (2/2)');
});
+
+ it('never closes the cap gate when the cap is unlimited (the default)', () => {
+ // -1 means the tally is not consulted at all. The remaining gates — the
+ // reset horizon, the reserve, an observed refusal — still bound the spend,
+ // and they read live numbers rather than a count.
+ const uncapped = { ...family, maxDispatchesPerWindow: -1 };
+ const quotas = [quota('grok', '2026-07-26T18:00:00.000Z')];
+ const selected = selectBurnCandidates(quotas, { families: { grok: uncapped } }, { now: NOW })[0];
+ expect(reasonFor(uncapped, quotas, { dispatches: { [selected.dispatchKey]: 999 } })).toBeUndefined();
+ // …and the horizon still closes on the same plan.
+ expect(reasonFor(uncapped, [quota('grok', '2026-07-28T12:00:00.000Z')])).toMatch(/outside the 24h window/);
+ });
});
describe('selectBurnCandidates bypassGatesFor', () => {
diff --git a/server/services/quotaBurnJobs/agentPrompt.js b/server/services/quotaBurnJobs/agentPrompt.js
index cd286aaec1..3d9fb95066 100644
--- a/server/services/quotaBurnJobs/agentPrompt.js
+++ b/server/services/quotaBurnJobs/agentPrompt.js
@@ -15,7 +15,7 @@ import { addTask } from '../cosTaskStore.js';
import { getAppById } from '../apps.js';
import { getAllProviders } from '../providers.js';
import { commandBasename } from '../../lib/providerModels.js';
-import { burnTaskDescription } from '../../lib/quotaBurnConfig.js';
+import { burnTaskDescription, isUnlimitedDispatchCap } from '../../lib/quotaBurnConfig.js';
import { windowLabelOf } from '../../lib/quotaWindows.js';
/**
@@ -115,7 +115,7 @@ export function renderBurnPrompt({ family, candidate, prompt }) {
...(showsLimiting
? [`Shorter window in play: ${windowLabelOf(limiting)} at ${limiting.percentRemaining}% remaining — it is what will refuse this run if it empties.`]
: []),
- `Dispatch cap: ${family.maxDispatchesPerWindow} for this reset window.`,
+ `Dispatch cap: ${isUnlimitedDispatchCap(family.maxDispatchesPerWindow) ? 'unlimited' : family.maxDispatchesPerWindow} for this reset window.`,
'',
'Carry out the configured work below. Do not use another provider family as a substitute.',
'',
diff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.js
index 7b59b583e8..ed6bbbf11b 100644
--- a/server/services/quotaBurnRunner.js
+++ b/server/services/quotaBurnRunner.js
@@ -176,10 +176,10 @@ export async function runQuotaBurnCycle(options = {}) {
/**
* Run the continuations that arrived while a cycle was in flight, one at a time.
*
- * Bounded by the same ledger every other dispatch charges: a drained family gets
- * one cycle, which the gate ladder can decline. A completion that lands DURING
- * the drain re-enters the set legitimately — it is a different agent finishing —
- * and is likewise bounded by `maxDispatchesPerWindow`. Errors are swallowed here
+ * Bounded by the same gate ladder every other dispatch faces: a drained family
+ * gets one cycle, which the reserve or the reset horizon can decline. A
+ * completion that lands DURING the drain re-enters the set legitimately — it is
+ * a different agent finishing — and faces that ladder too. Errors are swallowed here
* rather than allowed to replace the outer cycle's result: this runs from the
* caller's `finally`, so a throw would mask what that cycle actually decided.
*/
@@ -437,15 +437,18 @@ async function lastScheduledRunAt() {
* NEXT job in the plan goes out.
*
* Without this the plan advances only once per `checkIntervalMinutes` — at the
- * 12-hour default, two dispatches a day against a `maxDispatchesPerWindow` of 5
- * on a window that resets every 5 hours, so most of the allowance the feature
- * exists to spend expired unspent. Completion is the right pacing signal: it
- * runs the plan strictly one agent at a time and asks the gate ladder, every
- * time, whether there is still quota to spend.
+ * 12-hour default, two dispatches a day against a window that resets every 5
+ * hours, so most of the allowance the feature exists to spend expired unspent.
+ * Completion is the right pacing signal: it runs the plan strictly one agent at
+ * a time and asks the gate ladder, every time, whether there is still quota to
+ * spend.
*
- * It cannot run away. Every continuation dispatch is charged to the window's
- * ledger, so `maxDispatchesPerWindow` bounds the chain, and the reserve /
- * reset-horizon gates close it earlier when the quota actually runs out.
+ * It cannot run away. The chain is serial by construction — the next dispatch
+ * needs an agent to finish first — and every link re-reads the family's live
+ * quota, so the reserve, the reset horizon, and an observed provider refusal
+ * each close it as soon as the numbers say to. A `maxDispatchesPerWindow` other
+ * than the unlimited default bounds it earlier still, from the same ledger every
+ * continuation dispatch is charged to.
*/
function onBurnAgentCompleted(agent) {
const familyId = agent?.metadata?.taskQuotaBurnFamily;