strategy

package
v0.29.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 17 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package strategy decides which account the engine should be on.

Index

Constants

View Source
const (
	// DefaultHysteresisPct is the hysteresis margin, in percentage points of
	// SLACK: how far a candidate must beat the active account to displace it,
	// which is what stops a ping-pong near the threshold.
	//
	// The margin and its `hysteresis_pct` config key are settled; the number
	// is not, so it is chosen here. Ten points is the smallest margin that
	// actually does the job it is named for: the binding window can change
	// between two readings — an account whose five_hour and seven_day are a
	// point apart flips between them — and that alone moves headroom by a few
	// points with no usage at all. A margin under that noise floor lets the
	// engine ping-pong across the threshold on jitter, which is the one thing
	// this margin exists to prevent.
	DefaultHysteresisPct = 10.0

	// DefaultHeadroomRatio is 2.0. A candidate must have twice the active
	// account's headroom, which is what makes a REVERSE move need a 4x relative
	// burn: the forward move already required 2x in the other direction, so the
	// ratio between the two has to swing by 2x2. That squaring is the whole point,
	// and it falls out of applying the same 2.0 to every move rather than out of
	// remembering which account was left.
	DefaultHeadroomRatio = 2.0

	// DefaultCooldown is the 5-minute minimum gap between two switches, the
	// mechanism against switch storms.
	DefaultCooldown = 5 * time.Minute

	// DefaultRecoveryHysteresis is 300 s. It is the margin on the RECOVERY
	// axis, for the all-above-threshold mode that ranks by soonest recovery:
	// comparing headroom there would gate on a number the order did not use.
	DefaultRecoveryHysteresis = 300 * time.Second

	// DefaultQuarantine is how long a dead refresh token holds an account out.
	//
	// No expiry is fixed for it, so it is chosen here. An hour matches
	// DefaultRecoveryHorizon and is short enough that a MISCLASSIFIED failure
	// costs an hour rather than a day; a genuinely dead token costs one wasted
	// refresh an hour, which is nothing. Only re-authentication actually fixes
	// a dead token, so this expiry is a safety valve and not a healing time —
	// see Quarantine.
	DefaultQuarantine = time.Hour
)
View Source
const (
	// HoverHandoffThreshold is the threshold hover holds every window to: the
	// last point the endpoint reports before the reading that says the account
	// has stopped.
	//
	// Hover has no pace line, so the only line room is measured against is the
	// one it hands off at, and that is what `ccdad status --json` prints beside
	// each window. It also fixes what the shared machinery means under hover:
	// ModeRecovery is every account Spent -- past this line on a window no
	// model choice can dodge, because hover's table does not bind on the others
	// (ModelCapsDodged) -- which is when soonest-recovery is the right question,
	// and a blown cap on one model family does not get it there.
	//
	// And it is positive, which admittedWindows relies on when it reads the
	// opt-in for a scope this build cannot name: a non-positive per-window entry
	// reads as "not opted in", and hover's table carries the user's opt-ins at
	// this line, so a non-positive one would silently revoke that consent.
	HoverHandoffThreshold = 100 - handoffRoomPct

	// HoverCreditThreshold is the figure a primary credit seat is measured on.
	//
	// A credit seat has no window and no reset, so there is no rollover to wait
	// for. 95 rather than the hand-off line because credits do not come back at
	// all: the last few points are the only warning a user gets that the seat
	// is nearly spent, where a subscription window's last few points are gone
	// in hours anyway.
	HoverCreditThreshold = 95.0

	// HoverCooldown is 2 minutes rather than the stock 5.
	//
	// It is the only hold on the pre-emptive move -- Decide answers pre-emption
	// before every margin but not before the cooldown -- so it is sized for that
	// move: two polls at the 60 s urgent cadence, so that a session handed on
	// can be handed on again before a second limit lands. It no longer has to
	// bound a rotation, which is what lets it be this short. The order does
	// that: a return onto an account left at a limit waits for that account's
	// window to roll, a move between two weekly-only seats needs one week to end
	// recovery_hysteresis sooner than the other, and a five-hour account is left
	// only at a limit. The out-and-back two minutes and one second apart that
	// this cooldown once allowed needs none of the three.
	HoverCooldown = 2 * time.Minute
)
View Source
const (
	// DefaultThreshold is the utilization percent above which an account counts
	// as spent. `ccdad config` supplies the real value; this is what stands in
	// when it has not.
	DefaultThreshold = 80.0

	// DefaultCreditThreshold is the utilization percent above which a
	// credit-metered account counts as spent.
	//
	// It matches DefaultThreshold because it answers the same question on a
	// different meter — a share of a credit balance rather than of a plan
	// window — and it is its own constant so that the two can be moved apart
	// without the credit axis silently inheriting a change made for
	// subscriptions.
	DefaultCreditThreshold = 80.0

	// DefaultRecoveryHorizon is how soon a spent account has to come back before
	// "it comes back soon" outranks "it is less blown".
	//
	// The 300 s recovery hysteresis has a fixed default; nothing fixes this
	// one, so it is chosen here. An hour matches the window the endpoint's own
	// request budget slides over (pollpolicy.Recent429Window), and it is about
	// the longest wait a user would sit through rather than switching by hand.
	// Past it, "when does it come back" stops being the useful question and how
	// badly an account is blown is the better discriminator — which is exactly
	// what the far tier ranks on.
	DefaultRecoveryHorizon = time.Hour
)
View Source
const CreditSubscriptionNotExhausted = CreditMainPoolNotExhausted

CreditSubscriptionNotExhausted is CreditMainPoolNotExhausted under the name it had while the main pool was subscriptions and nothing else.

Deprecated: use CreditMainPoolNotExhausted. Kept for one release for the same reason SubscriptionExhausted is.

View Source
const CreditWindow usage.WindowName = "extra_usage"

creditWindow is the binding-window name a primary seat reports. It is extra_usage's own key on the wire, and it is deliberately NOT one of the six window names: a caller looking it up in Snapshot.AllWindows finds nothing, which is the true answer -- there is no window behind it and no reset, so recoveryOf answers "no recovery" without needing to be told about this axis.

View Source
const EvaluationInterval = time.Second

EvaluationInterval is how often the engine is asked: the daemon's tick, τ in the hand-off rule. It lives here so the daemon's loop and the weekly simulation read one constant, and so "before the engine next looks" is stated in the unit the engine actually looks in.

View Source
const (
	StateFileName = "strategy.json"
)

Variables

This section is empty.

Functions

func ColdWindow added in v0.5.0

func ColdWindow(s *usage.Snapshot, model string, t Thresholds, now time.Time) (usage.WindowName, time.Time, bool)

ColdWindow is the first window in an account's own candidate set — the windows its table admits (admittedWindows), a cap hover does not count as a limit included — whose clock is not running, together with the rollover the reading reported for it and whether there was one.

A five-hour window is anchored at first use and does not stretch when more is spent against it, so a clock started early is elapsed time the account gets for free — that is what a warm-up buys, and this names the window that has none running.

There are two ways to have no clock, and both are here because a warm-up answers both:

  • NEVER SPENT: nothing used, no reset. This is the original question, and the one an account added five minutes ago asks.
  • ROLLED OVER: the reading carries a reset that has already PASSED. The window ran down; the cached reading is simply older than the event. This arm is why the warm-up can land on the same tick as the poll that finds the window cold — without it the daemon must wait for one poll to write {0, null} and then for the NEXT poll's tick to notice, and both intervals are the ten-minute idle cadence.

A window at more than 0% with no reset is in neither arm; neverSpent says why.

It does not stop at the single BINDING window the way HeadroomFor does. An account's five-hour window can sit with no clock while a weekly cap binds tighter and has a running one of its own: from the ranking's point of view that account has pace already, but the five-hour clock is still stopped, and stopping is what costs lockout later. Ties resolve on the schema's own order, the same way HeadroomFor's do, which in practice means the plain five-hour window — first in wire order — wins over a weekly one when both qualify, and that is the window worth having.

func CreditRoom

func CreditRoom(s SpendInfo, ceiling float64) (float64, bool)

CreditRoom is the room calculation. Its local is named `capacity` rather than `cap` so it does not shadow the builtin.

The IsInf and IsNaN checks are load-bearing, not decoration. `max_auto_spend = inf` is valid TOML, and an infinite ceiling with no account cap yields unlimited unattended spending; NaN slips a plain `<= 0` because every NaN comparison is false.

func FixedWindowFamily added in v0.3.0

func FixedWindowFamily(n usage.WindowName) (string, bool)

FixedWindowFamily is the family a FIXED window is scoped to. It is written out rather than derived from the window's name, so that a future window whose key happens to contain a family token does not become model-scoped by accident.

This is the one place the correspondence is spelled. internal/daemon's probeModel and internal/cli's probeWindow both go through it — the first forward, the second through WindowForFixedFamily's reverse table — rather than each carrying its own switch, which is how the same two cases used to drift out of sync silently: a family added here without a matching case there left a probe that woke nothing and cost a turn every six hours, forever, with no test able to see the other switch at all.

func MainPoolExhausted added in v0.3.0

func MainPoolExhausted(cands []Candidate, o Options) bool

MainPoolExhausted answers step 2 of the credit gate: may the LAST-RESORT credit pool be considered at all?

The main pool is what Rank puts in Result.Order: the subscription accounts, and the credit seats marked primary. A primary seat with room means the pool is not exhausted, because its credits are quota the user is already paying for -- spending overage while it sits unused is the exact inversion the gate order exists to prevent.

An account that could not be read holds the pool OPEN. It is not known to be spent, and the fail-closed direction on money is to keep using what is already bought rather than to start spending because one poll failed. A pool with nothing in it is exhausted trivially.

The test is Spent against the table o carries, and on this path WHICH table is the money question. Decide asks before hover is installed, so it is the CONFIGURED one: the threshold a user typed is them saying where they want an account to stop, and only a number they chose may open a pool that buys credits. Hover's own line is not theirs: TestHoverThresholdDoesNotOpenTheCreditPool.

func ModelFamily added in v0.2.0

func ModelFamily(name string) (string, bool)

ModelFamily reduces a model name to the family a per-model window is scoped to, and reports whether it could tell at all.

It answers false rather than guessing, and both false cases matter. A name carrying no known family is a model ccdad has not heard of, and a name carrying two is a string that is not a model name at all. Callers read false as "cannot rule this window out", which keeps an unrecognized name on the conservative side: it never narrows anything away.

func ModelFamilyNames added in v0.2.0

func ModelFamilyNames() []string

ModelFamilyNames lists the families ModelFamily knows, in its own order, so a CLI can build its refusal out of the same list the matcher reads.

func NextResetAmong added in v0.5.0

func NextResetAmong(s *usage.Snapshot, model string, t Thresholds, now time.Time) (time.Time, bool)

NextResetAmong is the earliest FUTURE rollover among an account's candidate windows, or false when no window has one.

FUTURE, and over the whole candidate set rather than the binding window: the caller is scheduling the poll that will find a clock stopped, and the binding window is routinely a weekly one whose reset is days out while the five-hour clock this exists to restart runs down within hours. A reset already in the past is not a schedule either — it is the event that has already happened, and ColdWindow is what answers for it. The set is ColdWindow's, so a poll is aimed at every rollover a warm-up could follow.

func OutOfQuota added in v0.5.0

func OutOfQuota(h Headroom) (out, known bool)

OutOfQuota is whether some window this account carries has nothing left in it at all -- not "past the number it was given", which is Spent, but empty.

The two questions were one question for as long as every window shared one threshold: at a flat 80, slack is raw room shifted by twenty, so "past its threshold" and "nearly empty" ordered accounts identically and one predicate answered both. Per-window thresholds broke that: a week held to 60 and a five-hour window held to 95 measure slack from two different lines, and which window is past its line says nothing about which one has run dry.

It reads a MINIMUM rather than Pct for the reason those minima exist: Pct describes whichever window is tightest on the SLACK axis, and the window that is empty is not always that one.

Which minimum is the question this predicate turns on, and it is MinAnyModelPct rather than MinPct. "Nothing left in it at all" has to mean nothing left that any model could spend, because that is what every caller does with the answer: the empty tier files the account behind everything else, the anti-flap gate waves every margin through to get off it, and MainPoolExhausted starts buying credits once they all say yes. A weekly cap scoped to ONE model family satisfies none of that — an account whose Fable week is gone and whose all-model weekly holds a fifth can serve every prompt that is not Fable, and reading it as empty throws that fifth away and buys credits to replace quota already paid for.

MinPct keeps its own job: Spent still reads it, so a blown sub-cap still makes the account spent and still moves the engine off it in good time. The difference between the two predicates is now exactly the difference between "past a line" and "cannot serve anything", which is what they were always named for.

Three-valued for the same reason Spent is. An account nobody could read is not an empty one.

An unnamed MinAnyModelWindow falls back to MinPct rather than answering unknown, and that is the conservative direction on two counts. An account whose only readable window is model-scoped has nothing else to go on, and a blown sub-cap is then the only thing known about it. And every Headroom built by hand — the ranking's own fixtures, the TUI's colour cases, a consumer outside this package — leaves the pair unset and keeps exactly the answer it has today.

func RecordCodexSwitch added in v0.11.0

func RecordCodexSwitch(uuid string) error

RecordCodexSwitch stamps the Codex anti-flap cooldown after a repoint has succeeded. It is the sibling of switcher.RecordSwitch and it lives HERE rather than there because internal/codexswitch is the only caller and that package must not be able to reach internal/switcher at all -- the import gate on its dependency closure is what makes "a Codex repoint can never install a Claude credential" a property rather than a promise.

An EXPLICIT `ccdad switch <codex>` stamps it too, for the reason the Claude side does: the user has just chosen an account, and a lane evaluating ten seconds later must not immediately override the choice.

func RoomOf added in v0.19.0

func RoomOf(h Headroom) float64

RoomOf is the raw room the session will actually be stopped by: the least room among the windows a model choice cannot dodge, falling back to the least room anywhere when no such window was readable.

It is OutOfQuota's own reading, as a number rather than as a yes/no. The two have to agree: a rule that measured room one way and emptiness another would file an account as having four points left and as out of quota at once.

func Spent added in v0.3.0

func Spent(h Headroom) (spent, known bool)

Spent is whether an account is past a threshold on any window it carries.

One test covers them all: a negative slack means the binding window is over the threshold that window was given, and the binding window is the one with the least slack, so every other window has slack to spare.

It is three-valued on purpose. An account that could not be read is neither spent nor unspent, and folding that into a boolean is the bug that left cswap parked on the account that reset last.

The MinPct clause states "empty implies spent" STRUCTURALLY rather than leaving it to arithmetic on a threshold. A threshold of exactly 100 is one a user may set, and under it a window with nothing left reports a slack of zero, not a negative one -- which would file an account with nothing in it as unspent and, because allOver is built from this predicate, keep ModeRecovery from the whole pool on the strength of that one account.

On hover's table the line is the last point, and the windows it is asked of are the ones no model choice can dodge (ModelCapsDodged), so a blown cap on one model family is not spent: a fleet whose Fable weeks are all gone still ranks on hover's order rather than on when those caps come back. TestABlownModelCapEverywhereDoesNotPutHoverIntoRecovery. It is PAST the line, where lastPoint is AT it: an account on its last point still has that point to spend, and recovery is for a pool that has none.

func StatePath

func StatePath() (string, error)

StatePath is where the state lives.

func StrategyNames

func StrategyNames() []string

StrategyNames lists every strategy a caller may name, in this type's own order. A CLI builds its help text and its error message from this, so a strategy added here cannot be forgotten in one of them.

func SubscriptionExhausted deprecated

func SubscriptionExhausted(cands []Candidate, o Options) bool

SubscriptionExhausted is MainPoolExhausted under the name it had while the main pool was subscriptions and nothing else.

Deprecated: use MainPoolExhausted. It is kept for one release so a caller that has not been updated -- internal/strategy/antiflap.go among them -- keeps compiling and keeps getting the same answer, rather than a name that quietly means less than it used to.

func WarmPhase added in v0.29.0

func WarmPhase(uuid string, s *usage.Snapshot, name usage.WindowName) time.Duration

WarmPhase is how long this account's warm-up waits after its rollover, so the fleet's anchors stop landing in one band.

The phase is derived from the UUID rather than from a position in a list, because there is no list here: the warm-up is asked about one account, and the identity peers it could reach are a singleton on a fleet where every account carries its own organization. A hash is stable across restarts -- a per-process seed would re-phase the whole fleet on every daemon start, which is the batch re-forming by another route -- needs nothing but the account, and spreads a fleet of any size without any account having to know the size.

It is capped at HALF the window, and the cap is the cost being bounded rather than tidiness: a delayed warm-up leaves that account's clock stopped for the delay, which is elapsed window time the account does not get back. Half a cycle turns this fleet's forty-minute band into a hundred-and-fifty-minute one, which is enough to break the batch, while holding the worst case to something an axis with a 1.99x margin can pay.

A window whose length this build cannot name gets no phase. That is the codex window with no limit_window_seconds: with no scale to state a phase on, the answer is silence rather than a guess.

The length comes from the COLD window itself and not from the next rollover among the readable ones, and that is not interchangeable: at the moment this is asked the window has already rolled over, so it has no future reset for a walk to find, and a phase derived that way would be zero on every account this gate exists to spread.

func WarmTarget added in v0.29.0

func WarmTarget(s *usage.Snapshot, thr Thresholds, now time.Time, rnd float64) time.Time

WarmTarget is when the next of this account's clocks runs down, plus the margin that keeps the reading aimed at it from arriving before the rollover it is aimed at. Zero means there is nothing to aim at.

Zero is the ordinary answer for the account this exists to serve, and that is not a contradiction: an account whose five-hour clock is already stopped has no future rollover to schedule against, and it does not need one -- it is warm-up-due on this very tick. The schedule matters for the account whose clock is RUNNING, which is the one that will go cold later and unattended.

The margin is jittered across [ProbeWakeMargin, 2*ProbeWakeMargin), rnd in [0, 1) choosing where, because rollover instants cluster: a fleet warmed in one batch rolls over in one batch -- the live one warmed three accounts within 19 minutes -- and the anchors themselves land on ten-minute boundaries. An unjittered margin would put several `claude -p` children on the same second.

func WarmUpDue added in v0.29.0

func WarmUpDue(uuid string, s *usage.Snapshot, probe usage.ProbeState, thr Thresholds, now time.Time) (usage.WindowName, bool)

WarmUpDue is the window a warm-up of this account would start now, and whether it is due: a cold window (ColdWindow) a turn may be spent on without reaching credits (WarmUpWouldSpendCredits), an attempt the probe record allows (usage.ProbeState.MayProbe), and the account's phase after the rollover passed (WarmPhase).

func WarmUpWouldSpendCredits added in v0.5.0

func WarmUpWouldSpendCredits(s *usage.Snapshot, model string, t Thresholds) bool

WarmUpWouldSpendCredits reports whether spending one turn on this account could land on METERED CREDITS rather than on quota already paid for.

It is the one gate the warm-up loop shares with the credit gate's reasoning, and it is here rather than in the daemon so that reporting and scheduling refuse on the same predicate. Fully automatic must not become fully automatic SPENDING: the ceiling and the account's own overage switch are the two independent opt-ins unattended overage requires, and a mode cannot supply either on the user's behalf — least of all a mode whose whole job is to spend small turns nobody asked for one at a time.

Two conditions, and the first is the narrow one on purpose. A turn only reaches credits when there is no subscription quota LEFT, which is a window at 100%, not a window past its threshold: an account at 80% of its week under a threshold of 46 has a fifth of its quota in hand and the turn lands on that. Reading "past its threshold" as "out" here would have stopped warming five of the six accounts on the fleet this was written against, which is most of the benefit for none of the risk.

The second fails closed the way credit.go's every branch does. Only an account whose overage is demonstrably off — Disabled, or Blocked by an org or seat policy — is evidence that a turn CANNOT be billed. Unknown is not, and an unread extra_usage is the state a bug looks like.

func WindowForFixedFamily added in v0.3.0

func WindowForFixedFamily(family string) (usage.WindowName, bool)

WindowForFixedFamily is FixedWindowFamily's reverse: the fixed window one family's turn has to be spent against to reach it. A family FixedWindowFamily does not answer for is refused here too — a --model naming a real family with no fixed window of its own still falls through to the caller's own five-hour fallback, which is the honest answer for a family this build cannot scope.

func WithState

func WithState(timeout time.Duration, fn func(*State) error) (err error)

WithState runs fn against the state under a cross-process lock and writes back what it changed. This is the only safe way to modify it.

An atomic rename alone is not enough. The daemon stamps a cooldown while `ccdad switch` clears a quarantine, and both do a read-modify-write of the same document: without the lock the second rename silently drops the first one's change — and the change it drops is a cooldown, which is a switch storm.

fn returning an error leaves the file exactly as it was.

Types

type Action

type Action uint8

Action is what the engine should do.

const (
	// ActionStay is "the world is already how it should be", exit 3.
	ActionStay Action = iota
	// ActionSwitch is a move to Plan.Target.
	ActionSwitch
	// ActionBlocked is "a move was wanted and there is no viable target",
	// exit 4. The 3-versus-4 line in the exit contract is the actionability
	// line, and this is the side the user has to do something about.
	ActionBlocked
)

func (Action) String

func (a Action) String() string

type Candidate

type Candidate struct {
	UUID     string
	Kind     identity.Kind
	Disabled bool
	// Elsewhere marks an account another machine's ccdad owns. It is ranked out
	// exactly like Disabled, and it is a separate field for the same reason it
	// is a separate flag on the account: the two answer different questions, and
	// a listing that folds them prints the wrong reason beside the row.
	Elsewhere bool
	// Primary marks a credit-metered account that is the seat's ordinary
	// metering rather than an overage: it ranks with the subscriptions instead
	// of waiting in the last-resort pool. Nothing sets it here; the flag is an
	// account fact, read off the store.
	Primary bool
	// Usage is the account's most recent reading, or nil when there has never
	// been one. Nil is UNKNOWN, never empty.
	Usage *usage.Snapshot
	// FetchedAt is when this reading was taken and NextPollAt when the next one
	// is due. Both are copied from usage.Entry, and the gap between them is the
	// interval during which the engine is blind: a projection that has to guess
	// it would be guessing the one number the cache already knows.
	FetchedAt  time.Time
	NextPollAt time.Time
	// LastRateLimited is when the USAGE POLLER last took a 429 for this account,
	// zero for never.
	//
	// It is not evidence that the account is out of quota, and nothing here may
	// treat it as such. The throttle is on /api/oauth/usage, and the sharper of
	// the two experiments on record found a Retry-After of 0 scoped to the
	// ACCESS TOKEN rather than to the account -- so a 429 here can be an
	// artefact of the token ccdad happens to be polling with. Filing a throttled
	// account as spent is the cswap failure this package warns about in three
	// other places: unreadable is not empty.
	//
	// What it does mean is that the reading will not be refreshed soon: the poll
	// policy floors the cadence at Post429MinInterval and lets it climb to
	// Post429MaxInterval. So it is read in exactly one place -- the pre-emptive
	// switch, which is the rule that acts on a PROJECTION rather than on a
	// figure, and which therefore has something to lose by running to an account
	// whose numbers it cannot check.
	LastRateLimited time.Time
	// BurnPerMin is the rate measured across this account's last two readings,
	// in points of its binding window a minute, and HasBurn whether one could be
	// taken at all. Both are copied from usage.PollState.
	//
	// It is a fact about the SESSION rather than about the account, and that is
	// the whole of how it must be read. An account nobody is spending measures
	// zero; the moment a session moves onto it, it burns at whatever rate that
	// session burns. So the figure that answers "how long would this candidate
	// last" is the LIVE account's rate applied to the candidate's room -- never
	// the candidate's own, which is zero for every account the engine might move
	// to and would report that each of them lasts forever.
	//
	// HasBurn false is "cannot say" and never "nothing is being spent". A
	// measured idle account carries zero with HasBurn true, and the two send the
	// engine down different arms: no measurement leaves every rule exactly as it
	// was before this field existed.
	BurnPerMin float64
	HasBurn    bool
	// BurnWindow is the window BurnPerMin was measured on. Empty on a reading
	// cached before it was recorded; see sessionBurn.onWindow for how that is read.
	BurnWindow usage.WindowName
	// LiveBurns is the last rate measured on each of this account's windows
	// across two readings that were both taken while it was live -- the work's
	// rate rather than the account's -- copied from usage.PollState. Hover reads
	// the pool's latest one per window length as the work's rate; see
	// workRatesOf.
	LiveBurns []usage.LiveBurn
	// SharedBy is how many accounts draw on this account's polling budget, itself
	// included (store.SharingIdentity); zero reads as one. The scheduler divides
	// the identity's cadence among them, the prompt poll a switch schedules
	// too, so the first live reading after a move onto this account is that much
	// later -- which the carry test has to count (carries).
	SharedBy int
	// WorkRunning is whether this account's most recent live pair saw the work
	// running, and LastPairAt when that pair's later reading was taken
	// (usage.PollState.LastPairRunning, LastPairAt). The latest pair across the
	// pass is the work's, like its rate (work.running): it says whether a
	// projection that has the live account out is a measurement or a forecast
	// across a pause (Ranked.lastResortOpen).
	WorkRunning bool
	LastPairAt  time.Time
}

Candidate is one account the engine may rank. It is deliberately not a store.Account: ranking needs a handful of facts, and taking only those keeps this package independent of how accounts are persisted.

type Config

type Config struct {
	// HysteresisPct is how many points of SLACK a candidate must beat the
	// active account by.
	HysteresisPct float64
	// HeadroomRatio is the multiplicative margin on the same axis.
	HeadroomRatio float64
	// Cooldown is the minimum gap between two switches.
	Cooldown time.Duration
	// RecoveryHysteresis is how much sooner a candidate must recover.
	RecoveryHysteresis time.Duration
	// QuarantineFor is how long a dead refresh token holds an account out.
	QuarantineFor time.Duration
	// MaxAutoSpend is the credit gate's ceiling, in the currency's major unit.
	// Its default is 0 — the explicit opt-in — so unlike every other field here
	// a zero is honoured rather than replaced.
	MaxAutoSpend float64
	// Manual holds the engine to WATCHING. It still polls, still ranks, still
	// builds hover's table and still fills the history the forecast is built
	// on; it just never moves the login.
	//
	// It is a field on Config rather than on Options because Config is the half
	// that comes from config.toml and is copied into the pass, and because the
	// question it answers is about the DECISION rather than about the ranking:
	// everything a reporting caller renders is computed exactly as it would be
	// with the mode off, so `ccdad status`, the TUI and `ccdad runway` do not
	// have to know the mode exists to stay correct.
	//
	// Unlike every other field here a zero is the honoured value: the default
	// is automatic switching, which is what ccdad is for.
	Manual bool
}

Config is the anti-flap set, as knobs.

Every field defaults when it is not positive, so the ZERO VALUE of this struct is the full default set. That direction is deliberate: an under-populated Config must never read as "every anti-flap mechanism off", and there is no way to switch one off at all. `ccdad config` supplies the real values; these are what stands in when it has not.

func HoverConfig added in v0.3.0

func HoverConfig(cfg Config) Config

HoverConfig is the anti-flap set hover imposes: the cooldown, and nothing else.

recovery_hysteresis is the user's again, because it is not a pace knob any longer: it is the margin on the reset axis, which is what hover moves weekly-only seats on, so a user who wants two Ultra seats to trade places only when one week ends an hour sooner can say so. hysteresis_pct and headroom_ratio are passed through untouched and read by nothing under hover: hoverMove makes every hover move, on the order's own rules rather than a margin on room (config.HoverOverrides marks them so).

preempt_lead is absent because it is not an anti-flap knob, and hover does not read it: the live account's reserve is the poll policy's (hoverReserve).

MaxAutoSpend is deliberately not touched, and that is the line this function exists to hold. Fully automatic must not become fully automatic SPENDING: the ceiling is one of the two independent opt-ins unattended overage requires, and an opt-in a mode supplies on the user's behalf is not an opt-in.

type CreditReason

type CreditReason uint8

CreditReason says why the gate answered as it did. It reaches a user-facing notification, so every value has a name.

const (
	// CreditAllowed: there is armed room and both opt-ins are in place.
	CreditAllowed CreditReason = iota
	// CreditMainPoolNotExhausted: it is not the credit pool's turn. Steps 1 and
	// 2 of the gate order -- the last-resort credit pool is consulted only once
	// the MAIN pool is EXHAUSTED, not merely once its best candidate has failed
	// hysteresis. The main pool is the subscription accounts and the credit
	// seats marked primary.
	CreditMainPoolNotExhausted
	// CreditNotOptedIn: max_auto_spend is 0, which is the default.
	CreditNotOptedIn
	// CreditAccountDisabled: the account's own overage switch is off.
	CreditAccountDisabled
	// CreditAccountBlocked: the organization or seat refused overage — a spend
	// cap reached, credits out. Different from disabled, and worth saying so.
	CreditAccountBlocked
	// CreditSpendUnreadable: the figures needed to price a switch are missing.
	CreditSpendUnreadable
	// CreditNoRoom: the armed cap is spent.
	CreditNoRoom
	// CreditCeilingInvalid: the configured ceiling is infinite, NaN or negative.
	CreditCeilingInvalid
)

func (CreditReason) String

func (r CreditReason) String() string

type Decision

type Decision struct {
	// Allow is whether the engine may switch to this credit account.
	Allow bool
	// Reason is why.
	Reason CreditReason
	// Blocked marks a refusal the user should act on: exit 4 and a
	// notification, never a silent exit 3. cswap conflates these two and a
	// money-blocked engine becomes invisible to cron.
	Blocked bool
	// Room is the armed spend left, when there is any.
	Room float64
	// DisabledReason is the organization's own word for its refusal, kept
	// verbatim: it is the difference between "turn overage on" and "your org
	// hit its spend cap".
	DisabledReason string
}

Decision is the gate's answer.

func CreditGate

func CreditGate(e usage.ExtraUsage, ceiling float64, mainPoolExhausted bool) Decision

CreditGate is the last two steps of the credit gate, applied to one LAST-RESORT credit account: when the configured ceiling is 0, its default, answer blocked — exit 4 and a notification — rather than switch; and refuse when spend cannot be read.

mainPoolExhausted carries the first two steps — look for a target in the main pool, and reach the credit pool only once that pool is exhausted. It is supplied by the ranking pass: it must mean the main pool has no viable target left, not that its best candidate merely failed hysteresis.

A PRIMARY credit account never reaches this function, and that is structural rather than a branch: Rank puts one in Result.Order, so it is not in the pool Decide walks and armedRoom is not computed for it. Removing the ceiling for that one account is correct because max_auto_spend exists to bound OVERAGE -- spending beyond quota that is already paid for -- and a seat billed only in credits has no such quota, so the ceiling would not be bounding an overage, it would be refusing the account's only meter. For every other credit account it is still two independent opt-ins: the account's own extra-usage switch, checked below, and a ceiling a human wrote into config.toml. A primary seat has two of its own -- the same extra-usage switch on the wire, and a human typing `ccdad primary <ACCOUNT> on` at a named account.

ceiling is passed in rather than read from config, so this package never touches the config loader: it is max_auto_spend, 0 is its default, and Decide is what copies it from Config.MaxAutoSpend.

type Departure added in v0.29.0

type Departure struct {
	From    string
	Closing usage.WindowName
}

Departure is the half of a switch the ranking later reads: the account the engine left, and the window that had it at a limit. Closing is empty when the account left was not at one -- a return to a five-hour account, a move to a weekly-only seat whose week ends sooner, a user's own switch.

type Headroom

type Headroom struct {
	// Pct is 100 minus the binding window's utilization. It can go negative,
	// and is kept that way: how far past its limit an account already is still
	// orders it against other spent accounts. This is the DISPLAY axis, the one
	// the engine's headroom projection prints, and it asks the same question of every
	// window.
	Pct float64
	// Slack is the binding window's threshold minus its utilization, and it is
	// the axis the ranking orders on.
	//
	// It stops agreeing with Pct the moment two windows carry different
	// thresholds. An account at 55% of a weekly window whose threshold is 60 has
	// 45 points of raw headroom and 5 points of slack; five is the distance that
	// decides whether the next prompt trips a limit, and forty-five is the
	// number that would have ranked it first.
	Slack float64
	// Threshold is the number Slack was measured against.
	//
	// It is carried rather than recovered as Slack+100-Pct: that identity is
	// exact in arithmetic and not in float64, and this figure is printed. It is
	// also the only way a consumer holding a Headroom alone can report the
	// threshold — `ccdad auto --json` renders a ranked pool and never sees the
	// bundle the pass was run with.
	Threshold float64
	// MinPct is the LEAST raw room any binding window has, and MinWindow names
	// it. It is a SEPARATE figure from Pct and it has to be.
	//
	// Pct is read off the window with the least SLACK, and once windows carry
	// thresholds of their own those are two different windows. A five-hour
	// window three percent into its cycle sits under a threshold of twenty and
	// binds at 25% used, while the weekly one behind it is at 95% under a
	// threshold of ninety-nine: Pct reports the five-hour window's 75 points
	// while the weekly is what will actually stop the session eight prompts
	// later. Slack is the right answer to "which window is this account closest
	// to breaching"; it is the wrong answer to "how much work can this account
	// still take", and this field is the second question asked in its own
	// terms.
	MinPct    float64
	MinWindow usage.WindowName
	// MinAnyModelPct is the least raw room among the windows a session cannot
	// avoid by choosing a different model, and MinAnyModelWindow names it. It is
	// what OutOfQuota reads, and it is a SEPARATE figure from MinPct for one
	// reason: a window that caps ONE model family cannot empty an account.
	//
	// A blown weekly_scoped:model:Fable cap beside a weekly_all at 80% says the
	// account has a fifth of its week left and that none of it may be spent on
	// Fable. Read through MinPct that account reports zero room, which files it
	// in the empty tier, hands it to nobody, and throws the fifth away — every
	// week, on every account, for as long as the sub-cap stays blown. That is
	// quota already paid for and it is the whole reason this field exists.
	//
	// What still empties an account is a window no model choice can dodge: the
	// five-hour window, the all-model weekly, seven_day_oauth_apps, a
	// SURFACE-scoped cap (Claude Code is itself a surface, so a spent one is
	// spent whatever runs), the codex pair, and any opted-in window under a
	// scope key this build cannot read — an unreadable scope is not evidence
	// that a different model would escape it.
	//
	// MinPct is deliberately left alone. It is the honest "least room anywhere"
	// figure, Spent still reads it so a blown sub-cap still counts as spent, and
	// the display still names the blown window through Floor -- on a table whose
	// model caps bind; hover's leaves them out of the set (ModelCapsDodged). This
	// field answers the narrower question the empty tier was always asking: can
	// this account serve a prompt at all.
	// MinAnyModelWindow being EMPTY is how a consumer tells "no window binding
	// every model was readable" from "one was, and it is full". There is no
	// third field carrying that: a bool would have to be exported for the
	// literals other packages build to be able to state it, and one they forgot
	// to set would silently mean the opposite of what the same literal means
	// today. A name nothing wrote is unmistakable, and OutOfQuota falls back to
	// MinPct when it finds one — the conservative reading, and the one every
	// Headroom built by hand keeps.
	MinAnyModelPct    float64
	MinAnyModelWindow usage.WindowName
	// Known is false when no window reported a utilization. An account that
	// could not be read is NOT an empty one, and treating it as one is the
	// exact bug that parked cswap's engine permanently.
	Known bool
	// Binding names the window Pct, Slack and Threshold all came from: the one
	// with the least slack. It is the ORDERING axis and the spent test, and the
	// three figures describe ONE window deliberately, so that Slack is always
	// Threshold minus that window's utilization.
	Binding usage.WindowName
	// Floor names the WEEKLY window that has to clear before this account is
	// usable again, and HasFloor is whether there is one at all. Two kinds
	// qualify — one past the number it was given, and one with nothing left in
	// it — and an empty one wins over a merely-tripped one. HeadroomFor's own
	// loop spells out why it takes both.
	//
	// It is the REPORTING axis, and it is separate from Binding because it
	// answers a different question. Binding is what is tightest right now; Floor
	// is what will still be tight in two days. An account whose five-hour window
	// rolls over in eight minutes has not recovered while its weekly cap is
	// blown until Friday, so a tripped weekly window is what a user has to be
	// told about and what has to clear before the account is usable again. It
	// never participates in ordering.
	Floor    usage.WindowName
	HasFloor bool
	// FloorSlack and FloorThreshold are the FLOOR window's own pair: the
	// threshold that window was given, and that threshold minus its
	// utilization. They mean nothing when HasFloor is false and are left at
	// zero there, exactly as Floor itself is.
	//
	// They are here because Slack and Threshold above are assigned off BINDING
	// in one statement, and the moment there is a floor those two names
	// describe two different windows. Every human view resolves the window it
	// reports through Floor -- a blown weekly is what a user has to be told
	// about -- and then has nothing but Slack to reach for, which is a number
	// measured on some other window entirely. The shape it was found on, under
	// the pace rotation hover used to run: a five-hour window at 98% used bound
	// with 3.667 of slack while the weekly beside it had nothing left in it. A
	// bar drawn at the weekly's 100% and coloured from the binding window's
	// 3.667 is a full bar that says "plenty of room".
	//
	// Taken in the pass that already computes them rather than recovered by a
	// second one. A second pass would have to rebuild the window set, and then
	// there is a way for a window to be admitted to one and narrowed out of the
	// other -- which is the same failure the floor selection sits inside this
	// loop to avoid.
	FloorSlack     float64
	FloorThreshold float64
}

Headroom is how much of an account's BINDING window is left, and how far that window is from the threshold it was given.

It is deliberately not one window's number. An account carries a five-hour window and several weekly ones, and the one that binds is whichever is closest to its own threshold: ranking on five_hour alone hands work to an account whose weekly Opus quota is gone, and it hits a hard limit one prompt later.

func HeadroomFor added in v0.2.0

func HeadroomFor(s *usage.Snapshot, model string, t Thresholds) Headroom

HeadroomFor finds the binding window for a session that will run model, against that pass's own per-window thresholds.

The set it ranges over excludes cinder_cove: that is a one-time credit grant whose resets_at is an expiry, so a spent one would otherwise read as a permanently exhausted account. seven_day_oauth_apps IS included even though it is the one of the fixed five that reads as though it belonged to some other client — Claude Code is itself an OAuth app, nothing in the bundle says the window means anything else, and counting a window that does not bind is the cheaper of the two mistakes.

Windows tie on the first in the schema's own order, and the scoped ones come after the fixed five in wire order, so the answer does not depend on map iteration.

func HeadroomOf

func HeadroomOf(s *usage.Snapshot, t Thresholds) Headroom

HeadroomOf finds the binding window for a session that has not named a model, which is every caller that is reporting rather than choosing.

func HeadroomOrCredit added in v0.9.0

func HeadroomOrCredit(s *usage.Snapshot, t Thresholds) Headroom

HeadroomOrCredit is the headroom to SHOW for an account: its binding plan window when it has one, and its credit allowance when it has none.

It exists because HeadroomOf reads plan windows and nothing else, while rank.go:measure reassigns a primary credit seat onto the credit axis before ranking it. Every caller that rendered HeadroomOf therefore printed "?" for a seat the engine was ranking on a perfectly good number — the dashboard and the engine describing one account with two answers.

The order is the same one Classify makes for the same reading, and it has to be: an account with a live window and overage switched on is metered by the window, and its credits are what it spends AFTER that window runs out. So a window that binds always wins, and the credit axis is reached only when there is no window at all.

It is not a replacement for HeadroomOf. The RANKING must keep using the window-only form plus the primary-seat reassignment, because whether a credit balance may be spent at all is the credit gate's question and not this one; answering it here would rank a non-primary credit account as though its money were quota. This is the DISPLAY axis: what is left, on whichever meter this account actually runs on.

func (Headroom) OnCreditAxis added in v0.9.0

func (h Headroom) OnCreditAxis() bool

OnCreditAxis reports whether this headroom was measured against a credit balance rather than a plan window.

A caller needs it because the two are not interchangeable downstream: the credit axis has no reset, no rollover and no entry in Snapshot.AllWindows, so anything that resolves the binding name to a window finds nothing and has to know whether that absence is "unreadable" or "there is no window here by construction". The comparison lives here so the literal extra_usage is spelled in one place.

type HoverPlan added in v0.3.0

type HoverPlan struct {
	// CreditThreshold is what a primary credit seat is measured on.
	CreditThreshold float64
	// contains filtered or unexported fields
}

HoverPlan is one hover pass over one pool.

func HoverThresholds added in v0.3.0

func HoverThresholds(cands []Candidate, o Options) HoverPlan

HoverThresholds builds the table for one pool: every window an account can be stopped by, held to the hand-off line.

It takes the pool AFTER quarantine rather than the whole store: the table is for the accounts the ranking will actually consider, and a quarantined account is not one of them.

func (HoverPlan) For added in v0.3.0

func (p HoverPlan) For(uuid string) Thresholds

For is the threshold table one account is measured against.

type Mode

type Mode uint8

Mode is the situation the ranking actually found itself in — one of the four below. It is reported so `ccdad status` can say WHY an order looks the way it does.

const (
	// ModeHeadroom: at least one account has room, or some account could not be
	// read and might. Rank by most headroom.
	ModeHeadroom Mode = iota
	// ModeRecovery: every account is known to be over threshold. Rank by
	// soonest recovery, because sitting still burns the active account to a
	// hard limit while a peer that frees up in eight minutes is never tried.
	ModeRecovery
	// ModeConsumeFirst: the user asked for perishable quota to be spent first.
	ModeConsumeFirst
	// ModeHover: hover's order -- five-hour accounts first, then the soonest
	// weekly reset; see tier.go. Appended LAST, for the reason Reason's late
	// values are: the numbers are named in a report, and renumbering them is a
	// diff nobody can review.
	ModeHover
)

func (Mode) String

func (m Mode) String() string

type ModelCaps added in v0.29.0

type ModelCaps uint8

ModelCaps is whether a window that caps ONE model family -- a fixed per-model window, or a weekly_scoped entry under the model scope (capsOneModelFamily) -- binds an account measured on a table.

const (
	// ModelCapsBind: such a window binds like any other. It is the configured
	// strategies' rule, the one bindingWindows has always stated: counting a
	// window that does not bind costs one conservative switch, and a threshold a
	// user typed is where they said to stop, whatever the window caps.
	ModelCapsBind ModelCaps = iota
	// ModelCapsDodged: such a window does not bind, because a session stopped
	// on one model family goes on with another -- unless nothing else on the
	// account could be read, when it is all anyone knows. It is hover's rule
	// (D5): one line, and only for limits that stop the session.
	ModelCapsDodged
)

type Options

type Options struct {
	Now time.Time
	// Threshold is the utilization percent above which an account is spent. It
	// is the fallback for any window the table below does not name.
	Threshold float64
	// WindowThreshold is the threshold for a named window, for the windows that
	// have one of their own. A window missing from it — and nil, which is every
	// window missing — falls back to Threshold.
	//
	// It is keyed by the window name the wire uses, scoped names included, so
	// the map a user's configuration builds needs no translation table between
	// what was typed and what the snapshot reports.
	WindowThreshold map[usage.WindowName]float64
	// CreditThreshold is the utilization percent above which a credit-metered
	// account counts as spent.
	CreditThreshold float64
	// PreemptLead is how far ahead of a projected exhaustion the engine moves.
	//
	// A zero switches pre-emption OFF, and that is a real answer rather than an
	// omission: this is an opt-out a user may legitimately want, the same
	// direction MaxAutoSpend already takes, and unlike an anti-flap margin it is
	// not a mechanism that must never be switched off. The default lives in the
	// configuration, which is the only thing that knows a user did not say.
	PreemptLead time.Duration
	// Horizon is how soon a recovery has to be to win its tier.
	Horizon  time.Duration
	Strategy Strategy
	// Model is the model the session about to run will use, as the user typed
	// it. Empty is the unqualified pass — every window binds — and is what the
	// daemon and every reporting caller use. A named model narrows the ranking
	// to the windows that bind for it; see bindingWindows for the rule.
	//
	// It is a free string rather than a parsed family because the refusal for a
	// name ccdad cannot place belongs at the CLI, where there is a user to tell.
	// Reaching the engine, an unplaceable name simply narrows nothing.
	Model string
	// Hover replaces the ranking with hover's order and every threshold in this
	// struct with the hand-off line. It is a mode rather than a knob, so it is a
	// plain bool with no default to fall back to.
	Hover bool

	// MaxAutoSpend is the credit gate's ceiling, and it is here for ONE reason:
	// the credit pool is ordered by armed room, and room cannot be computed
	// without it.
	//
	// It is the same number Config.MaxAutoSpend carries, and Decide copies it
	// from there rather than trusting a caller to set both — a pass that ranked
	// on one ceiling while the gate decided on another would walk to a first
	// choice the gate then refuses. 0 is the default and arms nothing, which
	// leaves the pool in the uuid order it had before this field existed.
	//
	// It does not bound a primary credit account; see Candidate.Primary.
	MaxAutoSpend float64
	// contains filtered or unexported fields
}

Options configures one ranking pass.

func (Options) Thresholds added in v0.3.0

func (o Options) Thresholds() Thresholds

Thresholds is this pass's thresholds as one value, which is the shape every consumer outside this package takes.

The defaulting lives in Thresholds rather than here, so there is one place a zero can be turned into DefaultThreshold and no way for a caller to reach a comparison with a bare zero — which would make an account at one percent read as spent and open the credit gate.

type Plan

type Plan struct {
	// Action is what to do.
	Action Action
	// Reason is why.
	Reason Reason
	// Target is where to move, set only when Action is ActionSwitch.
	Target Ranked
	// Departure is the account a switch leaves and the window that had it at a
	// limit, set only when Action is ActionSwitch. The caller hands it to
	// State.RecordSwitch once the move has happened, which is what puts the
	// mark hover's order reads; Decide itself never writes.
	Departure Departure
	// Result is the ranking this plan was made from. It covers the pool AFTER
	// quarantined accounts were removed, so the mode it reports is the mode the
	// decision was actually made in.
	Result Result
	// Quarantined lists the eligible accounts held out of the pass, in uuid
	// order.
	Quarantined []string
	// SubscriptionExhausted answers "is the subscription pool spent", which is
	// the only thing that opens the credit pool. Reported so a caller can
	// say why the credit pool was or was not consulted.
	SubscriptionExhausted bool
	// Hover is the pass the thresholds came from, set only when hover was on.
	// nil is what says the mode was not in force; `ccdad status` reads
	// this rather than deriving a second table of its own.
	Hover *HoverPlan
	// Credit is the gate's answer, set only when the credit pool was reached.
	Credit Decision
	// CreditConsulted records that it was reached at all, because a refusing
	// Decision and a never-consulted one are both zero-ish and mean opposite
	// things.
	CreditConsulted bool
	// RetryAt is when the blocking condition lifts, when that is knowable — the
	// end of a cooldown, or the soonest quarantine expiry. It is advice for a
	// scheduler, never a promise that the answer changes then.
	RetryAt time.Time
	// HasRetryAt is whether RetryAt was set. A zero time is a real instant.
	HasRetryAt bool
	// Held is the move a hold refused, set only when the hold was about one
	// target: the cooldown holding a move the decision had already chosen, or a
	// margin refusing the account ranked first. It is the move `ccdad switch
	// --force` may make -- an override of a margin or the cooldown, never of a
	// limit, so a hold with nowhere to go names nothing.
	Held Ranked
}

Plan is one engine evaluation.

func Decide

func Decide(cands []Candidate, o Options, cfg Config, st *State, activeUUID string) Plan

Decide is the anti-flap margins and the credit gate's order over one ranking pass.

activeUUID must be the account in the LIVE CREDENTIALS FILE, derived by attributing that file against the stored credentials. It must NOT be store.ActiveUUID(): store.go documents that field as a display HINT, and it goes stale the moment the user runs /login inside Claude Code. Hysteresis measured against a stale baseline compares the candidate to an account that is not there, which is how an engine talks itself into a switch it already made. "" means the live login could not be attributed to a managed account, which is a real state and not an error: there is then no baseline to hold a margin against, and the margins that need one are skipped.

st carries the persisted cooldown and quarantines. It is never written here — deciding is not switching, and a plan that is not executed must not leave a cooldown behind.

func (*Plan) MoveTo added in v0.29.0

func (p *Plan) MoveTo(target Ranked, activeUUID string)

MoveTo turns the plan into a move to target: the action, the target, and what the move leaves behind. It leaves the reason alone, because a caller that overrides a decision -- `ccdad switch --force` past a hold -- reports the hold it overrode.

It is the ONE way a plan becomes a move, and it is exported for that caller: an override that set the action and target by hand left the departure out, so the account it left at a limit carried no mark and the next tick took the session straight back. Every arm of Decide that switches goes through it too.

type Quarantine

type Quarantine struct {
	// Since is when the account was quarantined.
	Since time.Time `json:"since"`
	// Until is when the quarantine lapses on its own. The expiry is a safety
	// valve rather than a healing time: a genuinely dead token comes back,
	// fails one refresh, and is quarantined again.
	Until time.Time `json:"until"`
	// Reason is why, kept because it reaches a user-facing notification.
	Reason string `json:"reason,omitempty"`
}

Quarantine is one account held out of auto-rotation by the engine.

It carries an expiry AND can be cleared explicitly, and it needs both. Only re-authentication actually fixes a dead refresh token, so an expiry alone would put a dead account back into rotation forever; but a quarantine that only an explicit clear could lift would make a misclassified failure permanent, and nothing else in ccdad would ever notice.

func (Quarantine) Active

func (q Quarantine) Active(now time.Time) bool

Active reports whether this quarantine still holds at now.

A zero Until never lapses. That is not a degradation: a hand-edited or truncated file that loses the timestamp must fail towards holding the account OUT of rotation, because the only reason an account is in here is that its credential did not work.

type Ranked

type Ranked struct {
	UUID     string
	Kind     identity.Kind
	Headroom Headroom
	// LastPoint names the window hover is handing this account off on because
	// it is down to the last point it can report, or is "" when none is; see
	// lastPoint and lastPointOf. It is a name and not a flag for the
	// reason Closing and HeldOut are: the departure mark waits for THAT window
	// to roll over.
	LastPoint usage.WindowName

	// ShortWindow names the window shorter than a week this account carries,
	// or "" when it carries none: the tier hover orders on, read off the
	// reading's presence rather than its utilization. See shortWindowOf.
	ShortWindow usage.WindowName
	// Closing names the window this account would run out of before the
	// engine can act on it, or "" when none would. Each mode states what
	// "before the engine can act" is in its own rules (passrules.go): under
	// hover, on some window within that window's own reserve after the live
	// account's next reading, and on the live account alone (hoverRules);
	// under the configured strategies, inside each account's own pre-emptive
	// horizon (configuredRules).
	Closing usage.WindowName
	// HasRunway is whether the work running now has a rate to project on this
	// account's windows, and RunsOutAt when that projection has the work stop
	// it, on RunsOutOn; a zero RunsOutAt with HasRunway is a runway nothing
	// stops. See runwayOf. Computed for every account, read only by hover's
	// decision and by what reports it.
	HasRunway bool
	RunsOutAt time.Time
	RunsOutOn usage.WindowName

	// Carries is whether the account would not be at a limit at its first live
	// reading if the work moved to it now: hover's carrier test (Options.carries).
	// An account the order prefers that does not carry the work is passed over.
	Carries bool
	// HeldOut names the window that holds this account out of hover's order --
	// the one it was left at a limit on, which has not rolled since -- or ""
	// when nothing holds it. Under hover only; see departure.go.
	HeldOut usage.WindowName
	// RecoversAt is when the binding window rolls over.
	RecoversAt  time.Time
	HasRecovery bool
	// WeeklyResetsAt is the soonest weekly reset, which consume-first ranks on.
	WeeklyResetsAt time.Time
	HasWeeklyReset bool
	// ReturnsInsideHorizon is the tier bit of lessRecovery's tiered key.
	ReturnsInsideHorizon bool
	// CreditRoom is the armed spend the credit gate would allow, for a credit
	// account under the configured ceiling. It is the credit pool's ordering
	// key and is reported so `ccdad status` can explain that order rather than
	// only obey it.
	CreditRoom float64
	// HasCreditRoom is whether there is any. False covers every refusal the
	// gate would make — no ceiling configured, overage switched off, spend
	// unreadable, the armed cap spent — so it is not a claim that the account
	// has none, only that none can be armed right now. It is also false for a
	// PRIMARY credit seat, where no room was priced at all: Rank routes such a
	// seat into Result.Order and the ceiling never applied to it.
	HasCreditRoom bool
	// contains filtered or unexported fields
}

Ranked is a candidate with the figures the ranking used, so a caller can explain the order rather than only obey it.

func (Ranked) AtLimit added in v0.29.0

func (r Ranked) AtLimit() usage.WindowName

AtLimit names the window that has this account at a limit, or "" when it is not at one.

Three ways, each one that precedes the 429 rather than following it: nothing left (OutOfQuota), the last point before the endpoint reports nothing left (lastPoint, hover's alone), or a projection that the next reading lands past the limit (Closing). Emptiness names the window its room was read off, the last point the window that is on it -- on a primary credit seat that can be a plan cap beside the credit meter it is ranked on -- and the projection the window it saw run out.

func (Ranked) Empty added in v0.29.0

func (r Ranked) Empty() (usage.WindowName, bool)

Empty is whether this account has nothing left on a window no model choice can dodge, and which window: the one "nothing left" every decision reads -- the rung, the limit, the last resort, the empty-live waiver, the carry and bridge tests.

A credit seat carries two meters, and either one spent empties it. A primary seat's Headroom is the credit balance, and under hover its plan's windows are a limit too where the user opted them in; an opted-in cap at 100% stops the seat whatever its balance says, and reading the balance alone would pick it as the last place to go. A pool seat's Headroom is its plan windows, and its credit balance is the other meter: a spent monthly limit leaves it nothing whatever its windows read. TestAnEmptyOptedInCapIsEmptyWhateverTheBalance, TestAPoolSeatIsEmptyWhenItsBalanceIsSpent.

func (Ranked) Rung added in v0.29.0

func (r Ranked) Rung() Rung

Rung files this account on the hover order.

The limits are asked first and the hold after them, so an account that is both held out and at a limit is at the limit: the hold says when it may be taken back, and an account at a limit is not somewhere to take a session whatever the hold says.

type Reason

type Reason uint8

Reason is why the engine answered as it did. Every value has a name because every one of them reaches a user through `ccdad auto --json` or a notification, and "no switch" with no reason is the cswap behaviour the exit contract exists to fix.

const (
	// ReasonBetterTarget: a candidate cleared every margin.
	ReasonBetterTarget Reason = iota
	// ReasonAlreadyBest: the live account already tops the ranking.
	ReasonAlreadyBest
	// ReasonCooldown: a switch happened too recently.
	ReasonCooldown
	// ReasonHysteresis: the candidate is ahead, but not by the margin.
	ReasonHysteresis
	// ReasonHeadroomRatio: the candidate beat the margin but not the ratio.
	ReasonHeadroomRatio
	// ReasonRecoveryHysteresis: the candidate recovers sooner, but not by 300 s.
	ReasonRecoveryHysteresis
	// ReasonWeeklyResetMargin: consume-first's equivalent on the reset axis.
	ReasonWeeklyResetMargin
	// ReasonNoCandidates: nothing is eligible to rank at all.
	ReasonNoCandidates
	// ReasonAllQuarantined: everything eligible is held out by a quarantine.
	ReasonAllQuarantined
	// ReasonAllExhausted: every account is spent and there is no credit pool.
	ReasonAllExhausted
	// ReasonCreditGate: the credit pool was reached and the credit gate refused
	// it. The gate's own answer is in Plan.Credit.
	ReasonCreditGate
	// ReasonNoSubscriptionRoom: the engine is on a credit account and no
	// subscription account has room to go back to. Staying is right; moving to
	// a spent subscription account would break the session for nothing.
	ReasonNoSubscriptionRoom
	// ReasonProjectedExhaustion: the live account's binding window is projected
	// to reach its limit before the next reading lands, and some candidate still
	// has slack. Appended LAST on purpose — nothing persists these values, but
	// renumbering an enum that a report and a notification both name is a diff
	// nobody can review.
	ReasonProjectedExhaustion
	// ReasonManual: manual mode is on, so the engine watches and never moves the
	// login. Appended after ReasonProjectedExhaustion for the reason that one
	// was appended last: the numbers are named in a report and a notification,
	// and renumbering them is a diff nobody can review.
	ReasonManual
	// ReasonNothingCanServe: the live account is out of quota and so is every
	// account it could move to, so the move buys the session nothing and costs a
	// credential rotation. Appended last, for the reason the two above were.
	//
	// It is NOT ReasonAllExhausted. That one is about the pool the ranking was
	// given -- every account spent against its THRESHOLD, with no credit pool
	// behind it -- and it is answered before a target is ever chosen. This one
	// is about the pair in hand: a target was ranked first and it has nothing in
	// it either. Plan.RetryAt carries the soonest rollover, because that is the
	// instant the answer can change.
	ReasonNothingCanServe
	// ReasonLastPoint: the live account is down to its last point on a window
	// no model choice can dodge, and the target is not at a limit. The four
	// hover reasons are appended last for the reason every value since
	// ReasonProjectedExhaustion was.
	ReasonLastPoint
	// ReasonShortWindowRoom: under hover, a five-hour account has room again and
	// the live account is not one -- the return rule 3 of hover's order names.
	ReasonShortWindowRoom
	// ReasonSoonerWeeklyReset: under hover, a weekly-only account whose week
	// ends sooner than the live one's by more than recovery_hysteresis.
	ReasonSoonerWeeklyReset
	// ReasonStayUntilLimit: under hover, another five-hour account ranks first
	// but the live one is a five-hour account with room, and a five-hour
	// account is left only at a limit.
	ReasonStayUntilLimit
	// ReasonCannotCarry: under hover, the live account has room and the account
	// the order prefers would not carry the work running now -- it would be at
	// a limit at its first live reading -- so the session stays.
	ReasonCannotCarry
	// ReasonWaitsForAReading: under hover, the live account is at a limit --
	// projected there, or for the credit pool on its last point by level --
	// and every move left waits on its own reading. Either the move costs
	// money -- the credit pool, with a seat the gate arms, or a primary seat
	// dearer than the account the session is on -- and money is decided on
	// readings; or it is onto another account's last point, which is taken
	// only once the live account reads empty (lastResort). The session stays
	// until a reading shows the live account at its last point or empty, as
	// the move needs. Plan.RetryAt carries that reading, or a rollover that
	// comes before it. Appended last.
	ReasonWaitsForAReading
)

func (Reason) String

func (r Reason) String() string

type RefreshOutcome

type RefreshOutcome uint8

RefreshOutcome is what a token-refresh failure means for the engine.

Every TokenErrorKind gets its own value, and only one of them quarantines. The quarantine has exactly one trigger, a refresh token the server rejected, and collapsing these would fire it on anything: a transport failure quarantines every account the first time the laptop sleeps, and a bad status does it the first time Anthropic returns a 503.

const (
	// RefreshOK is no failure at all.
	RefreshOK RefreshOutcome = iota
	// RefreshUnreachable is oauth.TokenErrorTransport: the request never got an
	// HTTP answer. That is the network, not the account.
	RefreshUnreachable
	// RefreshDead is oauth.TokenErrorInvalidCode: the refresh token itself was
	// rejected. This is the ONLY outcome that quarantines.
	RefreshDead
	// RefreshScopeRefused is oauth.TokenErrorInvalidScope. The credential is
	// live and the request was wrong, so quarantining the account would blame
	// it for ccdad's own bug.
	RefreshScopeRefused
	// RefreshUpstream is oauth.TokenErrorStatus: the endpoint answered, badly.
	RefreshUpstream
	// RefreshUnknown is an error that is not a token-endpoint failure at all —
	// a context deadline, a store read. It is not evidence about the token.
	RefreshUnknown
)

func ClassifyRefresh

func ClassifyRefresh(err error) RefreshOutcome

ClassifyRefresh maps a token-refresh failure onto the engine's answer. It is the only thing that may decide an account is dead.

func (RefreshOutcome) Quarantines

func (o RefreshOutcome) Quarantines() bool

Quarantines reports whether this outcome may quarantine the account. It is a method rather than a comparison at every call site so that adding a kind cannot quietly add a way to quarantine.

func (RefreshOutcome) String

func (o RefreshOutcome) String() string

type Result

type Result struct {
	// Order is the MAIN POOL, best first: the subscription accounts and the
	// credit seats marked primary, ranked together.
	Order []Ranked
	// Credit is the last-resort credit accounts, ordered by most armed room;
	// see lessCredit. They are not ranked on headroom and never appear in
	// Order: such an account is metered in money and carries no plan windows,
	// so its headroom is permanently unknown — which would file it in the "we
	// have no idea" tier, ahead of every account known to be spent, and make
	// the engine's best candidate the one that costs money. A credit account is
	// a last resort, and the gate, not this comparator, is what decides whether
	// one may be used. A credit account the user marked primary is NOT here: it
	// is in Order, ranked on the credit utilization that is its ordinary meter.
	Credit []Ranked
	// AllOverThreshold is true only when every MAIN-POOL candidate is KNOWN
	// to be over threshold (Spent) -- under hover, past its last point on a
	// window no model choice can dodge. An account that could not be read
	// makes it false: it is neither over nor under, and letting one expired
	// token decide this is how cswap's engine came to park itself permanently.
	// Last-resort credit accounts are excluded, or a registered credit
	// account's permanently unknown headroom would pin this to false and make
	// ModeRecovery unreachable.
	AllOverThreshold bool
	Mode             Mode
}

Result is one ranking pass.

func Rank

func Rank(cands []Candidate, o Options) Result

Rank orders the eligible accounts, best first. It does not reorder its input.

type Rung added in v0.29.0

type Rung uint8

Rung is where hover's order files an account, best first. It is exported because the order is reported -- `ccdad status` prints one line per account and `ccdad auto --json` one field -- and a reporter that re-derived it from the fields would be a second implementation of the order, free to drift from the one that moves the session.

const (
	// RungShortWindow is an account that carries a window shorter than a week
	// -- a five-hour window, on today's plans -- with room on everything that
	// can stop a session. These are spent first: their quota comes back every
	// five hours, so a point of it not spent now is a point thrown away.
	RungShortWindow Rung = iota
	// RungWeeklyOnly is an account with room whose every window is a week. A
	// verified Ultra seat is one; so is a primary credit seat, which carries no
	// window at all and so, having no weekly reset either, sorts last here.
	RungWeeklyOnly
	// RungUnknown is an account nobody could read. A maybe beats a no, which
	// is the place headroomTier gives it too: behind every account known to
	// have room, ahead of every account known not to.
	RungUnknown
	// RungHeldOut is an account the engine left at a limit on a window that
	// has not rolled since; departure.go says why that has to be remembered.
	// Above the limit rungs, so it is the first choice once nothing roomier is
	// left.
	RungHeldOut
	// RungAtLimit is an account down to its last point, or the live account
	// projected to run out inside the reserve after its next reading. An
	// account the session is not on is filed by its levels and its mark only:
	// whether it can carry the work is the hand-off's question (handoff.go),
	// asked of it where the order is walked, not a rung.
	RungAtLimit
	// RungEmpty is an account with nothing left on a window no model choice
	// can dodge.
	RungEmpty
)

func (Rung) String added in v0.29.0

func (r Rung) String() string

type SpendInfo

type SpendInfo struct {
	// Enabled is the account's own overage switch — one of the two independent
	// opt-ins. The other is the configured ceiling.
	Enabled bool
	// Limit is the account's own monthly cap. Nil means the account sets none,
	// so the configured ceiling is the only bound.
	Limit *float64
	// Used is what has already been spent. Nil means it could not be read, and
	// that refuses.
	Used *float64
}

SpendInfo is the credit axis, in the shape CreditRoom takes. Limit and Used are pointers because the wire declares both nullable and the difference between "not reported" and "zero" is the difference between refusing and spending.

type State

type State struct {
	// contains filtered or unexported fields
}

State is the parsed anti-flap state.

func LoadState

func LoadState() (*State, error)

LoadState reads the state without taking a lock.

No lock is needed to read: every write is a rename, so a reader sees one whole version of the document or another, never a torn one. A file that cannot be read or parsed degrades to an empty state — no cooldown, no quarantine — and records why in LoadError. That degradation is deliberately towards MORE switching rather than less: a quarantine that cannot be read is not evidence that an account is dead, and refusing to switch at all on a corrupt file would park the engine exactly the way anti-flap must never park it: those margins bound the rate of switching, not whether the engine can switch at all.

func NewState

func NewState() *State

NewState builds an empty in-memory state. It touches no disk, which is what makes the engine testable without one.

func (*State) ClearQuarantine

func (s *State) ClearQuarantine(uuid string) bool

ClearQuarantine lifts an account's quarantine and reports whether there was one. `ccdad add claude` re-authenticating an existing uuid must call this: store.Add updates in place, so without it the user re-logs-in successfully and the engine goes on refusing to use the account.

func (*State) CodexLastSwitch added in v0.11.0

func (s *State) CodexLastSwitch() (time.Time, string)

CodexLastSwitch is when the Codex lane last repointed the serving account and where to.

func (*State) CooldownRemaining

func (s *State) CooldownRemaining(now time.Time, d time.Duration) (time.Duration, bool)

CooldownRemaining is how long the anti-flap cooldown still has to run, and whether one is in force at all.

A LastSwitchAt in the future is a clock that moved backwards rather than a switch that has not happened yet, and it is deliberately still honoured: the conservative direction here is to wait, and the wait is bounded by the cooldown itself once the clock settles.

func (*State) ForProvider added in v0.11.0

func (s *State) ForProvider(p provider.ID) *State

ForProvider is this state as one lane sees it.

The anti-flap gates read LastSwitch, and there is exactly one implementation of them. Rather than give the Codex lane a second cooldown gate that would be free to drift from the first, the Codex view PRESENTS the codex pair under the name the gates already read.

It is a shallow copy on purpose, and the quarantine map is therefore SHARED. This is a read view for a decision, not a handle to write through: the two writers of this document both go through WithState, which loads its own State. A caller that mutated a quarantine on the returned value would be mutating the original's map, which is why nothing does.

func (*State) Forget added in v0.29.0

func (s *State) Forget(uuid string)

Forget drops what the engine remembers about one account -- its quarantine and the departure mark hover's order holds it out on -- so an account removed and added again under the same uuid comes back neither quarantined nor held out.

It is told the uuid that went rather than the set that stays, and that is the whole of its contract. The caller's set is its own copy of the store, read before this lock was taken, so an account another process added in between is not in it: a prune of everything outside the set would delete that account's fresh quarantine. Naming the one account touches nothing else. TestRemoveForgetsOnlyTheAccountItRemoved.

func (*State) LastSwitch

func (s *State) LastSwitch() (time.Time, string)

LastSwitch is when the engine last moved and where to.

func (*State) LoadError

func (s *State) LoadError() error

LoadError is why the state came back empty when a file did exist. It is not fatal — an unreadable state file means no cooldown and no quarantine, which is the state a first run is in — but `ccdad doctor` should be able to say so rather than having the corruption stay invisible.

func (*State) Quarantine

func (s *State) Quarantine(uuid string, now time.Time, d time.Duration, reason string)

Quarantine holds an account out of auto-rotation. Callers must have decided the failure warrants it — see ClassifyRefresh, which is the only thing that may make that call.

func (*State) Quarantined

func (s *State) Quarantined(uuid string, now time.Time) (Quarantine, bool)

Quarantined reports an account's live quarantine, if it has one.

func (*State) QuarantinedUUIDs

func (s *State) QuarantinedUUIDs(now time.Time) []string

QuarantinedUUIDs lists every account under a live quarantine, in uuid order so the answer does not depend on map iteration.

func (*State) RecordCodexSwitch added in v0.11.0

func (s *State) RecordCodexSwitch(uuid string, at time.Time)

RecordCodexSwitch stamps a completed Codex repoint. The rule RecordSwitch states applies here unchanged: the caller records it AFTER the pointer was written, because a cooldown earned by a repoint that failed would hold the lane off its own retry.

func (*State) RecordSwitch

func (s *State) RecordSwitch(to string, at time.Time, left Departure)

RecordSwitch stamps a completed switch to the account to, and remembers the account left when a limit was what it was left at. The caller records it AFTER the credential swap succeeded: a cooldown earned by a switch that failed would hold the engine off the retry, and a mark left by a move that never happened would hold an account out for a departure it never made.

A departure that names no closing window writes nothing, and it does not clear an older mark either. The mark answers one question -- has the window that had this account at a limit rolled since? -- and leaving the account for some other reason does not answer it.

type Strategy

type Strategy uint8

Strategy is which question the ranking asks.

const (
	// StrategyHeadroom is the default: keep the engine on whichever account has
	// the most left.
	StrategyHeadroom Strategy = iota
	// StrategyConsumeFirst spends perishable weekly quota before it expires.
	StrategyConsumeFirst
)

func ParseStrategy

func ParseStrategy(name string) (Strategy, bool)

ParseStrategy is String's inverse. Unlike identity.ParseKind it does NOT fall back to a default: a name that reaches here came from a user typing it, and silently running the wrong strategy for a typo is the cswap behaviour the exit contract exists to fix.

func (Strategy) String

func (s Strategy) String() string

type Thresholds added in v0.3.0

type Thresholds struct {
	// Default is the threshold for a window with no entry of its own, which is
	// every window until a user writes a table.
	Default float64
	// PerWindow is the per-window table, keyed by the window name the wire
	// uses — scoped names included — so the map a user's configuration builds
	// needs no translation between what was typed and what a snapshot reports.
	PerWindow map[usage.WindowName]float64
	// Credit is the utilization percent above which a credit-metered account
	// counts as spent. It is a separate number from Default because the two
	// meter different things: Default is a share of a plan window, this is a
	// share of a credit balance.
	Credit float64
	// ModelCaps is whether a window that caps one model family binds. The zero
	// value is that it does, which is every table a user's configuration builds.
	ModelCaps ModelCaps
}

Thresholds is every threshold one ranking pass may consult, in one value.

It is a value type with a nil-safe map, so a caller never branches on presence: the zero Thresholds is the built-in default set, and a nil PerWindow is the ordinary state rather than a missing one.

func (Thresholds) CreditThreshold added in v0.3.0

func (t Thresholds) CreditThreshold() float64

CreditThreshold is the credit meter's threshold, defaulted the same way and for the same fail-open-on-money reason.

func (Thresholds) For added in v0.3.0

For is the threshold for one window: its own entry when it has one, Default when it does not.

Both fallbacks default rather than being read literally, and it matters. A zero threshold read literally means "over threshold if utilization > 0", so an account with a single percent used counts as spent — which flows straight into SubscriptionExhausted, the input that opens the credit gate. A zero-valued Thresholds would therefore fail OPEN on money, against everything the credit gate stands for. Defaulting makes the omission harmless instead, and a non-positive entry in the table is treated as the same omission for the same reason.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL