Skip to main content

costroid_config/
lib.rs

1//! The shared Costroid user-config crate: a non-secret TOML at
2//! `${XDG_CONFIG_HOME:-$HOME/.config}/costroid/config.toml`, hand-edited by the user and
3//! **read-only** here — Costroid never writes it (no writer, no `budget set` command). It is
4//! forward-compatible: every section/field defaults and unknown keys are ignored, so an older
5//! build reads a newer file (and vice-versa) without error.
6//!
7//! Both apps consume this one schema + loader: the `costroid` CLI/TUI (T14/T17) and the
8//! `costroid-bar` taskbar (Step 6, T20) — extracted out of `apps/cli/src/config.rs` so the bar
9//! gets the same `[budget]`/`[alerts]` parsing without depending on `apps/cli`. A pure leaf of the
10//! workspace: it depends only on `costroid-core` (for the config-neutral [`AlertThresholds`] /
11//! [`BudgetTargets`] input types) + `serde`/`toml`/`rust_decimal`; it links no network/keychain code.
12//!
13//! **Secrets never live here** — credentials are keychain-only (`costroid-connect`). Today the
14//! file carries `[budget]` targets (monthly $ caps, API-lane only; money is
15//! `rust_decimal::Decimal`, never f64), the `[alerts]` opt-in (T17, default off), and the
16//! `[breakeven]` what-if scenario defaults (M4, all optional; every numeric knob is exact
17//! `Decimal` — quote for guaranteed exactness).
18//!
19//! ```toml
20//! [budget]
21//! total_monthly_usd = 100.00
22//!
23//! [budget.per_tool]
24//! claude-code = 60.00
25//! codex = 40.00
26//!
27//! [alerts]
28//! enabled = true        # opt-in; default false (quiet) — the master switch
29//! # quota_warn = 0.80   # optional per-class overrides (default 0.80 / 0.95)
30//! # quota_critical = 0.95
31//! # forecast = true     # advisory (T17b): month-end projection over the TOTAL budget; default off
32//! # anomalies = true    # advisory (T17b): a daily spend spike vs your own norm; default off
33//!
34//! [breakeven]           # `costroid breakeven` what-if defaults (M4); CLI flags override these
35//! # depreciation_period_days = 1095     # the break-even amortization calendar (the basis, MED3)
36//! # output_share = 0.5                  # output-token share for the cloud-price blend (0..=1)
37//! # utilization = 1.0                   # duty cycle for the feasibility ceiling (0..=1)
38//! # electricity_rate_per_kwh = "0.16"   # quote for exactness (a bare 0.16 is not f64-exact)
39//! # hardware_price = "2000.00"          # the amortized capex
40//! # cloud_model = "claude-opus-4-8"     # the cloud model to compare against
41//! ```
42//!
43//! `forecast` and `anomalies` are opt-in advisory SUB-flags — each off by default and each still
44//! requiring `enabled = true`. They surface heads-up advisories (a projected total-budget overrun
45//! and a spend spike) in the same banner / `alerts` list as the hard quota and budget crossings.
46
47use std::collections::BTreeMap;
48use std::fmt;
49use std::path::{Path, PathBuf};
50use std::str::FromStr;
51
52use costroid_core::{AlertThresholds, BudgetTargets};
53use rust_decimal::Decimal;
54use serde::de::{self, Deserializer, Visitor};
55use serde::Deserialize;
56
57/// The parsed user config. Forward-compatible: every section defaults, so a missing or partial
58/// file is valid and unknown keys are silently ignored (serde's default behavior — no
59/// `deny_unknown_fields`).
60#[derive(Debug, Clone, Default, Deserialize)]
61#[serde(default)]
62pub struct Config {
63    budget: BudgetConfig,
64    alerts: AlertsConfig,
65    breakeven: BreakevenConfig,
66}
67
68/// The `[budget]` section: optional monthly $ caps. API-lane only — a flat-fee subscription is
69/// never given a $ target (the core [`budget_view`](costroid_core::budget_view) enforces this).
70#[derive(Debug, Clone, Default, Deserialize)]
71#[serde(default)]
72struct BudgetConfig {
73    /// An optional overall monthly cap across all API-lane spend.
74    total_monthly_usd: Option<Money>,
75    /// Per-tool monthly caps, keyed by the `x_Tool` id (`claude-code`/`codex`/`cursor`).
76    per_tool: BTreeMap<String, Money>,
77}
78
79/// The `[alerts]` section (T17): opt-in threshold alerts, OFF by default. `enabled` is the master
80/// switch for the whole feature — the inline `now` banner AND the `costroid alerts` /
81/// `alerts --check` command. The optional per-class quota overrides default to the core's
82/// canonical near-limit fractions (0.80 / 0.95) when unset. Budget alerts carry no threshold here:
83/// the crossing is the monthly $ target itself (an over-budget [`costroid_core::BudgetRow`]).
84/// Forward-compat: `#[serde(default)]`, so an absent section ⇒ off and a newer file is tolerated.
85#[derive(Debug, Clone, Default, Deserialize)]
86#[serde(default)]
87struct AlertsConfig {
88    /// Master switch. Default false — alerts are opt-in and quiet.
89    enabled: bool,
90    /// Optional WARN quota fraction override (default [`costroid_core::ALERT_WARN_FRACTION`]).
91    quota_warn: Option<f64>,
92    /// Optional CRITICAL quota fraction override (default
93    /// [`costroid_core::ALERT_CRITICAL_FRACTION`]).
94    quota_critical: Option<f64>,
95    /// Opt-in advisory source (T17b): a month-end TOTAL-budget projection over target. Default
96    /// false; the master `enabled` switch is still required for it to do anything.
97    forecast: bool,
98    /// Opt-in advisory source (T17b): a daily spend-spike anomaly vs your own norm. Default false;
99    /// the master `enabled` switch is still required.
100    anomalies: bool,
101}
102
103/// The `[breakeven]` section (M4 T6): defaults for the `costroid breakeven` what-if scenario, all
104/// optional and overridable by CLI flags. `#[serde(default)]` ⇒ an absent section is the
105/// zero-config default and a newer file is tolerated. Every numeric knob is the exact [`Money`]
106/// newtype (a `Decimal` accepting a TOML integer/float/quoted-string — quote for guaranteed
107/// exactness, e.g. `"0.16"`). The break-even amortization basis is `depreciation_period_days`;
108/// `hardware_lifetime_seconds` is carried ONLY to reject its misuse as the break-even basis (MED3).
109#[derive(Debug, Clone, Default, Deserialize)]
110#[serde(default)]
111struct BreakevenConfig {
112    /// The workload's daily token volume (context vs. the crossover).
113    tokens_per_day: Option<Money>,
114    /// The output-token share for the cloud blend (0..=1).
115    output_share: Option<Money>,
116    /// The utilization fraction for the feasibility ceiling (0..=1).
117    utilization: Option<Money>,
118    /// The break-even depreciation period, in DAYS (the calendar amortization basis, MED3).
119    depreciation_period_days: Option<Money>,
120    /// The per-run `x_AmortizedHwCost` lifetime — NOT the break-even basis. Present only so the
121    /// projection can reject it being used as one (MED3); use `depreciation_period_days` instead.
122    hardware_lifetime_seconds: Option<Money>,
123    /// Override the electricity rate (per kWh).
124    electricity_rate_per_kwh: Option<Money>,
125    /// Override the hardware purchase price (the amortized capex).
126    hardware_price: Option<Money>,
127    /// The cloud model id to compare against (a pricing-catalog model).
128    cloud_model: Option<String>,
129}
130
131impl Config {
132    /// Project the parsed config into the core's config-neutral budget input.
133    pub fn budget_targets(&self) -> BudgetTargets {
134        BudgetTargets {
135            total_monthly_usd: self.budget.total_monthly_usd.map(|money| money.0),
136            per_tool: self
137                .budget
138                .per_tool
139                .iter()
140                .map(|(tool, money)| (tool.clone(), money.0))
141                .collect(),
142        }
143    }
144
145    /// Whether the alerts feature is enabled (default false — opt-in). The master switch — it also
146    /// gates the two advisory sub-flags below.
147    pub fn alerts_enabled(&self) -> bool {
148        self.alerts.enabled
149    }
150
151    /// Whether the advisory forecast-projection source is on (T17b). Requires BOTH the master
152    /// `enabled` switch and the `forecast` sub-flag — the sub-flag alone does nothing.
153    pub fn alerts_forecast_enabled(&self) -> bool {
154        self.alerts.enabled && self.alerts.forecast
155    }
156
157    /// Whether the advisory spend-spike source is on (T17b). Requires BOTH the master `enabled`
158    /// switch and the `anomalies` sub-flag.
159    pub fn alerts_anomalies_enabled(&self) -> bool {
160        self.alerts.enabled && self.alerts.anomalies
161    }
162
163    /// Project the `[alerts]` overrides into the core's config-neutral [`AlertThresholds`]. An
164    /// override is applied only when finite and strictly positive (a `NaN`/`inf`/zero/negative
165    /// value falls back to the canonical default), so the pure detector never sees a threshold it
166    /// can't reason about.
167    pub fn alert_thresholds(&self) -> AlertThresholds {
168        let mut thresholds = AlertThresholds::default();
169        if let Some(warn) = sane_fraction(self.alerts.quota_warn) {
170            thresholds.quota_warn_fraction = warn;
171        }
172        if let Some(critical) = sane_fraction(self.alerts.quota_critical) {
173            thresholds.quota_critical_fraction = critical;
174        }
175        // Cross-field sanity: a self-contradictory pair (warn > critical) would make CRITICAL fire
176        // below the user's intended WARN floor and leave WARN unreachable. Reject the whole pair back
177        // to the canonical defaults — mirroring sane_fraction's per-field discipline, so the detector
178        // never sees an inverted pair it can't reason about.
179        if thresholds.quota_warn_fraction > thresholds.quota_critical_fraction {
180            thresholds = AlertThresholds::default();
181        }
182        thresholds
183    }
184
185    /// Project the `[breakeven]` section into the core's config-neutral [`BreakevenScenario`] (M4
186    /// T6). Enforces the one-lifetime rule (MED3): `depreciation_period_days` is the break-even
187    /// basis; `hardware_lifetime_seconds` is the per-run `x_AmortizedHwCost` attribution only —
188    /// supplying it (especially alongside `depreciation_period_days`) is a typed error, not a
189    /// silent fallback. Physical knobs convert via `from_f64_retain` (a non-finite value drops to
190    /// `None`); money via the exact [`Money`] newtype.
191    pub fn breakeven_scenario(&self) -> Result<costroid_core::BreakevenScenario, ConfigError> {
192        let breakeven = &self.breakeven;
193        // NB: this hand-writes the MED3 four-arm match rather than reusing
194        // `costroid_core::resolve_depreciation_days` ON PURPOSE — the core helper treats
195        // `(None, None)` as an error ("break-even needs a calendar"), but the config projection
196        // must treat it as `None` (zero-config; the CLI fills it from a flag/default). The two
197        // `(None, None)` semantics genuinely differ, so reuse would break the zero-config arm.
198        let depreciation_period_days = match (
199            breakeven.depreciation_period_days,
200            breakeven.hardware_lifetime_seconds,
201        ) {
202            (Some(_), Some(_)) => {
203                return Err(ConfigError::Breakeven {
204                    detail: "[breakeven] sets both `depreciation_period_days` and \
205                             `hardware_lifetime_seconds`; the former is the break-even basis, the \
206                             latter is the per-run x_AmortizedHwCost attribution only — set just \
207                             `depreciation_period_days`"
208                        .to_string(),
209                });
210            }
211            (None, Some(_)) => {
212                return Err(ConfigError::Breakeven {
213                    detail: "[breakeven] sets `hardware_lifetime_seconds`, which is the per-run \
214                             x_AmortizedHwCost attribution, not the break-even basis — use \
215                             `depreciation_period_days`"
216                        .to_string(),
217                });
218            }
219            (Some(days), None) => Some(days.0),
220            (None, None) => None,
221        };
222        Ok(costroid_core::BreakevenScenario {
223            tokens_per_day: breakeven.tokens_per_day.map(|money| money.0),
224            output_share: breakeven.output_share.map(|money| money.0),
225            utilization: breakeven.utilization.map(|money| money.0),
226            depreciation_period_days,
227            electricity_rate_per_kwh: breakeven.electricity_rate_per_kwh.map(|money| money.0),
228            hardware_price: breakeven.hardware_price.map(|money| money.0),
229            cloud_model: breakeven.cloud_model.clone(),
230        })
231    }
232}
233
234/// Accept a user-supplied fraction override only when finite and strictly positive; anything else
235/// (`NaN`/`inf`/zero/negative) falls back to the canonical default. A value above `1.0` is left
236/// as-is — a legitimate way to silence a class (the threshold can never be reached).
237fn sane_fraction(value: Option<f64>) -> Option<f64> {
238    value.filter(|fraction| fraction.is_finite() && *fraction > 0.0)
239}
240
241/// A monthly $ amount parsed from TOML into an exact [`Decimal`]. Accepts a TOML integer
242/// (`60`), a float (`60.00`), or a quoted string (`"60.00"`). Integers and quoted strings are
243/// exact; a *bare float* transits f64 (TOML has no decimal type) and is converted best-effort —
244/// quote the value for guaranteed exactness. The internal money type is always `Decimal`,
245/// never f64.
246#[derive(Debug, Clone, Copy)]
247struct Money(Decimal);
248
249impl<'de> Deserialize<'de> for Money {
250    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
251        struct MoneyVisitor;
252
253        impl Visitor<'_> for MoneyVisitor {
254            type Value = Money;
255
256            fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
257                formatter.write_str("a dollar amount (a number or a quoted decimal string)")
258            }
259
260            fn visit_i64<E: de::Error>(self, value: i64) -> Result<Money, E> {
261                Ok(Money(Decimal::from(value)))
262            }
263
264            fn visit_u64<E: de::Error>(self, value: u64) -> Result<Money, E> {
265                Ok(Money(Decimal::from(value)))
266            }
267
268            fn visit_f64<E: de::Error>(self, value: f64) -> Result<Money, E> {
269                Decimal::from_f64_retain(value)
270                    .map(Money)
271                    .ok_or_else(|| de::Error::custom("dollar amount must be a finite number"))
272            }
273
274            fn visit_str<E: de::Error>(self, value: &str) -> Result<Money, E> {
275                Decimal::from_str(value.trim()).map(Money).map_err(|err| {
276                    de::Error::custom(format!("invalid dollar amount '{value}': {err}"))
277                })
278            }
279        }
280
281        // TOML is self-describing, so `deserialize_any` dispatches on the actual scalar
282        // (integer / float / string) to the matching visitor method above.
283        deserializer.deserialize_any(MoneyVisitor)
284    }
285}
286
287/// Resolve the config-file path `${XDG_CONFIG_HOME:-$HOME/.config}/costroid/config.toml`.
288/// `None` when neither `$XDG_CONFIG_HOME` nor `$HOME` yields a base directory (treated as "no
289/// config" — the zero-config default, never an error). Mirrors `costroid-connect`'s
290/// `default_registry_path`, but rooted at the *config* dir (this file is non-secret).
291pub fn config_path() -> Option<PathBuf> {
292    let base = std::env::var_os("XDG_CONFIG_HOME")
293        .map(PathBuf::from)
294        .filter(|path| !path.as_os_str().is_empty())
295        .or_else(|| std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config")))?;
296    Some(base.join("costroid").join("config.toml"))
297}
298
299/// A config-load failure. A *missing* file is NOT one of these — it yields the zero-config
300/// default. These are surfaced as a TUI/taskbar status line (never a crash).
301#[derive(Debug)]
302pub enum ConfigError {
303    /// The file exists but could not be read.
304    Read {
305        path: PathBuf,
306        source: std::io::Error,
307    },
308    /// The file exists but is not valid TOML / carries an invalid value.
309    Parse {
310        path: PathBuf,
311        source: toml::de::Error,
312    },
313    /// A semantically-invalid `[breakeven]` scenario in an otherwise-valid file (e.g. two
314    /// break-even lifetimes — MED3). Surfaced by the [`Config::breakeven_scenario`] projection.
315    Breakeven { detail: String },
316}
317
318impl fmt::Display for ConfigError {
319    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
320        match self {
321            ConfigError::Read { path, source } => {
322                write!(
323                    formatter,
324                    "could not read config {}: {source}",
325                    path.display()
326                )
327            }
328            ConfigError::Parse { path, source } => {
329                // TOML errors are multi-line; collapse to the first line for the status bar.
330                let detail = source.to_string();
331                let first = detail.lines().next().unwrap_or(&detail);
332                write!(formatter, "invalid config {}: {first}", path.display())
333            }
334            ConfigError::Breakeven { detail } => {
335                write!(formatter, "invalid [breakeven] config: {detail}")
336            }
337        }
338    }
339}
340
341impl std::error::Error for ConfigError {}
342
343/// Load the user config from the resolved default path. A missing file (or an unresolved path)
344/// yields the zero-config default (no budgets) — only a present-but-malformed file is an error.
345pub fn load() -> Result<Config, ConfigError> {
346    match config_path() {
347        Some(path) => load_from(&path),
348        None => Ok(Config::default()),
349    }
350}
351
352/// Load the config from an explicit path — the testable seam (no env access). A missing file =>
353/// default; an unreadable file or invalid TOML => a typed [`ConfigError`].
354pub fn load_from(path: &Path) -> Result<Config, ConfigError> {
355    let text = match std::fs::read_to_string(path) {
356        Ok(text) => text,
357        Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Config::default()),
358        Err(source) => {
359            return Err(ConfigError::Read {
360                path: path.to_path_buf(),
361                source,
362            })
363        }
364    };
365    toml::from_str::<Config>(&text).map_err(|source| ConfigError::Parse {
366        path: path.to_path_buf(),
367        source,
368    })
369}
370
371#[cfg(test)]
372mod tests {
373    use super::*;
374
375    /// A unique, auto-cleaned temp directory (no `tempfile` dep — mirrors `costroid-connect`'s
376    /// test temp helper). Tests write fixture config files here, never to the user's real config.
377    struct TempDir {
378        path: PathBuf,
379    }
380
381    impl TempDir {
382        fn new() -> Self {
383            use std::sync::atomic::{AtomicU32, Ordering};
384            static COUNTER: AtomicU32 = AtomicU32::new(0);
385            let n = COUNTER.fetch_add(1, Ordering::Relaxed);
386            let pid = std::process::id();
387            let path = std::env::temp_dir().join(format!("costroid-config-test-{pid}-{n}"));
388            if let Err(err) = std::fs::create_dir_all(&path) {
389                panic!("temp dir should create: {err}");
390            }
391            Self { path }
392        }
393
394        fn write(&self, contents: &str) -> PathBuf {
395            let file = self.path.join("config.toml");
396            if let Err(err) = std::fs::write(&file, contents) {
397                panic!("fixture config should write: {err}");
398            }
399            file
400        }
401    }
402
403    impl Drop for TempDir {
404        fn drop(&mut self) {
405            let _ = std::fs::remove_dir_all(&self.path);
406        }
407    }
408
409    fn cents(value: i64, scale: u32) -> Decimal {
410        Decimal::new(value, scale)
411    }
412
413    #[test]
414    fn absent_file_loads_the_zero_config_default() {
415        let dir = TempDir::new();
416        let missing = dir.path.join("does-not-exist.toml");
417        let config = match load_from(&missing) {
418            Ok(config) => config,
419            Err(err) => panic!("absent file should default, not error: {err}"),
420        };
421        assert!(config.budget_targets().is_empty());
422    }
423
424    fn scenario_of(contents: &str) -> Result<costroid_core::BreakevenScenario, ConfigError> {
425        let dir = TempDir::new();
426        let path = dir.write(contents);
427        match load_from(&path) {
428            Ok(config) => config.breakeven_scenario(),
429            Err(err) => panic!("the fixture should load: {err}"),
430        }
431    }
432
433    #[test]
434    fn breakeven_section_loads_into_the_scenario() {
435        // Integers, floats, and a quoted-decimal money value all parse to exact `Decimal`.
436        let scenario = match scenario_of(
437            r#"
438[breakeven]
439tokens_per_day = 500000
440output_share = 0.25
441utilization = 0.5
442depreciation_period_days = 1000
443electricity_rate_per_kwh = "0.16"
444hardware_price = "2000.00"
445cloud_model = "claude-opus-4-8"
446"#,
447        ) {
448            Ok(scenario) => scenario,
449            Err(err) => panic!("a valid [breakeven] should project: {err}"),
450        };
451        assert_eq!(scenario.tokens_per_day, Some(cents(500_000, 0)));
452        assert_eq!(scenario.output_share, Some(cents(25, 2)));
453        assert_eq!(scenario.utilization, Some(cents(5, 1)));
454        assert_eq!(scenario.depreciation_period_days, Some(cents(1000, 0)));
455        // Quoted "0.16" is EXACT (an f64 0.16 would not be) — the reason money knobs use Money.
456        assert_eq!(scenario.electricity_rate_per_kwh, Some(cents(16, 2)));
457        assert_eq!(scenario.hardware_price, Some(cents(2000, 0)));
458        assert_eq!(scenario.cloud_model.as_deref(), Some("claude-opus-4-8"));
459    }
460
461    #[test]
462    fn absent_breakeven_section_is_the_zero_config_default() {
463        let scenario = match scenario_of("[budget]\ntotal_monthly_usd = 60\n") {
464            Ok(scenario) => scenario,
465            Err(err) => panic!("absent [breakeven] should default: {err}"),
466        };
467        assert_eq!(scenario, costroid_core::BreakevenScenario::default());
468        assert!(scenario.depreciation_period_days.is_none());
469    }
470
471    #[test]
472    fn unknown_breakeven_key_is_ignored_forward_compat() {
473        let scenario =
474            match scenario_of("[breakeven]\ndepreciation_period_days = 1000\nfuture_knob = 42\n") {
475                Ok(scenario) => scenario,
476                Err(err) => panic!("an unknown key must be ignored, not error: {err}"),
477            };
478        assert_eq!(scenario.depreciation_period_days, Some(cents(1000, 0)));
479    }
480
481    #[test]
482    fn med3_both_lifetimes_set_is_a_typed_error() {
483        // depreciation_period_days (break-even basis) + hardware_lifetime_seconds (per-run only).
484        let result = scenario_of(
485            "[breakeven]\ndepreciation_period_days = 1000\nhardware_lifetime_seconds = 94608000\n",
486        );
487        assert!(matches!(result, Err(ConfigError::Breakeven { .. })));
488    }
489
490    #[test]
491    fn med3_hardware_lifetime_alone_is_not_the_breakeven_basis() {
492        let result = scenario_of("[breakeven]\nhardware_lifetime_seconds = 94608000\n");
493        assert!(matches!(result, Err(ConfigError::Breakeven { .. })));
494    }
495
496    #[test]
497    fn present_file_parses_total_and_per_tool_targets() {
498        let dir = TempDir::new();
499        let path = dir.write(
500            "[budget]\n\
501             total_monthly_usd = 100.00\n\n\
502             [budget.per_tool]\n\
503             claude-code = 60.00\n\
504             codex = 40\n",
505        );
506        let config = match load_from(&path) {
507            Ok(config) => config,
508            Err(err) => panic!("valid config should parse: {err}"),
509        };
510        let targets = config.budget_targets();
511        assert!(!targets.is_empty());
512        assert_eq!(targets.total_monthly_usd, Some(cents(10_000, 2)));
513        assert_eq!(targets.per_tool.get("claude-code"), Some(&cents(6_000, 2)));
514        // A bare TOML integer (`40`) parses to an exact Decimal too.
515        assert_eq!(targets.per_tool.get("codex"), Some(&cents(40, 0)));
516    }
517
518    #[test]
519    fn quoted_string_money_is_exact() {
520        let dir = TempDir::new();
521        let path = dir.write("[budget]\ntotal_monthly_usd = \"99.99\"\n");
522        let config = match load_from(&path) {
523            Ok(config) => config,
524            Err(err) => panic!("quoted money should parse: {err}"),
525        };
526        assert_eq!(
527            config.budget_targets().total_monthly_usd,
528            Some(cents(9_999, 2))
529        );
530    }
531
532    #[test]
533    fn malformed_file_is_a_typed_error_not_a_panic() {
534        let dir = TempDir::new();
535        // Not valid TOML (unterminated table header).
536        let path = dir.write("[budget\ntotal_monthly_usd = 100\n");
537        match load_from(&path) {
538            Ok(config) => panic!("malformed config should error, got {config:?}"),
539            Err(err @ ConfigError::Parse { .. }) => {
540                // The Display is a single, status-bar-friendly line.
541                let message = err.to_string();
542                assert!(message.contains("invalid config"), "message: {message}");
543                assert!(
544                    !message.contains('\n'),
545                    "status must be one line: {message}"
546                );
547            }
548            Err(other) => panic!("expected a Parse error, got {other}"),
549        }
550    }
551
552    #[test]
553    fn invalid_money_value_is_a_typed_error() {
554        let dir = TempDir::new();
555        let path = dir.write("[budget]\ntotal_monthly_usd = \"not-a-number\"\n");
556        match load_from(&path) {
557            Ok(config) => panic!("invalid money should error, got {config:?}"),
558            Err(ConfigError::Parse { .. }) => {}
559            Err(other) => panic!("expected a Parse error, got {other}"),
560        }
561    }
562
563    #[test]
564    fn unknown_keys_are_ignored_for_forward_compatibility() {
565        let dir = TempDir::new();
566        let path = dir.write(
567            "schema_version = 99\n\
568             [budget]\n\
569             total_monthly_usd = 50\n\
570             future_field = true\n\n\
571             [alerts]\n\
572             enabled = true\n",
573        );
574        let config = match load_from(&path) {
575            Ok(config) => config,
576            Err(err) => panic!("unknown keys should be ignored, not error: {err}"),
577        };
578        assert_eq!(
579            config.budget_targets().total_monthly_usd,
580            Some(cents(50, 0))
581        );
582    }
583
584    #[test]
585    fn empty_file_is_the_zero_config_default() {
586        let dir = TempDir::new();
587        let path = dir.write("");
588        let config = match load_from(&path) {
589            Ok(config) => config,
590            Err(err) => panic!("empty file should default: {err}"),
591        };
592        assert!(config.budget_targets().is_empty());
593    }
594
595    // ----- [alerts] (T17) -----
596
597    #[test]
598    fn alerts_default_off_with_canonical_thresholds() {
599        // No file, and a budget-only file, both yield alerts OFF + the canonical default thresholds.
600        let dir = TempDir::new();
601        for contents in ["", "[budget]\ntotal_monthly_usd = 100\n"] {
602            let path = dir.write(contents);
603            let config = match load_from(&path) {
604                Ok(config) => config,
605                Err(err) => panic!("should default: {err}"),
606            };
607            assert!(
608                !config.alerts_enabled(),
609                "alerts must default OFF: {contents:?}"
610            );
611            let thresholds = config.alert_thresholds();
612            assert_eq!(
613                thresholds.quota_warn_fraction,
614                costroid_core::ALERT_WARN_FRACTION
615            );
616            assert_eq!(
617                thresholds.quota_critical_fraction,
618                costroid_core::ALERT_CRITICAL_FRACTION
619            );
620        }
621    }
622
623    #[test]
624    fn alerts_enabled_parses_and_keeps_default_thresholds() {
625        let dir = TempDir::new();
626        let path = dir.write("[alerts]\nenabled = true\n");
627        let config = match load_from(&path) {
628            Ok(config) => config,
629            Err(err) => panic!("alerts config should parse: {err}"),
630        };
631        assert!(config.alerts_enabled());
632        let thresholds = config.alert_thresholds();
633        assert_eq!(
634            thresholds.quota_warn_fraction,
635            costroid_core::ALERT_WARN_FRACTION
636        );
637        assert_eq!(
638            thresholds.quota_critical_fraction,
639            costroid_core::ALERT_CRITICAL_FRACTION
640        );
641    }
642
643    #[test]
644    fn alerts_threshold_overrides_apply() {
645        let dir = TempDir::new();
646        let path = dir.write("[alerts]\nenabled = true\nquota_warn = 0.5\nquota_critical = 0.9\n");
647        let config = match load_from(&path) {
648            Ok(config) => config,
649            Err(err) => panic!("alert overrides should parse: {err}"),
650        };
651        let thresholds = config.alert_thresholds();
652        assert_eq!(thresholds.quota_warn_fraction, 0.5);
653        assert_eq!(thresholds.quota_critical_fraction, 0.9);
654    }
655
656    #[test]
657    fn alerts_hostile_threshold_overrides_fall_back_to_defaults() {
658        // Zero / negative are not sane fractions → the canonical default stands (never breaks the
659        // detector). A present-but-odd value is not a parse error.
660        let dir = TempDir::new();
661        let path = dir.write("[alerts]\nquota_warn = 0.0\nquota_critical = -0.5\n");
662        let config = match load_from(&path) {
663            Ok(config) => config,
664            Err(err) => panic!("odd-but-valid values should parse: {err}"),
665        };
666        let thresholds = config.alert_thresholds();
667        assert_eq!(
668            thresholds.quota_warn_fraction,
669            costroid_core::ALERT_WARN_FRACTION
670        );
671        assert_eq!(
672            thresholds.quota_critical_fraction,
673            costroid_core::ALERT_CRITICAL_FRACTION
674        );
675    }
676
677    #[test]
678    fn alerts_inverted_threshold_pair_falls_back_to_defaults() {
679        // warn > critical is self-contradictory (CRITICAL would fire below the WARN floor and WARN
680        // would be dead) — the whole pair falls back to the canonical defaults, never a nonsense pair.
681        let dir = TempDir::new();
682        let path = dir.write("[alerts]\nenabled = true\nquota_warn = 0.9\nquota_critical = 0.5\n");
683        let config = match load_from(&path) {
684            Ok(config) => config,
685            Err(err) => panic!("inverted-but-valid values should parse: {err}"),
686        };
687        let thresholds = config.alert_thresholds();
688        assert_eq!(
689            thresholds.quota_warn_fraction,
690            costroid_core::ALERT_WARN_FRACTION
691        );
692        assert_eq!(
693            thresholds.quota_critical_fraction,
694            costroid_core::ALERT_CRITICAL_FRACTION
695        );
696        // A single low-critical override that inverts against the DEFAULT warn also falls back.
697        let path2 = dir.write("[alerts]\nenabled = true\nquota_critical = 0.5\n");
698        let config2 = match load_from(&path2) {
699            Ok(config) => config,
700            Err(err) => panic!("should parse: {err}"),
701        };
702        let t2 = config2.alert_thresholds();
703        assert_eq!(t2.quota_warn_fraction, costroid_core::ALERT_WARN_FRACTION);
704        assert_eq!(
705            t2.quota_critical_fraction,
706            costroid_core::ALERT_CRITICAL_FRACTION
707        );
708    }
709
710    #[test]
711    fn malformed_alerts_value_is_a_typed_error_not_a_panic() {
712        // `enabled` must be a bool — a string is a typed Parse error (the non-crash contract),
713        // never a panic.
714        let dir = TempDir::new();
715        let path = dir.write("[alerts]\nenabled = \"yes\"\n");
716        match load_from(&path) {
717            Ok(config) => panic!("malformed alerts should error, got {config:?}"),
718            Err(ConfigError::Parse { .. }) => {}
719            Err(other) => panic!("expected a Parse error, got {other}"),
720        }
721    }
722
723    // ----- advisory sub-flags (T17b) -----
724
725    #[test]
726    fn advisory_subflags_default_off() {
727        // Absent section, and an enabled-but-no-subflags section, both leave BOTH advisory sources off.
728        let dir = TempDir::new();
729        for contents in ["", "[alerts]\nenabled = true\n"] {
730            let path = dir.write(contents);
731            let config = match load_from(&path) {
732                Ok(config) => config,
733                Err(err) => panic!("should default: {err}"),
734            };
735            assert!(
736                !config.alerts_forecast_enabled(),
737                "forecast must default OFF: {contents:?}"
738            );
739            assert!(
740                !config.alerts_anomalies_enabled(),
741                "anomalies must default OFF: {contents:?}"
742            );
743        }
744    }
745
746    #[test]
747    fn advisory_subflags_parse_on_when_master_enabled() {
748        let dir = TempDir::new();
749        let path = dir.write("[alerts]\nenabled = true\nforecast = true\nanomalies = true\n");
750        let config = match load_from(&path) {
751            Ok(config) => config,
752            Err(err) => panic!("advisory sub-flags should parse: {err}"),
753        };
754        assert!(config.alerts_forecast_enabled());
755        assert!(config.alerts_anomalies_enabled());
756    }
757
758    #[test]
759    fn advisory_subflags_require_the_master_switch() {
760        // A sub-flag set WITHOUT the master `enabled` does nothing — `enabled` is still required.
761        let dir = TempDir::new();
762        let path = dir.write("[alerts]\nforecast = true\nanomalies = true\n");
763        let config = match load_from(&path) {
764            Ok(config) => config,
765            Err(err) => panic!("should parse: {err}"),
766        };
767        assert!(!config.alerts_enabled());
768        assert!(
769            !config.alerts_forecast_enabled(),
770            "forecast must stay off without the master switch"
771        );
772        assert!(
773            !config.alerts_anomalies_enabled(),
774            "anomalies must stay off without the master switch"
775        );
776    }
777
778    #[test]
779    fn advisory_subflags_are_independent() {
780        // Each sub-flag is independent — enabling one does not enable the other.
781        let dir = TempDir::new();
782        let path = dir.write("[alerts]\nenabled = true\nforecast = true\n");
783        let config = match load_from(&path) {
784            Ok(config) => config,
785            Err(err) => panic!("should parse: {err}"),
786        };
787        assert!(config.alerts_forecast_enabled());
788        assert!(!config.alerts_anomalies_enabled());
789    }
790}