oomtop-config 0.2.0

oomtop configuration: layered config, themes, keymaps, JSON Schema, comment-preserving writes
Documentation
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
//! Layered config (UX §12.1.3), later wins:
//! `built-in defaults → /etc/oomtop/ → ~/.config/oomtop/config.toml → config.d/*.toml (alphabetical) →
//! config.d/host-<hostname>.toml → OOMTOP_* env vars → CLI flags → runtime toggles`.
//!
//! Every leaf value records its [`Origin`] (file:line for files). A layer that fails to parse or validate is
//! reported with file:line and a fix hint, and **its last good version stays in effect** (when one is known
//! from an earlier load through the same [`LayerCache`], i.e. during live reload); otherwise the layer is
//! skipped. Env vars and flags are applied one by one, so one bad variable does not discard the others.

use crate::model::Config;
use crate::paths::{short_hostname, system_dir, toml_files, ConfigPaths};
use crate::ConfigError;
use std::collections::{BTreeMap, HashMap};
use std::path::{Path, PathBuf};
use toml::{Table, Value};

/// Where an effective value came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Origin {
    Default,
    File { path: PathBuf, line: Option<usize> },
    Env(String),
    Flag,
    Runtime,
}

impl std::fmt::Display for Origin {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Origin::Default => write!(f, "default"),
            Origin::File { path, line } => {
                // user files by name (`config.toml:12`, `host-air.toml:3`, UX §12.8); the system layer by its
                // full path so `/etc/oomtop/config.toml` is never mistaken for the user's `config.toml`
                let name = if path.starts_with(system_dir()) {
                    path.display().to_string()
                } else {
                    path.file_name()
                        .map(|n| n.to_string_lossy().into_owned())
                        .unwrap_or_default()
                };
                match line {
                    Some(l) => write!(f, "{name}:{l}"),
                    None => write!(f, "{name}"),
                }
            }
            Origin::Env(k) => write!(f, "env {k}"),
            Origin::Flag => write!(f, "flag"),
            Origin::Runtime => write!(f, "runtime"),
        }
    }
}

impl Origin {
    /// Short label for the settings screen: `default`, `config.toml:12`, `host-air.toml:3`, `env`, `flag`,
    /// `runtime` (UX §12.8).
    pub fn short(&self) -> String {
        match self {
            Origin::Env(_) => "env".into(),
            o => o.to_string(),
        }
    }
}

/// Inputs to [`load_layered`]. `Default` = the real user environment.
#[derive(Debug, Clone, Default)]
pub struct LoadOptions {
    /// `--config` / `OOMTOP_CONFIG`: replaces `config.toml` (drop-ins still apply from its directory).
    pub config_path: Option<PathBuf>,
    /// Override the user config dir (tests); default `paths::config_dir()`.
    pub config_dir: Option<PathBuf>,
    /// Override `/etc/oomtop` (tests). `Some(empty path)` disables the system layer.
    pub system_dir: Option<PathBuf>,
    pub hostname: Option<String>,
    /// Environment pairs; `None` = read `OOMTOP_*` from the process environment.
    pub env: Option<Vec<(String, String)>>,
    /// CLI flag overrides as (dotted key, TOML value literal or bare string).
    pub flags: Vec<(String, String)>,
}

impl LoadOptions {
    /// The user config directory these options resolve to.
    pub fn user_dir(&self) -> PathBuf {
        self.explicit_config()
            .and_then(|p| p.parent())
            // a bare relative `--config my.toml` lives in the current directory
            .map(|d| {
                if d.as_os_str().is_empty() {
                    PathBuf::from(".")
                } else {
                    d.to_path_buf()
                }
            })
            .or_else(|| self.config_dir.clone())
            .unwrap_or_else(crate::paths::config_dir)
    }

    /// The explicitly named config file (`--config` / `OOMTOP_CONFIG`); an empty value counts as unset.
    pub fn explicit_config(&self) -> Option<&Path> {
        self.config_path.as_deref().filter(|p| !p.as_os_str().is_empty())
    }

    /// Paths of the user config directory.
    pub fn paths(&self) -> ConfigPaths {
        ConfigPaths::new(&self.user_dir())
    }

    /// The main config file (`--config` or `config.toml`).
    pub fn main_file(&self) -> PathBuf {
        self.explicit_config()
            .map(Path::to_path_buf)
            .unwrap_or_else(|| self.paths().config_toml)
    }

    pub fn hostname(&self) -> String {
        self.hostname.clone().unwrap_or_else(short_hostname)
    }

    /// The system layer directory, if enabled.
    pub fn system(&self) -> Option<PathBuf> {
        let sys = self.system_dir.clone().unwrap_or_else(system_dir);
        (!sys.as_os_str().is_empty()).then_some(sys)
    }

    /// Every config file in precedence order (existing or not): system (`config.toml`, drop-ins, its host
    /// file), then user (main file, drop-ins, host file). `host-*.toml` drop-ins are per-machine in **both**
    /// directories: only `host-<this hostname>.toml` applies, last within its directory.
    pub fn layer_files(&self) -> Vec<PathBuf> {
        let host = self.hostname();
        let mut v = Vec::new();
        if let Some(sys) = self.system() {
            v.push(sys.join("config.toml"));
            let sys_paths = ConfigPaths::new(&sys);
            v.extend(
                toml_files(&sys_paths.config_d)
                    .into_iter()
                    .filter(|p| !is_host_file(p)),
            );
            v.push(sys_paths.host_file(&host));
        }
        v.push(self.main_file());
        let paths = self.paths();
        v.extend(
            toml_files(&paths.config_d)
                .into_iter()
                .filter(|p| !is_host_file(p)),
        );
        v.push(paths.host_file(&host));
        v
    }

    /// `config.d/host-*.toml` files (system and user) that are **not** applied because they are for another
    /// host name. Normal in dotfiles shared between machines, but also what a mistyped host name or a
    /// drop-in that merely starts with `host-` looks like — so frontends show them as a note.
    pub fn skipped_host_files(&self) -> Vec<PathBuf> {
        let host = self.hostname();
        let mut dirs = Vec::new();
        if let Some(sys) = self.system() {
            dirs.push(ConfigPaths::new(&sys));
        }
        dirs.push(self.paths());
        let mut out = Vec::new();
        for d in dirs {
            let mine = d.host_file(&host);
            out.extend(
                toml_files(&d.config_d)
                    .into_iter()
                    .filter(|p| is_host_file(p) && *p != mine),
            );
        }
        out
    }
}

fn is_host_file(p: &Path) -> bool {
    p.file_name()
        .is_some_and(|n| n.to_string_lossy().starts_with("host-"))
}

/// Last good version of each config file, so an invalid edit keeps the previous values (UX §11 test 9).
#[derive(Debug, Clone, Default)]
pub struct LayerCache {
    files: HashMap<PathBuf, (String, Table)>,
}

impl LayerCache {
    pub fn new() -> Self {
        Self::default()
    }
    pub fn len(&self) -> usize {
        self.files.len()
    }
    pub fn is_empty(&self) -> bool {
        self.files.is_empty()
    }
}

/// Result of loading.
#[derive(Debug, Clone)]
pub struct Loaded {
    pub config: Config,
    /// Dotted leaf key → origin.
    pub origins: BTreeMap<String, Origin>,
    /// Files that were read (in precedence order).
    pub files: Vec<PathBuf>,
    /// Problems found (the offending layer was skipped or kept at its last good version).
    pub errors: Vec<ConfigError>,
    /// Informational lines that are not errors (e.g. a `host-*.toml` drop-in for another host name), for
    /// `oomtop config validate` and `config print --origin`.
    pub notes: Vec<String>,
    merged: Table,
    /// Dotted key → sequence number of the layer that set it last (later = higher precedence).
    order: BTreeMap<String, usize>,
    /// Dotted key → every non-default layer that set it, in precedence order.
    set_by: BTreeMap<String, Vec<Origin>>,
}

/// One effective setting (for `oomtop config print --effective --origin` and the settings screen).
#[derive(Debug, Clone, PartialEq)]
pub struct EffectiveEntry {
    pub key: String,
    pub value: String,
    pub origin: Origin,
}

/// Flattens a table into dotted leaf keys. Empty tables are leaves.
pub fn leaves(t: &Table) -> Vec<(String, Value)> {
    fn walk(prefix: &str, v: &Value, out: &mut Vec<(String, Value)>) {
        match v {
            Value::Table(t) if !t.is_empty() => {
                for (k, v) in t {
                    let key = if prefix.is_empty() {
                        k.clone()
                    } else {
                        format!("{prefix}.{k}")
                    };
                    walk(&key, v, out);
                }
            }
            _ => out.push((prefix.to_string(), v.clone())),
        }
    }
    let mut out = Vec::new();
    for (k, v) in t {
        walk(k, v, &mut out);
    }
    out
}

pub(crate) fn set_path(t: &mut Table, key: &str, v: Value) {
    let parts: Vec<&str> = key.split('.').collect();
    let mut cur = t;
    for p in &parts[..parts.len() - 1] {
        let entry = cur
            .entry(p.to_string())
            .or_insert_with(|| Value::Table(Table::new()));
        if !entry.is_table() {
            *entry = Value::Table(Table::new());
        }
        let Value::Table(next) = entry else { return };
        cur = next;
    }
    cur.insert(parts[parts.len() - 1].to_string(), v);
}

/// Merges `src` over `dst`. Tables merge key by key, so an empty table in a later layer (e.g. an
/// uncommented `[appearance]` header with nothing under it) changes nothing instead of resetting the section.
pub(crate) fn deep_merge(dst: &mut Table, src: &Table) {
    for (k, v) in src {
        match (dst.get_mut(k), v) {
            (Some(Value::Table(d)), Value::Table(s)) => deep_merge(d, s),
            _ => {
                dst.insert(k.clone(), v.clone());
            }
        }
    }
}

/// 1-based line of a byte offset.
pub fn line_of(text: &str, offset: usize) -> usize {
    let end = offset.min(text.len());
    text.as_bytes()[..end].iter().filter(|b| **b == b'\n').count() + 1
}

/// Every dotted key of a TOML document (tables, arrays of tables and leaves) → 1-based line of its key.
pub fn key_lines(text: &str) -> BTreeMap<String, usize> {
    use toml_edit::{Item, TableLike};
    fn walk(t: &dyn TableLike, prefix: &str, text: &str, out: &mut BTreeMap<String, usize>) {
        for (k, item) in t.iter() {
            let key = if prefix.is_empty() {
                k.to_string()
            } else {
                format!("{prefix}.{k}")
            };
            let span = t
                .get_key_value(k)
                .and_then(|(key, _)| key.span())
                .or_else(|| item.span());
            if let Some(s) = span {
                out.entry(key.clone()).or_insert_with(|| line_of(text, s.start));
            }
            match item {
                Item::Table(sub) => {
                    if let Some(s) = sub.span() {
                        out.entry(key.clone()).or_insert_with(|| line_of(text, s.start));
                    }
                    walk(sub, &key, text, out);
                }
                Item::ArrayOfTables(a) => {
                    for (i, sub) in a.iter().enumerate() {
                        if let Some(s) = sub.span() {
                            let l = line_of(text, s.start);
                            out.entry(key.clone()).or_insert(l);
                            out.entry(format!("{key}.{i}")).or_insert(l);
                        }
                        walk(sub, &format!("{key}.{i}"), text, out);
                    }
                }
                Item::Value(toml_edit::Value::InlineTable(it)) => walk(it, &key, text, out),
                _ => {}
            }
        }
    }
    let mut out = BTreeMap::new();
    if let Ok(doc) = toml_edit::Document::parse(text) {
        walk(doc.as_table(), "", text, &mut out);
    }
    out
}

/// Best-effort 1-based line of a dotted key in TOML text (the key itself, else its nearest parent).
pub fn find_line(text: &str, key: &str) -> Option<usize> {
    let lines = key_lines(text);
    let mut k = key.to_string();
    loop {
        if let Some(l) = lines.get(&k) {
            return Some(*l);
        }
        match k.rsplit_once('.') {
            Some((parent, _)) => k = parent.to_string(),
            None => return None,
        }
    }
}

fn levenshtein(a: &str, b: &str) -> usize {
    let b: Vec<char> = b.chars().collect();
    let mut prev: Vec<usize> = (0..=b.len()).collect();
    for (i, ca) in a.chars().enumerate() {
        let mut cur = vec![i + 1; b.len() + 1];
        for (j, cb) in b.iter().enumerate() {
            cur[j + 1] = (prev[j] + usize::from(ca != *cb))
                .min(prev[j + 1] + 1)
                .min(cur[j] + 1);
        }
        prev = cur;
    }
    prev[b.len()]
}

/// Closest candidate within edit distance 2 (or a shared prefix of ≥ 3 chars).
pub fn closest<'a>(word: &str, candidates: impl IntoIterator<Item = &'a str>) -> Option<&'a str> {
    candidates
        .into_iter()
        .map(|c| (levenshtein(word, c), c))
        .filter(|(d, c)| *d <= 2 || (word.len() >= 3 && c.starts_with(word)))
        .min_by_key(|(d, _)| *d)
        .map(|(_, c)| c)
}

/// A fix hint for a serde/toml message ("unknown field `thme`, expected one of `theme`, …").
pub fn hint_for(message: &str) -> Option<String> {
    let bad = message.split('`').nth(1)?;
    let (_, expected) = message.split_once("expected")?;
    let options: Vec<&str> = expected.split('`').skip(1).step_by(2).collect();
    closest(bad, options.iter().copied()).map(|c| format!("did you mean `{c}`?"))
}

fn with_hint(message: &str) -> String {
    let m = message.trim().to_string();
    match hint_for(&m) {
        Some(h) => format!("{m} — {h}"),
        None => m,
    }
}

fn toml_error(path: &Path, text: &str, e: &toml::de::Error) -> ConfigError {
    ConfigError {
        path: Some(path.to_path_buf()),
        line: e.span().map(|s| line_of(text, s.start)),
        message: with_hint(e.message()),
    }
}

/// Parses a flag/env value: TOML literal if it parses, else a bare string.
pub fn parse_value(s: &str) -> Value {
    match toml::from_str::<Table>(&format!("v = {s}")) {
        Ok(mut t) => t.remove("v").unwrap_or_else(|| Value::String(s.to_string())),
        Err(_) => Value::String(s.to_string()),
    }
}

/// Parses and validates one layer's text (syntax, types and the [`crate::semantic`] rules). `Err` carries
/// file:line; when several rules are broken this is the first one ([`parse_layer_all`] returns them all).
pub fn parse_layer(path: &Path, text: &str) -> Result<Table, ConfigError> {
    parse_layer_all(path, text).map_err(|mut es| es.swap_remove(0))
}

/// [`parse_layer`] reporting every broken semantic rule (never an empty `Err`).
pub fn parse_layer_all(path: &Path, text: &str) -> Result<Table, Vec<ConfigError>> {
    let table: Table = toml::from_str(text).map_err(|e| vec![toml_error(path, text, &e)])?;
    // Deserializing the text directly keeps spans, so type errors point at the offending line.
    let cfg = toml::from_str::<Config>(text).map_err(|e| vec![toml_error(path, text, &e)])?;
    // Only what this layer sets is this layer's business: the rest are (valid) defaults.
    let set_here: Vec<String> = leaves(&table).into_iter().map(|(k, _)| k).collect();
    let problems: Vec<crate::semantic::Problem> = crate::semantic::problems(&cfg)
        .into_iter()
        .filter(|p| {
            set_here
                .iter()
                .any(|k| *k == p.key || k.starts_with(&format!("{}.", p.key)) || is_array_entry(&p.key, k))
        })
        .collect();
    if problems.is_empty() {
        return Ok(table);
    }
    let lines = key_lines(text);
    Err(problems
        .into_iter()
        .map(|p| ConfigError {
            path: Some(path.to_path_buf()),
            line: nearest_line(&lines, &p.key),
            message: p.message,
        })
        .collect())
}

/// `views.0.layout` belongs to the leaf `views` (arrays are leaves).
fn is_array_entry(problem_key: &str, leaf: &str) -> bool {
    problem_key
        .strip_prefix(leaf)
        .is_some_and(|rest| rest.starts_with('.'))
}

fn semantic_error(cfg: &Config) -> Option<String> {
    let p = crate::semantic::problems(cfg);
    (!p.is_empty()).then(|| p.into_iter().map(|p| p.message).collect::<Vec<_>>().join("; "))
}

struct Acc<'c> {
    merged: Table,
    origins: BTreeMap<String, Origin>,
    set_by: BTreeMap<String, Vec<Origin>>,
    order: BTreeMap<String, usize>,
    seq: usize,
    files: Vec<PathBuf>,
    errors: Vec<ConfigError>,
    cache: &'c mut LayerCache,
}

/// Why a layer was not merged.
enum Rejected {
    /// The merged result does not deserialize.
    Type(String),
    /// It deserializes but breaks a [`crate::semantic`] rule.
    Rule(String),
}

impl Rejected {
    fn message(self) -> String {
        match self {
            Rejected::Type(m) | Rejected::Rule(m) => m,
        }
    }
}

/// Records that `key` was set by a non-default layer: its children's and its (default, empty-table)
/// ancestors' entries go, so the origin of a map-valued setting such as `adapters.ports` is the layer that
/// filled it, not "default".
fn claim_origin(
    origins: &mut BTreeMap<String, Origin>,
    order: &mut BTreeMap<String, usize>,
    key: &str,
    origin: Origin,
    seq: usize,
) {
    let prefix = format!("{key}.");
    origins.retain(|existing, _| !existing.starts_with(&prefix));
    order.retain(|existing, _| !existing.starts_with(&prefix));
    let mut k = key;
    while let Some((parent, _)) = k.rsplit_once('.') {
        origins.remove(parent);
        order.remove(parent);
        k = parent;
    }
    origins.insert(key.to_string(), origin);
    order.insert(key.to_string(), seq);
}

impl Acc<'_> {
    /// Merges a layer if the result still deserializes; returns the error otherwise.
    fn apply(&mut self, layer: &Table, origin_of: &dyn Fn(&str) -> Origin) -> Result<(), Rejected> {
        let mut candidate = self.merged.clone();
        deep_merge(&mut candidate, layer);
        let cfg = Value::Table(candidate.clone())
            .try_into::<Config>()
            .map_err(|e| Rejected::Type(with_hint(&e.to_string())))?;
        if let Some(m) = semantic_error(&cfg) {
            return Err(Rejected::Rule(m));
        }
        self.merged = candidate;
        self.seq += 1;
        for (k, v) in leaves(layer) {
            // an empty table sets nothing (see `deep_merge`), so it takes no origin either
            if matches!(&v, Value::Table(t) if t.is_empty()) {
                continue;
            }
            let o = origin_of(&k);
            self.set_by.entry(k.clone()).or_default().push(o.clone());
            claim_origin(&mut self.origins, &mut self.order, &k, o, self.seq);
        }
        Ok(())
    }

    fn apply_text(&mut self, path: &Path, text: &str, table: &Table) -> Result<(), Rejected> {
        let lines = key_lines(text);
        let p = path.to_path_buf();
        self.apply(table, &|k| Origin::File {
            path: p.clone(),
            line: nearest_line(&lines, k),
        })
    }

    /// Reads and merges one file. `explicit` = the user named this very file, so it must exist.
    fn file(&mut self, path: &Path, explicit: bool) {
        let text = match std::fs::read_to_string(path) {
            Ok(t) => t,
            Err(e) => {
                // a missing layer is normal; an unreadable one (permissions, not UTF-8, a directory) is reported
                if e.kind() == std::io::ErrorKind::NotFound && explicit {
                    // `--config` / `OOMTOP_CONFIG` named this file: a typo must not silently mean "defaults"
                    self.errors.push(ConfigError {
                        path: Some(path.to_path_buf()),
                        line: None,
                        message: "config file not found (named by --config / OOMTOP_CONFIG); using the \
                                  other layers and built-in defaults"
                            .into(),
                    });
                }
                if e.kind() != std::io::ErrorKind::NotFound {
                    let kept = self
                        .cache
                        .files
                        .get(path)
                        .cloned()
                        .is_some_and(|(old_text, old)| self.apply_text(path, &old_text, &old).is_ok());
                    self.errors.push(ConfigError {
                        path: Some(path.to_path_buf()),
                        line: None,
                        message: format!(
                            "cannot read: {e}{}",
                            if kept {
                                " (keeping the last good version of this file)"
                            } else {
                                " (this file is ignored until fixed)"
                            }
                        ),
                    });
                    if !kept {
                        self.cache.files.remove(path);
                    }
                    return;
                }
                self.cache.files.remove(path);
                return;
            }
        };
        self.files.push(path.to_path_buf());
        let parsed = parse_layer_all(path, &text).and_then(|t| {
            self.apply_text(path, &text, &t).map(|_| t).map_err(|r| {
                vec![ConfigError {
                    path: Some(path.to_path_buf()),
                    line: None,
                    message: r.message(),
                }]
            })
        });
        match parsed {
            Ok(t) => {
                self.cache.files.insert(path.to_path_buf(), (text, t));
            }
            Err(mut es) => {
                let suffix = match self.cache.files.get(path).cloned() {
                    Some((old_text, old)) if self.apply_text(path, &old_text, &old).is_ok() => {
                        " (keeping the last good version of this file)"
                    }
                    _ => " (this file is ignored until fixed)",
                };
                for e in &mut es {
                    e.message.push_str(suffix);
                }
                self.errors.extend(es);
            }
        }
    }

    /// One env var / flag: TOML literal first, then the raw string (so `OOMTOP_APPEARANCE__COLOR=256` works).
    fn single(&mut self, key: &str, raw: &str, origin: Origin, label: &str) {
        let mut attempts = vec![parse_value(raw)];
        if !matches!(attempts[0], Value::String(_)) {
            attempts.push(Value::String(raw.to_string()));
        }
        let mut last_err = String::new();
        let mut rule_err = None;
        for v in attempts {
            let mut layer = Table::new();
            set_path(&mut layer, key, v);
            match self.apply(&layer, &|_| origin.clone()) {
                Ok(()) => return,
                // a value of the right type that breaks a rule is the more useful message
                Err(Rejected::Rule(m)) => rule_err = rule_err.or(Some(m)),
                Err(Rejected::Type(m)) => last_err = m,
            }
        }
        let last_err = rule_err.unwrap_or(last_err);
        self.errors.push(ConfigError {
            path: None,
            line: None,
            message: format!("{label}: {last_err} (ignored)"),
        });
    }
}

fn nearest_line(lines: &BTreeMap<String, usize>, key: &str) -> Option<usize> {
    let mut k = key;
    loop {
        if let Some(l) = lines.get(k) {
            return Some(*l);
        }
        k = k.rsplit_once('.')?.0;
    }
}

fn default_table() -> Table {
    match Value::try_from(Config::default()) {
        Ok(Value::Table(t)) => t,
        _ => Table::new(),
    }
}

/// `OOMTOP_APPEARANCE__THEME` → `appearance.theme` (double underscore = nesting). `None` for variables that are
/// not settings (`OOMTOP_CONFIG`, single-underscore names).
pub fn env_key(var: &str) -> Option<String> {
    let rest = var.strip_prefix("OOMTOP_")?;
    if rest == "CONFIG" || !rest.contains("__") {
        return None;
    }
    let key = rest.to_ascii_lowercase().replace("__", ".");
    (!key.split('.').any(str::is_empty)).then_some(key)
}

/// Loads all layers.
pub fn load_layered(opts: &LoadOptions) -> Loaded {
    load_layered_cached(opts, &mut LayerCache::new())
}

/// Loads all layers; files that became invalid fall back to their version in `cache` (live reload).
pub fn load_layered_cached(opts: &LoadOptions, cache: &mut LayerCache) -> Loaded {
    let defaults = default_table();
    let mut acc = Acc {
        origins: leaves(&defaults)
            .into_iter()
            .map(|(k, _)| (k, Origin::Default))
            .collect(),
        merged: defaults,
        set_by: BTreeMap::new(),
        order: BTreeMap::new(),
        seq: 0,
        files: Vec::new(),
        errors: Vec::new(),
        cache,
    };
    let explicit = opts.explicit_config().map(Path::to_path_buf);
    for f in opts.layer_files() {
        let named = explicit.as_deref() == Some(f.as_path());
        acc.file(&f, named);
    }
    let host = opts.hostname();
    let notes: Vec<String> = opts
        .skipped_host_files()
        .iter()
        .map(|p| {
            format!(
                "{}: not applied — host-*.toml drop-ins are per-machine and this host is {host:?} \
                 (its file is host-{host}.toml)",
                p.display()
            )
        })
        .collect();

    let env: Vec<(String, String)> = match &opts.env {
        Some(e) => e.clone(),
        None => std::env::vars()
            .filter(|(k, _)| k.starts_with("OOMTOP_"))
            .collect(),
    };
    let mut env = env;
    env.sort();
    let mut no_learn = None;
    for (k, v) in &env {
        if k == "OOMTOP_NO_LEARN" {
            if v != "0" && !v.is_empty() && !v.eq_ignore_ascii_case("false") {
                no_learn = Some(k.clone());
            }
            continue;
        }
        // An empty variable (`OOMTOP_APPEARANCE__THEME=`) is "not set", not the empty string.
        if v.is_empty() {
            continue;
        }
        if let Some(key) = env_key(k) {
            acc.single(&key, v, Origin::Env(k.clone()), k);
        }
    }
    // The opt-out is applied after every other variable, so `OOMTOP_PERSONALIZATION__LEARN=true` in the same
    // environment cannot switch learning back on (flags and runtime toggles, being explicit, still can).
    if let Some(k) = no_learn {
        acc.single("personalization.learn", "false", Origin::Env(k.clone()), &k);
    }
    for (k, v) in &opts.flags {
        acc.single(k, v, Origin::Flag, &format!("--set {k}"));
    }
    let config = Value::Table(acc.merged.clone())
        .try_into::<Config>()
        .unwrap_or_default();
    Loaded {
        config,
        origins: acc.origins,
        files: acc.files,
        errors: acc.errors,
        notes,
        merged: acc.merged,
        order: acc.order,
        set_by: acc.set_by,
    }
}

impl Loaded {
    /// Every effective leaf value with its origin.
    pub fn effective(&self) -> Vec<EffectiveEntry> {
        leaves(&self.merged)
            .into_iter()
            .map(|(key, v)| {
                let origin = self.origin_of_leaf(&key);
                EffectiveEntry {
                    value: v.to_string(),
                    key,
                    origin,
                }
            })
            .collect()
    }

    fn origin_of_leaf(&self, key: &str) -> Origin {
        let mut k = key;
        loop {
            if let Some(o) = self.origins.get(k) {
                return o.clone();
            }
            match k.rsplit_once('.') {
                Some((parent, _)) => k = parent,
                None => return Origin::Default,
            }
        }
    }

    /// Origin of one dotted key. For a section or a map-valued setting (`adapters.ports`, `aliases`) this is
    /// the highest-precedence layer that set anything inside it, `default` when none did.
    pub fn origin(&self, key: &str) -> Origin {
        if let Some(o) = self.origins.get(key) {
            return o.clone();
        }
        let prefix = format!("{key}.");
        let inside = self
            .origins
            .iter()
            .filter(|(k, o)| k.starts_with(&prefix) && **o != Origin::Default)
            .max_by_key(|(k, _)| self.order.get(*k).copied().unwrap_or(0));
        match inside {
            Some((_, o)) => o.clone(),
            None => self.origin_of_leaf(key),
        }
    }

    /// Every layer that set `key` (lowest precedence first). More than one entry means the value is
    /// overridden elsewhere (UX §12.8).
    pub fn set_by(&self, key: &str) -> Vec<Origin> {
        self.set_by
            .iter()
            .filter(|(k, _)| *k == key || k.starts_with(&format!("{key}.")))
            .flat_map(|(_, v)| v.iter().cloned())
            .collect()
    }

    /// The effective value of one dotted key as TOML text.
    pub fn value(&self, key: &str) -> Option<String> {
        let mut cur = &self.merged;
        let parts: Vec<&str> = key.split('.').collect();
        for (i, p) in parts.iter().enumerate() {
            let v = cur.get(*p)?;
            if i + 1 == parts.len() {
                return Some(v.to_string());
            }
            cur = v.as_table()?;
        }
        None
    }

    /// The effective configuration as TOML.
    pub fn effective_toml(&self) -> String {
        toml::to_string(&self.config).unwrap_or_default()
    }

    /// Applies a runtime toggle (not persisted).
    pub fn set_runtime(&mut self, key: &str, value: &str) -> Result<(), ConfigError> {
        let mut last = None;
        let mut attempts = vec![parse_value(value)];
        if !matches!(attempts[0], Value::String(_)) {
            attempts.push(Value::String(value.to_string()));
        }
        for v in attempts {
            let mut layer = Table::new();
            set_path(&mut layer, key, v);
            let mut candidate = self.merged.clone();
            deep_merge(&mut candidate, &layer);
            match Value::Table(candidate.clone()).try_into::<Config>() {
                Ok(cfg) => {
                    if let Some(m) = semantic_error(&cfg) {
                        return Err(ConfigError {
                            path: None,
                            line: None,
                            message: m,
                        });
                    }
                    self.merged = candidate;
                    self.config = cfg;
                    let seq = self.order.values().copied().max().unwrap_or(0) + 1;
                    claim_origin(&mut self.origins, &mut self.order, key, Origin::Runtime, seq);
                    self.set_by
                        .entry(key.to_string())
                        .or_default()
                        .push(Origin::Runtime);
                    return Ok(());
                }
                Err(e) => last = Some(e),
            }
        }
        Err(ConfigError {
            path: None,
            line: None,
            message: with_hint(&last.map(|e| e.to_string()).unwrap_or_default()),
        })
    }
}

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

    fn opts(dir: &Path) -> LoadOptions {
        LoadOptions {
            config_dir: Some(dir.to_path_buf()),
            system_dir: Some(PathBuf::new()),
            hostname: Some("air".into()),
            env: Some(vec![]),
            ..Default::default()
        }
    }

    #[test]
    fn precedence_and_origins() {
        let d = tempfile::tempdir().unwrap();
        let sys = d.path().join("etc");
        std::fs::create_dir_all(sys.join("config.d")).unwrap();
        std::fs::write(
            sys.join("config.toml"),
            "[appearance]\ntheme = \"mint\"\nborders = \"thick\"\n[general]\nmouse = false\n",
        )
        .unwrap();
        std::fs::write(
            sys.join("config.d/10-site.toml"),
            "[general]\nhost_refresh_ms = 1500\n",
        )
        .unwrap();
        let user = d.path().join("user");
        std::fs::create_dir_all(user.join("config.d")).unwrap();
        std::fs::write(
            user.join("config.toml"),
            "# mine\n[appearance]\ntheme = \"mono\"\ndensity = \"compact\"\n",
        )
        .unwrap();
        std::fs::write(
            user.join("config.d/10-x.toml"),
            "[appearance]\ntheme = \"ember\"\n",
        )
        .unwrap();
        std::fs::write(
            user.join("config.d/05-a.toml"),
            "[appearance]\ntheme = \"sand\"\n",
        )
        .unwrap();
        std::fs::write(
            user.join("config.d/host-air.toml"),
            "[general]\nrefresh_ms = 5000\n[appearance]\ntheme = \"coral\"\n",
        )
        .unwrap();
        std::fs::write(
            user.join("config.d/host-other.toml"),
            "[general]\nrefresh_ms = 1\n",
        )
        .unwrap();
        let mut o = opts(&user);
        o.system_dir = Some(sys.clone());
        o.env = Some(vec![
            ("OOMTOP_APPEARANCE__BORDERS".into(), "plain".into()),
            ("OOMTOP_NO_LEARN".into(), "1".into()),
            ("OOMTOP_PERSONALIZATION__WEIGHTS__AFFINITY".into(), "0.9".into()),
            ("OOMTOP_CONFIG".into(), "/nope".into()),
            ("OOMTOP_UNRELATED".into(), "x".into()),
        ]);
        o.flags = vec![("format.decimals".into(), "2".into())];
        let l = load_layered(&o);
        assert!(l.errors.is_empty(), "{:?}", l.errors);
        assert_eq!(l.config.appearance.theme, "coral", "host file wins over drop-ins");
        assert_eq!(l.config.appearance.density, crate::model::Density::Compact);
        assert_eq!(l.config.general.refresh_ms, 5000);
        assert!(!l.config.general.mouse, "system layer applies");
        assert_eq!(l.config.general.host_refresh_ms, 1500);
        assert_eq!(l.config.appearance.borders, crate::model::Borders::Plain);
        assert!(!l.config.personalization.learn);
        assert_eq!(l.config.personalization.weights.affinity, 0.9);
        assert_eq!(l.config.format.decimals, 2);
        assert_eq!(l.origin("appearance.theme").to_string(), "host-air.toml:4");
        assert_eq!(l.origin("appearance.density").to_string(), "config.toml:4");
        assert_eq!(l.origin("general.refresh_ms").to_string(), "host-air.toml:2");
        assert_eq!(l.origin("general.mouse").to_string(), "config.toml:5");
        assert_eq!(
            l.origin("appearance.borders").to_string(),
            "env OOMTOP_APPEARANCE__BORDERS"
        );
        assert_eq!(l.origin("appearance.borders").short(), "env");
        assert_eq!(l.origin("format.decimals"), Origin::Flag);
        assert_eq!(l.origin("serve.listen"), Origin::Default);
        // theme was set by 5 layers: system, config.toml, 05-a, 10-x, host
        let by: Vec<String> = l
            .set_by("appearance.theme")
            .iter()
            .map(|o| o.to_string())
            .collect();
        assert_eq!(
            by,
            [
                "config.toml:2",
                "config.toml:3",
                "05-a.toml:2",
                "10-x.toml:2",
                "host-air.toml:4"
            ]
        );
        assert_eq!(l.value("appearance.theme").as_deref(), Some("\"coral\""));
        assert_eq!(l.files.len(), 6);
        assert!(l
            .effective()
            .iter()
            .any(|e| e.key == "general.refresh_ms" && e.value == "5000"));
    }

    #[test]
    fn invalid_layer_is_skipped_with_location_and_hint() {
        let d = tempfile::tempdir().unwrap();
        std::fs::write(d.path().join("config.toml"), "[appearance]\ntheme = \"mono\"\n").unwrap();
        std::fs::create_dir(d.path().join("config.d")).unwrap();
        std::fs::write(
            d.path().join("config.d/20-bad.toml"),
            "[general]\nmouse = true\nrefresh_ms = \"fast\"\n",
        )
        .unwrap();
        std::fs::write(d.path().join("config.d/30-syntax.toml"), "[general\nx=1\n").unwrap();
        std::fs::write(
            d.path().join("config.d/40-typo.toml"),
            "\n[appearance]\nthme = \"x\"\n",
        )
        .unwrap();
        let l = load_layered(&opts(d.path()));
        assert_eq!(l.config.appearance.theme, "mono");
        assert_eq!(l.config.general.refresh_ms, 2000);
        assert_eq!(l.errors.len(), 3, "{:?}", l.errors);
        assert_eq!(l.errors[0].line, Some(3));
        assert_eq!(l.errors[1].line, Some(1));
        assert_eq!(l.errors[2].line, Some(3));
        assert!(
            l.errors[2].message.contains("did you mean `theme`?"),
            "{}",
            l.errors[2]
        );
        assert!(l.errors[2]
            .to_string()
            .contains("40-typo.toml:3: unknown field `thme`"));
    }

    #[test]
    fn env_values_are_coerced_and_isolated() {
        let d = tempfile::tempdir().unwrap();
        let mut o = opts(d.path());
        o.env = Some(vec![
            ("OOMTOP_APPEARANCE__COLOR".into(), "256".into()),
            ("OOMTOP_GENERAL__REFRESH_MS".into(), "fast".into()),
            ("OOMTOP_HEADROOM__MIN_MARGIN".into(), "2G".into()),
            ("OOMTOP_PROTECTED__NAMES".into(), "[\"postgres\"]".into()),
        ]);
        let l = load_layered(&o);
        assert_eq!(l.config.appearance.color, crate::model::ColorMode::C256);
        assert_eq!(l.config.headroom.min_margin, "2G");
        assert_eq!(l.config.protected.names, vec!["postgres".to_string()]);
        assert_eq!(l.config.general.refresh_ms, 2000);
        assert_eq!(l.errors.len(), 1);
        assert!(l.errors[0].message.starts_with("OOMTOP_GENERAL__REFRESH_MS:"));
        assert_eq!(env_key("OOMTOP_A__B_C"), Some("a.b_c".into()));
        assert_eq!(env_key("OOMTOP_A____B"), None);
        assert_eq!(env_key("OOMTOP_CONFIG"), None);
    }

    #[test]
    fn cache_keeps_last_good_file() {
        let d = tempfile::tempdir().unwrap();
        let f = d.path().join("config.toml");
        std::fs::write(&f, "[appearance]\ntheme = \"mono\"\n").unwrap();
        let mut cache = LayerCache::new();
        let o = opts(d.path());
        assert_eq!(
            load_layered_cached(&o, &mut cache).config.appearance.theme,
            "mono"
        );
        std::fs::write(&f, "[appearance]\ntheme = 3\n").unwrap();
        let l = load_layered_cached(&o, &mut cache);
        assert_eq!(l.config.appearance.theme, "mono");
        assert_eq!(l.errors.len(), 1);
        assert!(l.errors[0].message.contains("keeping the last good version"));
        assert_eq!(l.errors[0].line, Some(2));
        // without the cache the file is ignored
        let l = load_layered(&o);
        assert_eq!(l.config.appearance.theme, "terminal");
        assert!(l.errors[0].message.contains("ignored until fixed"));
    }

    #[test]
    fn lines_of_nested_keys() {
        let text = "a = 1\n[p]\nx.y = 2\nz = { q = 3 }\n\n[[views]]\nname = \"v\"\n[[views]]\nname = \"w\"\n";
        let l = key_lines(text);
        assert_eq!(l["a"], 1);
        assert_eq!(l["p"], 2);
        assert_eq!(l["p.x.y"], 3);
        assert_eq!(l["p.z.q"], 4);
        assert_eq!(l["views"], 6);
        assert_eq!(l["views.1.name"], 9);
        assert_eq!(find_line(text, "p.z.nope"), Some(4));
        assert_eq!(find_line(text, "nope"), None);
    }

    #[test]
    fn empty_section_header_keeps_lower_layers() {
        // regression: an uncommented `[appearance]` header with nothing under it used to replace the whole
        // section with defaults (dropping the system layer's theme) and claim every appearance.* origin
        let d = tempfile::tempdir().unwrap();
        let sys = d.path().join("etc");
        std::fs::create_dir_all(&sys).unwrap();
        std::fs::write(
            sys.join("config.toml"),
            "[appearance]\ntheme = \"mint\"\n[adapters.ports]\nollama = 11500\n",
        )
        .unwrap();
        let user = d.path().join("user");
        std::fs::create_dir_all(&user).unwrap();
        std::fs::write(
            user.join("config.toml"),
            "# from `config init`, headers uncommented only\n[appearance]\n\n[adapters]\n[adapters.ports]\n[aliases]\n",
        )
        .unwrap();
        let mut o = opts(&user);
        o.system_dir = Some(sys.clone());
        let l = load_layered(&o);
        assert!(l.errors.is_empty(), "{:?}", l.errors);
        assert_eq!(l.config.appearance.theme, "mint");
        assert_eq!(l.config.adapters.ports.get("ollama"), Some(&11500));
        assert_eq!(
            l.origin("appearance.theme"),
            Origin::File {
                path: sys.join("config.toml"),
                line: Some(2)
            }
        );
        assert_eq!(l.origin("appearance.density"), Origin::Default);
        assert!(l.set_by("appearance").len() == 1, "{:?}", l.set_by("appearance"));
    }

    #[test]
    fn system_origin_is_labelled_by_full_path() {
        let o = Origin::File {
            path: system_dir().join("config.toml"),
            line: Some(2),
        };
        assert_eq!(o.to_string(), "/etc/oomtop/config.toml:2");
        let o = Origin::File {
            path: PathBuf::from("/home/u/.config/oomtop/config.d/host-air.toml"),
            line: Some(3),
        };
        assert_eq!(o.short(), "host-air.toml:3");
    }

    #[test]
    fn unreadable_layer_is_reported_not_silently_skipped() {
        let d = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(d.path().join("config.d")).unwrap();
        // a directory where a drop-in file is expected cannot be read as text
        std::fs::create_dir_all(d.path().join("config.toml")).unwrap();
        std::fs::write(d.path().join("config.d/bin.toml"), [0xff, 0xfe, 0x00]).unwrap();
        let l = load_layered(&opts(d.path()));
        assert_eq!(l.errors.len(), 2, "{:?}", l.errors);
        assert!(l.errors.iter().all(|e| e.message.starts_with("cannot read")));
        assert_eq!(l.config, Config::default());
    }

    #[test]
    fn missing_explicit_config_is_an_error() {
        // regression: a typo in --config / OOMTOP_CONFIG silently meant "built-in defaults"
        let d = tempfile::tempdir().unwrap();
        let mut o = opts(d.path());
        o.config_path = Some(d.path().join("nope/typo.toml"));
        let l = load_layered(&o);
        assert_eq!(l.errors.len(), 1, "{:?}", l.errors);
        assert!(
            l.errors[0].message.starts_with("config file not found"),
            "{}",
            l.errors[0]
        );
        assert_eq!(
            l.errors[0].path.as_deref(),
            Some(d.path().join("nope/typo.toml").as_path())
        );
        // the default config.toml may be missing, and an empty OOMTOP_CONFIG is "unset"
        assert!(load_layered(&opts(d.path())).errors.is_empty());
        let mut o = opts(d.path());
        o.config_path = Some(PathBuf::new());
        assert!(load_layered(&o).errors.is_empty());
        assert_eq!(o.main_file(), d.path().join("config.toml"));
    }

    #[test]
    fn semantic_rules_reject_a_layer_like_type_errors() {
        // regression: `format.decimals = 200` loaded fine and printed 200 decimals
        let d = tempfile::tempdir().unwrap();
        let f = d.path().join("config.toml");
        std::fs::write(&f, "[format]\ndecimals = 2\n").unwrap();
        let mut cache = LayerCache::new();
        let mut o = opts(d.path());
        assert_eq!(load_layered_cached(&o, &mut cache).config.format.decimals, 2);
        std::fs::write(
            &f,
            "[format]\ndecimals = 200\n[general]\nrefresh_ms = 0\n[keys]\npreset = \"bogus\"\n",
        )
        .unwrap();
        let l = load_layered_cached(&o, &mut cache);
        assert_eq!(l.config.format.decimals, 2, "last good value kept");
        assert_eq!(l.config.general.refresh_ms, 2000);
        let msgs: Vec<String> = l.errors.iter().map(|e| e.to_string()).collect();
        assert_eq!(msgs.len(), 3, "{msgs:#?}");
        assert!(msgs
            .iter()
            .any(|m| m.contains("config.toml:4: general.refresh_ms: must be ≥ 250 ms")));
        assert!(msgs.iter().any(|m| m.contains("config.toml:2: format.decimals")));
        assert!(msgs
            .iter()
            .any(|m| m.contains("config.toml:6: keys.preset: unknown key preset \"bogus\"")));
        assert!(msgs
            .iter()
            .all(|m| m.ends_with("(keeping the last good version of this file)")));
        // env vars and flags go through the same rules, one by one
        std::fs::write(&f, "").unwrap();
        o.env = Some(vec![
            ("OOMTOP_GENERAL__REFRESH_MS".into(), "0".into()),
            ("OOMTOP_HEADROOM__MIN_MARGIN".into(), "banana".into()),
            ("OOMTOP_ADAPTERS__TIMEOUT_MS".into(), "300".into()),
        ]);
        o.flags = vec![("headroom.margin_pct".into(), "nan".into())];
        let l = load_layered(&o);
        assert_eq!(l.config.general.refresh_ms, 2000);
        assert_eq!(l.config.headroom.min_margin, "1.5G");
        assert_eq!(l.config.headroom.margin_pct, 8.0);
        assert_eq!(l.config.adapters.timeout_ms, 300);
        let msgs: Vec<String> = l.errors.iter().map(|e| e.to_string()).collect();
        assert_eq!(msgs.len(), 3, "{msgs:#?}");
        assert!(
            msgs.iter()
                .any(|m| m == "OOMTOP_GENERAL__REFRESH_MS: general.refresh_ms: must be ≥ 250 ms (perf budget, SPEC §14) (ignored)"),
            "{msgs:#?}"
        );
        assert!(msgs
            .iter()
            .any(|m| m.starts_with("--set headroom.margin_pct: headroom.margin_pct: must be between")));
        // runtime toggles too
        let mut l = load_layered(&opts(d.path()));
        let e = l.set_runtime("format.decimals", "9").unwrap_err();
        assert!(
            e.message.contains("format.decimals: must be between 0 and 3"),
            "{e}"
        );
        assert_eq!(l.config.format.decimals, 1);
    }

    #[test]
    fn host_files_are_per_machine_in_both_directories() {
        let d = tempfile::tempdir().unwrap();
        let sys = d.path().join("etc");
        let user = d.path().join("user");
        for dir in [&sys, &user] {
            std::fs::create_dir_all(dir.join("config.d")).unwrap();
        }
        // regression: /etc/oomtop/config.d/host-*.toml applied on every machine
        std::fs::write(sys.join("config.d/host-other.toml"), "[general]\nmouse = false\n").unwrap();
        std::fs::write(sys.join("config.d/host-air.toml"), "[format]\ndecimals = 2\n").unwrap();
        std::fs::write(sys.join("config.d/zz-site.toml"), "[format]\ndecimals = 3\n").unwrap();
        std::fs::write(
            user.join("config.d/host-limits.toml"),
            "[appearance]\ntheme = \"mint\"\n",
        )
        .unwrap();
        std::fs::write(
            user.join("config.d/hosting.toml"),
            "[appearance]\ndensity = \"compact\"\n",
        )
        .unwrap();
        let mut o = opts(&user);
        o.system_dir = Some(sys.clone());
        let l = load_layered(&o);
        assert!(l.errors.is_empty(), "{:?}", l.errors);
        assert!(
            l.config.general.mouse,
            "another host's system file is not applied"
        );
        assert_eq!(
            l.config.format.decimals, 2,
            "this host's system file wins over system drop-ins"
        );
        assert_eq!(l.config.appearance.theme, "terminal");
        assert_eq!(
            l.config.appearance.density,
            crate::model::Density::Compact,
            "`hosting.toml` is a normal drop-in"
        );
        assert_eq!(
            o.skipped_host_files(),
            vec![
                sys.join("config.d/host-other.toml"),
                user.join("config.d/host-limits.toml")
            ]
        );
        // regression: nothing said that host-limits.toml was being ignored
        assert_eq!(l.notes.len(), 2, "{:?}", l.notes);
        assert!(
            l.notes[1].contains("host-limits.toml: not applied"),
            "{}",
            l.notes[1]
        );
        assert!(l.notes[1].contains("this host is \"air\""), "{}", l.notes[1]);
    }

    #[test]
    fn origin_of_map_valued_settings() {
        // regression: `config set adapters.ports '{ ollama = 11500 }'` answered "adapters.ports is still set
        // by default, which takes precedence" because the default empty table kept its `default` origin
        let d = tempfile::tempdir().unwrap();
        std::fs::create_dir(d.path().join("config.d")).unwrap();
        let main = d.path().join("config.toml");
        std::fs::write(
            &main,
            "[adapters]\nports = { ollama = 11500 }\n[aliases]\nllm = \"kind:model\"\n",
        )
        .unwrap();
        let o = opts(d.path());
        let l = load_layered(&o);
        assert_eq!(l.origin("adapters.ports").to_string(), "config.toml:2");
        assert_eq!(l.origin("adapters.ports.ollama").to_string(), "config.toml:2");
        assert_eq!(l.origin("aliases").to_string(), "config.toml:4");
        assert_eq!(l.origin("adapters.enabled"), Origin::Default);
        assert_eq!(l.origin("protected.names"), Origin::Default);
        assert_eq!(l.origin("general"), Origin::Default, "a section nobody touched");
        // several layers fill the map: the section reports the highest-precedence one
        let dropin = d.path().join("config.d/50-x.toml");
        std::fs::write(&dropin, "[adapters.ports]\nvllm = 8001\n").unwrap();
        let mut l = load_layered(&o);
        assert_eq!(l.origin("adapters.ports").to_string(), "50-x.toml:2");
        assert_eq!(l.origin("adapters.ports.ollama").to_string(), "config.toml:2");
        assert_eq!(l.origin("adapters").to_string(), "50-x.toml:2");
        l.set_runtime("adapters.ports.ollama", "11434").unwrap();
        assert_eq!(l.origin("adapters.ports"), Origin::Runtime);
        // every effective leaf still has exactly one origin
        assert!(l
            .effective()
            .iter()
            .any(|e| e.key == "adapters.ports.vllm" && e.origin.to_string() == "50-x.toml:2"));
    }

    #[test]
    fn no_learn_wins_and_empty_env_values_are_unset() {
        let d = tempfile::tempdir().unwrap();
        let mut o = opts(d.path());
        // regression: applied alphabetically, OOMTOP_PERSONALIZATION__LEARN=true undid the opt-out
        o.env = Some(vec![
            ("OOMTOP_NO_LEARN".into(), "1".into()),
            ("OOMTOP_PERSONALIZATION__LEARN".into(), "true".into()),
            // regression: an empty variable set the theme to ""
            ("OOMTOP_APPEARANCE__THEME".into(), String::new()),
            ("OOMTOP_LAYOUT__NAME".into(), String::new()),
        ]);
        let l = load_layered(&o);
        assert!(l.errors.is_empty(), "{:?}", l.errors);
        assert!(!l.config.personalization.learn);
        assert_eq!(
            l.origin("personalization.learn").to_string(),
            "env OOMTOP_NO_LEARN"
        );
        assert_eq!(l.config.appearance.theme, "terminal");
        assert_eq!(l.origin("appearance.theme"), Origin::Default);
        // OOMTOP_NO_LEARN=0 is not an opt-out, and an explicit flag still outranks the environment
        o.env = Some(vec![("OOMTOP_NO_LEARN".into(), "0".into())]);
        assert!(load_layered(&o).config.personalization.learn);
        o.env = Some(vec![("OOMTOP_NO_LEARN".into(), "1".into())]);
        o.flags = vec![("personalization.learn".into(), "true".into())];
        assert!(load_layered(&o).config.personalization.learn);
    }

    #[test]
    fn runtime_toggle() {
        let d = tempfile::tempdir().unwrap();
        let mut l = load_layered(&opts(d.path()));
        l.set_runtime("appearance.theme", "none").unwrap();
        assert_eq!(l.config.appearance.theme, "none");
        assert_eq!(l.origin("appearance.theme"), Origin::Runtime);
        l.set_runtime("appearance.color", "16").unwrap();
        assert_eq!(l.config.appearance.color, crate::model::ColorMode::C16);
        assert!(l.set_runtime("general.refresh_ms", "\"x\"").is_err());
        let e = l.set_runtime("appearance.density", "compat").unwrap_err();
        assert!(e.message.contains("did you mean `compact`?"), "{e}");
    }
}