alphai-tui 0.7.0

Terminal stock dashboard: live quotes and charts plus AI-scored financial news and SEC Form 4 insider activity from AlphaAI
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
use std::collections::BTreeMap;
use std::ops::RangeInclusive;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use clap::ValueEnum;
use serde::{Deserialize, Serialize};

use crate::app::{ChartStyle, NewsLayout, NewsScope, RANGE_PRESETS};
use crate::domain::{Interval, Range};
use crate::indicators;
use crate::theme::Theme;
use crate::ui;

/// Used when neither the CLI nor the config file provides symbols.
pub const DEFAULT_WATCHLIST: [&str; 4] = ["AAPL", "MSFT", "NVDA", "BTC-USD"];

/// One credential a price source (or the app itself) needs. `config_name`
/// is the field name inside `[keys]` in config.toml; existing names are
/// frozen, renaming one would orphan the key in users' files. The env var
/// wins over the file at resolution time.
pub struct KeyField {
    pub config_name: &'static str,
    pub env_var: &'static str,
    /// Row label in the settings screen.
    pub label: &'static str,
}

/// The AlphaAI news key: app-level rather than a price source, but it lives
/// in the same `[keys]` table and the same settings list.
pub const ALPHAI_KEY_FIELD: KeyField = KeyField {
    config_name: "alphai",
    env_var: "ALPHAI_API_KEY",
    label: "AlphaAI key",
};

/// Persisted app settings. Precedence at use time: CLI args > env vars
/// (for API keys) > this file > built-in defaults.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    pub source: Option<String>,
    pub watchlist: Vec<String>,
    pub every: Option<u64>,
    pub range: Option<String>,
    pub interval: Option<String>,
    /// Where Enter opens a news article: "alphai" (article page on
    /// alphai.io, the default) or "original" (the source site).
    pub news_open: Option<String>,
    /// API keys by `KeyField::config_name`. A map rather than a struct so a
    /// key this binary does not know (say, a config written by a newer
    /// version) survives a load -> save round trip instead of being dropped.
    pub keys: BTreeMap<String, String>,
    /// `[ui]` startup defaults (view, news layout and scope).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ui: Option<UiConfig>,
    /// `[chart]` startup defaults and indicator parameters.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub chart: Option<ChartConfig>,
    /// `[theme]` color overrides by slot name (see `theme::Theme`). Kept as
    /// raw strings: validation happens in `resolve`, per slot, so one typo
    /// never degrades the whole file.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub theme: Option<BTreeMap<String, String>>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct UiConfig {
    pub default_view: Option<String>,
    pub news_layout: Option<String>,
    pub news_scope: Option<String>,
    /// Raw i64 rather than u8: an out-of-range number must degrade to a
    /// warning in `resolve`, not fail deserializing the whole file.
    pub news_min_score: Option<i64>,
    pub insider_min_score: Option<i64>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ChartConfig {
    pub style: Option<String>,
    pub sma: Option<bool>,
    pub rsi: Option<bool>,
    pub sma_fast: Option<usize>,
    pub sma_slow: Option<usize>,
    pub rsi_period: Option<usize>,
    /// The t/T cycle, as pairs like `["1d", "5m"]`.
    pub presets: Option<Vec<Vec<String>>>,
}

/// Everything derived and validated from the raw config. Semantic problems
/// in these sections warn and fall back per entry; only a TOML syntax error
/// degrades the whole file (in `load_at`).
pub struct Resolved {
    pub theme: Theme,
    pub chart: ChartDefaults,
    pub ui: UiDefaults,
}

/// Validated `[chart]` values; `Default` is the traditional look. The
/// session keys (c, m, i, t) still toggle everything live, these only seed
/// the startup state and the indicator math.
#[derive(Clone, Debug, PartialEq)]
pub struct ChartDefaults {
    pub style: ChartStyle,
    pub sma: bool,
    pub rsi: bool,
    pub sma_fast: usize,
    pub sma_slow: usize,
    pub rsi_period: usize,
    pub presets: Vec<(Range, Interval)>,
}

impl Default for ChartDefaults {
    fn default() -> Self {
        Self {
            style: ChartStyle::Candles,
            sma: true,
            rsi: true,
            sma_fast: indicators::SMA_FAST,
            sma_slow: indicators::SMA_SLOW,
            rsi_period: indicators::RSI_PERIOD,
            presets: RANGE_PRESETS.to_vec(),
        }
    }
}

/// Startup default of the news score filter: relevance 7 and up (the API
/// itself defaults to 4; +/- adjust it live, `[ui] news_min_score` seeds it).
pub const DEFAULT_NEWS_MIN_SCORE: u8 = 7;

/// Startup default of the insider score filter. Insider rows are scored from
/// the event's dollar value, so this is a trade-size filter; 4 matches the
/// server default and keeps every filing the feed used to show.
pub const DEFAULT_INSIDER_MIN_SCORE: u8 = 4;

/// Validated `[ui]` startup values.
#[derive(Clone, Debug, PartialEq)]
pub struct UiDefaults {
    pub view_idx: usize,
    pub news_layout: NewsLayout,
    pub news_scope: NewsScope,
    pub news_min_score: u8,
    pub insider_min_score: u8,
}

impl Default for UiDefaults {
    fn default() -> Self {
        Self {
            view_idx: ui::view_index(ui::ViewId::Split),
            news_layout: NewsLayout::default(),
            news_scope: NewsScope::default(),
            news_min_score: DEFAULT_NEWS_MIN_SCORE,
            insider_min_score: DEFAULT_INSIDER_MIN_SCORE,
        }
    }
}

/// Validate the raw config into ready-to-use values plus human-readable
/// warnings (printed to stderr before the TUI starts).
pub fn resolve(cfg: &Config) -> (Resolved, Vec<String>) {
    let mut warnings = Vec::new();
    let theme = Theme::from_config(cfg.theme.as_ref(), &mut warnings);
    let chart = resolve_chart(cfg.chart.as_ref(), &mut warnings);
    let ui = resolve_ui(cfg.ui.as_ref(), &mut warnings);
    (Resolved { theme, chart, ui }, warnings)
}

fn resolve_chart(raw: Option<&ChartConfig>, warnings: &mut Vec<String>) -> ChartDefaults {
    let mut out = ChartDefaults::default();
    let Some(raw) = raw else { return out };
    if let Some(style) = &raw.style {
        match style.to_lowercase().as_str() {
            "candles" => out.style = ChartStyle::Candles,
            "line" => out.style = ChartStyle::Line,
            other => warnings.push(format!(
                "[chart] style: unknown \"{other}\" (candles or line), keeping candles"
            )),
        }
    }
    if let Some(v) = raw.sma {
        out.sma = v;
    }
    if let Some(v) = raw.rsi {
        out.rsi = v;
    }
    out.sma_fast = period(raw.sma_fast, out.sma_fast, "sma_fast", 2..=250, warnings);
    out.sma_slow = period(raw.sma_slow, out.sma_slow, "sma_slow", 2..=250, warnings);
    out.rsi_period = period(raw.rsi_period, out.rsi_period, "rsi_period", 2..=100, warnings);
    if let Some(rows) = &raw.presets {
        let mut presets = Vec::new();
        for row in rows {
            match parse_preset(row) {
                Some(p) => presets.push(p),
                None => warnings.push(format!(
                    "[chart] presets: bad pair {row:?}, expected like [\"1d\", \"5m\"]"
                )),
            }
        }
        if presets.is_empty() {
            warnings.push("[chart] presets: no valid pairs, keeping the built-in cycle".into());
        } else {
            out.presets = presets;
        }
    }
    out
}

fn period(
    raw: Option<usize>,
    default: usize,
    name: &str,
    valid: RangeInclusive<usize>,
    warnings: &mut Vec<String>,
) -> usize {
    match raw {
        Some(v) if valid.contains(&v) => v,
        Some(v) => {
            warnings.push(format!(
                "[chart] {name}: {v} is outside {}..={}, keeping {default}",
                valid.start(),
                valid.end()
            ));
            default
        }
        None => default,
    }
}

fn parse_preset(row: &[String]) -> Option<(Range, Interval)> {
    let [range, interval] = row else { return None };
    Some((
        Range::from_str(range, true).ok()?,
        Interval::from_str(interval, true).ok()?,
    ))
}

fn resolve_ui(raw: Option<&UiConfig>, warnings: &mut Vec<String>) -> UiDefaults {
    let mut out = UiDefaults::default();
    let Some(raw) = raw else { return out };
    if let Some(name) = &raw.default_view {
        // Matched by title, so the list stays correct as views register.
        match ui::VIEWS.iter().position(|v| v.title().eq_ignore_ascii_case(name)) {
            Some(idx) => out.view_idx = idx,
            None => {
                let names: Vec<String> =
                    ui::VIEWS.iter().map(|v| v.title().to_lowercase()).collect();
                warnings.push(format!(
                    "[ui] default_view: unknown \"{name}\" (one of {}), keeping split",
                    names.join(", ")
                ));
            }
        }
    }
    if let Some(layout) = &raw.news_layout {
        match layout.to_lowercase().as_str() {
            "side" => out.news_layout = NewsLayout::Side,
            "stacked" => out.news_layout = NewsLayout::Stacked,
            other => warnings.push(format!(
                "[ui] news_layout: unknown \"{other}\" (side or stacked), keeping side"
            )),
        }
    }
    if let Some(scope) = &raw.news_scope {
        match scope.to_lowercase().as_str() {
            "ticker" => out.news_scope = NewsScope::Ticker,
            "market" => out.news_scope = NewsScope::Market,
            "trending" => out.news_scope = NewsScope::Trending,
            other => warnings.push(format!(
                "[ui] news_scope: unknown \"{other}\" (ticker, market or trending), keeping ticker"
            )),
        }
    }
    out.news_min_score = min_score(raw.news_min_score, out.news_min_score, "news_min_score", warnings);
    out.insider_min_score = min_score(
        raw.insider_min_score,
        out.insider_min_score,
        "insider_min_score",
        warnings,
    );
    out
}

/// One `[ui] *_min_score` entry: 1..=10 or a warning plus the default.
fn min_score(raw: Option<i64>, default: u8, name: &str, warnings: &mut Vec<String>) -> u8 {
    match raw {
        Some(n) if (1..=10).contains(&n) => n as u8,
        Some(n) => {
            warnings.push(format!("[ui] {name}: {n} is outside 1..=10, keeping {default}"));
            default
        }
        None => default,
    }
}

impl Config {
    /// Resolved credential for one key field: the env var wins so a
    /// shell-exported key keeps working after a config file appears; blank
    /// values count as unset.
    pub fn key_value(&self, field: &KeyField) -> Option<String> {
        env_key(field.env_var).or_else(|| {
            self.keys
                .get(field.config_name)
                .map(|v| v.trim().to_string())
                .filter(|v| !v.is_empty())
        })
    }

    pub fn alphai_key(&self) -> Option<String> {
        self.key_value(&ALPHAI_KEY_FIELD)
    }

    /// True when Enter on a news article should open the original source
    /// instead of the alphai.io article page.
    pub fn news_open_original(&self) -> bool {
        self.news_open.as_deref() == Some("original")
    }
}

fn env_key(name: &str) -> Option<String> {
    std::env::var(name).ok().filter(|v| !v.trim().is_empty())
}

/// Unix (including macOS) follows the terminal-tool convention:
/// `$XDG_CONFIG_HOME` or `~/.config`. Windows uses the platform config dir.
pub fn path() -> Option<PathBuf> {
    let base = if cfg!(windows) {
        dirs::config_dir()?
    } else {
        std::env::var_os("XDG_CONFIG_HOME")
            .map(PathBuf::from)
            .filter(|p| p.is_absolute())
            .unwrap_or(dirs::home_dir()?.join(".config"))
    };
    Some(base.join("alphai-tui").join("config.toml"))
}

/// Load from an explicit path (the `--config` flag) or the default
/// location. Returns the config, whether a file existed, and the path Save
/// must write back to (None when the platform has no config dir). A missing
/// file is a normal first run; an unreadable one degrades to defaults with
/// a stderr warning rather than blocking startup.
pub fn load_at(override_path: Option<&Path>) -> (Config, bool, Option<PathBuf>) {
    let Some(p) = override_path.map(Path::to_path_buf).or_else(path) else {
        return (Config::default(), false, None);
    };
    match load_from(&p) {
        Ok(Some(cfg)) => (cfg, true, Some(p)),
        Ok(None) => (Config::default(), false, Some(p)),
        Err(e) => {
            eprintln!("warning: ignoring bad config at {}: {e:#}", p.display());
            (Config::default(), false, Some(p))
        }
    }
}

pub fn load_from(p: &Path) -> Result<Option<Config>> {
    if !p.exists() {
        return Ok(None);
    }
    let raw = std::fs::read_to_string(p).context("read failed")?;
    Ok(Some(toml::from_str(&raw).context("parse failed")?))
}

/// Save to the path `load_at` resolved (the settings screen passes it back).
pub fn save_at(path: Option<&Path>, cfg: &Config) -> Result<()> {
    let p = path.context("no config directory on this platform")?;
    save_to(p, cfg)
}

/// The file may hold API keys, so it is created user-only (0600) on unix.
pub fn save_to(p: &Path, cfg: &Config) -> Result<()> {
    if let Some(dir) = p.parent() {
        std::fs::create_dir_all(dir).context("create config dir failed")?;
    }
    let raw = toml::to_string_pretty(cfg).context("serialize failed")?;
    std::fs::write(p, raw).context("write failed")?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let _ = std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o600));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A key field whose env var can never be set, so tests exercise the
    /// file side of the resolution deterministically.
    const TEST_FIELD: KeyField = KeyField {
        config_name: "finnhub",
        env_var: "ALPHAI_TUI_TEST_NEVER_SET",
        label: "test",
    };

    #[test]
    fn round_trip() {
        let dir = std::env::temp_dir().join(format!("alphai-tui-test-{}", std::process::id()));
        let p = dir.join("config.toml");
        let cfg = Config {
            source: Some("finnhub".into()),
            watchlist: vec!["AAPL".into(), "BTC-USD".into()],
            every: Some(30),
            range: Some("5d".into()),
            interval: Some("15m".into()),
            news_open: Some("original".into()),
            keys: BTreeMap::from([
                ("finnhub".to_string(), "fh-key".to_string()),
                ("alphai".to_string(), "ak_live_x".to_string()),
                ("alpaca_key_id".to_string(), "PKTEST123".to_string()),
                ("alpaca_secret".to_string(), "alpaca-secret-x".to_string()),
            ]),
            ui: Some(UiConfig {
                default_view: Some("news".into()),
                news_layout: Some("stacked".into()),
                news_scope: None,
                news_min_score: Some(6),
                insider_min_score: Some(5),
            }),
            chart: Some(ChartConfig {
                style: Some("line".into()),
                sma_slow: Some(200),
                presets: Some(vec![vec!["1d".into(), "5m".into()]]),
                ..Default::default()
            }),
            theme: Some(BTreeMap::from([("accent".to_string(), "magenta".to_string())])),
        };
        save_to(&p, &cfg).unwrap();
        let loaded = load_from(&p).unwrap().unwrap();
        assert_eq!(loaded, cfg);
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn missing_file_is_none() {
        let p = Path::new("/nonexistent/alphai-tui/config.toml");
        assert!(load_from(p).unwrap().is_none());
    }

    #[test]
    fn partial_file_fills_defaults() {
        let cfg: Config = toml::from_str("source = \"yahoo\"").unwrap();
        assert_eq!(cfg.source.as_deref(), Some("yahoo"));
        assert!(cfg.watchlist.is_empty());
        assert!(cfg.keys.is_empty());
    }

    /// The exact `[keys]` shape written by pre-registry versions (and shown
    /// in the README) keeps parsing; those field names are frozen.
    #[test]
    fn old_keys_table_parses_verbatim() {
        let cfg: Config = toml::from_str(
            r#"
            source = "yahoo"
            [keys]
            alphai = "ak_live_x"
            finnhub = ""
            alpaca_key_id = "PK123"
            alpaca_secret = "sec"
            "#,
        )
        .unwrap();
        assert_eq!(cfg.keys.get("alphai").map(String::as_str), Some("ak_live_x"));
        assert_eq!(cfg.keys.get("alpaca_secret").map(String::as_str), Some("sec"));
        // A blank file value counts as unset at resolution time.
        assert_eq!(cfg.key_value(&TEST_FIELD), None);
    }

    #[test]
    fn key_value_reads_and_trims_file_values() {
        let cfg: Config = toml::from_str("[keys]\nfinnhub = \" fh-key \"").unwrap();
        assert_eq!(cfg.key_value(&TEST_FIELD).as_deref(), Some("fh-key"));
        assert_eq!(Config::default().key_value(&TEST_FIELD), None);
    }

    /// A `[keys]` entry this binary does not know must survive load -> save
    /// (a struct with named fields would silently drop it).
    #[test]
    fn unknown_key_survives_round_trip() {
        let cfg: Config = toml::from_str("[keys]\nnewsource = \"k\"").unwrap();
        let raw = toml::to_string_pretty(&cfg).unwrap();
        let again: Config = toml::from_str(&raw).unwrap();
        assert_eq!(again.keys.get("newsource").map(String::as_str), Some("k"));
    }

    /// Unknown sections and keys are tolerated on load: a typo never takes
    /// the whole file (and its API keys) down.
    #[test]
    fn unknown_sections_and_fields_are_tolerated() {
        let cfg: Config =
            toml::from_str("nonsense = 1\n[thme]\naccent = \"red\"").expect("must parse");
        assert_eq!(cfg, Config::default());
    }

    #[test]
    fn theme_section_resolves_and_stays_absent_by_default() {
        let cfg: Config = toml::from_str("[theme]\naccent = \"magenta\"").unwrap();
        let (resolved, warnings) = resolve(&cfg);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(resolved.theme.accent, ratatui::style::Color::Magenta);

        let (_, warnings) = resolve(&toml::from_str::<Config>("[theme]\nup = \"banana\"").unwrap());
        assert_eq!(warnings.len(), 1, "{warnings:?}");

        // Absent sections must not serialize: Save would spray empty tables
        // into every config otherwise.
        let bare = toml::to_string_pretty(&Config::default()).unwrap();
        for section in ["[theme]", "[ui]", "[chart]"] {
            assert!(!bare.contains(section), "{bare}");
        }
    }

    #[test]
    fn chart_section_validates_per_entry() {
        let cfg: Config = toml::from_str(
            r#"
            [chart]
            style = "line"
            sma_fast = 50
            sma_slow = 9000
            rsi_period = 21
            presets = [["1d", "5m"], ["nope", "5m"], ["1y"]]
            "#,
        )
        .unwrap();
        let (resolved, warnings) = resolve(&cfg);
        assert_eq!(resolved.chart.style, ChartStyle::Line);
        assert_eq!(resolved.chart.sma_fast, 50);
        // Out of range: warned, default kept.
        assert_eq!(resolved.chart.sma_slow, indicators::SMA_SLOW);
        assert_eq!(resolved.chart.rsi_period, 21);
        // One valid pair survives; the two bad ones warn.
        assert_eq!(resolved.chart.presets, vec![(Range::D1, Interval::M5)]);
        assert_eq!(warnings.len(), 3, "{warnings:?}");

        // All presets bad: fall back to the built-in cycle.
        let cfg: Config = toml::from_str("[chart]\npresets = [[\"x\", \"y\"]]").unwrap();
        let (resolved, warnings) = resolve(&cfg);
        assert_eq!(resolved.chart.presets, RANGE_PRESETS.to_vec());
        assert_eq!(warnings.len(), 2, "{warnings:?}");
    }

    #[test]
    fn ui_section_validates_per_entry() {
        let cfg: Config = toml::from_str(
            "[ui]\ndefault_view = \"News\"\nnews_layout = \"stacked\"\nnews_scope = \"market\"",
        )
        .unwrap();
        let (resolved, warnings) = resolve(&cfg);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(resolved.ui.view_idx, ui::view_index(ui::ViewId::News));
        assert_eq!(resolved.ui.news_layout, NewsLayout::Stacked);
        assert_eq!(resolved.ui.news_scope, NewsScope::Market);

        let cfg: Config = toml::from_str("[ui]\ndefault_view = \"nwes\"").unwrap();
        let (resolved, warnings) = resolve(&cfg);
        assert_eq!(resolved.ui.view_idx, ui::view_index(ui::ViewId::Split));
        assert_eq!(warnings.len(), 1, "{warnings:?}");
        assert!(warnings[0].contains("nwes"), "{warnings:?}");
    }

    #[test]
    fn news_min_score_validates_per_entry() {
        let cfg: Config =
            toml::from_str("[ui]\nnews_min_score = 4\ninsider_min_score = 8").unwrap();
        let (resolved, warnings) = resolve(&cfg);
        assert!(warnings.is_empty(), "{warnings:?}");
        assert_eq!(resolved.ui.news_min_score, 4);
        assert_eq!(resolved.ui.insider_min_score, 8);

        // Out of range warns and keeps the default; a number outside u8 must
        // not fail the whole file (the raw field is i64 for exactly that).
        for bad in ["0", "11", "300", "-2"] {
            let cfg: Config =
                toml::from_str(&format!("[ui]\nnews_min_score = {bad}")).expect("must parse");
            let (resolved, warnings) = resolve(&cfg);
            assert_eq!(resolved.ui.news_min_score, DEFAULT_NEWS_MIN_SCORE, "at {bad}");
            assert_eq!(warnings.len(), 1, "at {bad}: {warnings:?}");
        }

        let defaults = UiDefaults::default();
        assert_eq!(defaults.news_min_score, DEFAULT_NEWS_MIN_SCORE);
        assert_eq!(defaults.insider_min_score, DEFAULT_INSIDER_MIN_SCORE);
    }

    /// Every ```toml block in the README must parse as a Config and resolve
    /// without warnings, so the documentation cannot rot silently.
    #[test]
    fn readme_toml_examples_parse_and_resolve() {
        let readme = include_str!("../README.md");
        let mut in_block = false;
        let mut block = String::new();
        let mut checked = 0;
        for line in readme.lines() {
            if !in_block && line.trim_start().starts_with("```toml") {
                in_block = true;
                block.clear();
                continue;
            }
            if in_block && line.trim_start().starts_with("```") {
                in_block = false;
                let cfg: Config = toml::from_str(&block)
                    .unwrap_or_else(|e| panic!("README toml does not parse: {e}\n{block}"));
                let (_, warnings) = resolve(&cfg);
                assert!(warnings.is_empty(), "README example warns: {warnings:?}\n{block}");
                checked += 1;
                continue;
            }
            if in_block {
                block.push_str(line);
                block.push('\n');
            }
        }
        assert!(checked >= 2, "expected at least two toml blocks in the README");
    }
}