switcher

package
v0.18.0 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 15 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.

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.

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 RecordSwitch

func RecordSwitch(uuid string) 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.

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
}

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
	// 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
)

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.

func (LiveState) String added in v0.5.0

func (s LiveState) String() string

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 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
}

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
	// 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. 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
	// 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.

Jump to

Keyboard shortcuts

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