Documentation
¶
Overview ¶
Package config is ~/.ccdad/config.toml: the auto-switch engine's knobs, their defaults, and the re-read the daemon's tick loop performs every second.
KEY STYLE, and this is a compatibility commitment rather than a preference. Every key here is SNAKE_CASE, which is the style accounts.toml already uses (`active_uuid`): `hysteresis_pct` and `max_auto_spend`, never a camelCase spelling of either. `credit` is the one key group that keeps its own table, so the ceiling is `credit.max_auto_spend`.
`ccdad config get|set|list` names these keys and prints these spellings, so changing one later breaks scripts. Add keys; do not rename them.
There is deliberately no `version` key. accounts.toml carries one because ccdad writes it and would have to migrate it; this file is written by hand as often as by `ccdad config set`, and a version a reader never checks is a promise nothing keeps. Unknown keys round-trip and are ignored, which is what makes adding one later — `version` included — a widening rather than a break.
Index ¶
- Constants
- Variables
- func HoverOverrides(key string) bool
- func Keys() []string
- func Path() (string, error)
- func UnknownKeys(raw []byte) ([]string, error)
- func WithDocument(fn func(*Document) error) (err error)
- type Config
- type Document
- func (d *Document) Config() (Config, error)
- func (d *Document) Encode() ([]byte, error)
- func (d *Document) Keys() []string
- func (d *Document) OptedInWindows() []string
- func (d *Document) Set(key, value string) error
- func (d *Document) UnknownKeys() []string
- func (d *Document) Unset(key string) (bool, error)
- func (d *Document) Value(key string) (string, bool, error)
- type Reloader
Constants ¶
const FileName = "config.toml"
FileName is the config file's basename inside the ccdad store.
const KeyHover = keyHover
KeyHover is the config key `ccdad hover` writes. It is the one key a command outside this package names directly, so it is exported rather than spelled as a literal there: a second copy of the name is exactly the drift keys.go exists to prevent.
const KeyMCPSwitchWithoutElicitation = keyMCPSwitchWithoutElicitation
KeyMCPSwitchWithoutElicitation is the second key a package outside this one names directly. internal/mcpsrv prints it in the refusal a model reads when nobody can be asked to confirm a switch, and a name spelled twice is exactly the drift keys.go exists to prevent -- here it would print a key that `ccdad config set` then refuses.
Variables ¶
var ErrUnknownKey = errors.New("unknown config key")
ErrUnknownKey is a key this release does not have. It is a sentinel because the CLI maps it to exit 2 — a typo is a usage error — while a bad VALUE for a real key is a different sentence with the same exit code, and `ccdad doctor` may one day want to tell them apart.
var LockTimeout = 5 * time.Second
LockTimeout bounds how long `ccdad config set` waits for the lock. It is a var so a test can shrink it and reach the timeout path without an unbounded contention test.
Functions ¶
func HoverOverrides ¶ added in v0.3.0
HoverOverrides reports whether hover derives this key's value for itself, which is to say whether the value in the file has stopped being read.
Every key under the window-threshold section answers true, listed or not: a well-formed window name this build does not know still round-trips through the file, and the annotation has to be right for it whenever a caller asks.
func Keys ¶
func Keys() []string
Keys lists every settable key this release knows by name, in file order, which is also the order `ccdad config list` prints them in. A CLI builds its help and its error messages from this, so a key added here cannot be forgotten in either. The top-level keys come first and the two tables that can name their keys in advance follow, so the listing groups each sub-table the way a hand-written file does. [tui] is last because it is the group that governs nothing the daemon does: a reader scanning the listing for the engine's settings reaches the end of them before the display ones start.
It is not the whole settable surface. window_threshold takes one key per rate-limit window and a scoped window is named after a model or a surface the server invented, so that half cannot be listed in advance. Document.Keys is the listing that adds the ones a file actually names.
func UnknownKeys ¶
UnknownKeys lists the keys in a document that this ccdad does not know, in dotted form and in sorted order.
They are NOT an error. A config written by a newer ccdad has to leave an older one running — the same rule the credentials swap follows — so the loader ignores them and this reports them, which is how `ccdad config list` can say "these are being ignored" instead of the file silently doing less than it looks like it does. It is also the only warning a hand-edited typo ever gets, since a typo is indistinguishable from a future key.
func WithDocument ¶
WithDocument runs fn against the document under a cross-process lock and writes back what it changed.
The read happens INSIDE the lock, which is the half an atomic rename cannot provide: two `ccdad config set` calls that each read the file, change one key and write it back would otherwise lose one of the two keys, because the second rename replaces a document the first one's reader never saw.
fn returning an error leaves the file exactly as it was.
Types ¶
type Config ¶
type Config struct {
// Threshold is the utilization percent above which an account counts as
// spent, for any window with no threshold of its own.
Threshold float64
// HysteresisPct is the additive anti-flap margin, in points of headroom.
HysteresisPct float64
// HeadroomRatio is the multiplicative anti-flap margin on the same axis.
HeadroomRatio float64
// Cooldown is the anti-flap minimum gap between two switches.
Cooldown time.Duration
// RecoveryHysteresis is the anti-flap margin on the recovery axis.
RecoveryHysteresis time.Duration
// Strategy is which question the ranking asks.
Strategy strategy.Strategy
// MaxAutoSpend is the credit gate's ceiling, in the currency's major unit.
// 0 refuses, and is the default.
MaxAutoSpend float64
// WindowThreshold is a threshold per window, overriding Threshold for the
// windows named in it. Nil is every window using Threshold.
//
// Nothing mutates it after Parse builds it, which is what makes handing the
// same map to the ranking safe where a Config crosses goroutines — the
// daemon copies the struct under a mutex, and copying a struct copies the
// map header, not the map.
WindowThreshold map[usage.WindowName]float64
// CreditThreshold is the utilization percent above which a credit-metered
// account counts as spent. It is a second number rather than Threshold
// because the two are different axes: credits are metered spending and a
// subscription window is metered quota, so a user who tightens one has said
// nothing about the other.
CreditThreshold float64
// PreemptLead is how far ahead of a projected exhaustion the engine
// switches, on top of the blind interval between two polls. 0 is the
// pre-emptive switch off, which is a value a user may choose.
PreemptLead time.Duration
// ProbeUnknown is whether the daemon may spend one turn against a window
// that has never been used, to get the reset time such a window reports as
// null.
ProbeUnknown bool
// Hover is the fully automatic mode: thresholds derived from pace, and
// every tuning key ignored.
Hover bool
// MCPSwitchWithoutElicitation allows ccdad's MCP server to rewrite the live
// login on a client that cannot ask the person at the keyboard first.
//
// It is the only field here the engine never reads, and the reason it lives
// in this file rather than in an option the caller passes is the threat it
// answers: a model reaches that server through tool arguments and through
// nothing else, so a permission that can only be granted by editing this
// file -- or by an environment variable on the server's own process -- is
// one the model cannot grant itself in the call it is making.
//
// It defaults to false, which refuses.
MCPSwitchWithoutElicitation bool
// TUITheme is which palette ccdad's own screens paint with, held as a
// STRING rather than as the palette package's own type.
//
// The string is the deliberate half. A typed field would make this package
// the one that decides what a theme IS, and it is not: resolving `auto`
// needs the terminal's background, which the daemon that loads this file has
// never looked at and must not look at -- it has no terminal, and a daemon
// that queried one would be answering a question about a screen nobody is
// watching. So the file's answer travels as the word the user wrote, and the
// command that owns a terminal turns it into a palette. What this package
// owes is that the word is one the palette layer will accept, which is what
// validTheme checks at the moment the word arrives.
TUITheme string
// TUIGlyphs is which glyph set those screens draw with: auto, unicode or
// ascii. It is a string for the reason above and for one more: `auto`
// resolves against the console's code page and against an environment
// variable read once at process start, and the daemon has neither.
TUIGlyphs string
}
Config is the effective configuration: what the file says, over the defaults.
No field is a pointer, and that is the property being kept: absence is resolved during parsing and never leaves this package, so no consumer has to ask whether a field was set. WindowThreshold is a map and keeps the same promise — a nil map is not "unset", it is every window using Threshold, which is the answer a missing key gives too, so nothing downstream needs a nil check.
Being comparable with == was a CONSEQUENCE of having no pointers rather than the goal, and the map ends it. Compare two configs with Equal.
func Defaults ¶
func Defaults() Config
The defaults are the ENGINE's own defaults, never a second copy of them.
strategy.Config's zero value is already the full anti-flap default set and strategy.Options defaults its threshold the same way, so a number written again here could drift from the one the engine falls back to — and then omitting a key from config.toml would change behaviour by omitting it, which is the one thing a defaults table must never do.
MaxAutoSpend is the exception in the other direction: 0 is an ANSWER rather than an omission. The credit gate requires two independent opt-ins for unattended spending and this is one of them, so the default refuses.
PreemptLead is an answer in the same shape and the reason its number is config's own: 0 there means the pre-emptive switch is off, which is a choice a user may make — it is an opt-out, not an anti-flap mechanism that must never be switched off — so the engine must not re-default it, and something has to say 2m. This is that something.
ProbeUnknown and Hover are answers too. ProbeUnknown is ON because a window that has never been used reports a null reset, which leaves the account invisible to the ranking, and the only way to obtain a reading is to spend against the window — one turn, which is why it is a key at all rather than unconditional. Hover is OFF because it overrides every number the user tuned, and a mode that ignores the config file has to be asked for.
TUITheme and TUIGlyphs are answers in a third shape. Their real default is a MEASUREMENT of the terminal that will draw the screen -- how dark its background is, what its console code page says it can carry -- and this function has no terminal. `auto` is the word that says "measure it", so it is the honest default rather than a placeholder standing in for one. Naming a palette here would be one machine's answer written down for every machine.
WindowThreshold is deliberately absent. Nil IS the default — every window using Threshold — and an empty map here would allocate one per call to say the same thing.
func Load ¶
Load reads the config from disk. A machine with no config file gets the full default set and no error — that is the ordinary state, not a degradation.
A file that exists and cannot be read IS an error. Reporting the defaults for it would run the engine on numbers the user does not believe are in force, and a permission problem on a file they wrote is exactly the case where they would never think to look.
func Parse ¶
Parse turns a config document into the effective configuration.
It is the whole loader minus the filesystem, which is what lets every trap the credit gate sets be pinned by a test that writes no file. A document that fails validation yields the ZERO Config alongside its error and never a partly applied one: half a config file is not a configuration, and the caller that falls back to the defaults has to be sure it is falling back to all of them.
func (Config) Effective ¶ added in v0.3.0
Effective is the configuration the engine actually runs on.
It is the parsed file everywhere except under hover, where one key changes: probe_unknown is forced on. Hover derives every threshold from how far through its own window each account is, and a window that has never been spent against reports no reset -- so it has no share elapsed, falls back to a fixed 80, and stays there. Only a turn spent against that window puts a reset on it, so probe_unknown off under hover is the one state hover cannot climb out of by itself.
It is deliberately NOT applied by Parse or by Document.Config. `ccdad config list` reads those, and a listing that printed `probe_unknown true` beside the word `file` for a file that says `false` would be a falsehood in the column whose whole job is provenance. The listing marks the key overridden instead, and this is where the override actually happens.
func (Config) Equal ¶ added in v0.3.0
Equal is == for a Config, which the map field ended.
The map compares by CONTENT, and a nil map equals an empty one: both say "every window uses Threshold", so reporting them as different configurations would have the daemon announce a config change nobody made.
Every field is listed. TestEqualComparesEveryFieldOfConfig walks the struct by reflection and fails on a field this method forgot, because the symptom of a forgotten one is silent: a config change the reload path decides is not a change.
func (Config) RankOptions ¶
RankOptions is the ranking half, for a pass evaluated at now.
Horizon is deliberately left at its zero value: no configuration key names the horizon, so strategy.DefaultRecoveryHorizon stays the single place it is decided. PreemptLead is the opposite case and is always carried: the engine reads a zero as the pre-emptive switch OFF, so a lead left behind here would silently disable a mechanism the user configured.
WindowThreshold is handed over rather than copied, for the reason Thresholds gives: the ranking only reads it and nothing mutates it after Parse.
Hover is carried through rather than resolved here. The mode's effect depends on the POOL -- how many accounts have a reading, and how far through its own window each one is -- and this package has neither. All that travels is the bit; the engine derives everything from it.
func (Config) StrategyConfig ¶
StrategyConfig is the anti-flap half, in the shape strategy.Decide takes.
func (Config) Thresholds ¶ added in v0.3.0
func (c Config) Thresholds() strategy.Thresholds
Thresholds is every threshold one ranking pass may consult, in one value.
It is the accessor every consumer outside this package uses, and the three fields are not read individually: a caller that took Threshold on its own would be asking the old single-threshold question and would quietly disagree with the engine the moment a user wrote one per-window key.
The map is handed over rather than copied. The engine only reads it, nothing mutates it after Parse built it, and a copy would allocate on every cadence for a table that changes only when the file does.
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
Document is config.toml as it is written.
func LoadDocument ¶
LoadDocument reads the document from disk, or an empty one when there is no file yet. It takes no lock: every write is an atomic rename, so a reader sees one whole version of the document or another.
func ParseDocument ¶
ParseDocument reads a document without touching the filesystem.
func (*Document) Keys ¶ added in v0.3.0
Keys is every key `ccdad config list` prints for THIS document: the ones Keys() names, and the window thresholds the document itself carries.
The second half cannot come from a list. A scoped window is named after a model or a surface the server invented, so the set of legal names is open and only the file knows which of them are in use. A document that names no window therefore adds no row at all rather than a placeholder row for a key nothing has set — which would be a row `ccdad config unset` could not remove.
A name in the table that is not a window is left out here and named in a notice instead. For most of them that notice is UnknownKeys', the answer an unknown top-level key already gets: it round-trips, it is ignored, and it is named once. A scoped name under a key this build does not know is the exception and gets its own, because that one IS read — see OptedInWindows. That omission is load-bearing rather than tidy — `ccdad config list` calls Config.Value on every key it is handed and returns the error, so offering one would turn a forward-compatible file into a failed command.
func (*Document) OptedInWindows ¶ added in v0.3.0
OptedInWindows lists the window_threshold keys this release cannot validate and reads anyway, in dotted sorted form.
They are the exception to everything UnknownKeys says. A weekly cap filed under a scope key this build does not name is carried but left OUT of the ranking, because ccdad cannot state what such a cap covers; a threshold naming that window is the opt-in, and the only one, since `ccdad config set` refuses a scope it cannot verify. So the key is unknown to the config surface and live to the engine at the same time, and reporting it as ignored tells a user who just typed it that it does nothing.
func (*Document) Set ¶
Set validates a value the way the loader would and stores it.
Validation happens HERE and not only at read time, because the alternative is a `config set` that succeeds and a daemon that then refuses the whole file: the user would have written a value nothing rejected and switched nothing off but the engine.
func (*Document) UnknownKeys ¶
UnknownKeys lists the keys this release does not know AND does not read, in dotted sorted form. Its whole use is a notice telling a reader those keys are being ignored, so a key that is in fact read may not appear here — see OptedInWindows for the one kind that is.
func (*Document) Unset ¶
Unset removes the key and reports whether it was there. It is not an error for it to be absent — that is exit 3, the world already being as the caller asked.
type Reloader ¶
type Reloader struct {
// contains filtered or unexported fields
}
Reloader is the tick loop's "pick up external config changes", with the property the cadence alone does not give and the daemon depends on: a broken edit must not stop the engine.
Reload always reports what it found, and always hands back a USABLE config — the last one that parsed, or the defaults if none ever did. A daemon that exits on a bad hand-edit is a daemon that stops switching accounts silently, which is worse than running on a config that is one edit out of date.
A Reloader is not safe for concurrent use: it is the tick loop's, and the tick loop is one goroutine.
func NewReloader ¶
func NewReloader() *Reloader
NewReloader starts on the defaults, having read nothing.