switcher

package
v0.31.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 18 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 switcher performs the credential swap, and answers the question the swap turns on: which managed account is live right now.

It exists because the swap used to be ~90 lines of Cobra RunE. The daemon needs the same sequence, and a second copy of it diverges from the one path anybody has hand-tested — so the sequence lives here and both callers reach it. The CLI keeps the words; this package keeps the behaviour.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoLogin = errors.New("this account has no Claude Code login to install")

ErrNoLogin is a target that cannot become the credentials file's login.

A setup-token account is the ordinary case: `claude setup-token` prints the token and deliberately skips saving it, so Claude Code reads it from the environment and there is no file to install it into. An api-key account is installable, but by a different route entirely — two writes to ~/.claude.json and the credentials file — which is the CLI's to perform and which the engine never asks for, because an account with no quota windows has nothing for a usage-aware ranking to compare.

It is returned BEFORE any lock is taken. Handing cclink a snapshot it will refuse would put a doomed switch in front of Claude Code's own refresh.

View Source
var ErrNotClaude = errors.New("switcher: target is not a Claude account")

ErrNotClaude is a switch asked to install an account that is not a Claude account. This function writes Claude Code's credentials file; a Codex account is served by the proxy and has nothing to install here.

View Source
var ErrStoredLoginMoved = errors.New("the account's stored login changed while the switch waited for " +
	"Claude Code's locks, so nothing was written; run it again")

ErrStoredLoginMoved is an attended switch whose target's stored login changed while it waited for Claude Code's locks -- a poll stored a rotated pair. Nothing was written; running it again installs the new one.

Functions

func APIKeyOwner

func APIKeyOwner(accounts []store.Account, lookup Lookup, key string) (store.Account, bool)

APIKeyOwner finds the managed account whose stored credential is key.

func AttributeFile

func AttributeFile(live cclink.Blob, accounts []store.Account, lookup Lookup) (store.Account, bool)

AttributeFile matches the live credentials file against the managed accounts.

The bool answers "is this a managed account", which is what a caller that only needs a name wants. A caller deciding whether to WRITE the file wants LiveStateOf instead: false here spans both LiveNone and LiveUnattributed.

func CredentialIdentity

func CredentialIdentity(b cclink.Blob) string

CredentialIdentity is the value attribution compares, for accounts whose credential really does live in the credentials file.

The refresh token leads because it survives an access-token rotation: a Claude Code that has refreshed since the switch still carries it. An access token is the fallback, for a record that has been through Claude Code's dead-token clear or was written without one.

There is deliberately no API-key case: the claudeAiOauth object has exactly eight keys and none of them is an API key, so a branch for one would be dead code pretending to be defensive. Token accounts are matched by AttributeLogin instead, where Claude Code actually reads them from.

The kind prefix is load-bearing: without it an access token stored by one account could match a refresh token stored by another. "" means "cannot identify" and never matches anything, including another "" — which is the case for every token account, whose stored blob has no OAuth record at all.

It is cclink.LoginIdentity: cclink needs the same comparison to read back a keychain write that ran out of time, and two copies of it would be two answers to "is this the same login".

func DisplacementNote added in v0.3.0

func DisplacementNote(lead string, res Result) string

DisplacementNote is the ONE sentence every caller prints when a switch is outranked, built from the source rather than from a variable name.

It exists because widening the gate without widening its messages is what this function was added to repair: the gate had grown from one environment variable to six sources, three of which have no variable, while four call sites went on telling the user to unset CLAUDE_CODE_OAUTH_TOKEN. A single renderer is what stops the fifth from being written that way.

lead is the caller's own opening ("Note: " for an attended switch, "not switching: " for the engine), because the two differ in tense and nothing else.

func Explain

func Explain(plan strategy.Plan) string

Explain turns a plan into a sentence, adding the detail the reason alone cannot carry. Both callers use it, so the engine says the same thing in a terminal and in daemon.log.

func Installable

func Installable(creds cclink.Blob, err error) bool

Installable reports whether an account can become the live login at all.

A SETUP-TOKEN account is stored but has no claudeAiOauth record and no file Claude Code would read it from, so there is nothing to install. Left in the pool it can rank first and then fail the switch, turning a strategy the user asked for into an error they cannot act on — so it is excluded from the ranking rather than rejected after winning it. An explicit `switch <ACCT>` still names one and still gets the message that says how to use it.

An API-KEY account IS installable: `switch` writes primaryApiKey into ~/.claude.json and clears the login in front of it. It is still never chosen by the engine, but for a different reason and in a different place — strategy.eligible drops identity.KindAPIKey because an account with no quota windows has nothing for a usage-aware ranking to compare. Saying so here instead would state the same exclusion twice and let the two spellings disagree.

The signature takes the (Blob, error) pair a lookup returns, so a caller can hand it one call rather than unpacking at every site.

func LoginOf added in v0.3.0

func LoginOf(live cclink.Blob) identity.Login

LoginOf reads the credentials file as the two fields the OAuth resolver's last branch tests, and nothing else.

It lives here rather than in internal/identity because that package must not depend on the one that reads and writes Claude Code's files -- the same rule that made APIKeyApproval a duplicated three lines rather than an import.

The access token is reduced to a BOOL and never carried further: the question is whether one exists, and passing a live bearer token around to answer that is what this tree's credentials rule forbids. A record that will not parse is the zero Login, which is the right answer for it -- cclink's loader is where a malformed credentials file is reported, not here.

func PendingTarget added in v0.29.1

func PendingTarget() string

PendingTarget is the target of ccdad's own switch whose outcome could not be confirmed, or "" -- including when the engine state cannot be read, which leaves the repair to decide by recency, as it would with nothing pending.

func RecordSwitch

func RecordSwitch(uuid string, left strategy.Departure) error

RecordSwitch stamps the anti-flap cooldown after a swap has succeeded.

An EXPLICIT switch stamps it too, and that is the point: the user has just chosen an account, and a daemon evaluating ten seconds later must not immediately override the choice. Stamping before the swap would let a switch that FAILED hold the engine off its own retry.

It is exported because Execute is not the only way an account becomes the live credential: installing an api-key account writes ~/.claude.json instead, and a cooldown that only some switches stamped would let the engine override exactly the ones it did not see.

left is the departure the engine's plan named, written in the SAME locked write as the cooldown: hover's order reads the two together, and a mark without its stamp, or the reverse, is a state no single switch produces. A write that fails loses both, which degrades towards more switching -- the direction the cooldown's own failure already takes.

It stamps the wall clock, which is the clock of the commands that call it directly; Execute, which runs on the request's clock, calls RecordSwitchAt.

func RecordSwitchAt added in v0.29.0

func RecordSwitchAt(uuid string, at time.Time, left strategy.Departure) error

RecordSwitchAt is RecordSwitch at the instant at, on the caller's clock: Execute's is the request's (Request.now), the one the prompt poll beside it is scheduled on, so a switch on an injected clock stamps its cooldown on that clock too.

func SchedulePromptPoll added in v0.29.0

func SchedulePromptPoll(uuid string, now time.Time, accounts int) error

SchedulePromptPoll brings the next poll of the account a switch just made live forward to pollpolicy.PromptPollAt, so the work's first reading on it does not wait out the idle cadence it was being read on.

It writes NextPollAt once, here, and the account's own next commit overwrites it with the live cadence, whether that poll succeeds or fails -- so a poll that keeps failing backs off as it always has rather than retrying at the tick rate.

Beside it, under the same lock, it records that the switch made the account live at now (PollState.LiveSince). A poll of the account already in flight was sent while it was idle, and the daemon's live label is set only after Execute returns; the commit reads the record under the cache lock instead, so that poll commits as the live account's reading and on the prompt's schedule rather than writing an idle cadence over it. An account with no row yet -- its first poll may be the one in flight -- gets a row holding just the record; with no reading it is due already. accounts is how many draw on the account's polling budget (store.SharingIdentity), which the prompt's floor is shared among. TestASwitchOntoAnAccountWithNoRowStillRecordsIt.

func SyncGlobalConfigIdentity added in v0.4.1

func SyncGlobalConfigIdentity(s *store.Store, target, previousLive store.Account, previousLiveKnown bool) error

SyncGlobalConfigIdentity keeps ~/.claude.json's oauthAccount pointed at whichever account this call just confirmed live -- target.

Claude Code's own token-refresh handler enriches oauthAccount's cosmetic fields (displayName, billingType, the trial and onboarding flags...) but never rewrites accountUuid, emailAddress, or organizationUuid once the object exists (see cclink's oauthaccount.go). A switch that only replaces the credentials file therefore leaves Claude Code DISPLAYING whoever was live before, forever -- even though the credentials file, and everything Claude Code actually authenticates and meters with, is already target's.

If target has never been synced before, oauthAccount is reset to a minimal object naming just who it is; if a real snapshot was captured the last time ccdad switched away from target, that exact object is restored instead. Either way, if the object already names target, it is left untouched -- touching it here would discard any cosmetic enrichment Claude Code's own refresh has since added, for no gain.

previousLive and previousLiveKnown are what the caller believes was live immediately before this call; Execute already decides this under Claude Code's credential locks. They are used only to decide whose snapshot to back the displaced object up as, so target's own correctness never depends on a caller supplying them -- a caller that cannot loses only that courtesy. It is exported for the one other attended path that installs a login without going through Execute: `ccdad add claude --activate`.

Types

type Attribution

type Attribution struct {
	Account store.Account
	OK      bool
	// Via names the mechanism, in the caller's words.
	Via string
	// FromLoginStore says the credential came from the LOGIN STORE -- the
	// keychain item or the credentials file -- rather than from an environment
	// override or a stored API key.
	//
	// It exists because a failure to attribute means different things on the
	// two axes, and only one of them supports the sentence ccdad used to print
	// for both. A login store's refresh token is rotated by Claude Code on
	// every refresh, and attribution matches on that token, so an
	// unattributable login is very often one of the user's OWN accounts seconds
	// after a refresh -- calling it unmanaged asserts ownership nothing
	// established. A token handed over in CLAUDE_CODE_OAUTH_TOKEN is not
	// rotated by anything ccdad can miss, so there the claim can be made.
	FromLoginStore bool
}

Attribution is what AttributeLogin learned: the account, and how Claude Code gets to it. The how is reported even when the account is not one ccdad manages, because "not managed" plus "because apiKeyHelper is set" is actionable where "not managed" alone is not.

func AttributeLogin

func AttributeLogin(live cclink.Blob, accounts []store.Account,
	lookup Lookup, env identity.APIKeyEnvironment, oauthEnv identity.OAuthEnvironment,
	liveSource cclink.CredentialSource) Attribution

AttributeLogin answers "which managed account is Claude Code actually using".

It models Claude Code's two competing axes in the order Claude Code resolves them, which is documented rule by rule in identity/apikey.go:

  • An API key from the ENVIRONMENT, a file descriptor or an apiKeyHelper turns the OAuth path off entirely (`BE()`), so it is asked first. The credentials file must not even be consulted then: reporting its account would name one Claude Code is not using.
  • Otherwise the OAuth axis answers, in ITS OWN resolver's order. That order is not "the environment token, then the file": ANTHROPIC_AUTH_TOKEN outranks CLAUDE_CODE_OAUTH_TOKEN, a session host can inject a token at a path with no variable behind it, an Anthropic CLI profile sits in front of the file, and the file itself counts only when its scopes carry user:inference. identity/oauth.go is that model; this function renders it.
  • Only when the OAuth axis has nothing does a STORED primaryApiKey become the credential. It is Claude Code's lowest-priority source, and treating it as the answer while a login exists is the single mistake this whole model exists to avoid.

liveSource is WHICH STORE live came from, and it is a parameter rather than something this function works out: the read already happened, and re-deriving it here would be a second answer that can disagree with the first. Callers get it from cclink.LoadWithSource.

type EvalOptions

type EvalOptions struct {
	// Strategy overrides the configured one. `switch --strategy` is explicit
	// and the file is not, so the flag wins; leave HasStrategy false and the
	// config's own key decides, which is the daemon's case.
	Strategy    strategy.Strategy
	HasStrategy bool
	// Model is the model the chosen account is about to run, as the user typed
	// it. It narrows the ranking to the windows that bind for that model;
	// empty is the unqualified pass, which is what the daemon runs. There is no
	// Has- flag beside it because there is no config key to override: an empty
	// model IS the default, rather than the absence of an opinion.
	Model string
	// Force bypasses the anti-flap margins, and only those. It never bypasses
	// the credit gate: that one spends money, and a flag named "force" is not
	// the two independent opt-ins a switch onto a credit account requires.
	Force bool
	// Now is the clock. Zero means time.Now.
	Now time.Time
	// Config supplies the engine's knobs, and whatever went wrong getting them.
	// The config it returns is used either way: that IS the warning contract.
	//
	// Nil reads the file and falls back to the built-in defaults, which is
	// right for a one-shot — there is no previous config to keep. A daemon must
	// pass config.Reloader.Reload instead: the last-good-config rule says an
	// unusable file leaves the engine on the LAST CONFIG THAT PARSED, and
	// silently reverting a tuned threshold to stock because somebody mistyped an
	// edit is the failure that rule exists to prevent.
	Config func() (config.Config, error)
	// Provider narrows the pass to one provider's accounts. The ZERO value
	// reads as Claude, which is what keeps every existing call site on the
	// path it is on today without naming one.
	//
	// It is not a filter on the OUTPUT. It is handed to the candidate builder,
	// so an account of the other provider is never ranked, never wins, and is
	// never returned as a target -- which is the property that has to hold,
	// because a target is handed to a switch that rewrites Claude Code's
	// credentials file.
	Provider provider.ID
	// Owners is the identity oracle's memory: the daemon passes it so a login
	// store it has already named reads as that account's (LiveResolved). Nil
	// knows nothing, which is every one-shot caller.
	Owners Owners
	// Record is the record of spent stored logins to decide from. Nil reads
	// it from disk; the daemon passes its own, which holds records it could
	// not write yet.
	Record store.OracleRecord
}

EvalOptions are the inputs that do not come from disk.

type Evaluation

type Evaluation struct {
	// Plan is the ranking's answer. Its Action maps onto the exit contract's
	// codes: ActionSwitch is 0, ActionStay is 3, ActionBlocked is 4.
	//
	// Decided says whether the ranking ran at all, and reading Plan without it
	// is the trap this field exists for: a zero Plan does not stringify to
	// nothing, it stringifies to plausible values — Reason(0) is "a better
	// target cleared every margin" and Mode(0) is "headroom" — so a report
	// built from one does not look empty, it looks wrong.
	Plan    strategy.Plan
	Decided bool
	// Target is Plan.Target resolved against the store, set only when the plan
	// says to switch.
	Target    store.Account
	HasTarget bool
	// Live is the account the credentials FILE names, which is the hysteresis
	// baseline and the value an unattended swap is conditional on.
	//
	// LiveState is the same read kept at four values rather than two. An
	// unattended caller needs it: LiveKnown false spans a machine with nobody
	// logged in and a machine whose live login this store cannot name, and only
	// the first of those is safe to overwrite.
	Live      store.Account
	LiveKnown bool
	LiveState LiveState
	// LiveErr is a live file that could not be read. It is not fatal: the
	// baseline is lost, so every candidate is compared against nothing, and
	// this is the state where moving to a known-good account matters most.
	LiveErr error
	// Login is who each login store holds beside ccdad's record, from the same
	// read Live came from; LoginKnown is false when that read failed. A caller
	// that acts checks Login.Split() before the plan: a split login is repaired
	// first, because a plan ranked against the item alone is a plan about a
	// machine Claude Code may not be on.
	Login      LoginView
	LoginKnown bool
	// Stores is the raw read Login was built from. The daemon's identity
	// oracle needs a store's own access token to ask whose login it is.
	Stores cclink.LoginStores
	// Spent is every account whose stored refresh token is spent
	// (store.Account.StoredLoginSpent), so it is not a target. When the stores
	// could not be read, the daemon's record decides it alone.
	Spent map[string]store.Hold
	// NoReadings means nothing has ever been polled, so there is no evidence to
	// choose on. Distinct from ActionBlocked, which is a choice that was made
	// and came back empty — exit 4 is "wanted, but no viable target", and both
	// end there, but only one of them is worth telling the user to run the
	// daemon about.
	NoReadings bool
	// Forced reports that Force overrode an anti-flap hold.
	Forced bool
	// ConfigErr is a config file that could not be used; the built-in defaults
	// were substituted. Refusing to switch because a threshold was mistyped is
	// a worse answer than switching on the documented default.
	ConfigErr error
	// StateErr is engine state that could not be read; the pass ran with no
	// cooldown and no quarantines.
	StateErr error
	// LastSwitchAt and LastSwitchTo are the cooldown stamp this pass read. The
	// daemon publishes them; nothing in the ranking needs them, because the
	// cooldown gate has already been applied by the time this is returned.
	LastSwitchAt time.Time
	LastSwitchTo string
}

Evaluation is one pass of the engine over the store and the on-disk usage cache: what the ranking could see, and what it decided.

It carries the degraded inputs rather than reporting them, because the two callers report differently — the CLI to a terminal, the daemon to a log and an NDJSON stream — and a package that printed would force one of them to parse the other's sentences.

func Evaluate

func Evaluate(s *store.Store, opts EvalOptions) (Evaluation, error)

Evaluate runs the engine once. It READS the usage cache and never fetches: that is the same rule `ccdad status` follows, and for the same reason — /api/oauth/usage allows roughly 28-30 requests per identity per rolling hour over a SLIDING window, so a command a user can run in a loop must not be a way to spend it.

It takes no Claude Code lock at all. The swap does; this only decides.

func EvaluateCodex added in v0.11.0

func EvaluateCodex(s *store.Store, root string, opts EvalOptions, book *codexproxy.LimitBook) (Evaluation, error)

EvaluateCodex is the Codex lane's own pass over the store and the usage cache.

IT IS NOT A LOOP AROUND Evaluate, and the reason is engineCandidates: its first line skips any account whose blob is not Installable, and a codex credential never is -- so every Codex account would be dropped before any provider check ran, and the lane would silently rank an empty pool forever.

Three things differ from the Claude pass, and each is a decision:

  • The BASELINE is the serving pointer, never the account Claude Code is logged in as. A baseline that is not among the candidates makes cooldownGate's no-baseline arm fire on every pass, which turns the cooldown into a no-op and the lane into a repoint on every tick.
  • PreemptLead is forced to zero and Hover to false AFTER RankOptions, so a user's Claude tuning cannot switch on for codex two mechanisms this version does not implement for it: there is no forecast for a Codex window and no hover table over a two-window snapshot.
  • The cooldown comes from the codex stamp, through State.ForProvider.

opts.Provider is accepted for readability at the call sites and is not read: this function ranks Codex accounts and nothing else.

book may be nil, which means "nothing is known to be throttled". An attended `ccdad switch` has no proxy in its process and passes nil.

type LiveState added in v0.5.0

type LiveState uint8

LiveState is what the credentials file holds, in the four answers a swap needs to tell apart.

AttributeFile used to return two, and collapsing the last two into one bool is what let the engine overwrite a running session's login. "No login in the file" and "a login this store cannot name" have OPPOSITE answers for an unattended swap: the first is a machine with nothing to lose, and the second is very often a managed account whose refresh token Claude Code has just rotated — installing over it re-presents a superseded grant and takes the whole family down with it.

The same distinction is already drawn, correctly, one package over: the daemon's probeDue refuses to spend quota against an account when the live one "could not be worked out", for exactly this reason. This type is that rule given a name so the swap path can hold it too.

const (
	// LiveNone: the file carries no OAuth login at all. Nobody is logged in,
	// and a swap has nothing to overwrite.
	LiveNone LiveState = iota
	// LiveManaged: the file's login is one of this store's accounts.
	LiveManaged
	// LiveUnattributed: the file carries an OAuth login that matches no stored
	// snapshot. It may be an account nothing here manages, or it may be a
	// managed account that has rotated since ccdad last saw it, and the file
	// alone cannot say which.
	LiveUnattributed
	// LiveUnreadable: the login store could not be READ, so what it holds is
	// not known -- not even whether it holds anything.
	//
	// This is the fourth answer, and it was missing for the same reason the
	// third one was. A caller that could not read the store passed a nil blob,
	// which lands on LiveNone above -- "nobody is logged in, and a swap has
	// nothing to overwrite" -- and that is the most dangerous of the four
	// things it could mean. On macOS the ordinary way to get here is a locked
	// login keychain answering errSecInteractionNotAllowed while Claude Code,
	// whose combinator falls back to the credentials file, carries on serving a
	// live session from a store ccdad cannot see.
	//
	// It is appended rather than inserted so the existing values keep their
	// numbers, the same rule Outcome carries.
	LiveUnreadable
	// LiveResolved: a login whose refresh token matches no stored snapshot,
	// whose OWNER is nonetheless known to be one of this store's accounts --
	// by that account's own history (a login its stored one replaced), or
	// because the identity oracle has named it. It is a generation of that
	// account's login ccdad does not store now: newer and not yet taken in,
	// or older and already spent. Only a LoginView produces it -- its view of
	// a store finds the history, and Owners carries the oracle's naming;
	// LiveStateOf alone never does. Appended, for the reason LiveUnreadable
	// is.
	LiveResolved
)

func LiveStateOf added in v0.5.0

func LiveStateOf(live cclink.Blob, accounts []store.Account, lookup Lookup) (store.Account, LiveState)

LiveStateOf is AttributeFile without the collapse. Which account a login is, is store.OwnerByEvidence's to say -- a Claude row's stored login, never another provider's (it says why) -- and only its stored-login answer makes the login managed here: a login an account's stored one replaced is a generation ccdad no longer stores, which a LoginView names LiveResolved.

func (LiveState) String added in v0.5.0

func (s LiveState) String() string

type LoginView added in v0.29.1

type LoginView struct {
	// HasItem is whether there is a keychain item. Without one the file is the
	// only store, and Item is not consulted.
	HasItem bool
	Item    StoreHolder
	File    StoreHolder
	// Recorded is the account ccdad last recorded as active. Its UUID is ""
	// when nothing is recorded; an account no longer in the store keeps only
	// its UUID.
	Recorded store.Account
	// Intent is the target of ccdad's own switch whose outcome could not be
	// confirmed (strategy.State.Pending), or "". It decides the repair's
	// direction before recency does; see RepairTarget.
	Intent string
}

LoginView is each login store's account beside the account ccdad records as active (accounts.toml's active_uuid).

func ViewLogin added in v0.29.1

func ViewLogin(st cclink.LoginStores, accounts []store.Account, lookup Lookup, recorded string, owners Owners) LoginView

ViewLogin attributes each store on its own and sets them beside the record. owners may be nil.

func (LoginView) AllOn added in v0.29.1

func (v LoginView) AllOn(uuid string) bool

AllOn reports whether every store AND the record name uuid: the only state in which a switch to uuid has nothing at all to do.

func (LoginView) At added in v0.29.1

func (v LoginView) At() StoresAt

At is the view's StoresAt.

func (LoginView) Describe added in v0.29.1

func (v LoginView) Describe() string

Describe names which store holds which account, in a user's terms: email and uuid, never a token.

func (LoginView) Lead added in v0.29.1

func (v LoginView) Lead() StoreHolder

Lead is the store Claude Code reads first: the item when there is one.

func (LoginView) RecordBehind added in v0.29.1

func (v LoginView) RecordBehind() bool

RecordBehind reports stores that agree on a named account while ccdad's record names another. Nothing needs installing; the record is corrected.

func (LoginView) RecordedName added in v0.29.1

func (v LoginView) RecordedName() string

RecordedName is the recorded account as Describe names it, or "no account".

func (LoginView) RepairTarget added in v0.29.1

func (v LoginView) RepairTarget() store.Account

RepairTarget is the account a split is repaired TOWARDS, decided in this order:

  1. ccdad's OWN switch whose outcome could not be confirmed (Intent), when a store holds its target. Recency cannot see this one: a switch installs a stored login that may have been issued hours ago, while the account it leaves was refreshed in place since -- so the login ccdad just chose is often the OLDER of the two, and recency would undo the switch.
  2. The store holding the more recently issued login.
  3. On a tie, the keychain item.

Recency, after intent, rather than a fixed store, because either store can be ahead:

  • The item is ahead after a ccdad switch whose file write never happened -- the 2026-11-10 incident -- and after Claude Code's /login or refresh, which write the item and skip the file.
  • The file is ahead after any of those whose KEYCHAIN write failed: Claude Code's store then writes the file instead, and on the loaded Mac where splits happen its keychain writes fail as often as ccdad's do.

Whichever was issued later is the most recent decision anyone made, and the older login is the one that has been superseded -- for the same account its refresh token is already spent. The record is never the target: ccdad writes it only after both stores, so it is the oldest of the three. The tie goes to the item because it is the store Claude Code reads first.

func (LoginView) Split added in v0.29.1

func (v LoginView) Split() bool

Split reports a login the engine repairs: stores that disagree, or a record behind agreeing stores.

func (LoginView) StoresDisagree added in v0.29.1

func (v LoginView) StoresDisagree() bool

StoresDisagree reports two stores holding different logins whose owners are both established, with the newer one -- the one a repair copies -- held as ccdad's stored login for its account. That is a split the engine can repair: it knows what it is copying and whose it is.

The newer one has to be the stored snapshot because the repair installs the snapshot (read again under the lock); a newer login the store has not taken in yet is adopted first, by the daemon's oracle step, and repaired on the pass after.

func (LoginView) StoresOn added in v0.29.1

func (v LoginView) StoresOn(uuid string) bool

StoresOn reports whether the stores hold uuid's stored login and nothing else. It is what decides that a switch to uuid writes no credential.

With an item, the file must hold the SAME login or none. A file with a different login -- another account's, an older or newer one of the same account, or one this store cannot name -- is a store a switch to uuid has to write, and it is the state in which `ccdad switch` used to say "Already on". A missing file is not: some Claude Code releases delete it behind an item, and creating it is not a switch's business. This is the same line Split and Unresolved draw, so a machine `switch` would rewrite is one the daemon and doctor do not call fine.

func (LoginView) Unresolved added in v0.29.1

func (v LoginView) Unresolved() bool

Unresolved reports two stores holding different logins where the engine cannot repair: one of them cannot be named, or the newer one is not yet ccdad's stored login. Nothing is written over it; the daemon asks the identity oracle, and doctor warns.

It is the case the first version of this file waved through as "Claude Code refreshed the item and left the file behind". That is one reading. Claude Code writing its newer login to the FILE when its keychain write failed is another, and the two cannot be told apart without naming the login.

type Lookup

type Lookup func(uuid string) (cclink.Blob, error)

Lookup reads an account's stored credential snapshot. It is a parameter rather than a *store.Store so attribution can be exercised without one, and so a caller that has already opened the store does not open a second.

type Outcome

type Outcome uint8

Outcome is what one Execute did. Everything except Switched left the credentials file exactly as it found it.

const (
	// NotSwitched is the zero value, and it is deliberately not Switched:
	// Execute fills the Outcome in as it goes, so a call that returned an error
	// leaves it here. A zero value meaning "switched" would report every
	// failure as a success to any caller that read the Result before the error.
	NotSwitched Outcome = iota
	// Switched: the target is now the credentials file's login.
	Switched
	// AlreadyOn: the target was already the login, decided under the lock.
	AlreadyOn
	// Raced: the live login is no longer the one the decision was made
	// against, so an unattended swap stood down. Attended callers never see
	// this.
	Raced
	// Overridden: CLAUDE_CODE_OAUTH_TOKEN is set, so the swap would change
	// nothing about what Claude Code uses. Unattended callers only.
	Overridden
	// Contended: another ccdad STORE's engine is driving this credential home,
	// so an unattended swap stood down rather than undo its work — which it
	// would then undo back, forever. Unattended callers only; see credhome.
	//
	// Appended at the end of this block on purpose. Nothing persists these
	// numbers today, and appending is what keeps that true if something ever
	// does.
	Contended
	// Stale: the target's stored credential sits inside the window Claude Code
	// refreshes in, and no refresh could move it out. Nothing was written.
	Stale
	// Unreadable: this machine's login store could not be READ, so whether any
	// account is live is not known -- not even whether anything is logged in.
	// Nothing was written. Appended, for the reason Contended and Stale are.
	Unreadable
	// Unattributed: the credentials file holds an OAuth login this store
	// cannot name, and the caller did not establish that it is foreign. An
	// unattended swap stands down rather than write over what may be a managed
	// account mid-rotation. Unattended callers only.
	Unattributed
)

func (Outcome) String

func (o Outcome) String() string

type Owners added in v0.29.1

type Owners func(id string) (uuid string, ok bool)

Owners names the managed account a login belongs to, by its LoginIdentity, when the identity oracle has already answered for it. Nil knows nothing.

type PendingSettlement added in v0.29.1

type PendingSettlement uint8

PendingSettlement is what SettlePending found.

const (
	// PendingOpen: nothing pending, or the stores do not yet say how it went
	// -- they disagree, and the repair carries it out.
	PendingOpen PendingSettlement = iota
	// PendingCompleted: both stores hold the target. The switch took effect
	// with nothing left to write, and it has been recorded as the switch it
	// was: the account as live, the cooldown, and the departure.
	PendingCompleted
	// PendingNotTaken: both stores hold another account. The switch did not
	// take effect, and it is forgotten.
	PendingNotTaken
)

func SettlePending added in v0.29.1

func SettlePending(s *store.Store, v LoginView, viewAt, now time.Time) (PendingSettlement, string, error)

SettlePending closes out ccdad's own switch whose keychain write could not be confirmed (strategy.State.Pending), once the stores agree and so no repair will.

Agreeing on the TARGET is not "nothing to do". The plan that made the switch left an account behind -- possibly at a limit, which is what its departure records -- and the cooldown is what holds the engine off moving straight back. A switch whose file write landed through some other path (the file already held the target, say) would otherwise be recorded by nobody, and only the record would be corrected.

viewAt is when v was read. An intent recorded AFTER it is one v knows nothing about -- a switch that started writing after the read -- and is left alone; and what is cleared or completed is exactly the intent read here, checked again under the state lock, never a later one recorded meanwhile.

type Request

type Request struct {
	// Target is the account to install.
	Target store.Account

	// LiveUUID is the account the caller observed as live when it decided, or
	// "" for a file it could not attribute.
	//
	// Unattended, it is a PRECONDITION: if the file under the lock names anyone
	// else, the swap stands down with Raced. That guard cannot be replaced by
	// the anti-flap cooldown, because the engine read the cooldown before the
	// hand switch that stamped it.
	//
	// Attended it is ignored. A human typed the command and is watching the
	// result, so a login that changed underneath is something to report, not a
	// reason to refuse what they just asked for.
	LiveUUID string

	// Unattended marks a caller with nobody watching: the daemon, or a cron
	// line. It turns two warnings into refusals — see LiveUUID and Overridden —
	// because a notice printed to a log nobody reads is not a notice.
	Unattended bool

	// Force installs the target even when it is already live. It bypasses the
	// already-on answer and nothing else.
	Force bool

	// Now is the clock the staleness precondition reads. Nil is time.Now.
	Now func() time.Time

	// Freshen refreshes the target's stored credential and returns what to
	// install in its place. It is called ONLY when the stored one sits inside
	// cclink.SelfRefreshThreshold, and never for the account the caller
	// believes is already live.
	//
	// It is a hook rather than a direct call into the token machinery for two
	// reasons. It reaches the network, and this package's whole ordering
	// discipline is that the network is touched BEFORE Claude Code's
	// credential locks are taken (cclink.ActivateWith says why); putting it
	// behind a field keeps that visible at the one place it is invoked. And a
	// caller with no way to refresh — a test, an offline path — gets the
	// refusal rather than a package that quietly grew a dependency on the
	// token endpoint.
	//
	// Nil means "cannot refresh", which is a refusal, not permission to
	// install what is stored.
	Freshen func(uuid string) (cclink.Blob, error)

	// LiveForeign says the caller POSITIVELY established that the login in the
	// credentials file belongs to no account this store manages -- it resolved
	// the token's owner and the answer was somebody else.
	//
	// It is not "the file did not match a stored snapshot". That is the state
	// a managed account is in the moment Claude Code rotates its refresh token,
	// and an unattended swap that reads it as "nobody is live" installs over a
	// running session. Only a caller that has RESOLVED the login may set this,
	// and setting it without resolving reintroduces the loop by hand.
	//
	// Attended callers do not need it: a human is watching, so an unnameable
	// login is something to report rather than a reason to refuse.
	//
	// It is a finding about the file the caller READ, so it is checked against
	// the file under the lock like LiveUUID is: a file that has become a
	// managed account's since then is a race, not a foreign login.
	LiveForeign bool

	// Departure is what the engine's plan says this swap leaves behind --
	// strategy.Plan.Departure -- and it is recorded with the cooldown once the
	// swap has happened. Every swap the engine chose passes it, a targetless
	// `ccdad switch` included; a swap to an account a person named passes the
	// zero value, because the mark is the engine's own record of an account it
	// left at a limit and a hand switch is not one.
	Departure strategy.Departure

	// Expect is what both login stores held when the caller decided, and under
	// the lock it REPLACES the LiveUUID precondition: if either store holds a
	// different login now, an unattended swap stands down with Raced. LiveUUID
	// asks only about the store Claude Code reads first, and a decision about a
	// split login is a decision about both -- a /login that landed in the file
	// while this call waited for the lock is a change LiveUUID cannot see.
	Expect *StoresAt

	// Sync marks a write that carries out a login one store already holds
	// rather than a move the engine chose: a split-login repair. It records
	// the account as live and stamps NO cooldown and no departure -- a
	// cooldown there would hold the engine on an account it may need to leave
	// at once. A repair that completes an ENGINE switch whose outcome was
	// unknown is that switch, and passes Sync false with its departure.
	//
	// An attended switch to the account Claude Code already reads first is a
	// sync whatever this says: the person named the account that is live, and
	// what the call does is make the other store agree.
	Sync bool

	// Record is the record of spent stored logins the decision under the lock
	// takes (see EvalOptions.Record). Nil reads it from disk.
	Record store.OracleRecord

	// Owners is the identity oracle's memory (see EvalOptions.Owners). The
	// decision under the lock attributes the stores again, and without it a
	// login the oracle has named -- an older generation of the account being
	// repaired towards -- reads as unattributable there and stands every
	// repair down.
	Owners Owners
}

Request is one swap.

type Result

type Result struct {
	Outcome Outcome
	// Target is the account Execute was asked for.
	Target store.Account
	// Live is who the credentials file attributed to under the lock, and
	// LiveKnown whether it attributed at all.
	//
	// LiveState is the same read without the collapse, and it is the one a
	// decision to WRITE has to consult: LiveKnown false spans both "nobody is
	// logged in" and "a login this store cannot name", which want opposite
	// answers.
	Live      store.Account
	LiveKnown bool
	LiveState LiveState
	// Before is who each login store held, and whom ccdad recorded, under the
	// lock before the write. Before.Split() on a Switched outcome means this
	// call repaired a split login as well as -- or instead of -- moving it, and
	// a caller says so.
	Before LoginView
	// RecordedNow is an AlreadyOn whose stores both held Target while ccdad's
	// record named someone else; the record now names Target.
	RecordedNow bool
	// Synced is a Switched outcome that was a sync (Request.Sync): no cooldown
	// was stamped and no prompt poll scheduled.
	Synced bool
	// IntentErr is a failure to write the switch's intent ahead of it (see
	// Execute). Reported rather than returned: the switch went ahead.
	IntentErr error
	// UnderLock says the outcome was decided under Claude Code's credential
	// locks, after the keychain was read -- a stand-down there cost a lock
	// hold and a keychain spawn, which a caller retrying it has to pace.
	UnderLock bool
	// CompletedPending is a write to the target of ccdad's own unconfirmed
	// switch: it is recorded as that switch, cooldown and departure, even when
	// the caller asked for a sync.
	CompletedPending bool
	// UnknownKeys are the unrecognized top-level keys the unknown-key probe
	// found, read from the file that was actually merged. Merge preserves them;
	// the operator still needs to know a new key exists.
	UnknownKeys []string
	// EnvTokenWins reports that SOMETHING outranks the credentials file on
	// Claude Code's OAuth axis, so the swap changed nothing about what a session
	// authenticates as. Attended, the swap still happened and this is the reason
	// it appears not to have.
	//
	// It was one variable once, and the name is kept because the outcome it
	// drives is. What it is NOT any more is a variable: DisplacedBy names the
	// source, and three of the sources it can name have no variable at all --
	// printing "unset CLAUDE_CODE_OAUTH_TOKEN" for those is the failure this
	// field's own consumers were widened to stop.
	EnvTokenWins bool
	// DisplacedBy is the source that outranks the file, valid when EnvTokenWins.
	// It is what every message about this state must be written from: it carries
	// its own wording and its own remedy, and they differ per source.
	DisplacedBy identity.OAuthSource
	// DisplacedUnresolved reports that ccdad DECLINED rather than named a
	// source -- the bg-auth snapshot, which is a credential ccdad refuses to
	// read and which Claude Code consumes before anything else. The swap is
	// stood down for it because "cannot tell" and "something wins" have the same
	// consequence for an unattended engine.
	DisplacedUnresolved bool
	// ClearedKey reports that ccdad's own stored primaryApiKey was removed from
	// Claude Code's config, and ClearedKeyOwner whose it was.
	ClearedKey      bool
	ClearedKeyOwner store.Account

	// FreshenErr is why the Stale outcome could not be repaired, when a
	// Freshen hook was wired and failed -- or store.ErrStoredLoginSpent, when
	// the target's stored login is one a newer login in the stores has
	// superseded and nothing would make it installable. Nil with a Stale
	// outcome means either no hook was wired or the refresh succeeded and still
	// came back inside Claude Code's refresh window.
	FreshenErr error

	// CooldownErr, KeyErr, and ProfileSyncErr are failures that happened AFTER
	// the credentials file was written. They are reported rather than
	// returned: the switch is on disk by then, and turning any of them into
	// Execute's error would report a completed swap as a failure.
	CooldownErr error
	KeyErr      error
	// PromptPollErr is a failure to bring the new live account's next poll
	// forward (SchedulePromptPoll). The account is then read on the schedule
	// it already had, which is how every switch behaved before this existed.
	PromptPollErr error
	// ProfileSyncErr is a failure to keep ~/.claude.json's oauthAccount
	// pointed at Target -- see SyncGlobalConfigIdentity. Left nil (and
	// SyncGlobalConfigIdentity never called) when EnvTokenWins: something
	// else is what a session actually authenticates as, and writing Target's
	// identity there would misdescribe it.
	ProfileSyncErr error

	// Claim is what the credential-home claim said at the moment of the write.
	//
	// Unattended, a StandDown here IS the Contended outcome and nothing was
	// written. Attended it is a warning and the swap happened anyway: a human
	// typed the command and is watching, and the useful thing to tell them is
	// that another store's engine is likely to switch it back — not to refuse.
	//
	// Its Notice is set when the claim could not be read definitively, which is
	// never a reason to stand down and always a reason to say something.
	Claim credhome.Verdict
}

Result is what happened, in facts rather than sentences. The caller owns the words: the CLI prints them, the daemon logs them, and neither has to parse the other's.

func Execute

func Execute(s *store.Store, req Request) (Result, error)

Execute performs the swap: the whole sequence, for both callers.

The order is the design, and two steps of it are ordering constraints rather than preferences:

  • The already-on answer and the LiveUUID precondition are decided INSIDE Claude Code's credential locks, against the file as it is at the moment of the write. Deciding them from a pre-lock read means deciding from a file that may have been replaced while this call waited for the lock.
  • SetActive comes after Activate has returned, never around it. store/lock.go names the store lock the OUTER one: a caller may take Claude Code's credential locks while holding it, and nothing may take the store lock while holding a credential lock. Two callers that pick opposite orders deadlock, and reproducing that needs a daemon and a CLI racing.

Nothing is recorded for a write that did not land. A compromised lock means Claude Code may have written after us, so SetActive would assert a login that is not there and the cooldown would hold the engine off its own retry.

type StoreHolder added in v0.29.1

type StoreHolder struct {
	Account store.Account
	State   LiveState
	// ID is the login's cclink.LoginIdentity, "" when the store holds none or
	// could not be read. Two stores with equal IDs hold the same login.
	ID string
	// Expires is the login's expiry, zero when it does not say. Every grant
	// lasts as long, so the later expiry is the login issued later.
	Expires time.Time
}

StoreHolder is what one login store holds.

type StoresAt added in v0.29.1

type StoresAt struct {
	HasItem bool
	ItemID  string
	FileID  string
}

StoresAt is what the two stores held when a decision was made, by login identity. A write that acts on a decision checks it again under Claude Code's locks and stands down if either store moved (Request.Expect).

Jump to

Keyboard shortcuts

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