Skip to content

Epic: quota intelligence (live remaining, burn-rate forecast, pre-flight awareness, invoice reconciliation) #725

Open

Description

@iamtoruk

Motivation

The single loudest unserved ask across every voice-of-customer source is a live "how close am I to the wall" view with a forecast: how much of my plan is left, and when will I hit the limit at this pace. Users describe it viscerally ("my lizard brain wants to hoard it"; weekly limits "gone in one or two days"), and the structural reason no one has built it is that no vendor exposes an official quota API for consumer plans. A local tool that already reads the session logs and the live rate-limit surfaces is the only thing that can physically see the signal, and see it across vendors in one place.

CodeBurn is already most of the way there without having named the target:

What's missing is the synthesis: a single quota model per plan, a burn-rate forecast against the plan window (not just the calendar month), pre-flight cost awareness, and one clear surface that answers "am I about to run out." This epic scopes that, decoupled so pieces can land independently.

Non-goals (this epic)

Proposed scope, decoupled parts

Part 1 — Quota model (src/quota.ts, foundation, no UI)

A provider-agnostic model of a plan's quota state: for each active window (5h, weekly, monthly, credit-based), the limit, the amount used, the reset time, and a pace (used / elapsed-fraction-of-window). Fed by two sources that already exist: derived-from-local-tokens (works offline, all providers) and live-quota-endpoint (Claude/Codex, authoritative when present). Live wins when available; local is the always-on fallback. Pure and testable, mirroring plan-usage.ts. Depends on nothing.

Part 2 — Burn-rate forecast (extends Part 1 + budget.ts math)

Given the window model and recent burn rate, project the exhaustion time: "at this pace you hit your weekly limit Thursday ~3pm" and "projected to end the window at 140%." Reuse the run-rate approach in budget.ts but anchor to the plan window boundaries from Part 1, not the calendar month. Honest about confidence with sparse data (same discipline as the outlier/young-project work). Depends on Part 1.

Part 3 — Surfaces (menubar + statusline + CLI + web)

  • Menubar Plan tab: a live burn-down bar per window and the forecast line, next to the Codex reset-credits row menubar: surface Codex limit-reset credits (count and next expiry) in the Plan tab #724 already added.
  • A first-class quota statusline (research flagged this as a parity gap with ccusage's ecosystem) showing remaining + forecast, distinct from guard --statusline which is cost caps.
  • codeburn plan / a codeburn quota view surfacing the same model in the TUI and --json.
    Depends on Parts 1 and 2. UI-only; each surface can land separately.

Part 4 — Pre-flight cost awareness (optional, opt-in)

Before an expensive turn, an ambient signal of what it will cost against the remaining window ("~40 credits, 3% of your month"). Delivered through the existing MCP server or a hook, never a blocking gate. Depends on Part 1; can follow the surfaces.

Part 5 — Invoice reconciliation (trust, separable)

An opt-in mode that reconciles CodeBurn's parsed spend against official billed spend where an API exists (Anthropic cost API, OpenRouter key endpoint, Claude Code OTEL) and flags drift. Directly answers "are these numbers even right." Strictly opt-in and network-gated, off by default, honoring the local-first promise. Independent of the rest; grouped here because it is the trust half of quota confidence.

Dependency order

Part 1 first. Parts 2 and 5 in parallel after (5 is fully independent and can start anytime). Part 3 after Part 2. Part 4 last. Each part is its own PR; UI surfaces in Part 3 are independently shippable.

Evidence gate (per the epic-#602 discipline)

Before Part 2's forecast ships to users, it must be validated against real historical windows: replay a month of local sessions, compute the forecast at each day, and check it against what actually happened at the window boundary. A forecast that is confidently wrong is worse than none, so the same reproduce-and-measure bar the acting layer used applies here.

Already shipped toward this

Contributions welcome on any decoupled part. Comment to claim one; design discussion on the model shape (Part 1) is the most useful place to start.

Activity

  1. avs-io commented on Jul 17, 2026

    @avs-io
    Collaborator

    Claiming Part 1 (quota model). Also for the record: #726 phase 1 (the Part 2 menubar slice you green-lit) is in progress now, so Part 1 here is next in queue after that lands.

    Proposed model shape for src/quota.ts, before any code — happy to adjust:

    type QuotaWindowKind = 'five_hour' | 'weekly' | 'monthly' | 'credits' | { custom: string }
    
    interface QuotaWindow {
      kind: QuotaWindowKind
      label: string                 // display label, provider-supplied when live
      usedFraction: number          // 0..1
      resetsAt?: Date
      windowSeconds?: number
      source: 'live' | 'derived'    // provenance is load-bearing, see below
      pace?: QuotaPace              // computed, never stored
    }
    
    interface QuotaPace {
      expectedFraction: number      // elapsed/duration
      deltaFraction: number         // used − expected; + = deficit
      projectedAtReset?: number     // linear; absent under the noise guards
      exhaustsAt?: Date             // absent unless projection > 1 and window long enough
    }
    
    interface PlanQuota {
      provider: string
      plan?: string                 // "pro", "max_20x", … when known
      windows: QuotaWindow[]
      asOf: Date
    }

    Semantics I'd commit to:

    1. Merge rule: live wins per (provider, kind); derived fills the gaps. The merged result keeps source per window rather than per plan — a Claude weekly from the live endpoint and a monthly derived from local tokens coexist, and every surface can (and should) render derived windows as estimates. Same discipline as costIsEstimated: a guess must never render as a measurement.
    2. Pace is a pure function of (window, now), computed on read, with the menubar: quota windows show no pace — add run-out projection (deficit, lasts-to-reset / runs-out-in) #726 guards (nothing until ~3% of the window has elapsed, reset-skew returns nothing, short windows get deficit but no exhaustion ETA). One implementation shared by every surface so the CLI, TUI, and menubar can never disagree about pace.
    3. Degradation is explicit: a provider with no live endpoint and no local signal yields no windows, not zeros. Absent ≠ empty.
    4. Tests: table-driven over the merge rule (live/derived collisions, partial coverage, staleness) and the pace guards, injected clock throughout — mirroring how plan-usage.ts is tested.

    One open question worth deciding before code: on the CLI side, where do live snapshots enter? The live fetchers currently live in the menubar (Swift), so Part 1 as a pure TS model works offline-first from day one, but "live wins" only activates for surfaces that have a live snapshot to hand it. Options: (a) model accepts an optional live snapshot param and the menubar is the first supplier via its existing payload path, or (b) the CLI grows its own read of the same endpoints later as a separate decision. I'd start with (a) — no new network surface, consistent with the epic's non-goals.

  2. added
    enhancement
    area: cli
    area: menubar
    status: has-pr
    on Sep 14, 2026
  3. added
    area: web-dash
    and removed
    status: has-pr
    on Sep 28, 2026
  4. hasanAbbas2004 commented on Nov 3, 2026

    @hasanAbbas2004
    Contributor

    Measured data for Parts 3/4: what one Claude Code turn costs against the 5-hour window

    I logged the 5-hour % from /api/oauth/usage at the start and end of every Claude Code turn (via hooks) and matched it against the local transcripts, on a Pro plan. Two findings that may help with the pre-flight signal (Part 4) and a quota statusline (Part 3):

    1. Output tokens drive the 5-hour %, context length barely does. In controlled tests, the same amount of output in a fresh context and in a long one moved the % by the same amount, even with 3.6× (Opus) and 71× (Sonnet) more cache reads. Predicting the second half of a window from the first: output tokens only had 0.8 points of error, API price weighting 1.4, all tokens flat 9.0.

    2. On Pro, 1% of the 5-hour window ≈ 6,000 output tokens on Opus 5.5 and ≈ 9,500 on Sonnet 5.5 (ranges 4,700–9,400 and 7,700–11,200; a least-squares fit over all readings gives 5,500 and 9,600).

    So a turn's cost can be estimated as output_tokens / ratio(model). CodeBurn's parser already reads output_tokens and model and dedupes streaming partials, so this needs no new network calls, which fits the epic's non-goals.

    Caveats: one account, one plan (Pro), two days, whole-number readings. Max plans will differ, so the ratio needs calibrating per plan (it can be fitted from % readings plus the transcripts: least squares over intervals of 15+ minutes, since the % lags usage by 1–2 min). Other pitfalls I hit: resets_at jitters across minute boundaries (round, don't truncate), and resumed sessions repeat earlier message ids.

    I've built this as a status line in a small local tool: 5h 41% · resets 1h 12m · task ~1.3%. Claude Code already passes rate_limits.five_hour.used_percentage / resets_at on the status line's stdin, so the live % needs no API call at all, and the task cost is just the transcript's output tokens since the last user prompt divided by the per-model ratio.

    I'd like to claim Part 3 with that. Proposal: extend codeburn guard statusline (Claude Code allows only one status line, and guard already installs it) to codeburn guard $1.24 · 5h 41% · resets 1h 12m · turn ≈1.3%. It would reuse computeSessionUsage's incremental fold to track output per model since the last user prompt, mark the estimate as derived per Part 1, and make no new network calls. Roughly 250 lines with tests.

    Questions before I start:

    1. Is extending guard's status line OK, or would you prefer a separate command?
    2. Where should the per-model ratios live (next to src/quota.ts?), and should they be per plan? I've only measured Pro.
    3. Guard reads only transcript_path, but subagent transcripts (<session>/subagents/) use the quota too. Should this PR count them, or should that be a separate change?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: cliarea: menubararea: web-dashenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions