1use 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#[derive(Debug, Clone, Default, Deserialize)]
61#[serde(default)]
62pub struct Config {
63 budget: BudgetConfig,
64 alerts: AlertsConfig,
65 breakeven: BreakevenConfig,
66}
67
68#[derive(Debug, Clone, Default, Deserialize)]
71#[serde(default)]
72struct BudgetConfig {
73 total_monthly_usd: Option<Money>,
75 per_tool: BTreeMap<String, Money>,
77}
78
79#[derive(Debug, Clone, Default, Deserialize)]
86#[serde(default)]
87struct AlertsConfig {
88 enabled: bool,
90 quota_warn: Option<f64>,
92 quota_critical: Option<f64>,
95 forecast: bool,
98 anomalies: bool,
101}
102
103#[derive(Debug, Clone, Default, Deserialize)]
110#[serde(default)]
111struct BreakevenConfig {
112 tokens_per_day: Option<Money>,
114 output_share: Option<Money>,
116 utilization: Option<Money>,
118 depreciation_period_days: Option<Money>,
120 hardware_lifetime_seconds: Option<Money>,
123 electricity_rate_per_kwh: Option<Money>,
125 hardware_price: Option<Money>,
127 cloud_model: Option<String>,
129}
130
131impl Config {
132 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 pub fn alerts_enabled(&self) -> bool {
148 self.alerts.enabled
149 }
150
151 pub fn alerts_forecast_enabled(&self) -> bool {
154 self.alerts.enabled && self.alerts.forecast
155 }
156
157 pub fn alerts_anomalies_enabled(&self) -> bool {
160 self.alerts.enabled && self.alerts.anomalies
161 }
162
163 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 if thresholds.quota_warn_fraction > thresholds.quota_critical_fraction {
180 thresholds = AlertThresholds::default();
181 }
182 thresholds
183 }
184
185 pub fn breakeven_scenario(&self) -> Result<costroid_core::BreakevenScenario, ConfigError> {
192 let breakeven = &self.breakeven;
193 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
234fn sane_fraction(value: Option<f64>) -> Option<f64> {
238 value.filter(|fraction| fraction.is_finite() && *fraction > 0.0)
239}
240
241#[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 deserializer.deserialize_any(MoneyVisitor)
284 }
285}
286
287pub 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#[derive(Debug)]
302pub enum ConfigError {
303 Read {
305 path: PathBuf,
306 source: std::io::Error,
307 },
308 Parse {
310 path: PathBuf,
311 source: toml::de::Error,
312 },
313 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 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
343pub fn load() -> Result<Config, ConfigError> {
346 match config_path() {
347 Some(path) => load_from(&path),
348 None => Ok(Config::default()),
349 }
350}
351
352pub 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 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 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 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 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(¢s(6_000, 2)));
514 assert_eq!(targets.per_tool.get("codex"), Some(¢s(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 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 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 #[test]
598 fn alerts_default_off_with_canonical_thresholds() {
599 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 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 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 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 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 #[test]
726 fn advisory_subflags_default_off() {
727 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 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 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}