oomtop-config 0.2.2

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
//! `oomtop config validate` (UX §12.9): schema-checks **all** files — config layers, themes, keymap, layouts,
//! rules, aliases and saved views — and reports every problem with file:line and a fix hint.

use crate::layered::{line_of, load_layered, LoadOptions, Loaded};
use crate::paths::toml_files;
use crate::ConfigError;
use std::path::Path;

/// Result of a full validation.
#[derive(Debug, Clone)]
pub struct Report {
    pub loaded: Loaded,
    /// Every file that was looked at.
    pub checked: Vec<std::path::PathBuf>,
    pub errors: Vec<ConfigError>,
    /// Informational lines that are not errors (a `host-*.toml` drop-in for another host name, …).
    pub notes: Vec<String>,
}

impl Report {
    pub fn is_ok(&self) -> bool {
        self.errors.is_empty()
    }
}

/// Validates a rules file (`rules.d/*.toml`) against the core rule format and compiles its globs/regexes.
pub fn validate_rules_text(text: &str, path: &Path) -> Vec<ConfigError> {
    let err = |line, message: String| ConfigError {
        path: Some(path.to_path_buf()),
        line,
        message,
    };
    let set: oomtop_core::attribution::RuleSet = match toml::from_str(text) {
        Ok(s) => s,
        Err(e) => {
            let m = e.message().trim().to_string();
            let m = match crate::layered::hint_for(&m) {
                Some(h) => format!("{m} — {h}"),
                None => m,
            };
            return vec![err(e.span().map(|s| line_of(text, s.start)), m)];
        }
    };
    let lines = crate::layered::key_lines(text);
    match oomtop_core::attribution::CompiledRules::compile(&set) {
        Ok(_) => Vec::new(),
        Err(e) => {
            // point at the offending rule when we can tell which one
            let msg = e.to_string();
            let line = set
                .rules
                .iter()
                .enumerate()
                .find(|(_, r)| {
                    let id =
                        r.id.clone()
                            .unwrap_or_else(|| oomtop_core::attribution::slug(&r.label));
                    msg.contains(&format!("{id:?}")) || msg.contains(&format!("{:?}", r.label))
                })
                .and_then(|(i, _)| lines.get(&format!("group.{i}")).copied());
            vec![err(line, msg)]
        }
    }
}

/// Validates everything under the resolved config directory.
pub fn validate_all(opts: &LoadOptions) -> Report {
    let loaded = load_layered(opts);
    let paths = opts.paths();
    let mut errors = loaded.errors.clone();
    let mut checked = loaded.files.clone();

    // themes
    for f in toml_files(&paths.themes) {
        checked.push(f.clone());
        let Ok(text) = std::fs::read_to_string(&f) else {
            continue;
        };
        match crate::theme::parse_theme(&text, &f.display().to_string()) {
            Err(e) => errors.push(ConfigError {
                path: Some(f.clone()),
                line: None,
                message: e.to_string(),
            }),
            Ok(t) => {
                let lines = crate::layered::key_lines(&text);
                // user files: structure only (contrast is nudged at load and shown by `theme check`)
                for issue in crate::theme::check_structure(&t, false) {
                    errors.push(ConfigError {
                        path: Some(f.clone()),
                        line: lines.get(&issue.token).copied().or_else(|| {
                            // quoted dotted token keys: [ui] "border.focus"
                            issue
                                .token
                                .split_once('.')
                                .and_then(|(sec, rest)| lines.get(&format!("{sec}.{rest}")).copied())
                        }),
                        message: format!("{}: {}", issue.token, issue.message),
                    });
                }
                if let Some(parent) = &t.inherits {
                    let name = f
                        .file_stem()
                        .map(|s| s.to_string_lossy().into_owned())
                        .unwrap_or_default();
                    if let Err(e) = crate::theme::load_theme(&name, Some(&paths.themes)) {
                        errors.push(ConfigError {
                            path: Some(f.clone()),
                            line: lines.get("inherits").copied(),
                            message: format!("inherits {parent:?}: {e}"),
                        });
                    }
                }
            }
        }
    }
    // the selected theme and layout must exist (the same check `config set` runs before writing)
    for p in crate::semantic::fs_problems(&loaded.config, &paths) {
        errors.push(origin_error(&loaded, &p.key, p.message));
    }

    // keymap
    if paths.keymap.is_file() {
        checked.push(paths.keymap.clone());
    }
    let (km, kerrs) = crate::keymap::load_keymap(
        &loaded.config.keys.preset,
        Some(&paths.keymap).filter(|p| p.is_file()).map(|p| p.as_path()),
    );
    for e in kerrs {
        if e.path.is_none() {
            errors.push(origin_error(&loaded, "keys.preset", e.message));
        } else {
            errors.push(e);
        }
    }
    let km_lines = std::fs::read_to_string(&paths.keymap)
        .map(|t| crate::layered::key_lines(&t))
        .unwrap_or_default();
    for c in km.conflicts() {
        let chord = c
            .actions
            .iter()
            .find_map(|a| a.split('"').nth(1).map(str::to_string));
        let line = km_lines
            .get(&format!("{}.{}", c.context, c.key))
            .or_else(|| chord.and_then(|ch| km_lines.get(&format!("{}.{ch}", c.context))))
            .copied();
        errors.push(ConfigError {
            path: Some(paths.keymap.clone()),
            line,
            message: format!("key conflict {c}"),
        });
    }

    // layouts
    for f in toml_files(&paths.layouts) {
        checked.push(f.clone());
        if let Ok(text) = std::fs::read_to_string(&f) {
            if let Err(es) = crate::layout::parse_layout(&text, &f) {
                errors.extend(es);
            }
        }
    }

    // rules
    for f in toml_files(&paths.rules_d) {
        checked.push(f.clone());
        if let Ok(text) = std::fs::read_to_string(&f) {
            errors.extend(validate_rules_text(&text, &f));
        }
    }

    // aliases & views
    errors.extend(crate::views::validate(&loaded, Some(&paths.layouts)));

    // Ranges, names and formats: the loader already rejects a layer that breaks one of these (so it is in
    // `loaded.errors` with file:line); this catches anything that still reached the effective config.
    for p in crate::semantic::problems(&loaded.config) {
        if !errors.iter().any(|e| e.message.contains(&p.key)) {
            errors.push(origin_error(&loaded, &p.key, p.message));
        }
    }
    // UX §14: polls faster than 100 ms are raised to 100 ms at run time; validation still points it out.
    let poll = loaded.config.general.watch_poll_ms;
    if poll != 0 && poll < 100 {
        errors.push(origin_error(
            &loaded,
            "general.watch_poll_ms",
            "general.watch_poll_ms: must be 0 (native file events) or ≥ 100 ms".into(),
        ));
    }
    let mut seen = std::collections::HashSet::new();
    errors.retain(|e| seen.insert(e.to_string()));
    let notes = loaded.notes.clone();
    Report {
        loaded,
        checked,
        errors,
        notes,
    }
}

fn origin_error(loaded: &Loaded, key: &str, message: String) -> ConfigError {
    match loaded.origin(key) {
        crate::layered::Origin::File { path, line } => ConfigError {
            path: Some(path),
            line,
            message,
        },
        o => ConfigError {
            path: None,
            line: None,
            message: format!("{message} (set by {o})"),
        },
    }
}

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

    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 empty_dir_is_valid() {
        let d = tempfile::tempdir().unwrap();
        let r = validate_all(&opts(d.path()));
        assert!(r.is_ok(), "{:?}", r.errors);
    }

    #[test]
    fn reports_every_kind_with_locations() {
        let d = tempfile::tempdir().unwrap();
        let p = d.path();
        for sub in ["themes", "layouts", "rules.d"] {
            std::fs::create_dir(p.join(sub)).unwrap();
        }
        std::fs::write(
            p.join("config.toml"),
            "[appearance]\ntheme = \"nightt\"\n[layout]\nname = \"gone\"\n",
        )
        .unwrap();
        // a broken rule rejects its own layer (file:line), so it lives in a drop-in here
        std::fs::create_dir(p.join("config.d")).unwrap();
        std::fs::write(
            p.join("config.d/10-serve.toml"),
            "[general]\nmouse = false\n[serve]\nlisten = \"localhost\"\n",
        )
        .unwrap();
        std::fs::write(p.join("themes/x.toml"), "[ui]\naccent = \"#3\"\n").unwrap();
        std::fs::write(
            p.join("keymap.toml"),
            "[global]\n\"x\" = \"quit\"\n\"q\" = \"quit\"\n\"g g\" = \"move:top\"\n",
        )
        .unwrap();
        std::fs::write(p.join("layouts/l.toml"), "[wide]\nrows = [\"nope\"]\n").unwrap();
        std::fs::write(
            p.join("rules.d/10-mine.toml"),
            "[[group]]\nkind = \"model\"\nlabel = \"S\"\nmatch.cmdline = [\"(unclosed\"]\n",
        )
        .unwrap();
        std::fs::write(
            p.join("rules.d/20-bad.toml"),
            "[[group]]\nkind = \"modle\"\nlabel = \"S\"\n",
        )
        .unwrap();
        let r = validate_all(&opts(p));
        let msgs: Vec<String> = r.errors.iter().map(|e| e.to_string()).collect();
        let has = |s: &str| msgs.iter().any(|m| m.contains(s));
        assert!(has("config.toml:2: theme \"nightt\" not found"), "{msgs:#?}");
        assert!(
            has("10-serve.toml:4: serve.listen: must be host:port"),
            "{msgs:#?}"
        );
        assert!(
            r.loaded.config.general.mouse,
            "the layer with the bad value is not applied"
        );
        assert!(has("config.toml:4: no layout \"gone\""), "{msgs:#?}");
        assert!(has("x.toml:2: ui.accent: invalid color \"#3\""), "{msgs:#?}");
        assert!(has("keymap.toml:4: key conflict [global] \"g\""), "{msgs:#?}");
        assert!(has("l.toml:2: unknown slot \"nope\""), "{msgs:#?}");
        assert!(has("10-mine.toml:1: rule \"s\": bad regex"), "{msgs:#?}");
        assert!(has("20-bad.toml:2: unknown variant `modle`"), "{msgs:#?}");
        assert!(r.checked.len() >= 5);
    }

    #[test]
    fn low_contrast_user_theme_is_not_a_validation_error() {
        let d = tempfile::tempdir().unwrap();
        std::fs::create_dir(d.path().join("themes")).unwrap();
        std::fs::write(
            d.path().join("themes/pale.toml"),
            "inherits = \"mono-light\"\n[ui]\ntext = \"#dddddd\"\naccent = \"#3b82f6\"\n",
        )
        .unwrap();
        std::fs::write(d.path().join("config.toml"), "[appearance]\ntheme = \"pale\"\n").unwrap();
        let r = validate_all(&opts(d.path()));
        assert!(r.is_ok(), "{:?}", r.errors);
    }

    #[test]
    fn numeric_limits_are_checked() {
        let d = tempfile::tempdir().unwrap();
        std::fs::write(
            d.path().join("config.toml"),
            "[general]\nhost_refresh_ms = 10\n\n[personalization]\nretention_days = 0\nlog_max_mb = 0\n[format]\ndecimals = 200\n[headroom]\nmargin_pct = -50\n[appearance]\nheader = [\"meter\"]\n",
        )
        .unwrap();
        // UX §14: a too-fast poll is raised at run time, so it does not reject its layer — but it is reported
        std::fs::create_dir(d.path().join("config.d")).unwrap();
        std::fs::write(
            d.path().join("config.d/10-poll.toml"),
            "[general]\nmouse = false\nwatch_poll_ms = 5\n",
        )
        .unwrap();
        let r = validate_all(&opts(d.path()));
        let msgs: Vec<String> = r.errors.iter().map(|e| e.to_string()).collect();
        for want in [
            "config.toml:2: general.host_refresh_ms",
            "10-poll.toml:3: general.watch_poll_ms",
            "config.toml:5: personalization.retention_days",
            "config.toml:6: personalization.log_max_mb",
            // regression: these three were accepted by the loader *and* by `config validate`
            "config.toml:8: format.decimals: must be between 0 and 3",
            "config.toml:10: headroom.margin_pct: must be between 0 and 100",
            "config.toml:12: appearance.header: unknown row \"meter\" — did you mean \"meters\"?",
        ] {
            assert!(msgs.iter().any(|m| m.contains(want)), "{want}: {msgs:#?}");
        }
        // nothing from the rejected file is in effect; the drop-in with only a warning is
        assert_eq!(r.loaded.config.format.decimals, 1);
        assert_eq!(r.loaded.config.general.host_refresh_ms, 1000);
        assert!(!r.loaded.config.general.mouse);
    }

    #[test]
    fn missing_explicit_config_and_foreign_host_files() {
        let d = tempfile::tempdir().unwrap();
        std::fs::create_dir(d.path().join("config.d")).unwrap();
        std::fs::write(
            d.path().join("config.d/host-limits.toml"),
            "[appearance]\ntheme = \"mint\"\n",
        )
        .unwrap();
        // regression: `--config /typo.toml config validate` said "ok: 0 file(s) checked (defaults only)"
        let mut o = opts(d.path());
        o.config_path = Some(d.path().join("typo.toml"));
        let r = validate_all(&o);
        assert!(!r.is_ok());
        assert!(
            r.errors[0]
                .to_string()
                .contains("typo.toml: config file not found"),
            "{:?}",
            r.errors
        );
        // regression: a host-* drop-in for another host name was ignored without a word
        assert_eq!(r.notes.len(), 1, "{:?}", r.notes);
        assert!(
            r.notes[0].contains("host-limits.toml: not applied"),
            "{}",
            r.notes[0]
        );
        assert!(r.notes[0].contains("host-air.toml"), "{}", r.notes[0]);
        // the default location may be absent: that is not an error
        let r = validate_all(&opts(d.path()));
        assert!(r.is_ok(), "{:?}", r.errors);
    }

    #[test]
    fn rules_with_a_stray_top_level_key_are_rejected() {
        // `[[groups]]` / `[[rule]]` instead of `[[group]]` used to parse as an empty rule set: the file
        // looked valid and its rules silently never applied
        for (text, key, line) in [
            ("# mine\n[[groups]]\nkind = \"app\"\nlabel = \"X\"\n", "groups", 2),
            ("[[rule]]\nkind = \"app\"\nlabel = \"X\"\n", "rule", 1),
            (
                "[[group]]\nkind = \"app\"\nlabel = \"X\"\n\n[settings]\nx = 1\n",
                "settings",
                5,
            ),
        ] {
            let errs = validate_rules_text(text, Path::new("r.toml"));
            assert_eq!(errs.len(), 1, "{key}: {errs:?}");
            let m = errs[0].to_string();
            assert!(m.contains(&format!("unknown field `{key}`")), "{m}");
            assert!(m.contains("expected `group`"), "{m}");
            assert_eq!(errs[0].line, Some(line), "{m}");
        }
        let e = validate_rules_text("[[groups]]\nlabel = \"X\"\n", Path::new("r.toml"));
        assert!(e[0].message.contains("did you mean `group`?"), "{}", e[0]);
        // and through `config validate`: exit-worthy, with file:line
        let d = tempfile::tempdir().unwrap();
        std::fs::create_dir(d.path().join("rules.d")).unwrap();
        std::fs::write(
            d.path().join("rules.d/10-mine.toml"),
            "[[rule]]\nkind = \"app\"\nlabel = \"X\"\n",
        )
        .unwrap();
        let r = validate_all(&opts(d.path()));
        assert!(!r.is_ok());
        assert!(
            r.errors[0]
                .to_string()
                .contains("10-mine.toml:1: unknown field `rule`"),
            "{:?}",
            r.errors
        );
    }

    #[test]
    fn rules_text_ok() {
        let ok = "[[group]]\nkind = \"agent_session\"\nlabel = \"Claude Code\"\nmatch.exe = [\"claude\"]\nsession_key = \"env:CLAUDE_CODE_SESSION_ID\"\n";
        assert!(validate_rules_text(ok, Path::new("r.toml")).is_empty());
    }
}