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
drop the per-family provider ID and window scope knobs from quota burn
[._.]/ Adam Eivye0b5ac37ce0e
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1f0ce50c7b..9da8782152 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,8 @@## Changed+- **Quota Burn's per-family "Provider ID" and "Window scope" boxes are gone.** Both were free-text overrides for decisions the page already makes correctly on its own: the family match already prefers the watchable TUI provider over the headless CLI (a hand-typed id could only ever pick a worse one), and window targeting already reads *every* window on the card — the broadest one as the target the reset horizon and dispatch cap key on, the narrowest as the one that will refuse first, the tightest as the one the reserve guards. Scope was a free-text filter over that, so its realistic uses were "type the same thing the classifier already picked" or "type a word this provider doesn't publish and silently never burn." A job still carries its own optional `providerId`, which is the level where naming a specific provider actually means something. Configs written before this load unchanged — the normalizer drops both keys on the next save — and migration 221 no longer carries them over from the retired per-app shape.+- **The `cosAgents.js` barrel is gone, so an agent function no longer arrives from a specifier that says nothing about which layer it lives in.** The #2530 decomposition split a ~1090-line module into four focused siblings — `cosAgentIndex.js` (date-bucket index + on-disk archive layout), `cosAgentLifecycle.js` (register / update / complete / output / terminate), `cosAgentFeedback.js` (capture + classifier), `cosAgentArchive.js` (state-eviction sweeps) — then put an `export *` wall back in front of all four so no import path had to change. Three years of imports later, `updateAgent` and `getAgentsByDate` came from the same specifier despite sitting in different layers, and the wall is what made `cos.js` a *two*-hop forwarder of a lifecycle transition, which is the shape #3450's guard exists to delete. All ~20 production importers and ~14 `vi.mock` targets now name the module that declares what they asked for — several of which turn out to want only the index (`cosReports.js`, the peer cos-history merge) or only the lifecycle layer (the runner sync, the TUI output spooler, the completion cleanup), so the graph gets narrower as well as flatter. The four leaf modules are unchanged; the two test files that only ever exercised one of them are renamed to sit beside it (`cosAgentLifecycle.test.js`, `cosAgentIndex.merge.test.js`). The forwarder guard in `agentImportCycles.test.js` — which walks re-export edges rather than naming barrels, so a new one is covered the day it is written — now asserts `cos.js` is the *only* module forwarding a transition, and was bypass-probed both ways: planting a fresh `export *` barrel turns it red, and so does routing a production import of `completeAgent` back through `cos.js`. Its two module-loading assertions also take an explicit timeout: they transform `cos.js`'s whole service graph, which lands at 5–10s and straddles Vitest's 10s default, so the guard was one busy machine away from failing for a reason that had nothing to do with the invariant (#3450).- **The agent lifecycle has a named entry point instead of seven mutually-recursive modules.** The `cos.js → cosAgents.js → cosAgentLifecycle.js → agentManagement.js → agents.js → subAgentSpawner.js → agentLifecycle.js` cluster has no owner, so reasoning about one transition — pause, kill, complete, spawn — means holding all seven files in mind, and several of the back-edges are `await import(...)` calls that exist only to dodge a load-time cycle. `server/services/agentOrchestrator.js` is the facade above that cluster: it imports the transition owners one-directionally, carries the transition-vs-leaf classification in its header so later passes start from it, and renames apart the two different functions both called `terminateAgent` — `requestAgentTermination` only emits the event and returns, while `terminateAgent` keeps the name for the real SIGTERM/SIGKILL sequence. The four agent routes (terminate, pause, kill, stats) now go through it, one hop instead of three. `agentImportCycles.test.js` gains a guard that fails if anything reachable from the facade imports it back, statically *or* via `import(...)` — the dynamic form matters because reaching across a blocked layer that way is exactly this cluster's habit, and the forbidden set is derived from the graph rather than listed so it can't fall behind. Widening that suite's graph builder to walk subdirectories closed a hole in the pre-existing cycle guard too: it read only top-level `server/services/*.js`, so a cycle routed through one subdirectory hop (`agentTuiSpawning/outputSpooler.js` already imports back up to `../cosAgents.js`) was invisible to it. The remaining call sites and the dynamic-import workarounds follow in later PRs (#3450).@@ -27,7 +29,7 @@## 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.+- **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 on the card, 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. 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.diff --git a/client/src/components/quotaBurn/FamilyCard.jsx b/client/src/components/quotaBurn/FamilyCard.jsxindex 5c8cd06ff6..76cbc9ae17 100644--- a/client/src/components/quotaBurn/FamilyCard.jsx+++ b/client/src/components/quotaBurn/FamilyCard.jsx@@ -13,7 +13,7 @@ import JobRow from './JobRow';import PresetPicker from './PresetPicker';import { jobFromPreset } from '../../lib/quotaBurnPatch';import { formatDateTime } from '../../utils/formatters';-import { NumberField, TextField } from './fields';+import { NumberField } from './fields';export default function FamilyCard({familyId, config, status, catalog, expanded, actionsBusy,@@ -24,7 +24,8 @@ export default function FamilyCard({// prop — merging them into the job objects would mean stripping them back off// before every save (the PUT schema is strict). Matched by id so a reorder// mid-save can't mis-pair them.- const pendingFor = (id) => (status?.jobs || []).find((row) => row.id === id)?.pending ?? null;+ const statusJobs = status?.jobs || [];+ const pendingFor = (id) => statusJobs.find((row) => row.id === id)?.pending ?? null;const patchJobs = (next) => onPatch({ jobs: next });const changeJob = (index, next) => patchJobs(jobs.map((job, i) => (i === index ? next : job)));@@ -64,12 +65,15 @@ export default function FamilyCard({}]);// A preset job inherits the app the plan is already pointed at, when the plan// is unambiguous about it — otherwise a one-click "add a UX audit" lands as a- // step that cannot run until the user notices the unset app picker.- const targetedAppIds = [...new Set(jobs.map((job) => job.params?.appId).filter(Boolean))];- const addPresetJob = (preset) => patchJobs([...jobs, jobFromPreset(preset, {- id: nextJobId(),- appId: targetedAppIds.length === 1 ? targetedAppIds[0] : null,- })]);+ // step that cannot run until the user notices the unset app picker. Derived at+ // click time, not per render: the page polls while any family is pending.+ const addPresetJob = (preset) => {+ const targetedAppIds = [...new Set(jobs.map((job) => job.params?.appId).filter(Boolean))];+ patchJobs([...jobs, jobFromPreset(preset, {+ id: nextJobId(),+ appId: targetedAppIds.length === 1 ? targetedAppIds[0] : null,+ })]);+ };return (<div className="rounded border border-port-border bg-port-card/40">@@ -155,11 +159,6 @@ export default function FamilyCard({<NumberField id={`burn-${familyId}-priority`} label="Priority" value={config.priority} onChange={(v) => onPatch({ priority: v })} min={0} max={100} hint="Lower wins when two windows reset together." /></div>- <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">- <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 targets the broadest window" />- </div>-<div className="space-y-3"><div className="flex items-center justify-between"><h3 className="text-xs uppercase tracking-wide text-gray-400">Burn plan — runs in order</h3>diff --git a/client/src/components/quotaBurn/fields.jsx b/client/src/components/quotaBurn/fields.jsxindex 60aca58c97..6ea2dd905e 100644--- a/client/src/components/quotaBurn/fields.jsx+++ b/client/src/components/quotaBurn/fields.jsx@@ -1,11 +1,11 @@/*** Shared field primitives for the Quota Burn config surface.*- * The three components here (`FamilyCard`, `JobRow`, `JobParamField`) all render- * the same dark label+control pair. Keeping the class string and the number- * field in one place means a styling change is one edit rather than four —- * before this, the identical Tailwind string was declared or inlined at four- * sites and had already started to drift.+ * `FamilyCard`, `JobRow`, `JobParamField` and `PresetPicker` all render the same+ * dark label+control pair. Keeping the class string and the number field in one+ * place means a styling change is one edit rather than four — before this, the+ * identical Tailwind string was declared or inlined at four sites and had+ * already started to drift.*/import { useState } from 'react';@@ -46,19 +46,3 @@ export function NumberField({ id, label, value, onChange, min, max, hint }) {</label>);}--/** A labeled text input. `value` is always controlled; `null` renders as empty. */-export function TextField({ id, label, value, onChange, placeholder }) {- return (- <label htmlFor={id} className="block text-xs text-gray-400">- {label}- <input- id={id}- className={inputClass}- value={value || ''}- placeholder={placeholder}- onChange={(event) => onChange(event.target.value || null)}- />- </label>- );-}diff --git a/client/src/pages/QuotaBurn.test.jsx b/client/src/pages/QuotaBurn.test.jsxindex 2c86ac793e..25f0770368 100644--- a/client/src/pages/QuotaBurn.test.jsx+++ b/client/src/pages/QuotaBurn.test.jsx@@ -19,11 +19,11 @@ const config = {checkIntervalMinutes: 30,families: {grok: {- enabled: true, providerId: null, scope: null, resetWithinHours: 24, reservePercent: 10,+ enabled: true, resetWithinHours: 24, reservePercent: 10,maxDispatchesPerWindow: 5, priority: 0,jobs: [{ id: 'j1', enabled: true, label: 'Bible images', jobType: 'universe-bible-images', model: null, providerId: null, params: {} }],},- codex: { enabled: false, providerId: null, scope: null, resetWithinHours: 24, reservePercent: 0, maxDispatchesPerWindow: 5, priority: 0, jobs: [] },+ codex: { enabled: false, resetWithinHours: 24, reservePercent: 0, maxDispatchesPerWindow: 5, priority: 0, jobs: [] },},};diff --git a/docs/QUOTA-BURN.md b/docs/QUOTA-BURN.mdindex 9d42fb6b96..28ce758389 100644--- a/docs/QUOTA-BURN.md+++ b/docs/QUOTA-BURN.md@@ -16,7 +16,7 @@ Every `checkIntervalMinutes` (default 30, bounded 5–720) the runner:2. Takes a zero-token quota reading for every enabled provider family.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+ have headroom above `reservePercent` in *every* window on the card, and that havenot spent `maxDispatchesPerWindow` for that window. Ties break on `priority`(lower wins).4. Runs the **first enabled job in that family's ordered plan that reports@@ -36,9 +36,9 @@ rolling one (claude/codex `session` ≈ 5h, antigravity `5-hour`) and a long one| | 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. |+| **Target** | The **broadest** window on the card (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 on the card (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 on the card 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@@ -49,9 +49,7 @@ 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 statesone (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.+classified at all falls back to soonest-reset ordering.## Stop condition: an observed refusaldiff --git a/scripts/migrations/221-quota-burn-global-config.js b/scripts/migrations/221-quota-burn-global-config.jsindex 9c5163743b..6181bbddec 100644--- a/scripts/migrations/221-quota-burn-global-config.js+++ b/scripts/migrations/221-quota-burn-global-config.js@@ -119,8 +119,6 @@ export function buildGlobalPlan(apps, { scheduleArmed = true } = {}) {});}const windowSettings = {- providerId: value.providerId || null,- scope: typeof value.scope === 'string' ? value.scope : null,resetWithinHours: Number.isFinite(Number(value.resetWithinHours)) ? Number(value.resetWithinHours) : 24,reservePercent: Number.isFinite(Number(value.reservePercent)) ? Number(value.reservePercent) : 0,maxDispatchesPerWindow: Number.isFinite(Number(value.maxDispatchesPerWindow)) ? Number(value.maxDispatchesPerWindow) : 5,diff --git a/server/lib/quotaBurnConfig.js b/server/lib/quotaBurnConfig.jsindex 2241b50e51..3efc529f1c 100644--- a/server/lib/quotaBurnConfig.js+++ b/server/lib/quotaBurnConfig.js@@ -74,7 +74,6 @@ export const QUOTA_BURN_BOUNDS = Object.freeze({jobsPerFamily: { max: 25 },idLength: { max: 64 },labelLength: { max: 120 },- scopeLength: { max: 60 },paramLength: { max: 8000 },});const BOUNDS = QUOTA_BURN_BOUNDS;@@ -139,17 +138,6 @@ export const QUOTA_BURN_JOB_CATALOG = Object.freeze([},]);-const DEFAULT_QUOTA_BURN_FAMILY = Object.freeze({- enabled: false,- providerId: null,- scope: null,- resetWithinHours: BOUNDS.resetWithinHours.default,- reservePercent: BOUNDS.reservePercent.default,- maxDispatchesPerWindow: BOUNDS.maxDispatchesPerWindow.default,- priority: BOUNDS.priority.default,- jobs: Object.freeze([]),-});-// Clamp against one QUOTA_BURN_BOUNDS entry, falling back to its documented// default when the value is missing or non-numeric.const clamp = ({ min, max, default: fallback }, value) => {@@ -224,8 +212,6 @@ export function normalizeQuotaBurnFamily(raw) {.filter(Boolean);return {enabled: value.enabled === true,- providerId: nullableString(value.providerId, BOUNDS.labelLength.max),- scope: nullableString(value.scope, BOUNDS.scopeLength.max),resetWithinHours: clamp(BOUNDS.resetWithinHours, value.resetWithinHours),reservePercent: clamp(BOUNDS.reservePercent, value.reservePercent),maxDispatchesPerWindow: clampInt(BOUNDS.maxDispatchesPerWindow, value.maxDispatchesPerWindow),diff --git a/server/lib/quotaBurnConfig.test.js b/server/lib/quotaBurnConfig.test.jsindex d42d98f784..473714a59f 100644--- a/server/lib/quotaBurnConfig.test.js+++ b/server/lib/quotaBurnConfig.test.js@@ -29,6 +29,17 @@ describe('normalizeQuotaBurnConfig', () => {});});+ it('drops the retired per-family providerId / scope keys from an older plan', () => {+ // Both were removed from the family shape; a config file written before that+ // must still load, minus the keys, rather than carrying dead state forward.+ const family = normalizeQuotaBurnConfig({+ families: { grok: { enabled: true, providerId: 'grok-cli', scope: 'session' } },+ }).families.grok;+ expect(family.enabled).toBe(true);+ expect(family).not.toHaveProperty('providerId');+ expect(family).not.toHaveProperty('scope');+ });+it('clamps the check interval into the polling bounds', () => {expect(normalizeQuotaBurnConfig({ checkIntervalMinutes: 1 }).checkIntervalMinutes).toBe(5);expect(normalizeQuotaBurnConfig({ checkIntervalMinutes: 99999 }).checkIntervalMinutes).toBe(720);diff --git a/server/lib/quotaBurnValidation.js b/server/lib/quotaBurnValidation.jsindex 43f8515770..16fe539056 100644--- a/server/lib/quotaBurnValidation.js+++ b/server/lib/quotaBurnValidation.js@@ -36,8 +36,6 @@ const quotaBurnJobSchema = z.object({const quotaBurnFamilySchema = z.object({enabled: z.boolean().optional(),- providerId: z.string().max(B.labelLength.max).nullable().optional(),- scope: z.string().max(B.scopeLength.max).nullable().optional(),resetWithinHours: z.number().min(B.resetWithinHours.min).max(B.resetWithinHours.max).optional(),reservePercent: z.number().min(B.reservePercent.min).max(B.reservePercent.max).optional(),maxDispatchesPerWindow: z.number().int().min(B.maxDispatchesPerWindow.min).max(B.maxDispatchesPerWindow.max).optional(),diff --git a/server/lib/quotaWindows.js b/server/lib/quotaWindows.jsindex f1d33e7603..c9013879af 100644--- a/server/lib/quotaWindows.js+++ b/server/lib/quotaWindows.js@@ -85,14 +85,14 @@ export function windowPeriodHours(limit) {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:+ * Split one card's 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.+ * Ties break on the soonest reset. Null when no window on the+ * card 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 adiff --git a/server/services/quotaBurn.js b/server/services/quotaBurn.jsindex e08f34f210..f04ffeadc7 100644--- a/server/services/quotaBurn.js+++ b/server/services/quotaBurn.js@@ -68,18 +68,14 @@ export async function recordQuotaBurnDispatch(key, { now = Date.now() } = {}) {});}-/** 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) {return Math.max(0, Number(limit?.percentRemaining) - family.reservePercent);}/**- * The window with the LEAST headroom among everything in scope — what the- * reserve is actually protecting.+ * The window with the LEAST headroom on the card — what the reserve is actually+ * protecting.** Checking only the soonest-resetting window (which is what selection keys on)* makes the reserve inert for every provider that reports two: claude, codex and@@ -89,8 +85,8 @@ 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(scoped, family) {- const measured = scoped.filter((limit) => Number.isFinite(Number(limit?.percentRemaining)));+function tightestBudget(limits, family) {+ const measured = limits.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));@@ -160,15 +156,7 @@ export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}// just refused. Opt-out only: absent means burnable.if (card.burnable === false) return { skipReason: 'provider reports no spendable headroom' };- // Distinguish "your scope filter matched nothing" from "the provider states- // no reset time". `scope` is a free-text field on the page, so a typo (`weekly`- // against a card whose windows are `week`/`month`) otherwise reads as a fault- // in the quota adapter and the family silently never burns.- if (family.scope && !(card.limits || []).some((limit) => limit.scope === family.scope)) {- 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(', ')})` : ''}` };- }- // ONE scoring pass over the in-scope windows yields both roles a burn reasons+ // ONE scoring pass over the card's windows yields both roles a burn reasons// about (see `lib/quotaWindows.js`)://// `target` — the BROADEST window: the allowance that expires unused. Not@@ -183,17 +171,17 @@ export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}// `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 }));+ const limits = card.limits || [];+ const { target, limiting } = classifyWindows(limits, (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 (!target) return { skipReason: 'no window states a reset time' };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+ // The reserve guards the TIGHTEST window on the card, not the one selection// happens to key on (see `tightestBudget`).- const tightest = tightestBudget(scoped, family) || target.limit;+ const tightest = tightestBudget(limits, family) || target.limit;const block = blocks[family.id];// The gates a forced run is allowed past. Evaluated regardless so the ordering@@ -227,7 +215,7 @@ export function evaluateFamily(family, card, { now = Date.now(), dispatches = {}card,limit: target.limit,hoursUntilReset: target.hours,- // The narrowest window in scope — what a refusal is actually about. Null+ // The narrowest window on the card — 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,diff --git a/server/services/quotaBurn.test.js b/server/services/quotaBurn.test.jsindex 668aa341ef..da29cc2a91 100644--- a/server/services/quotaBurn.test.js+++ b/server/services/quotaBurn.test.js@@ -246,7 +246,7 @@ describe('reserve across every window', () => {expect(verdict.skipReason).toMatch(/Weekly at 2% left is at or below the 40% reserve/);});- it('burns when EVERY in-scope window is above the reserve', () => {+ it('burns when EVERY window on the card is above the reserve', () => {expect(evaluateFamilies([twoWindow(100, 90)], family, { now: NOW })[0].candidate).toBeTruthy();});});@@ -277,14 +277,6 @@ describe('window targeting', () => {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 = {diff --git a/server/services/quotaBurnJobs/agentPrompt.js b/server/services/quotaBurnJobs/agentPrompt.jsindex cd6ccf9acb..cd286aaec1 100644--- a/server/services/quotaBurnJobs/agentPrompt.js+++ b/server/services/quotaBurnJobs/agentPrompt.js@@ -19,9 +19,9 @@ import { burnTaskDescription } from '../../lib/quotaBurnConfig.js';import { windowLabelOf } from '../../lib/quotaWindows.js';/**- * An agent-capable provider in the burning family. An explicit `providerId`- * (job first, then family) wins; otherwise match the family id against the- * enabled providers, PREFERRING the TUI.+ * An agent-capable provider in the burning family. A job's explicit+ * `providerId` wins; otherwise match the family id against the enabled+ * providers, PREFERRING the TUI.** Preferring the TUI is the point: a burn runs unattended for minutes on the* user's own subscription, and a TUI agent is watchable in Active Agents and can@@ -79,7 +79,7 @@ async function resolve({ params, job, family }) {const result = await getAllProviders();const provider = providerForFamily(Array.isArray(result) ? result : result?.providers,- { familyId: family?.id, providerId: job?.providerId || family?.providerId || null },+ { familyId: family?.id, providerId: job?.providerId || null },);if (!provider) return { error: `no enabled CLI/TUI provider in the ${family?.id} family` };return { app, prompt, provider };