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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
quota-burn: target the weekly window, not the 5-hour one, and stop on a refusal
[._.]/ Adam Eivyc70d9d4ee8ad
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0500a00209..09b4421253 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -27,6 +27,9 @@## Fixed- **Quota-burn tasks were queued and then never picked up, so the window they were meant to spend expired unspent anyway.** Three separate faults, each of which alone was enough to strand a burn. First, a queued burn inherited the per-app *review cooldown* — a 30-minute throttle re-stamped by every task that completes on that app. On an app that carries any other recurring CoS work (a perpetual claim-issue drain, which is itself exempt from the cooldown and therefore keeps completing) the cooldown never lapses, so the burn task sat in Pending indefinitely while agents ran past it. The cooldown was never this task's throttle: the burn plan's own gate ladder — the reset horizon, the family's reserve, and `maxDispatchesPerWindow` — is checked before the task is queued at all, so burns now bypass it, as pipeline continuations and perpetual drains already did. Tasks already queued carry no marker, so migration 225 back-fills it onto them rather than leaving them stranded — and a stranded burn is worse than late, because `addTask` dedupes on description + app, so a pending twin makes the runner report "an identical burn task is already pending" and that job in the plan is permanently unreachable. Second, the runner always walked the family's job plan from the top, and an `agent-prompt` job always probes as "work pending" (its probe only checks that an app and a provider resolve) — so job #1 won every dispatch forever and the other seven audits in an eight-job plan never ran once. The walk now resumes after the family's last dispatch, read from the run log rather than a second cursor file, and still runs the first job with pending work from there, so a probing job like `universe-bible-images` keeps its ordering. Third, the plan only advanced once per `checkIntervalMinutes` — at the 12-hour default, two dispatches a day against an allowance of five on a five-hour window. Each finished burn agent now re-evaluates its own family, so the plan is walked one agent at a time until a gate actually closes; the chain is bounded by the same ledger every other cycle charges, and switching the feature off ends it immediately. That re-evaluation reads only the burning family's quota card rather than respawning every enabled provider's TUI for numbers it then discards — a per-family scrape the usage page already asked for this way.+- **Quota Burn was watching the 5-hour window and calling it the weekly one, so its one real gate never gated anything — and it kept dispatching after the provider started refusing.** Every subscription family publishes two windows on the same card: a short rolling one (claude/codex `session` ≈ 5h, antigravity `5-hour`) and a long one (`week`, `month`). Selection picked "the soonest-resetting window", and the short one is nearly always the soonest — so a plan written against a weekly allowance showed "62% left · resets in 3h" on its card, `resetWithinHours: 24` was satisfied by a horizon that re-opened every five hours (making "only spend as the window is about to expire" bound nothing at all), and `maxDispatchesPerWindow: 5` silently meant *five burns every five hours* rather than five per week, because the dispatch ledger keyed on the short window's reset. A family now burns against its **target** window — the broadest one in scope, classified by period in the new `server/lib/quotaWindows.js` — and the card names which window its percentage and countdown describe, so the two can never be confused again. The **limiting** window (the narrowest) and the **tightest** window (least headroom, what `reservePercent` already guarded) stay separate concepts, because they answer different questions; the per-family Window scope field still pins the target explicitly for anyone who wants the old behavior. A provider whose window vocabulary this can't classify falls back to soonest-reset ordering rather than parking.++ Which exposed the second half: what actually *stops* a burn is the short window emptying underneath it. Spending a weekly allowance runs task after task until the 5-hour window is gone, at which point every further dispatch fails instantly, wastes an agent spawn and leaves a red card in the CoS queue — while the weekly card the runner gates on still reads "60% left, resets in 2 days", so nothing in the reported numbers ever says stop. That got sharper, not milder, once each finished burn agent started dispatching the next one immediately: the chain now walks straight into the wall at agent speed instead of interval speed. A refusal is therefore recorded as a fact rather than inferred from a meter — and recorded *inside* the completion continuation, awaited before it re-evaluates the family, because a block written after that dispatch (or from a second `agent:completed` subscriber, whose ordering against the continuation is not guaranteed) arrives one wasted agent too late every single time. The family is blocked until the reset the provider stated in its own refusal, else the reset of its limiting window, else a bounded 5-hour TTL so a reset-less block can't hold forever; a burn that *succeeds* clears it immediately, the provider serving being more current evidence than any stated reset. Four deliberate narrowings: only agents the burn plan itself dispatched count (the limiting window's reset rides on the task beside the `quotaBurnFamily` the cooldown exemption and the continuation already read, rather than inventing a second provenance shape); a transient `429` is a retry and not a spent window, so it does not block; an analyzer "usage-limit" verdict is trusted only when it came from a structured provider marker, not a loose keyword sweep over an agent narrating a prompt that happens to be *about* quota handling; and the block is bypassable by the ▶ forced run, which is how a user retries one they believe is stale. A ledger that can't be read is never overwritten and never silently reads as "nothing blocked", and the reset-out-of-refusal-text parsing is now one shared `parseObservedReset` rather than a second copy of what the image-gen quota ledger already did.- **Two agents working a swarm run could overwrite each other's pull-request descriptions.** Every agent in a swarm shares one scratch directory and — by design — runs byte-identical instructions, so when two of them reached the "write the PR description to a file" step they independently picked the same obvious filename and the second quietly overwrote the first. The failure was invisible: nothing errored, the text was well-formed, and it only surfaced minutes later when the first agent re-published its now-replaced description onto its own PR. Swarm runs now hand each agent its own scratch subdirectory named for the issue it's working, so no two agents can collide on a filename, and each agent re-reads its published description after creating or editing it to confirm the right one landed. Single-issue runs are unchanged.diff --git a/client/src/components/quotaBurn/FamilyCard.jsx b/client/src/components/quotaBurn/FamilyCard.jsxindex 7831a789da..5c8cd06ff6 100644--- a/client/src/components/quotaBurn/FamilyCard.jsx+++ b/client/src/components/quotaBurn/FamilyCard.jsx@@ -7,11 +7,12 @@* runner evaluates, so the card can't disagree with what actually happens.*/-import { ChevronDown, ChevronRight, Flame, Plus } from 'lucide-react';+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 { formatDateTime } from '../../utils/formatters';import { NumberField, TextField } from './fields';export default function FamilyCard({@@ -92,14 +93,29 @@ export default function FamilyCard({<BrailleSpinner /> reading quota…</span>) : status?.willBurn ? (+ /* The window is NAMED, not just measured: a family publishes a short+ rolling window and a weekly one, and "62% left · resets in 30h" is+ unreadable without knowing which allowance it describes. */<span className="inline-flex items-center gap-1 text-xs text-emerald-400"><Flame size={13} />- {status.percentRemaining}% left · resets in {status.hoursUntilReset}h · {status.dispatchesUsed}/{config.maxDispatchesPerWindow} used+ {status.windowLabel ? `${status.windowLabel}: ` : ''}{status.percentRemaining}% left · resets in {status.hoursUntilReset}h · {status.dispatchesUsed}/{config.maxDispatchesPerWindow} used</span>) : (<span className="text-xs text-gray-500">{status?.skipReason || 'not evaluated yet'}</span>)}+ {/* An observed refusal, shown even when some other gate is the one+ reported — "the provider said no" is the actionable fact, and it+ explains a family that looks healthy on paper but never burns. The+ server's skip reason deliberately omits the instant so this badge+ owns it, in the app's shared timestamp format. */}+ {status?.blockedUntil && (+ <span className="inline-flex items-center gap-1 text-xs text-amber-400" title={status.blockedReason || 'The provider refused the last burn.'}>+ <Ban size={13} />+ provider refused — retrying after {formatDateTime(status.blockedUntil)}+ </span>+ )}+{/* A collapsed card otherwise says nothing about whether this family hasa plan at all — and a family with zero enabled jobs can never burn,no matter how healthy its window looks. */}@@ -133,7 +149,7 @@ 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 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}-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}-priority`} label="Priority" value={config.priority} onChange={(v) => onPatch({ priority: v })} min={0} max={100} hint="Lower wins when two windows reset together." />@@ -141,7 +157,7 @@ export default function FamilyCard({<div className="grid grid-cols-1 sm:grid-cols-2 gap-3"><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" />+ <TextField id={`burn-${familyId}-scope`} label="Window scope (optional)" value={config.scope} onChange={(v) => onPatch({ scope: v })} placeholder="e.g. week — blank targets the broadest window" /></div><div className="space-y-3">diff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsxindex 4492198b9d..2c86ac793e 100644--- a/client/src/pages/QuotaBurn.test.jsx+++ b/client/src/pages/QuotaBurn.test.jsx@@ -30,7 +30,7 @@ const config = {const status = {enabled: false, checkIntervalMinutes: 30, running: false, lastRunAt: null,families: [- { id: 'grok', label: 'Grok', willBurn: true, percentRemaining: 62, hoursUntilReset: 2.4, dispatchesUsed: 1, skipReason: null, jobs: [{ id: 'j1', pending: { count: 4, detail: '4 bible entries have no image' } }] },+ { id: 'grok', label: 'Grok', willBurn: true, percentRemaining: 62, hoursUntilReset: 2.4, windowLabel: 'Weekly', dispatchesUsed: 1, skipReason: null, blockedUntil: null, blockedReason: null, jobs: [{ id: 'j1', pending: { count: 4, detail: '4 bible entries have no image' } }] },{ id: 'codex', label: 'Codex', willBurn: false, skipReason: 'disabled', jobs: [] },],runs: [{ at: new Date().toISOString(), trigger: 'scheduled', dispatched: false, reason: 'no burnable window' }],@@ -113,6 +113,29 @@ describe('QuotaBurn page', () => {expect(screen.queryByText(/reading quota…/)).not.toBeInTheDocument();});+ it('names WHICH window the reading describes', async () => {+ // A family publishes a short rolling window and a weekly one. "62% left ·+ // resets in 2.4h" is unreadable without knowing which allowance it is —+ // the ambiguity that hid the wrong window being selected server-side.+ renderPage();+ expect(await screen.findByText(/Weekly: 62% left/)).toBeInTheDocument();+ });++ 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.+ const blocked = {+ ...status,+ families: [+ { ...status.families[0], willBurn: false, skipReason: 'provider refused the last burn', blockedUntil: '2026-07-26T18:00:00.000Z', blockedReason: 'Usage limit exceeded' },+ status.families[1],+ ],+ };+ api.getQuotaBurn.mockResolvedValueOnce({ config, status: blocked });+ renderPage();+ expect(await screen.findByText(/provider refused — retrying after/)).toBeInTheDocument();+ });+it('does NOT poll when nothing is pending', async () => {renderPage();await screen.findByText(/62% left/);diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.mdindex 6cfaadb9aa..9d42fb6b96 100644--- a/docs/QUOTA-BURN.md+++ b/docs/QUOTA-BURN.md@@ -14,9 +14,11 @@ Every `checkIntervalMinutes` (default 30, bounded 5–720) the runner:1. Reads the plan from `data/cos/quota-burn.json`. If the master switch is off itstops here — **no provider is contacted**.2. Takes a zero-token quota reading for every enabled provider family.-3. Selects families whose soonest window is inside `resetWithinHours`, still has- headroom above `reservePercent`, and has not spent `maxDispatchesPerWindow`- for that window. Ties break on `priority` (lower wins).+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 in scope, and that have+ not spent `maxDispatchesPerWindow` for that window. Ties break on `priority`+ (lower wins).4. Runs the **first enabled job in that family's ordered plan that reportspending work** — at most one dispatch per cycle.5. Charges the window in `data/cos/quota-burn-dispatches.json` and appends the@@ -26,6 +28,70 @@ Everything fails closed: an unknown reset time, an unsupported provider, aquota-read error, a card that declares itself unburnable (`burnable: false`, e.g.the Image Gen card), or a family with no enabled jobs all mean "do not dispatch".+## Which window a family burns against++Every subscription family publishes **two** windows on the same card — a short+rolling one (claude/codex `session` ≈ 5h, antigravity `5-hour`) and a long one+(`week`, `month`). They answer different questions, and quota-burn reads both:++| | Which window | What it is used for |+| --- | --- | --- |+| **Target** | The **broadest** window in scope (usually weekly) | The allowance that expires unused. Its reset is the deadline `resetWithinHours` measures, its percentage and countdown are what the family card shows, and its reset epoch is the key `maxDispatchesPerWindow` counts against — so the cap means "per weekly window". |+| **Limiting** | The **narrowest** window in scope (usually 5-hour) | What actually refuses a run. It is the horizon a denial backs off to, and it is named in the burn prompt so the agent understands a mid-run refusal. |+| **Tightest** | Whichever window in scope has the least headroom | What `reservePercent` guards, so a full session window can't be used to justify draining a nearly-empty weekly one. |++Selecting the *soonest-resetting* window instead conflated target with limiting:+the 5-hour window is nearly always the soonest, so the page reported "resets in+3h" for a plan written against a weekly allowance, `resetWithinHours` re-opened+every five hours (so "only spend as the window is about to expire" bounded+nothing), and the dispatch cap meant "N burns every 5 hours".++Periods are classified in `server/lib/quotaWindows.js` from the `scope`/`label`+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 per-family **Window+scope** field still filters: set it to `week` to pin the target explicitly, or to+`session` to deliberately burn against the short window.++## Stop condition: an observed refusal++Reported numbers are stale by design (scraped every few minutes, rounded to whole+percent) and they describe the *target* window. What actually stops a burn is the+short window emptying underneath it: a plan spending a weekly allowance runs task+after task until the 5-hour window is gone, at which point every further dispatch+fails instantly, wastes an agent spawn, and leaves a red card in the CoS queue —+while the weekly card still reads "60% left, resets in 2 days".++So a refusal is recorded as a fact. When an agent a burn dispatched dies with a+usage-limit failure, `server/services/quotaBurnDenials.js` blocks that family in+`data/cos/quota-burn-denials.json` and `evaluateFamily` reports it as the gate:++- **Recorded inside the completion continuation, before it dispatches.** The+ runner's `onBurnAgentCompleted` awaits `recordBurnAgentCompletion` and only+ then re-evaluates the family. That ordering is load-bearing: the continuation+ sends the next job out the moment a burn agent finishes, so a block recorded+ after it — or from a second `agent:completed` subscriber, whose ordering+ against the continuation is not guaranteed — arrives one wasted agent too late,+ every time. A ledger failure degrades to a logged warning; telemetry never+ stalls the plan.+- **Until when** — the reset the provider stated in its own refusal, else the+ reset of the family's limiting (short) window, else a 5-hour TTL so a+ reset-less block can't hold forever.+- **Cleared** the moment a burn run for that family *succeeds* — the provider+ serving is more current evidence than any stated reset.+- **Only burn-dispatched agents count.** The family and the limiting window's+ reset ride on the task as `metadata.quotaBurnFamily` /+ `metadata.quotaBurnLimitingResetAt` (the same provenance the cooldown exemption+ and the continuation already read); an unrelated task that happens to hit a+ usage limit says nothing about the burn plan.+- **Narrower than a generic rate limit.** A transient `429` is a retry, not a+ spent window — blocking a family for hours over one would be worse than missing+ a burn. An analyzer `usage-limit` verdict is trusted only when it came from a+ structured provider marker, not a loose keyword sweep over the agent's own+ narration.+- **Bypassable by a forced run** (the ▶ on a job row), which is how a user+ retries a block they believe is stale.+## Burn jobsA family's plan is an **ordered list** — that ordering is the configuration ("do@@ -129,7 +195,7 @@ request), and the catalog descriptors the client renders as `min`/`max`.## Storage-Four files under `data/cos/`, all machine-local and intentionally **not federated**: the plan (`quota-burn.json`), the per-window dispatch ledger (`quota-burn-dispatches.json`), the run log (`quota-burn-runs.json`), and the in-flight set (`quota-burn-inflight.json` — entries a job enqueued whose renders have not landed yet, so the next cycle does not re-queue them; 6-hour TTL). They are not federated: quota belongs to a+Five files under `data/cos/`, all machine-local and intentionally **not federated**: the plan (`quota-burn.json`), the per-window dispatch ledger (`quota-burn-dispatches.json`), the run log (`quota-burn-runs.json`), the in-flight set (`quota-burn-inflight.json` — entries a job enqueued whose renders have not landed yet, so the next cycle does not re-queue them; 6-hour TTL), and the denial ledger (`quota-burn-denials.json` — per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL). They are not federated: quota belongs to aparticular machine and provider account, and the "which managed app" targetsdiffer per machine.@@ -148,8 +214,10 @@ 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/lib/quotaBurnPresets.js` | Ready-made single-focus audit prompts for `agent-prompt` jobs |+| `server/lib/quotaWindows.js` | Classifies a window by period — target (broadest) vs limiting (narrowest) || `server/services/quotaBurnStore.js` | `data/cos/quota-burn.json` + the run log || `server/services/quotaBurn.js` | `evaluateFamily` — the one gate ladder both selection and the page's skip reasons read — plus the dispatch ledger |+| `server/services/quotaBurnDenials.js` | The observed-refusal ledger and its `agent:completed` subscriber || `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/docs/STORAGE.md b/docs/STORAGE.mdindex 71ca04cf6f..e24f6ec4bb 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -56,7 +56,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- MortalLoom / Health / Meatspace health data — `data/health`, `data/meatspace`, MortalLoom iCloud store. Kept file-backed to preserve iCloud/file sync and avoid routing sensitive health records through the app DB before that boundary is designed.- App scaffolds / cloned repos / browser profiles — `data/repos`, `data/browser-profile` — inherently filesystem-oriented.- Sprite animation-track definitions — `data/sprites/animation-tracks.json` (#3152). A small hand-editable authoring config: which animation types exist beyond the compiled-in `walk` (label, directionality, frame/fps bounds, prompt template, and the on-disk `setKind` strings). `file-primary` rather than `db-primary` because it is **machine-local and inseparable from the on-disk sprite tree it describes** — a row names the `setKind` an approved set under `data/sprites/{id}/` already carries, so the two travel together or neither means anything — and because it has no cross-record queries, no relationships beyond `kinds` strings, and no sync cursor. Read synchronously and cached per process (`server/services/sprites/animationTrackStore.js`): `server/lib/validation.js` builds sprite Zod ranges from it at module load, so it must resolve without `await`. Seeded from `data.reference/sprites/animation-tracks.json` (migration 211), which is also the fallback read when no user copy exists yet. Backed up in full by the rsync snapshot.-- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + ordered job list. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and the plan's `agent-prompt` jobs name managed apps that only exist on this machine. No sync cursor, no tombstone. Its three companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), and `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).+- Quota-burn plan — `data/cos/quota-burn.json` (#3390). The install's burn plan: master switch, poll interval, and per-provider-family windows + ordered job list. `file-primary` and **intentionally machine-local — never federated**: quota belongs to a particular machine and provider account, so a synced plan would have each peer spending against the other's window budget, and the plan's `agent-prompt` jobs name managed apps that only exist on this machine. No sync cursor, no tombstone. Its four companions are `ephemeral-file` — regenerable telemetry, all safe to delete: `data/cos/quota-burn-dispatches.json` (per-window dispatch counts, self-pruning at 30 days), `data/cos/quota-burn-runs.json` (capped run log), `data/cos/quota-burn-inflight.json` (entries a burn job has enqueued but whose renders have not completed, self-pruning at 6 hours — deleting it only risks re-queueing a render already in flight), and `data/cos/quota-burn-denials.json` (per-family blocks from an observed provider refusal, cleared by the next successful burn or a 5-hour TTL — deleting it only risks one dispatch into a still-exhausted window). Backed up with the rest of `data/cos/`; a restored plan simply re-applies on this machine. See [Quota Burn](./QUOTA-BURN.md).- LoRA training datasets — `data/lora-datasets/{id}/index.json` + `images/*.png` (collectionStore). The record is inseparable from the image bytes it organizes, has no cross-record queries beyond a small characterId scan, and is **machine-local** like `data/loras/` itself (training artifacts tied to this machine's GPU output — never federates, no sync cursor/tombstone). Backed up in full: uploads and hand-edited captions are not re-creatable. Training RUN records are `db-primary` (`lora_training_runs`); run artifacts (checkpoints/samples) live under `data/training-runs/{runId}/` with checkpoints/cache excluded from backup.---diff --git a/server/lib/README.md b/server/lib/README.mdindex dbdc68a650..0b5de229b9 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -30,7 +30,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225. Pure — no storage, no provider I/O. || `quotaBurnPresets.js` | `QUOTA_BURN_PROMPT_PRESETS` — ready-made single-focus audit prompts for `agent-prompt` burn jobs (UX, a11y, mobile, failure paths, perf, test gaps, dead code, data safety, docs, security), each filing GitHub issues and changing no code. Templates: picking one COPIES its prompt into the job, so editing them never rewrites a configured job. `findQuotaBurnPreset(id)`. || `quotaBurnValidation.js` | Zod schemas for the Quota Burn routes (partial config PUT, manual-run body). |-| `quotaReset.js` | `parseHumanReset` turns a provider CLI's human reset string into ISO 8601 (call it from the adapter); `normalizeResetAt`/`hoursUntilReset` compute time remaining without treating unknown values as imminent resets. |+| `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. |+| `quotaWindows.js` | Classifies a quota window by PERIOD (`windowPeriodHours`); `classifyWindows` splits one card's windows into the weekly allowance that expires unused and the 5-hour one that refuses first, in one pass. `windowLabelOf` names a window. Pure. || `appleHealthValidation.js` | Apple Health import payloads. || `brainValidation.js` | Brain/memory route schemas (search, ingest, edit). || `catalogValidation.js` | Creative ingredients catalog route schemas (scraps, ingredients, links, relations, tags, revisions, sync envelope). |diff --git a/server/lib/index.js b/server/lib/index.jsindex f0cc44b4e8..02ad2f8ad4 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -116,6 +116,7 @@ export * from './quotaBurnConfig.js';export * from './quotaBurnPresets.js';export * from './quotaBurnValidation.js';export * from './quotaReset.js';+export * from './quotaWindows.js';export * from './opencodeConfig.js';// `runners.js` re-defines `isFlux2`/`isZImage`/`isErnie` that also live in// mediaModels.js — namespace it so the barrel surface is unambiguous.diff --git a/server/lib/quotaReset.js b/server/lib/quotaReset.jsindex 4810bea000..70d29427a8 100644--- a/server/lib/quotaReset.js+++ b/server/lib/quotaReset.js@@ -149,3 +149,65 @@ export function hoursUntilReset(limit, opts = {}) {const { epochMs } = normalizeResetAt(limit, opts);return epochMs === null ? null : (epochMs - (opts.now ?? Date.now())) / HOUR_MS;}++/**+ * Parse an absolute ISO instant out of free-form provider text.+ * Antigravity phrases it as `(around 2026-07-31T21:38:09Z)`. Pure.+ */+const parseAbsoluteObservedReset = (text, now) => {+ const match = text.match(/(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)/);+ if (!match) return null;+ const at = new Date(match[1]).getTime();+ // Narration also carries log lines and session stamps. A timestamp in the+ // past is not a reset time — accepting one would set a block to an+ // already-elapsed instant, which reads as "not blocked" downstream.+ return Number.isNaN(at) || at <= now ? null : at;+};++/**+ * Parse a relative reset window (`quota will reset in approximately 5 hours`,+ * `try again in 30 minutes`) into an absolute epoch ms. Pure given `now`.+ */+const parseRelativeObservedReset = (text, now) => {+ const match = text.match(/(?:reset|retry|try again|available)\b[^.]{0,40}?\bin\s+(?:approximately\s+|about\s+|~\s*)?(\d+(?:\.\d+)?)\s*(second|minute|hour|day)s?/i);+ if (!match) return null;+ const unitMs = { second: 1000, minute: 60_000, hour: 3_600_000, day: 86_400_000 }[match[2].toLowerCase()];+ return now + Number(match[1]) * unitMs;+};++/**+ * The reset instant a provider stated in its own refusal text, as epoch ms —+ * null when it stated none we can read.+ *+ * This is the OBSERVED half of quota state: a refusal is the only quota signal+ * some backends emit at all (see `imageGenQuota.js`), and it is what tells a+ * quota burn how long to back off after a CLI denied it (`quotaBurnDenials.js`).+ * Absolute wins over relative — a provider that states both ("in ~5 hours+ * (around <ISO>)") is more precise in the parenthetical, and the absolute form+ * survives a slow error path. Both reject an instant that is not in the future.+ *+ * Pure given `now`.+ */+export function parseObservedReset(text, { now = Date.now() } = {}) {+ const raw = typeof text === 'string' ? text : '';+ if (!raw.trim()) return null;+ return parseAbsoluteObservedReset(raw, now) ?? parseRelativeObservedReset(raw, now);+}++/**+ * Is a block recorded from an observed refusal still holding?+ *+ * `at` is what marks it blocked; `until` only says WHEN it lifts and is+ * legitimately unknown (a refusal need not state a reset). Keying "blocked" off+ * `until` alone collapses "blocked, reset unknown" into "not blocked" — so an+ * unknown reset holds for a bounded `ttlMs` instead, since nothing forces a+ * later attempt to happen and prove the provider is serving again.+ *+ * Shared by every observed-refusal ledger (`imageGenQuota.js`,+ * `quotaBurnDenials.js`); each supplies its own TTL, but the predicate — and the+ * reason `until`-alone is wrong — lives once. Pure.+ */+export function isObservedBlockActive({ at, until } = {}, { now = Date.now(), ttlMs } = {}) {+ if (!at) return false;+ return until ? until > now : now - at < ttlMs;+}diff --git a/server/lib/quotaWindows.js b/server/lib/quotaWindows.jsnew file mode 100644index 0000000000..f1d33e7603--- /dev/null+++ b/server/lib/quotaWindows.js@@ -0,0 +1,137 @@+/**+ * Classify a provider quota window by its PERIOD — how long the allowance it+ * meters lasts before it refills.+ *+ * Every subscription CLI reports at least two windows on the same card: a short+ * rolling one (claude/codex `session` ≈ 5h, antigravity `5-hour`) and a long one+ * (`week`, `month`). They answer different questions, and quota-burn needs both:+ *+ * - The LONG window is the allowance that expires unused — it is what "burn+ * the quota before it resets" is about, and its reset is the deadline the+ * user cares about.+ * - The SHORT window is what actually refuses a request. Exhausting it stops+ * work for a few hours even though the weekly allowance is untouched.+ *+ * Selecting "the soonest-resetting window" conflated the two: the 5-hour window+ * is almost always the soonest, so the Quota Burn page reported a reset a few+ * hours out when the weekly reset the plan was written against was days away,+ * and `resetWithinHours` gated on a horizon that re-opened every 5 hours.+ *+ * Pure module — no I/O, no provider knowledge beyond the vocabulary the adapters+ * in `providerUsage.js` already emit (`scope`, `label`, and the optional+ * `periodHours` a provider that states its window length exactly can supply).+ */++/**+ * Window periods, in hours, for the scope/label words the adapters emit.+ * Deliberately only the vocabulary that ships: anything else falls to the+ * documented `null` → soonest-reset fallback rather than being guessed at.+ */+const PERIOD_WORDS = Object.freeze([+ [/\bsession\b/i, 5],+ [/\b(?:day|daily)\b/i, 24],+ [/\b(?:week|weekly)\b/i, 7 * 24],+ [/\b(?:month|monthly)\b/i, 30 * 24],+]);++/**+ * `5-hour`, `5h window`, `2 days`, `45m window` → hours. Mirrors the shapes+ * `humanizeWindowMinutes` in `providerUsage.js` renders.+ */+const PERIOD_UNITS = Object.freeze([+ [/(\d+(?:\.\d+)?)\s*-?\s*(?:h|hr|hrs|hour|hours)\b/i, 1],+ [/(\d+(?:\.\d+)?)\s*-?\s*(?:d|day|days)\b/i, 24],+ [/(\d+(?:\.\d+)?)\s*-?\s*(?:m|min|mins|minute|minutes)\b/i, 1 / 60],+]);++function periodFromText(text) {+ if (typeof text !== 'string' || !text) return null;+ // Units before words: `5-hour` must read as 5, and a `Weekly` label with no+ // digits falls through to the word map.+ for (const [pattern, factor] of PERIOD_UNITS) {+ const match = text.match(pattern);+ if (match) {+ const hours = Number(match[1]) * factor;+ if (Number.isFinite(hours) && hours > 0) return hours;+ }+ }+ for (const [pattern, hours] of PERIOD_WORDS) {+ if (pattern.test(text)) return hours;+ }+ return null;+}++/**+ * How long this window's allowance lasts, in hours — or null when the limit+ * says nothing we can read.+ *+ * Null is a real answer, not zero: a window whose period we cannot classify must+ * not be ranked as the narrowest (which would make it the thing a denial backs+ * off to) NOR as the broadest (which would make it the burn deadline). Unknowns+ * are ranked last, and a set where every window is unknown falls back to+ * reset-time ordering.+ *+ * `periodHours` on the limit wins — codex's telemetry states `window_minutes`+ * exactly, and a plan with a 7-hour primary window must not be read as 5 just+ * because the adapter calls it a session.+ */+export function windowPeriodHours(limit) {+ const stated = Number(limit?.periodHours);+ if (Number.isFinite(stated) && stated > 0) return stated;+ return periodFromText(limit?.scope) ?? periodFromText(limit?.label);+}++/** How a window is named wherever one is reported to a human or an agent. */+export const windowLabelOf = (limit) => limit?.label || limit?.scope || 'window';++/**+ * Split one card's in-scope windows into the two roles a burn reasons about, in+ * a single scoring pass:+ *+ * `target` — `{ limit, hours }` for the BROADEST window that states a+ * readable reset: the allowance that expires unused. Its reset is+ * the deadline, and its epoch is what the dispatch cap keys on.+ * Ties break on the soonest reset. Null when no window in scope+ * states a reset at all.+ * `limiting` — the NARROWEST window: what refuses first. Exhausting a 5-hour+ * window stops every dispatch for hours while the weekly allowance+ * the plan targets is still mostly unspent, so it is the horizon a+ * denial backs off to. Null when nothing states a period — an+ * unknown period cannot be asserted to be the narrowest, and+ * picking one would set a backoff to the wrong clock.+ *+ * `hoursUntil` maps a limit to hours-until-reset (null when unreadable), so this+ * module stays free of date parsing. Computed once per limit rather than by each+ * role, since parsing a reset is the expensive half.+ */+export function classifyWindows(limits, hoursUntil) {+ const scored = (limits || []).map((limit) => ({+ limit,+ period: windowPeriodHours(limit),+ hours: hoursUntil(limit),+ }));++ const datable = scored.filter((entry) => entry.hours !== null);+ const known = datable.filter((entry) => entry.period !== null);+ // A set where nothing states a classifiable period keeps the pre-#3390+ // behavior — soonest reset first — which is still the best available answer+ // for a provider whose vocabulary this module doesn't know.+ const pool = known.length ? known : datable;+ const target = pool.length+ ? pool.reduce((best, entry) => {+ const broader = (entry.period ?? 0) - (best.period ?? 0);+ if (broader !== 0) return broader > 0 ? entry : best;+ return entry.hours < best.hours ? entry : best;+ })+ : null;++ // Not restricted to windows with a readable reset: a limiting window with no+ // stated reset still can't be the target, and excluding it here would promote+ // a broader one into the "what refuses first" role.+ const periodic = scored.filter((entry) => entry.period !== null);+ const limiting = periodic.length+ ? periodic.reduce((narrowest, entry) => (entry.period < narrowest.period ? entry : narrowest)).limit+ : null;++ return { target: target && { limit: target.limit, hours: target.hours }, limiting };+}diff --git a/server/lib/quotaWindows.test.js b/server/lib/quotaWindows.test.jsnew file mode 100644index 0000000000..1e7dcda3a6--- /dev/null+++ b/server/lib/quotaWindows.test.js@@ -0,0 +1,113 @@+import { describe, expect, it } from 'vitest';+import { classifyWindows, windowLabelOf, windowPeriodHours } from './quotaWindows.js';++// The scope/label vocabulary the four in-tree adapters actually emit — the point+// of the classifier is that each of these resolves, so a real card is never+// ranked by "unknown period".+describe('windowPeriodHours', () => {+ it('classifies every shape the providerUsage adapters emit', () => {+ expect(windowPeriodHours({ scope: 'session', label: 'Current session' })).toBe(5);+ expect(windowPeriodHours({ scope: 'week', label: 'Current week (all models)' })).toBe(168);+ expect(windowPeriodHours({ scope: 'week', label: 'Current week (Opus)' })).toBe(168);+ expect(windowPeriodHours({ scope: '5-hour', label: 'Gemini · 5-hour' })).toBe(5);+ expect(windowPeriodHours({ scope: 'weekly', label: 'Gemini · Weekly' })).toBe(168);+ expect(windowPeriodHours({ scope: 'month', label: 'Monthly' })).toBe(720);+ });++ it('prefers a stated periodHours over the scope word', () => {+ // Codex's telemetry states window_minutes exactly. A plan whose primary+ // window is 7h must not be read as the 5h `session` default.+ expect(windowPeriodHours({ scope: 'session', periodHours: 7 })).toBe(7);+ // Zero / negative / non-numeric are not statements — fall through.+ expect(windowPeriodHours({ scope: 'session', periodHours: 0 })).toBe(5);+ expect(windowPeriodHours({ scope: 'week', periodHours: 'soon' })).toBe(168);+ });++ it('reads a numeric unit out of a label before any keyword', () => {+ expect(windowPeriodHours({ label: 'Current 5h window' })).toBe(5);+ expect(windowPeriodHours({ label: 'Current 2 days' })).toBe(48);+ expect(windowPeriodHours({ label: 'Current 45m window' })).toBeCloseTo(0.75, 5);+ });++ it('returns null — not zero — for a window it cannot classify', () => {+ // Null must stay distinct from a real period: ranked as the narrowest, an+ // unknown window would become the clock a denial backs off to. Only the+ // vocabulary the adapters actually emit is classified; anything else takes+ // the documented soonest-reset fallback rather than being guessed at.+ expect(windowPeriodHours({ scope: 'image', label: 'Agy · imagen' })).toBeNull();+ expect(windowPeriodHours({ scope: 'annual', label: 'Yearly' })).toBeNull();+ expect(windowPeriodHours({})).toBeNull();+ expect(windowPeriodHours(null)).toBeNull();+ });+});++describe('classifyWindows', () => {+ const hoursUntil = (limit) => limit.hours ?? null;+ const session = { scope: 'session', label: '5-hour', hours: 3 };+ const week = { scope: 'week', label: 'Weekly', hours: 30 };+ const classify = (limits) => classifyWindows(limits, hoursUntil);++ it('targets the broadest window and marks the narrowest as limiting', () => {+ // The 5-hour window resets sooner, but the WEEKLY allowance is the one that+ // expires unused — and the 5-hour one is what will refuse the run.+ for (const order of [[session, week], [week, session]]) {+ const { target, limiting } = classify(order);+ expect(target.limit).toBe(week);+ expect(target.hours).toBe(30);+ expect(limiting).toBe(session);+ }+ });++ it('still targets the broadest when the weekly window is about to roll', () => {+ // Near the weekly reset the WEEK is the soonest-resetting window — ranking+ // by reset time would flip the target back to the 5-hour one right when the+ // deadline that matters is closest.+ const closing = { scope: 'week', label: 'Weekly', hours: 1 };+ expect(classify([session, closing]).target.limit).toBe(closing);+ });++ it('breaks a same-period tie on the soonest reset', () => {+ const all = { scope: 'week', label: 'Current week (all models)', hours: 30 };+ const opus = { scope: 'week', label: 'Current week (Opus)', hours: 26 };+ expect(classify([all, opus]).target.limit).toBe(opus);+ });++ it('falls back to soonest-reset when nothing states a classifiable period', () => {+ // A provider whose vocabulary this doesn't know must keep working, not park+ // — but nothing can be asserted to be the narrowest, so there is no limiter.+ const burst = { scope: 'burst', label: 'Burst', hours: 3 };+ const pool = { scope: 'pool', label: 'Pool', hours: 8 };+ const { target, limiting } = classify([burst, pool]);+ expect(target.limit).toBe(burst);+ expect(limiting).toBeNull();+ });++ it('ignores unclassifiable windows when a classifiable one exists', () => {+ const opaque = { scope: 'burst', label: 'Burst', hours: 50 };+ const { target, limiting } = classify([opaque, week]);+ expect(target.limit).toBe(week);+ expect(limiting).toBe(week);+ });++ it('excludes an unreadable reset from the target but not from the limiter', () => {+ // A short window whose reset the provider didn't state can't be the+ // deadline, but it is still what refuses first.+ const undated = { scope: 'session', label: '5-hour', hours: null };+ const { target, limiting } = classify([undated, week]);+ expect(target.limit).toBe(week);+ expect(limiting).toBe(undated);+ });++ it('returns nulls for an empty set', () => {+ expect(classify([])).toEqual({ target: null, limiting: null });+ expect(classify(null)).toEqual({ target: null, limiting: null });+ });+});++describe('windowLabelOf', () => {+ it('names a window however the adapter labelled it, falling back to its scope', () => {+ expect(windowLabelOf({ label: 'Weekly', scope: 'week' })).toBe('Weekly');+ expect(windowLabelOf({ scope: 'week' })).toBe('week');+ expect(windowLabelOf(null)).toBe('window');+ });+});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex adac1c1c82..77c132c36d 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -471,6 +471,12 @@ async function runAgentSpawn(task) {// so it must be able to tell a burn run from any other agent from the// agent record alone.taskQuotaBurnFamily: task.metadata?.quotaBurnFamily || null,+ // The reset of the short rolling window that refuses first, carried for the+ // same reason: when this run is REFUSED, the continuation blocks the family+ // until that window rolls instead of re-dispatching into the same wall+ // (see quotaBurnDenials.js). A COS-TASKS.md round-trip can hand it back as+ // a string, so coerce rather than projecting whatever arrived.+ taskQuotaBurnLimitingResetAt: Number(task.metadata?.quotaBurnLimitingResetAt) || null,// Same reason as taskLiProposal — a hand-picked projection, so this must be// listed explicitly. `declaresNoCommitCriterion` (taskTypeHooks.js) reads it// to decide whether a run declared a `[task-<id>]` commit criterion at all,diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex cedef415dc..1db33c9666 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -435,6 +435,13 @@ export async function addTask(taskData, taskType = 'user', { raw = false, ignore// `isCooldownExemptTask` (cosTaskGenerator.js, which owns the why) and by// quotaBurnRunner's completion continuation.if (taskData.quotaBurnFamily) metadata.quotaBurnFamily = taskData.quotaBurnFamily;+ // The reset of the SHORT rolling window that will refuse first, so a run the+ // provider refuses can block that family until the window rolls rather than+ // letting the continuation re-dispatch into the same wall (the weekly card+ // it gates on still reads healthy). See quotaBurnDenials.js.+ if (Number.isFinite(taskData.quotaBurnLimitingResetAt)) {+ metadata.quotaBurnLimitingResetAt = taskData.quotaBurnLimitingResetAt;+ }// Content-edit timestamp for cross-peer newest-edit-wins LWW (#1714). Stamped// at creation so a freshly-added task always carries a stamp; the merge treats// an absent stamp as oldest, so this also keeps a stamped task from losing adiff --git a/server/services/imageGenQuota.js b/server/services/imageGenQuota.jsindex 83d02530b2..34daf95cf4 100644--- a/server/services/imageGenQuota.js+++ b/server/services/imageGenQuota.js@@ -36,6 +36,7 @@ import { IMAGE_GEN_MODE, CLOUD_IMAGE_GEN_MODES, IMAGE_TOOL_NAMES } from './imageimport { imageGenEvents } from './imageGenEvents.js';import { atomicWrite, PATHS, readJSONFileStrict } from '../lib/fileUtils.js';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { isObservedBlockActive, parseObservedReset } from '../lib/quotaReset.js';const STATE_FILE = () => join(PATHS.data, 'imagegen-quota.json');@@ -85,31 +86,6 @@ async function readLedger() {return value && typeof value.modes === 'object' && value.modes !== null ? value : { modes: {} };}-/**- * Parse an absolute ISO instant out of provider error text.- * Antigravity phrases it as `(around 2026-07-31T21:38:09Z)`. Pure.- */-const parseAbsoluteReset = (text, now) => {- const m = text.match(/(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)/);- if (!m) return null;- const at = new Date(m[1]).getTime();- // Narration also carries log lines and session stamps. A timestamp in the- // past is not a reset time — accepting one would set `blockedUntil` to an- // already-elapsed instant, which reads as "not blocked" downstream.- return Number.isNaN(at) || at <= now ? null : at;-};--/**- * Parse a relative reset window (`quota will reset in approximately 5 hours`,- * `try again in 30 minutes`) into an absolute epoch ms. Pure given `now`.- */-const parseRelativeReset = (text, now) => {- const m = text.match(/(?:reset|retry|try again|available)\b[^.]{0,40}?\bin\s+(?:approximately\s+|about\s+|~\s*)?(\d+(?:\.\d+)?)\s*(second|minute|hour|day)s?/i);- if (!m) return null;- const unitMs = { second: 1000, minute: 60_000, hour: 3_600_000, day: 86_400_000 }[m[2].toLowerCase()];- return now + Number(m[1]) * unitMs;-};-/*** Phrases that mean "the image backend refused because you are out of quota".*@@ -149,12 +125,9 @@ export function parseImageQuotaSignal(text, { now = Date.now() } = {}) {const s = String(text || '');if (!s.trim()) return { exhausted: false, resetsAt: null };if (!IMAGE_QUOTA_PATTERNS.some((re) => re.test(s))) return { exhausted: false, resetsAt: null };- // Absolute wins: a provider that states both ("in ~5 hours (around <ISO>)")- // is more precise in the parenthetical, and it survives a slow error path.- // Both parsers reject an instant that isn't in the future — narration carries- // log/session timestamps too, and a PAST "reset" would read as "not blocked".- const resetsAt = parseAbsoluteReset(s, now) ?? parseRelativeReset(s, now);- return { exhausted: true, resetsAt };+ // Shared with the quota-burn denial ledger — a refusal's own stated reset is+ // parsed the same way wherever it is observed (see `parseObservedReset`).+ return { exhausted: true, resetsAt: parseObservedReset(s, { now }) };}/**@@ -267,8 +240,10 @@ export async function getImageGenQuota({ enabledModes = [], now = Date.now() } =// never stated one — for a bounded window after we observed it, so an// unknown-reset block still shows but can't stick forever on an install// that stops rendering. A success clears it either way.- const blocked = entry.blockedAt- && (entry.blockedUntil ? entry.blockedUntil > now : now - entry.blockedAt < UNKNOWN_BLOCK_TTL_MS);+ const blocked = isObservedBlockActive(+ { at: entry.blockedAt, until: entry.blockedUntil },+ { now, ttlMs: UNKNOWN_BLOCK_TTL_MS },+ );if (blocked) {limits.push({key,diff --git a/server/services/providerUsage.js b/server/services/providerUsage.jsindex 70c81584ef..328a408597 100644--- a/server/services/providerUsage.js+++ b/server/services/providerUsage.js@@ -100,7 +100,13 @@ function codexLimitEntry(scopeKey, window) {percentUsed,percentRemaining: Math.max(0, 100 - percentUsed),resetsAt: Number.isFinite(window.resets_at) ? new Date(window.resets_at * 1000).toISOString() : null,- timezone: null+ timezone: null,+ // How long this window's allowance lasts — stated exactly by the telemetry,+ // so quota-burn ranks it without inferring from the scope word (a plan whose+ // primary window is 7h must not be read as the 5h `session` default). See+ // `lib/quotaWindows.js`; omitted when the payload doesn't state it, which+ // falls back to that classifier.+ ...(Number.isFinite(window.window_minutes) ? { periodHours: window.window_minutes / 60 } : {})};}@@ -331,7 +337,13 @@ export function parseAgyUsage(text, { now = Date.now() } = {}) {// Grok's `/usage show` panel reports usage as `<Window> limit: N%` (percent// USED). Its binary strings expose both `Weekly limit` and `Monthly limit`, so// different plans surface different windows — parse whichever appear.-const GROK_WINDOWS = { weekly: { label: 'Weekly', scope: 'week' }, monthly: { label: 'Monthly', scope: 'month' } };+// `periodHours` is stated rather than left to `quotaWindows.js` to infer from+// the scope word: this table already knows the answer exactly, and quota-burn+// ranks the target/limiting windows off it (see lib/quotaWindows.js).+const GROK_WINDOWS = {+ weekly: { label: 'Weekly', scope: 'week', periodHours: 7 * 24 },+ monthly: { label: 'Monthly', scope: 'month', periodHours: 30 * 24 },+};/*** Parse the Grok Build `/usage show` panel text. Emits one row per usage window@@ -361,6 +373,7 @@ export function parseGrokUsage(text, { now = Date.now(), timezone } = {}) {key: window,label: GROK_WINDOWS[window].label,scope: GROK_WINDOWS[window].scope,+ periodHours: GROK_WINDOWS[window].periodHours,model: null,percentUsed,percentRemaining: Math.max(0, 100 - percentUsed),diff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.jsindex 5a3fe23e87..e08f34f210 100644--- a/server/services/quotaBurn.js+++ b/server/services/quotaBurn.js@@ -23,6 +23,8 @@ 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';+import { classifyWindows, windowLabelOf } from '../lib/quotaWindows.js';+import { isBlockActive } from './quotaBurnDenials.js';const LEDGER_FILE = () => join(PATHS.cos, 'quota-burn-dispatches.json');@@ -66,17 +68,9 @@ export async function recordQuotaBurnDispatch(key, { now = Date.now() } = {}) {});}-/**- * The soonest-resetting limit on a card that is still in scope for the family,- * or null when none of them state a reset time we can read.- */-function selectLimit(card, family, now) {- const scoped = (card.limits || []).filter((limit) => !family.scope || limit.scope === family.scope);- return scoped- .map((limit) => ({ limit, hours: hoursUntilReset(limit, { now }) }))- .filter((entry) => entry.hours !== null)- .sort((a, b) => a.hours - b.hours)[0] || null;-}+/** The limits on a card the family's `scope` filter admits. */+const scopedLimits = (card, family) =>+ (card.limits || []).filter((limit) => !family.scope || limit.scope === family.scope);/** Headroom the family is willing to spend on ONE window: what's left, minus its reserve. */export function burnBudgetRemaining(limit, family) {@@ -95,11 +89,10 @@ export function burnBudgetRemaining(limit, family) {* weekly allowance already far below the floor the user set — while the field's* own hint reads "Never spend below this much headroom".*/-function tightestBudget(card, family) {- const scoped = (card.limits || []).filter((limit) =>- (!family.scope || limit.scope === family.scope) && Number.isFinite(Number(limit?.percentRemaining)));- if (!scoped.length) return null;- return scoped.reduce((tightest, limit) =>+function tightestBudget(scoped, family) {+ const measured = scoped.filter((limit) => Number.isFinite(Number(limit?.percentRemaining)));+ if (!measured.length) return null;+ return measured.reduce((tightest, limit) =>(burnBudgetRemaining(limit, family) < burnBudgetRemaining(tightest, family) ? limit : tightest));}@@ -137,12 +130,12 @@ export function windowKey(familyId, limit, { now = Date.now() } = {}) {** `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+ * reserve / cap / denial 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 } = {}) {+export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}, blocks = {}, bypassGates = false } = {}) {// The two "switched off" gates. A forced run passes both: `enabled` on the// family and on a job governs the UNATTENDED loop, and the user clicking ▶ on// a specific row is a more specific instruction than a checkbox they set@@ -175,30 +168,56 @@ export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}const available = [...new Set((card.limits || []).map((limit) => limit.scope).filter(Boolean))];return { skipReason: `no window matches scope "${family.scope}"${available.length ? ` (this provider has: ${available.join(', ')})` : ''}` };}- const selected = selectLimit(card, family, now);+ // ONE scoring pass over the in-scope windows yields both roles a burn reasons+ // about (see `lib/quotaWindows.js`):+ //+ // `target` — the BROADEST window: the allowance that expires unused. Not+ // the soonest-resetting one. Claude, codex and agy each publish a short+ // rolling window (≈5h) alongside a weekly one, and the short window is+ // nearly always the soonest: keying on it made the page report "resets in+ // 3h" for a plan written against a weekly allowance, and re-opened+ // `resetWithinHours` every five hours, so "only spend as the window is+ // about to expire" never actually bounded anything. Its reset epoch is+ // also what the dispatch cap keys on, making `maxDispatchesPerWindow` mean+ // "per weekly window" rather than "per 5-hour window".+ // `limiting` — the NARROWEST window: what a weekly burn plan runs out of+ // long before the weekly allowance is spent, and so the horizon a denial+ // backs off to (see `quotaBurnDenials.js`).+ const scoped = scopedLimits(card, family);+ const { target, limiting } = classifyWindows(scoped, (limit) => hoursUntilReset(limit, { 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' };+ if (!target) return { skipReason: 'no window states a reset time' };- const dispatchKey = windowKey(family.id, selected.limit, { now });+ const dispatchKey = windowKey(family.id, target.limit, { now });const dispatchesUsed = Number(dispatches[dispatchKey] || 0);// The reserve guards the TIGHTEST window in scope, not the one selection// happens to key on (see `tightestBudget`).- const tightest = tightestBudget(card, family) || selected.limit;+ const tightest = tightestBudget(scoped, family) || target.limit;+ const block = blocks[family.id];- // 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.+ // The 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` };+ // An OBSERVED refusal outranks the reported numbers: the provider itself+ // just said no, while the card it says no against can still read "60% left".+ // Bypassable on purpose — a forced run is the user's way to retry a block+ // they believe is stale, and a run that then succeeds clears it.+ // The `until` is deliberately NOT restated here — the family card renders+ // `blockedUntil` as a localized timestamp of its own, and an ISO instant+ // stacked above it is the same fact twice in two formats.+ if (isBlockActive(block, now)) {+ return { skipReason: `provider refused the last burn — ${block.reason || 'out of quota'}` };+ }+ if (target.hours < 0) return { skipReason: 'window already reset' };+ if (target.hours > family.resetWithinHours) {+ return { skipReason: `resets in ${Math.ceil(target.hours)}h — outside the ${family.resetWithinHours}h window` };}if (dispatchesUsed >= family.maxDispatchesPerWindow) {return { skipReason: `dispatch cap reached (${dispatchesUsed}/${family.maxDispatchesPerWindow})` };}if (burnBudgetRemaining(tightest, family) <= 0) {- const which = tightest.label || tightest.scope || 'window';- return { skipReason: `${which} at ${tightest.percentRemaining}% left is at or below the ${family.reservePercent}% reserve` };+ return { skipReason: `${windowLabelOf(tightest)} at ${tightest.percentRemaining}% left is at or below the ${family.reservePercent}% reserve` };}}@@ -206,8 +225,12 @@ export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}candidate: {family,card,- limit: selected.limit,- hoursUntilReset: selected.hours,+ limit: target.limit,+ hoursUntilReset: target.hours,+ // The narrowest window in scope — what a refusal is actually about. Null+ // when the provider reports no window whose period we can classify.+ limitingLimit: limiting,+ limitingResetAt: limiting ? normalizeResetAt(limiting, { now }).epochMs : null,dispatchKey,dispatchesUsed,// Only an unforced burn is charged against the window's automatic budget.@@ -225,14 +248,16 @@ const familiesOf = (config) => Object.entries(config?.families || {})* first (ties broken by the family's `priority`).** `config` is a normalized quota-burn config; `quotas` the provider cards from- * `providerUsage.getProviderQuotas()`. `bypassGatesFor` names one family whose- * window/reserve/cap gates are skipped (see `evaluateFamily`).+ * `providerUsage.getProviderQuotas()`; `blocks` the active denial ledger from+ * `quotaBurnDenials.getActiveQuotaBurnBlocks()`. `bypassGatesFor` names one+ * family whose window/reserve/cap/denial gates are skipped (see+ * `evaluateFamily`).*/-export function selectBurnCandidates(quotas, config, { now = Date.now(), dispatches = {}, bypassGatesFor = null } = {}) {+export function selectBurnCandidates(quotas, config, { now = Date.now(), dispatches = {}, blocks = {}, bypassGatesFor = null } = {}) {const cards = new Map((quotas || []).map((card) => [card.family, card]));return familiesOf(config).map((family) => evaluateFamily(family, cards.get(family.id), {- now, dispatches, bypassGates: bypassGatesFor === family.id,+ now, dispatches, blocks, bypassGates: bypassGatesFor === family.id,}).candidate).filter(Boolean).sort((a, b) => a.hoursUntilReset - b.hoursUntilReset || a.family.priority - b.family.priority);@@ -243,10 +268,11 @@ export function selectBurnCandidates(quotas, config, { now = Date.now(), dispatc* 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 evaluateFamilies(quotas, config, { now = Date.now(), dispatches = {} } = {}) {+export function evaluateFamilies(quotas, config, { now = Date.now(), dispatches = {}, blocks = {} } = {}) {const cards = new Map((quotas || []).map((card) => [card.family, card]));return familiesOf(config).map((family) => ({family,- ...evaluateFamily(family, cards.get(family.id), { now, dispatches }),+ block: blocks[family.id] || null,+ ...evaluateFamily(family, cards.get(family.id), { now, dispatches, blocks }),}));}diff --git a/server/services/quotaBurn.test.js b/server/services/quotaBurn.test.jsindex 5838ec721c..668aa341ef 100644--- a/server/services/quotaBurn.test.js+++ b/server/services/quotaBurn.test.js@@ -219,22 +219,28 @@ describe('windowKey', () => {});});+/**+ * Every subscription family publishes a short rolling window AND a weekly one.+ * They answer different questions and both have to be read correctly: the weekly+ * allowance is what expires unused (the burn's deadline and its dispatch+ * budget), the short one is what actually refuses a run.+ */+const twoWindow = (sessionLeft, weekLeft, weekResetsAt = '2026-07-27T00:00:00.000Z') => ({+ family: 'claude', supported: true,+ limits: [+ { key: 'session', scope: 'session', label: '5-hour', resetsAt: '2026-07-26T15:00:00.000Z', percentRemaining: sessionLeft },+ { key: 'week', scope: 'week', label: 'Weekly', resetsAt: weekResetsAt, percentRemaining: weekLeft },+ ],+});+describe('reserve across every window', () => {- const twoWindow = (sessionLeft, weekLeft) => ({- family: 'claude', supported: true,- limits: [- { key: 'session', scope: 'session', label: '5-hour', resetsAt: '2026-07-26T15:00:00.000Z', percentRemaining: sessionLeft },- { key: 'week', scope: 'week', label: 'Weekly', resetsAt: '2026-08-01T00:00:00.000Z', percentRemaining: weekLeft },- ],- });const family = normalizeQuotaBurnConfig({families: { claude: { enabled: true, resetWithinHours: 24, reservePercent: 40, jobs: [job()] } },});it('refuses to drain the WEEKLY window just because the session window is full', () => {- // Claude/codex/agy all expose a short window AND a weekly one, and the short- // one is always the soonest — so checking only the selected limit made the- // reserve inert for every provider that has two.+ // Checking only the selected limit made the reserve inert for every provider+ // that reports two windows.const verdict = evaluateFamilies([twoWindow(100, 2)], family, { now: NOW })[0];expect(verdict.candidate).toBeUndefined();expect(verdict.skipReason).toMatch(/Weekly at 2% left is at or below the 40% reserve/);@@ -244,3 +250,84 @@ describe('reserve across every window', () => {expect(evaluateFamilies([twoWindow(100, 90)], family, { now: NOW })[0].candidate).toBeTruthy();});});++describe('window targeting', () => {+ const family = normalizeQuotaBurnConfig({+ families: { claude: { enabled: true, resetWithinHours: 24, reservePercent: 0, jobs: [job()] } },+ });++ it('reports the WEEKLY window, not the 5-hour one that resets sooner', () => {+ // The bug this exists for: the 5-hour window is nearly always the soonest to+ // reset, so selecting "soonest" made the page say "resets in 3h · 100% left"+ // for a plan written against a weekly allowance — and re-opened+ // resetWithinHours every five hours, so the horizon never bounded anything.+ const [{ candidate }] = evaluateFamilies([twoWindow(100, 62)], family, { now: NOW });+ expect(candidate.limit.label).toBe('Weekly');+ expect(candidate.hoursUntilReset).toBeCloseTo(12, 0);+ expect(candidate.limit.percentRemaining).toBe(62);+ // And the short window rides along as the one that will refuse first.+ expect(candidate.limitingLimit.label).toBe('5-hour');+ expect(candidate.limitingResetAt).toBe(Date.parse('2026-07-26T15:00:00.000Z'));+ });++ it('keys the dispatch cap on the WEEKLY reset, so the cap is per week', () => {+ // Keyed on the 5-hour reset, `maxDispatchesPerWindow: 5` silently meant+ // "5 burns every 5 hours" — ~24/day against a weekly allowance.+ const [{ candidate }] = evaluateFamilies([twoWindow(100, 62)], family, { now: NOW });+ expect(candidate.dispatchKey).toBe(windowKey('claude', { resetsAt: '2026-07-27T00:00:00.000Z' }, { now: NOW }));+ });++ it('honors an explicit scope filter over the broadest window', () => {+ const scoped = normalizeQuotaBurnConfig({+ families: { claude: { enabled: true, scope: 'session', resetWithinHours: 24, jobs: [job()] } },+ });+ const [{ candidate }] = evaluateFamilies([twoWindow(100, 62)], scoped, { now: NOW });+ expect(candidate.limit.label).toBe('5-hour');+ });++ it('falls back to soonest-reset when no window states a period it can classify', () => {+ // A provider whose vocabulary this doesn't know must keep working, not park.+ const opaque = {+ family: 'claude', supported: true,+ limits: [+ { key: 'a', scope: 'burst', label: 'Burst', resetsAt: '2026-07-26T15:00:00.000Z', percentRemaining: 80 },+ { key: 'b', scope: 'pool', label: 'Pool', resetsAt: '2026-07-26T20:00:00.000Z', percentRemaining: 80 },+ ],+ };+ const [{ candidate }] = evaluateFamilies([opaque], family, { now: NOW });+ expect(candidate.limit.label).toBe('Burst');+ expect(candidate.limitingLimit).toBeNull();+ });+});++/**+ * A refusal the provider actually issued outranks the numbers it reports: a burn+ * plan spending a weekly allowance exhausts the 5-hour window underneath it long+ * before the weekly card stops looking healthy, and without this the runner+ * re-dispatched into the same wall every tick.+ */+describe('denial blocks', () => {+ const family = normalizeQuotaBurnConfig({+ families: { claude: { enabled: true, resetWithinHours: 24, reservePercent: 0, jobs: [job()] } },+ });+ const quotas = [twoWindow(100, 62)];++ it('skips a family the provider refused, and names the block', () => {+ const blocks = { claude: { at: NOW - 1000, until: NOW + 3_600_000, reason: 'Usage limit exceeded' } };+ const [verdict] = evaluateFamilies(quotas, family, { now: NOW, blocks });+ expect(verdict.candidate).toBeUndefined();+ expect(verdict.skipReason).toMatch(/provider refused the last burn.*Usage limit exceeded/);+ expect(selectBurnCandidates(quotas, family, { now: NOW, blocks })).toEqual([]);+ });++ it('burns again once the block has lapsed', () => {+ const blocks = { claude: { at: NOW - 7_200_000, until: NOW - 1000, reason: 'Usage limit exceeded' } };+ expect(selectBurnCandidates(quotas, family, { now: NOW, blocks })).toHaveLength(1);+ });++ it('lets a forced run retry a block the user believes is stale', () => {+ // The force path is how a user retries; a run that then succeeds clears it.+ const blocks = { claude: { at: NOW - 1000, until: NOW + 3_600_000, reason: 'Usage limit exceeded' } };+ expect(selectBurnCandidates(quotas, family, { now: NOW, blocks, bypassGatesFor: 'claude' })).toHaveLength(1);+ });+});diff --git a/server/services/quotaBurnDenials.js b/server/services/quotaBurnDenials.jsnew file mode 100644index 0000000000..61d54218d5--- /dev/null+++ b/server/services/quotaBurnDenials.js@@ -0,0 +1,244 @@+/**+ * Quota-burn denial ledger — the observed "stop, you are out" signal.+ *+ * The quota gates in `quotaBurn.js` reason about the numbers a provider REPORTS.+ * Those numbers are stale by design (a card is scraped every few minutes and+ * rounded to whole percent), and they describe the window the burn is targeting+ * — usually the weekly one. What actually refuses a run is the SHORT rolling+ * window: a burn plan spending down a weekly allowance runs task after task and+ * eventually exhausts the 5-hour window, at which point every further dispatch+ * fails instantly, wastes an agent spawn, and leaves a red card in the queue —+ * while the weekly card still reads "60% left, resets in 2 days" and the runner+ * happily dispatches again on the next tick.+ *+ * So a refusal is recorded as a first-class fact: when a burn-dispatched agent+ * dies with a usage-limit error, the family is BLOCKED until the short window+ * resets, and `evaluateFamily` reports that as the gate. This is the same+ * "report what we observed, never what we assumed" posture as `imageGenQuota.js`+ * — a provider that just said no is more authoritative than a card that says+ * yes.+ *+ * Blocks are self-healing in both directions: a successful burn clears the+ * family immediately (proof it is serving again), and a block whose refusal+ * stated no reset expires on a bounded TTL so an install that stops burning+ * can't be blocked forever.+ *+ * Storage is `ephemeral-file` per docs/STORAGE.md — regenerable runtime+ * telemetry with an hours-long horizon, alongside the dispatch ledger in+ * `data/cos/`.+ */++import { join } from 'path';+import { atomicWrite, PATHS, readJSONFileStrict } from '../lib/fileUtils.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { isPlainObject } from '../lib/objects.js';+import { isObservedBlockActive, parseObservedReset } from '../lib/quotaReset.js';++const DENIALS_FILE = () => join(PATHS.cos, 'quota-burn-denials.json');++/**+ * How long a block whose refusal stated no reset — and whose family reported no+ * classifiable short window either — stays in force. Bounds an otherwise+ * open-ended block: nothing forces a later burn to happen and prove the family+ * is serving again. Five hours is the shortest rolling window every supported+ * CLI family publishes, so it is the smallest wait that is actually likely to+ * clear a real refusal.+ */+export const UNKNOWN_BLOCK_TTL_MS = 5 * 60 * 60 * 1000;++/**+ * Phrases that mean "the provider refused this run because its quota is spent".+ *+ * Deliberately NARROWER than the generic rate-limit matching in+ * `agentErrorAnalysis.js`: a transient `429` is a retry, not a spent window, and+ * blocking a family for five hours over one is a much worse error than missing a+ * burn. Every pattern here is a subscription-window idiom the CLIs print+ * verbatim when the allowance itself is gone.+ *+ * These are matched against an agent's own output, which quotes its prompt and+ * the files it read — so nothing here may be a phrase ordinary work can emit.+ * `usage limit` / `quota exceeded` / `plan limit` are anchored to a possessive+ * or a verb for that reason; a bare "limit" or "quota" would match a burn task+ * whose prompt is literally about quota handling.+ */+export const QUOTA_DENIAL_PATTERNS = Object.freeze([+ /hit your (?:usage )?limit/i,+ /(?:you(?:'ve| have) )?(?:reached|exceeded) your (?:usage |plan |weekly |session )?limit/i,+ /(?:usage|rate) limit reached/i,+ /(?:your )?(?:quota|usage) (?:has been |is )?exhausted/i,+ /out of (?:quota|credits)/i,+ /resource[\s_-]*exhausted/i,+ /upgrade to pro/i,+ /now using extra usage/i,+ /(?:5|five)[\s-]?hour limit/i,+ /weekly limit reached/i,+]);++/**+ * Classify one failed burn run's output. Returns `{ denied, resetsAt }` where+ * `resetsAt` is epoch ms or null. Pure given `now`; exported for tests.+ *+ * `errorAnalysis` is the structured verdict `analyzeAgentFailure` already+ * produced for this run — its `usage-limit` category is the provider-anchored+ * classification of exactly this condition, so it is trusted directly rather+ * than re-derived from the raw text. Only when that verdict came from a+ * STRUCTURED marker, though (`origin: 'provider'`): the same category is also+ * reached by a loose keyword sweep over the agent's own narration, which is the+ * false-positive class the pattern list below is deliberately narrow about. A+ * loose match falls through to those patterns rather than being trusted.+ */+export function parseQuotaDenial(text, { now = Date.now(), errorAnalysis = null } = {}) {+ const raw = typeof text === 'string' ? text : '';+ const categorized = errorAnalysis?.category === 'usage-limit' && errorAnalysis.origin === 'provider';+ const denied = categorized || QUOTA_DENIAL_PATTERNS.some((pattern) => pattern.test(raw));+ if (!denied) return { denied: false, resetsAt: null };+ // The usage-limit analysis extracts the CLI's own wait phrase but strips the+ // lead-in ("try again in " → "45 minutes"), so it is re-framed into a sentence+ // `parseObservedReset` recognizes before falling back to the full text — where+ // a reset stated outside the matched line still gets read.+ const waitTime = typeof errorAnalysis?.waitTime === 'string' ? errorAnalysis.waitTime.trim() : '';+ const stated = (waitTime ? parseObservedReset(`retry in ${waitTime}`, { now }) : null)+ ?? parseObservedReset(raw, { now });+ return { denied: true, resetsAt: stated };+}++/**+ * Everything a failed run said, as one blob to classify. `analyzeAgentFailure`+ * keeps no copy of the full transcript — `snippet` is the window around the+ * matched pattern, `details` the error lines it pulled out — so every field it+ * does keep is scanned rather than assuming any one carries the refusal.+ */+export const denialTextOf = (result) => [+ result?.errorAnalysis?.message,+ result?.errorAnalysis?.details,+ result?.errorAnalysis?.snippet,+ result?.error,+].filter((part) => typeof part === 'string' && part).join('\n');++/**+ * Raw ledger: `{ [familyId]: { at, until, reason } }`, or **null** when the file+ * could not be read.+ *+ * A failed/corrupt read must not come back as "nothing is blocked" — that would+ * re-open the gate on a family the provider is still refusing AND let the next+ * write clobber the surviving blocks with an empty object. Same posture as+ * `imageGenQuota.js`'s ledger read.+ */+export async function getQuotaBurnDenials() {+ const { ok, value } = await readJSONFileStrict(DENIALS_FILE(), {}, { logError: false });+ if (!ok) return null;+ return isPlainObject(value) ? value : {};+}++/**+ * Is this ledger entry still holding? A block with a known reset holds until it+ * passes; one without holds for `UNKNOWN_BLOCK_TTL_MS` after it was observed.+ * Pure; exported so the status page and the gate can't disagree.+ */+export const isBlockActive = (entry, now = Date.now()) =>+ isObservedBlockActive(entry, { now, ttlMs: UNKNOWN_BLOCK_TTL_MS });++/** Only the families blocked right now, keyed by family id. */+export async function getActiveQuotaBurnBlocks({ now = Date.now() } = {}) {+ const ledger = await getQuotaBurnDenials();+ if (!ledger) {+ console.error('❌ Quota-burn denial ledger unreadable — treating every family as unblocked this cycle');+ return {};+ }+ return Object.fromEntries(Object.entries(ledger).filter(([, entry]) => isBlockActive(entry, now)));+}++// Single tail: a denial and a success can land together (two families burning in+// the same cycle), and both are read-modify-writes on one file.+const denialWriteQueue = createFileWriteQueue();++/**+ * Read-modify-write the ledger inside the queue. `mutate` returns the next+ * ledger, or `null` for "nothing to change" — which skips the write, so the+ * common case (a successful burn for a family that was never blocked) costs one+ * read rather than a read plus a pointless rewrite.+ */+const writeLedger = (mutate) => denialWriteQueue(async () => {+ const ledger = await getQuotaBurnDenials();+ // Don't overwrite a ledger we couldn't read — that is exactly how a real+ // block gets erased by the next unrelated write.+ if (!ledger) return null;+ const next = mutate({ ...ledger });+ if (!next) return null;+ await atomicWrite(DENIALS_FILE(), next);+ return next;+});++/**+ * Record that `familyId` was refused.+ *+ * `until` is resolved in priority order — the provider's own stated reset, then+ * the reset of the family's narrowest reported window (the 5-hour one it just+ * ran out of), then null, which the TTL bounds. Never DOWNGRADE a known reset to+ * unknown: a second refusal during an active block typically restates nothing,+ * and erasing the first one's instant would shorten the block to the TTL.+ */+export async function recordQuotaBurnDenial({+ familyId, output = '', errorAnalysis = null, limitingResetAt = null, at = Date.now(),+} = {}) {+ if (!familyId) return null;+ const signal = parseQuotaDenial(output, { now: at, errorAnalysis });+ if (!signal.denied) return null;+ const stated = signal.resetsAt ?? (Number.isFinite(limitingResetAt) && limitingResetAt > at ? limitingResetAt : null);+ const ledger = await writeLedger((current) => ({+ ...current,+ [familyId]: {+ at,+ until: stated ?? current[familyId]?.until ?? null,+ reason: errorAnalysis?.message || 'the provider refused the run as out of quota',+ },+ }));+ const entry = ledger?.[familyId] || null;+ if (entry) {+ console.log(`🛑 Quota-burn ${familyId} denied by the provider — blocked until ${entry.until ? new Date(entry.until).toISOString() : `+${UNKNOWN_BLOCK_TTL_MS / 3_600_000}h`}`);+ }+ return entry;+}++/**+ * Clear `familyId`'s block. Called when a burn run SUCCEEDS: the provider served+ * it, which is direct evidence the window it refused on has rolled — more+ * current than any stated reset, which providers round.+ */+export async function clearQuotaBurnBlock(familyId) {+ if (!familyId) return null;+ return writeLedger(({ [familyId]: dropped, ...rest }) => {+ if (!dropped) return null; // never blocked — skip the write+ console.log(`✅ Quota-burn ${familyId} served a run — clearing its denial block`);+ return rest;+ });+}++/**+ * Fold one completed agent into the ledger: a refusal blocks its family, a+ * success clears it.+ *+ * Called from the runner's `agent:completed` continuation rather than from a+ * second subscriber of its own, and AWAITED there before the family is+ * re-evaluated. The ordering is the whole point — that continuation dispatches+ * the next job in the plan the moment a burn agent finishes, so a block recorded+ * after it runs would arrive one wasted agent too late, every time.+ *+ * Only agents spawned BY a burn are considered — `quotaBurnFamily` is stamped on+ * the task by `quotaBurnJobs/agentPrompt.js` and projected onto the agent record+ * at registration. An unrelated agent that happens to hit a usage limit says+ * nothing about whether the burn plan may spend; blocking on it would stall the+ * feature over someone else's failed task.+ */+export async function recordBurnAgentCompletion(agent) {+ const familyId = agent?.metadata?.taskQuotaBurnFamily;+ if (!familyId) return null;+ if (agent.result?.success) return clearQuotaBurnBlock(familyId);+ const limitingResetAt = Number(agent.metadata?.taskQuotaBurnLimitingResetAt);+ return recordQuotaBurnDenial({+ familyId,+ output: denialTextOf(agent.result),+ errorAnalysis: agent.result?.errorAnalysis || null,+ limitingResetAt: Number.isFinite(limitingResetAt) ? limitingResetAt : null,+ });+}diff --git a/server/services/quotaBurnDenials.test.js b/server/services/quotaBurnDenials.test.jsnew file mode 100644index 0000000000..25916b99ac--- /dev/null+++ b/server/services/quotaBurnDenials.test.js@@ -0,0 +1,194 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';+import { readFileSync, rmSync, writeFileSync } from 'fs';+import { join } from 'path';++const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-burn-denials-', extraOverrides: (root) => ({ cos: root }) });+vi.mock('../lib/fileUtils.js', async (importActual) => makeProxy(await importActual()));++const {+ clearQuotaBurnBlock, getActiveQuotaBurnBlocks, getQuotaBurnDenials, isBlockActive,+ parseQuotaDenial, recordBurnAgentCompletion, recordQuotaBurnDenial, UNKNOWN_BLOCK_TTL_MS,+} = await import('./quotaBurnDenials.js');++const NOW = Date.parse('2026-07-26T12:00:00.000Z');++beforeEach(() => rmSync(join(tempRoot, 'quota-burn-denials.json'), { force: true }));+afterAll(cleanup);++describe('parseQuotaDenial', () => {+ it('trusts a STRUCTURED usage-limit verdict the failure analyzer already produced', () => {+ // `analyzeAgentFailure` classifies exactly this condition and anchors its+ // patterns to provider-billing idioms — re-deriving it here would be a+ // second, drifting copy of the same judgement.+ const analyzed = { category: 'usage-limit', origin: 'provider' };+ expect(parseQuotaDenial('', { now: NOW, errorAnalysis: analyzed }).denied).toBe(true);+ // ...but only when it came from a structured marker. The same category is+ // also reached by a loose keyword sweep over the agent's own narration,+ // which is the false-positive class the pattern list guards against — so a+ // loose match falls through to those patterns instead of being trusted.+ expect(parseQuotaDenial('reviewing the daily limit copy', {+ now: NOW, errorAnalysis: { category: 'usage-limit', origin: 'output-scan' },+ }).denied).toBe(false);+ });++ it('matches a subscription-window refusal in the run output', () => {+ expect(parseQuotaDenial('Claude usage limit reached', { now: NOW }).denied).toBe(true);+ expect(parseQuotaDenial('You have hit your usage limit', { now: NOW }).denied).toBe(true);+ expect(parseQuotaDenial('5-hour limit reached for this account', { now: NOW }).denied).toBe(true);+ });++ it('does NOT block on a transient rate limit or on prompt text about quotas', () => {+ // A 429 is a retry, not a spent window — and blocking a family for hours+ // over one is far worse than missing a burn. The output being classified is+ // the agent's own narration, which quotes the prompt it was given.+ expect(parseQuotaDenial('API Error: 429 too many requests', { now: NOW }).denied).toBe(false);+ expect(parseQuotaDenial('Reviewing the quota limit handling in quotaBurn.js', { now: NOW }).denied).toBe(false);+ expect(parseQuotaDenial('', { now: NOW }).denied).toBe(false);+ expect(parseQuotaDenial(null, { now: NOW }).denied).toBe(false);+ });++ it('reads the reset the provider stated, absolute before relative', () => {+ const absolute = parseQuotaDenial(+ 'hit your usage limit — quota will reset in approximately 5 hours (around 2026-07-26T15:00:00Z)',+ { now: NOW },+ );+ expect(absolute.resetsAt).toBe(Date.parse('2026-07-26T15:00:00Z'));+ const relative = parseQuotaDenial('hit your usage limit, try again in 45 minutes', { now: NOW });+ expect(relative.resetsAt).toBe(NOW + 45 * 60_000);+ });++ it('re-frames the analyzer\'s stripped wait phrase so it still parses', () => {+ // The usage-limit extractor yields `waitTime: '45 minutes'` — the lead-in+ // ("try again in ") is already consumed by its own pattern.+ const signal = parseQuotaDenial('', {+ now: NOW,+ errorAnalysis: { category: 'usage-limit', origin: 'provider', waitTime: '45 minutes' },+ });+ expect(signal.resetsAt).toBe(NOW + 45 * 60_000);+ });+});++describe('recordQuotaBurnDenial', () => {+ it('blocks the family until the reset the provider stated', async () => {+ const entry = await recordQuotaBurnDenial({+ familyId: 'claude',+ output: 'hit your usage limit — try again in 3 hours',+ at: NOW,+ });+ expect(entry.until).toBe(NOW + 3 * 3_600_000);+ await expect(getActiveQuotaBurnBlocks({ now: NOW })).resolves.toHaveProperty('claude');+ await expect(getActiveQuotaBurnBlocks({ now: entry.until + 1 })).resolves.toEqual({});+ });++ it('falls back to the SHORT window\'s reset when the refusal states none', async () => {+ // The 5-hour window is what a weekly burn plan actually runs out of, so it+ // is the right clock to wait on — the weekly card still reads healthy.+ const limitingResetAt = NOW + 2 * 3_600_000;+ const entry = await recordQuotaBurnDenial({+ familyId: 'codex', output: 'usage limit reached', limitingResetAt, at: NOW,+ });+ expect(entry.until).toBe(limitingResetAt);+ });++ it('never downgrades a known reset to unknown on a repeat refusal', async () => {+ // A second refusal during an active block typically restates nothing;+ // erasing the first instant would silently shorten the block to the TTL.+ await recordQuotaBurnDenial({ familyId: 'claude', output: 'hit your usage limit — try again in 3 hours', at: NOW });+ const repeat = await recordQuotaBurnDenial({ familyId: 'claude', output: 'usage limit reached', at: NOW + 60_000 });+ expect(repeat.until).toBe(NOW + 3 * 3_600_000);+ });++ it('records nothing for a failure that is not a quota refusal', async () => {+ await expect(recordQuotaBurnDenial({ familyId: 'claude', output: 'ENOENT: no such file', at: NOW })).resolves.toBeNull();+ await expect(getQuotaBurnDenials()).resolves.toEqual({});+ });++ it('bounds a reset-less block on the TTL instead of holding forever', async () => {+ // Nothing forces a later burn to happen and prove the family is serving+ // again, so an unbounded block would strand the feature.+ const entry = await recordQuotaBurnDenial({ familyId: 'agy', output: 'usage limit reached', at: NOW });+ expect(entry.until).toBeNull();+ expect(isBlockActive(entry, NOW + UNKNOWN_BLOCK_TTL_MS - 1)).toBe(true);+ expect(isBlockActive(entry, NOW + UNKNOWN_BLOCK_TTL_MS)).toBe(false);+ });++ it('never clobbers a ledger it could not read', async () => {+ // A corrupt/unreadable file must not read as "nothing is blocked" — that+ // re-opens the gate on a family the provider is still refusing AND lets the+ // next write replace the surviving blocks with an empty object.+ await recordQuotaBurnDenial({ familyId: 'claude', output: 'usage limit reached', at: NOW });+ writeFileSync(join(tempRoot, 'quota-burn-denials.json'), '{ not json');+ await expect(getQuotaBurnDenials()).resolves.toBeNull();+ await expect(getActiveQuotaBurnBlocks({ now: NOW })).resolves.toEqual({});+ await recordQuotaBurnDenial({ familyId: 'codex', output: 'usage limit reached', at: NOW });+ expect(readFileSync(join(tempRoot, 'quota-burn-denials.json'), 'utf-8')).toBe('{ not json');+ });++ it('does not lose a block when two denials race', async () => {+ await Promise.all([+ recordQuotaBurnDenial({ familyId: 'claude', output: 'usage limit reached', at: NOW }),+ recordQuotaBurnDenial({ familyId: 'codex', output: 'usage limit reached', at: NOW }),+ ]);+ await expect(getQuotaBurnDenials()).resolves.toHaveProperty('codex');+ await expect(getQuotaBurnDenials()).resolves.toHaveProperty('claude');+ });+});++describe('clearQuotaBurnBlock', () => {+ it('clears on a successful burn — the provider serving IS the proof', async () => {+ await recordQuotaBurnDenial({ familyId: 'claude', output: 'usage limit reached', at: NOW });+ await clearQuotaBurnBlock('claude');+ await expect(getQuotaBurnDenials()).resolves.toEqual({});+ });++ it('is a no-op when the family was never blocked', async () => {+ await expect(clearQuotaBurnBlock('grok')).resolves.toBeNull();+ await expect(clearQuotaBurnBlock(null)).resolves.toBeNull();+ });+});++/**+ * Only agents a burn dispatched carry `taskQuotaBurnFamily`. An unrelated task+ * that happens to hit a usage limit says nothing about whether the burn plan may+ * spend — blocking on it would stall the feature over someone else's failure.+ */+describe('recordBurnAgentCompletion', () => {+ const burnAgent = (metadata, result) => ({+ metadata: { taskQuotaBurnFamily: 'claude', ...metadata }, result,+ });+ const refused = { success: false, errorAnalysis: { category: 'usage-limit', origin: 'provider', message: 'Usage limit exceeded' } };++ it('blocks the family until the limiting window rolls when a burn is refused', async () => {+ await recordBurnAgentCompletion(burnAgent({ taskQuotaBurnLimitingResetAt: Date.now() + 3_600_000 }, refused));+ await expect(getQuotaBurnDenials()).resolves.toHaveProperty('claude');+ });++ it('reads a limiting reset that round-tripped through COS-TASKS.md as a string', async () => {+ // Task metadata comes back off the markdown store stringified; projecting it+ // unchanged would fail the `Number.isFinite` guard and silently downgrade+ // every block to the TTL.+ const until = Date.now() + 2 * 3_600_000;+ await recordBurnAgentCompletion(burnAgent({ taskQuotaBurnLimitingResetAt: String(until) }, refused));+ const ledger = await getQuotaBurnDenials();+ expect(ledger.claude.until).toBe(until);+ });++ it('ignores an agent that was not dispatched by a burn', async () => {+ await recordBurnAgentCompletion({ metadata: {}, result: refused });+ await expect(getQuotaBurnDenials()).resolves.toEqual({});+ });++ it('clears the block when a burn run succeeds', async () => {+ await recordQuotaBurnDenial({ familyId: 'claude', output: 'usage limit reached', at: NOW });+ await recordBurnAgentCompletion(burnAgent({}, { success: true }));+ await expect(getQuotaBurnDenials()).resolves.toEqual({});+ });++ it('leaves the ledger alone for a burn that failed for an unrelated reason', async () => {+ await recordBurnAgentCompletion(burnAgent({}, {+ success: false, errorAnalysis: { category: 'bad-request', message: 'Bad request' },+ }));+ await expect(getQuotaBurnDenials()).resolves.toEqual({});+ });+});diff --git a/server/services/quotaBurnJobs/agentPrompt.js b/server/services/quotaBurnJobs/agentPrompt.jsindex 06bf947f35..cd6ccf9acb 100644--- a/server/services/quotaBurnJobs/agentPrompt.js+++ b/server/services/quotaBurnJobs/agentPrompt.js@@ -16,6 +16,7 @@ import { getAppById } from '../apps.js';import { getAllProviders } from '../providers.js';import { commandBasename } from '../../lib/providerModels.js';import { burnTaskDescription } from '../../lib/quotaBurnConfig.js';+import { windowLabelOf } from '../../lib/quotaWindows.js';/*** An agent-capable provider in the burning family. An explicit `providerId`@@ -93,14 +94,27 @@ export async function countPending({ params, job, family } = {}) {: { 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. */+/**+ * The burn context the agent sees above the user's own prompt.+ *+ * Names the TARGET window (the weekly allowance this burn is racing) and, when+ * the family reports a separate short rolling window, that one too — a run that+ * is refused mid-way is nearly always the short window running out, and an agent+ * told only "the weekly window has 60% left" reads that refusal as a bug.+ */export function renderBurnPrompt({ family, candidate, prompt }) {const hours = Math.max(0, Math.ceil(candidate?.hoursUntilReset ?? 0));+ const target = windowLabelOf(candidate?.limit);+ const limiting = candidate?.limitingLimit;+ const showsLimiting = limiting && limiting !== candidate?.limit;return [`# ${family.id} quota-burn task`,'',- `This ${family.id} quota window resets in about ${hours} hour${hours === 1 ? '' : 's'}.`,- `Window: ${candidate?.limit?.label || candidate?.limit?.scope || 'provider window'}; remaining: ${candidate?.limit?.percentRemaining}%; reserve: ${family.reservePercent}%.`,+ `The ${family.id} ${target} quota window resets in about ${hours} hour${hours === 1 ? '' : 's'}.`,+ `Window: ${target}; remaining: ${candidate?.limit?.percentRemaining}%; reserve: ${family.reservePercent}%.`,+ ...(showsLimiting+ ? [`Shorter window in play: ${windowLabelOf(limiting)} at ${limiting.percentRemaining}% remaining — it is what will refuse this run if it empties.`]+ : []),`Dispatch cap: ${family.maxDispatchesPerWindow} for this reset window.`,'','Carry out the configured work below. Do not use another provider family as a substitute.',@@ -157,8 +171,13 @@ export async function run({ params, job, family, candidate, context } = {}) {reviewLoop: false,// Burn provenance, read back after the task round-trips through// COS-TASKS.md by `isCooldownExemptTask` (cosTaskGenerator.js, which owns- // the why) and by the runner's completion continuation.+ // the why), by the runner's completion continuation, and by the denial+ // ledger — a burn the provider REFUSES is the signal that this family's+ // short rolling window is spent, but only a run this plan dispatched says+ // anything about that. The limiting window's reset rides along so the block+ // can wait on the right clock instead of a bounded guess.quotaBurnFamily: family.id,+ quotaBurnLimitingResetAt: candidate?.limitingResetAt ?? null,}, 'internal');// A duplicate means an identical burn task for this app is still pending ordiff --git a/server/services/quotaBurnRunner.js b/server/services/quotaBurnRunner.jsindex ba23ce9442..7b59b583e8 100644--- a/server/services/quotaBurnRunner.js+++ b/server/services/quotaBurnRunner.js@@ -38,9 +38,11 @@import { getProviderQuotas } from './providerUsage.js';import { getQuotaBurnDispatches, evaluateFamilies, recordQuotaBurnDispatch, selectBurnCandidates } from './quotaBurn.js';+import { getActiveQuotaBurnBlocks, recordBurnAgentCompletion } from './quotaBurnDenials.js';import { getQuotaBurnConfig, getQuotaBurnRuns, recordQuotaBurnRun } from './quotaBurnStore.js';import { countJobPending, runBurnJob } from './quotaBurnJobs/index.js';import { familyIsActionable } from '../lib/quotaBurnConfig.js';+import { windowLabelOf } from '../lib/quotaWindows.js';import { WAIT } from '../lib/staleWhileRevalidate.js';import { cosEvents } from './cosEvents.js';@@ -247,13 +249,13 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,});if (!quotas) return finish({ dispatched: false, reason: 'provider quota read failed' });- const dispatches = await getQuotaBurnDispatches();- // `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 [dispatches, blocks] = await Promise.all([getQuotaBurnDispatches(), getActiveQuotaBurnBlocks()]);+ // `force` is the page's per-job "Run now" — the window/reserve/cap/denial 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,+ dispatches, blocks, bypassGatesFor: force ? familyId : null,}).filter((candidate) => !familyId || candidate.family.id === familyId);if (!candidates.length) {@@ -262,7 +264,7 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,// off, "disabled" IS the answer — reporting a different family's verdict// instead (or claiming it is "ready" when it did not run) leaves them with// no path to the control they need.- const reasons = evaluateFamilies(quotas, config, { dispatches })+ const reasons = evaluateFamilies(quotas, config, { dispatches, blocks }).filter(({ family }) => (familyId ? family.id === familyId : family.enabled)).map(({ family, skipReason }) => `${family.id}: ${skipReason || 'ready'}`);return finish({@@ -358,30 +360,40 @@ async function evaluate({ trigger = 'scheduled', familyId = null, jobId = null,export async function getQuotaBurnStatus({ refresh = false } = {}) {// 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([+ const [config, quotas, dispatches, blocks, runs] = await Promise.all([getQuotaBurnConfig(),getProviderQuotas({ wait: refresh ? WAIT.FRESH : WAIT.NEVER }).catch((err) => {console.error(`❌ Quota-burn status could not read provider quota: ${err.message}`);return [];}),getQuotaBurnDispatches(),+ getActiveQuotaBurnBlocks(),getQuotaBurnRuns(),]);const cards = new Map(quotas.map((card) => [card.family, card]));// 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 }) => {+ const families = await Promise.all(evaluateFamilies(quotas, config, { dispatches, blocks })+ .map(async ({ family, candidate, skipReason, block }) => {const card = cards.get(family.id);return {id: family.id,label: candidate?.card?.label || card?.label || family.id,percentRemaining: candidate?.limit?.percentRemaining ?? null,hoursUntilReset: candidate ? Math.round(candidate.hoursUntilReset * 10) / 10 : null,+ // WHICH window those two numbers describe. Without it the card reports a+ // percentage and a countdown with no way to tell the weekly allowance+ // from the 5-hour one — the exact ambiguity that hid the wrong window+ // being selected in the first place.+ windowLabel: candidate ? windowLabelOf(candidate.limit) : null,dispatchesUsed: candidate?.dispatchesUsed ?? null,willBurn: Boolean(candidate),skipReason: skipReason || null,+ // An observed provider refusal, surfaced whether or not it is the gate+ // that closed — a family blocked AND out of window should say both.+ blockedUntil: block?.until ? new Date(block.until).toISOString() : null,+ blockedReason: block?.reason || null,// The reading for this family is being taken right now — the page polls// again instead of leaving a card that looks like it has no quota.pending: Boolean(card?.pending),@@ -441,7 +453,17 @@ function onBurnAgentCompleted(agent) {// Returned so tests can await the cycle. The emitter ignores it — this is a// fire-and-forget listener, and the `.catch` is what keeps a rejection from// reaching the emitter as an unhandled one.- return runQuotaBurnCycle({ trigger: 'continuation', familyId })+ //+ // The denial ledger is folded in FIRST and awaited. If this run was refused,+ // the family's short rolling window is spent and the very next thing this+ // function does — dispatch the next job — would walk straight into the same+ // wall. Recording after the cycle (or from a second `agent:completed`+ // subscriber, whose ordering against this one is not guaranteed) is one wasted+ // agent too late, every single time. A ledger failure must not stop the+ // continuation, so it degrades to a logged warning.+ return recordBurnAgentCompletion(agent)+ .catch((err) => console.error(`⚠️ Quota-burn denial ledger for ${familyId}: ${err.message}`))+ .then(() => runQuotaBurnCycle({ trigger: 'continuation', familyId })).catch((err) => console.error(`❌ Quota-burn continuation for ${familyId} failed: ${err.message}`));}diff --git a/server/services/quotaBurnRunner.test.js b/server/services/quotaBurnRunner.test.jsindex 79a6ce33fe..90474ecace 100644--- a/server/services/quotaBurnRunner.test.js+++ b/server/services/quotaBurnRunner.test.js@@ -12,6 +12,9 @@ const state = {pending: {},ran: [],contexts: [],+ blocks: {},+ settled: [],+ settleError: null,};vi.mock('./providerUsage.js', () => ({@@ -43,6 +46,20 @@ vi.mock('./quotaBurn.js', async (importActual) => ({recordQuotaBurnDispatch: vi.fn(async (key) => { state.recorded.push(key); }),}));+// Same posture as the dispatch ledger: the denial gate stays real (it lives in+// quotaBurn.js), only its storage is stubbed off the install's `data/cos/`.+// `recordBurnAgentCompletion` records into `state.settled` so the continuation's+// ordering — ledger first, THEN the next dispatch — is assertable.+vi.mock('./quotaBurnDenials.js', async (importActual) => ({+ ...(await importActual()),+ getActiveQuotaBurnBlocks: vi.fn(async () => state.blocks),+ recordBurnAgentCompletion: vi.fn(async (agent) => {+ state.settled.push(agent?.metadata?.taskQuotaBurnFamily ?? null);+ if (state.settleError) throw new Error(state.settleError);+ return null;+ }),+}));+const { normalizeQuotaBurnConfig } = await import('../lib/quotaBurnConfig.js');const { getQuotaBurnStatus, runQuotaBurnCycle, rotatePlanAfter, __tickQuotaBurn, __onBurnAgentCompleted, __resetQuotaBurnRunner } = await import('./quotaBurnRunner.js');@@ -75,6 +92,9 @@ beforeEach(() => {state.contexts = [];state.dispatches = {};state.recorded = [];+ state.blocks = {};+ state.settled = [];+ state.settleError = null;state.jobResult = undefined;__resetQuotaBurnRunner();});@@ -271,6 +291,54 @@ describe('getQuotaBurnStatus', () => {// A disabled family's jobs are not probed — the counts would never be acted on.expect(codex.jobs.every((job) => job.pending === null)).toBe(true);});++ it('names WHICH window the percentage and countdown describe', async () => {+ // A family publishes a short rolling window and a weekly one; a bare+ // "50% left · resets in 2h" says nothing about which allowance that is.+ const { status } = await getQuotaBurnStatus();+ expect(status.families.find((family) => family.id === 'grok').windowLabel).toBe('Weekly');+ });++ it('surfaces an observed provider refusal on the family card', async () => {+ state.blocks = { grok: { at: now - 1000, until: now + 3_600_000, reason: 'Usage limit exceeded' } };+ const { status } = await getQuotaBurnStatus();+ const grok = status.families.find((family) => family.id === 'grok');+ expect(grok.willBurn).toBe(false);+ expect(grok.blockedUntil).toBe(new Date(now + 3_600_000).toISOString());+ expect(grok.blockedReason).toBe('Usage limit exceeded');+ expect(grok.skipReason).toMatch(/provider refused the last burn/);+ });+});++/**+ * The stop condition the whole denial ledger exists for: a plan spending a+ * weekly allowance exhausts the SHORT rolling window underneath it, and every+ * further dispatch fails instantly — while the weekly card it gates on still+ * reads "50% left, resets in 2h".+ */+describe('denial blocks in a cycle', () => {+ it('dispatches nothing while the family is blocked, and says why', async () => {+ state.pending = { first: { count: 1 } };+ state.blocks = { grok: { at: now - 1000, until: now + 3_600_000, reason: 'Usage limit exceeded' } };+ const entry = await runQuotaBurnCycle({ trigger: 'scheduled' });+ expect(entry.dispatched).toBe(false);+ expect(entry.reason).toMatch(/provider refused the last burn/);+ expect(state.ran).toEqual([]);+ });++ it('resumes once the block lapses', async () => {+ state.pending = { first: { count: 1 } };+ state.blocks = { grok: { at: now - 7_200_000, until: now - 1000, reason: 'Usage limit exceeded' } };+ const entry = await runQuotaBurnCycle({ trigger: 'scheduled' });+ expect(entry.dispatched).toBe(true);+ });++ it('lets a forced run retry through a block', async () => {+ state.pending = { first: { count: 1 } };+ state.blocks = { grok: { at: now - 1000, until: now + 3_600_000, reason: 'Usage limit exceeded' } };+ const entry = await runQuotaBurnCycle({ trigger: 'manual', familyId: 'grok', jobId: 'first', force: true });+ expect(entry.dispatched).toBe(true);+ });});describe('run-now targeting', () => {@@ -428,6 +496,29 @@ describe('completion continuation', () => {expect(state.runs[0]).toMatchObject({ trigger: 'continuation', dispatched: true });});+ it('records a refusal BEFORE dispatching the next job', async () => {+ // The whole point of the ordering: this continuation dispatches the next job+ // the moment a burn agent finishes, so a block recorded after it runs (or+ // from a second `agent:completed` subscriber, whose ordering against this+ // one is not guaranteed) arrives one wasted agent too late, every time.+ state.pending = { first: { count: 1 } };+ // Whatever the ledger just learned is what selection reads on this very tick.+ state.blocks = { grok: { at: now - 1000, until: now + 3_600_000, reason: 'Usage limit exceeded' } };+ const entry = await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });+ expect(state.settled).toEqual(['grok']);+ expect(entry.dispatched).toBe(false);+ expect(entry.reason).toMatch(/provider refused the last burn/);+ expect(state.ran).toEqual([]);+ });++ it('still continues when the denial ledger itself fails', async () => {+ // Telemetry must never be able to stall the plan.+ state.pending = { first: { count: 1 } };+ state.settleError = 'ENOSPC';+ const entry = await __onBurnAgentCompleted({ metadata: { taskQuotaBurnFamily: 'grok' } });+ expect(entry.dispatched).toBe(true);+ });+it('scrapes only the burning family\'s quota, not every enabled provider\'s', async () => {// WAIT.FRESH bypasses the cache by design, so each card costs its own// multi-second PTY spawn — and every card but this family's is discarded.