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
//! JSON Schemas (draft 2020-12) for every oomtop file (UX §12.9): editor autocomplete/validation via taplo or
//! VS Code (`#:schema ./schemas/oomtop-config.schema.json` or a taplo `[[rule]]`).
//!
//! - `config.toml`, `config.d/*.toml` — from [`crate::model::Config`] (schemars)
//! - `themes/*.toml` — generated from [`crate::theme::TOKENS`]
//! - `keymap.toml` — contexts × keys → [`crate::keymap::ACTIONS`]
//! - `layouts/*.toml` — from [`crate::layout::Layout`] (schemars)
//! - `rules.d/*.toml` — mirror of `oomtop_core::attribution::RuleSet` (tested to stay in sync)

use crate::keymap::{ACTIONS, ACTION_ALIASES, CONTEXTS, UNBIND};
use crate::theme::{Style, SECTIONS, TOKENS};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use std::path::{Path, PathBuf};

/// Which file a schema describes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SchemaKind {
    Config,
    Theme,
    Keymap,
    Layout,
    Rules,
}

pub const SCHEMA_KINDS: &[SchemaKind] = &[
    SchemaKind::Config,
    SchemaKind::Theme,
    SchemaKind::Keymap,
    SchemaKind::Layout,
    SchemaKind::Rules,
];

impl SchemaKind {
    pub fn as_str(self) -> &'static str {
        match self {
            SchemaKind::Config => "config",
            SchemaKind::Theme => "theme",
            SchemaKind::Keymap => "keymap",
            SchemaKind::Layout => "layout",
            SchemaKind::Rules => "rules",
        }
    }
    pub fn parse(s: &str) -> Option<SchemaKind> {
        SCHEMA_KINDS.iter().copied().find(|k| k.as_str() == s)
    }
    /// `oomtop-<kind>.schema.json`.
    pub fn file_name(self) -> String {
        format!("oomtop-{}.schema.json", self.as_str())
    }
    /// Glob of the files this schema applies to, relative to the config dir.
    pub fn applies_to(self) -> &'static [&'static str] {
        match self {
            SchemaKind::Config => &["config.toml", "config.d/*.toml"],
            SchemaKind::Theme => &["themes/*.toml"],
            SchemaKind::Keymap => &["keymap.toml"],
            SchemaKind::Layout => &["layouts/*.toml"],
            SchemaKind::Rules => &["rules.d/*.toml"],
        }
    }
}

fn to_value<T: JsonSchema>() -> Value {
    serde_json::to_value(schemars::schema_for!(T)).unwrap_or(Value::Null)
}

fn with_meta(mut v: Value, kind: SchemaKind, title: &str) -> Value {
    if let Some(o) = v.as_object_mut() {
        o.insert(
            "$id".into(),
            json!(format!("https://oomtop.dev/schemas/{}", kind.file_name())),
        );
        o.insert("title".into(), json!(title));
        o.insert(
            "$schema".into(),
            json!("https://json-schema.org/draft/2020-12/schema"),
        );
    }
    v
}

fn theme_schema() -> Value {
    let style = to_value::<Style>();
    let color = json!({
        "type": "string",
        "description": "ANSI index 0-255 or name (\"yellow\", \"bright-black\"), \"default\", \"#rrggbb\", or a token reference \"@ui.accent\"",
        "anyOf": [
            {"pattern": "^#[0-9a-fA-F]{6}$"},
            {"pattern": "^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$"},
            {"enum": ["black","red","green","yellow","blue","magenta","cyan","white","bright-black","bright-red","bright-green","bright-yellow","bright-blue","bright-magenta","bright-cyan","bright-white","default"]},
            {"pattern": format!("^@({})$", TOKENS.join("|").replace('.', "\\."))}
        ]
    });
    let mut style_obj = style.clone();
    if let Some(o) = style_obj.as_object_mut() {
        o.remove("$schema");
        o.remove("title");
        if let Some(Value::Object(props)) = o.get_mut("properties") {
            props.insert("fg".into(), color.clone());
            props.insert("bg".into(), color.clone());
        }
    }
    let token_value = json!({"anyOf": [ {"$ref": "#/$defs/color"}, {"$ref": "#/$defs/style"} ]});
    let mut props = Map::new();
    props.insert("name".into(), json!({"type": "string"}));
    props.insert(
        "inherits".into(),
        json!({"type": "string", "description": "parent theme (built-in or themes/<name>.toml)"}),
    );
    props.insert("appearance".into(), json!({"enum": ["dark", "light"]}));
    for sec in SECTIONS {
        let mut sp = Map::new();
        for t in TOKENS
            .iter()
            .filter_map(|t| t.strip_prefix(&format!("{sec}.") as &str))
        {
            sp.insert(t.to_string(), token_value.clone());
            // nested form: border.focus = { … } → [ui.border] focus
            if let Some((head, tail)) = t.split_once('.') {
                let entry = sp.entry(head.to_string()).or_insert_with(|| token_value.clone());
                let nested = json!({"anyOf": [
                    {"$ref": "#/$defs/color"}, {"$ref": "#/$defs/style"},
                    {"type": "object", "properties": {tail: token_value.clone()}}
                ]});
                *entry = nested;
            }
        }
        props.insert(
            sec.to_string(),
            json!({"type": "object", "properties": sp, "additionalProperties": false}),
        );
    }
    let v = json!({
        "type": "object",
        "properties": props,
        "additionalProperties": false,
        "$defs": { "color": color, "style": style_obj },
    });
    with_meta(v, SchemaKind::Theme, "oomtop theme (themes/<name>.toml)")
}

fn keymap_schema() -> Value {
    let mut actions: Vec<&str> = ACTIONS.to_vec();
    actions.extend(ACTION_ALIASES.iter().map(|(a, _)| *a));
    actions.push(UNBIND);
    let binds = json!({
        "type": "object",
        "description": "\"key\" = \"action\"; keys like \"x\", \"G\", \"ctrl-k\", \"F9\", chords \"g g\"",
        "additionalProperties": {"enum": actions},
    });
    let mut props = Map::new();
    for c in CONTEXTS {
        props.insert(c.to_string(), binds.clone());
    }
    with_meta(
        json!({"type": "object", "properties": props, "additionalProperties": false}),
        SchemaKind::Keymap,
        "oomtop keymap (keymap.toml)",
    )
}

/// Mirror of `oomtop_core::attribution::MatchSpec` for the schema.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct MatchSpecDoc {
    /// Globs against the executable basename and full path (e.g. "claude", "**/bin/sd-server").
    pub exe: Vec<String>,
    /// Globs against the short process name (comm).
    pub name: Vec<String>,
    /// Globs against any argv element after argv[0] (node/python scripts, java main classes).
    pub script: Vec<String>,
    /// Regexes against the space-joined command line.
    pub cmdline: Vec<String>,
    /// Marker keys (must be in privacy.marker_allowlist); groups carriers into the rule's session.
    pub env: Vec<String>,
    /// Globs against cwd.
    pub cwd: Vec<String>,
    /// Globs against the macOS bundle id.
    pub bundle: Vec<String>,
    /// Globs against the Linux cgroup path.
    pub cgroup: Vec<String>,
}

/// Group kinds accepted in rules (SPEC §5; short aliases too).
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum KindDoc {
    AgentSession,
    App,
    ModelServer,
    Sandbox,
    BuildDaemon,
    System,
    #[default]
    Other,
    Agent,
    Model,
    Daemon,
}

/// Mirror of `oomtop_core::attribution::Rule` for the schema.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct RuleDoc {
    /// Optional stable id; defaults to the label slug.
    pub id: Option<String>,
    pub kind: KindDoc,
    pub label: String,
    /// Identity match; fields are OR'd.
    #[serde(rename = "match")]
    pub matcher: MatchSpecDoc,
    pub exclude: Option<MatchSpecDoc>,
    /// "env:KEY" → one group per distinct (hashed) marker value.
    pub session_key: Option<String>,
    pub priority: i32,
    /// Matching processes are never offered for actions.
    pub protected: bool,
}

/// `rules.d/*.toml`: `[[group]]` tables.
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct RulesDoc {
    pub group: Vec<RuleDoc>,
}

/// The `config.toml` schema: the types from [`crate::model::Config`] plus the [`crate::semantic`] rules that
/// JSON Schema can express (minimum/maximum, enums, patterns), so an editor flags what `oomtop config
/// validate` would.
pub fn config_schema() -> Value {
    use crate::semantic as sem;
    let mut v = to_value::<crate::model::Config>();
    let mut set = |def: &str, prop: &str, extra: Value| {
        let target = v.pointer_mut(&format!("/$defs/{def}/properties/{prop}"));
        if let (Some(Value::Object(t)), Value::Object(extra)) = (target, extra) {
            for (k, val) in extra {
                t.insert(k, val);
            }
        }
    };
    let size = "^\\s*[0-9][0-9_]*(\\.[0-9]+)?\\s*([KkMmGgTt]([Ii]?[Bb]?)?|[Bb])?\\s*$";
    set("General", "refresh_ms", json!({"minimum": sem::MIN_REFRESH_MS}));
    set(
        "General",
        "host_refresh_ms",
        json!({"minimum": sem::MIN_REFRESH_MS}),
    );
    set(
        "General",
        "watch_poll_ms",
        json!({"anyOf": [{"const": 0}, {"minimum": 100}]}),
    );
    set("Thresholds", "idle_cpu_pct", json!({"minimum": 0}));
    set(
        "HeadroomSection",
        "min_margin",
        json!({"pattern": size, "description": "Minimum safety margin, a size such as \"1.5G\"."}),
    );
    set(
        "HeadroomSection",
        "margin_override",
        json!({"anyOf": [{"const": ""}, {"pattern": size}]}),
    );
    set(
        "HeadroomSection",
        "margin_pct",
        json!({"minimum": 0, "maximum": sem::MAX_MARGIN_PCT}),
    );
    set(
        "HeadroomSection",
        "pressure_boost_pct",
        json!({"minimum": 0, "maximum": sem::MAX_PRESSURE_BOOST_PCT}),
    );
    set(
        "Adapters",
        "timeout_ms",
        json!({"minimum": sem::MIN_ADAPTER_TIMEOUT_MS, "maximum": sem::MAX_ADAPTER_TIMEOUT_MS}),
    );
    set(
        "Adapters",
        "ports",
        json!({"additionalProperties": {"type": "integer", "minimum": 1, "maximum": 65535}}),
    );
    set(
        "Appearance",
        "theme",
        json!({
            "pattern": "^[^./\\\\][^/\\\\]*$",
            "description": format!(
                "A built-in theme ({}) or the name of a file in themes/.",
                crate::theme::BUILTIN_THEMES.join(", ")
            ),
        }),
    );
    set(
        "Appearance",
        "header",
        json!({"items": {"enum": sem::HEADER_ROWS}, "uniqueItems": true}),
    );
    set("Format", "decimals", json!({"maximum": sem::MAX_DECIMALS}));
    set("Keys", "preset", json!({"enum": crate::keymap::PRESETS}));
    set(
        "LayoutSel",
        "name",
        json!({"anyOf": [{"const": ""}, {"pattern": "^[^./\\\\][^/\\\\]*$"}]}),
    );
    set(
        "Personalization",
        "half_life_days",
        json!({"exclusiveMinimum": 0}),
    );
    set("Personalization", "retention_days", json!({"minimum": 1}));
    set("Personalization", "log_max_mb", json!({"minimum": 1}));
    set(
        "Serve",
        "listen",
        json!({"pattern": "^(\\[[0-9A-Fa-f:.]+\\]|[A-Za-z0-9][A-Za-z0-9.-]*):[0-9]{1,5}$"}),
    );
    with_meta(
        v,
        SchemaKind::Config,
        "oomtop configuration (config.toml, config.d/*.toml)",
    )
}

/// The schema of one file kind.
pub fn schema_for(kind: SchemaKind) -> Value {
    match kind {
        SchemaKind::Config => config_schema(),
        SchemaKind::Theme => theme_schema(),
        SchemaKind::Keymap => keymap_schema(),
        SchemaKind::Layout => with_meta(
            to_value::<crate::layout::Layout>(),
            kind,
            "oomtop layout (layouts/<name>.toml)",
        ),
        SchemaKind::Rules => with_meta(
            to_value::<RulesDoc>(),
            kind,
            "oomtop detection rules (rules.d/*.toml)",
        ),
    }
}

/// Pretty JSON of one schema.
pub fn schema_text(kind: SchemaKind) -> String {
    serde_json::to_string_pretty(&schema_for(kind)).unwrap_or_else(|_| "{}".into()) + "\n"
}

/// A taplo config (`.taplo.toml`) associating every file with its schema.
pub fn taplo_config(schema_dir: &str) -> String {
    let mut out = String::from("# generated by `oomtop config schema --write`\n");
    for k in SCHEMA_KINDS {
        out.push_str("\n[[rule]]\n");
        let globs: Vec<String> = k.applies_to().iter().map(|g| format!("\"{g}\"")).collect();
        out.push_str(&format!("include = [{}]\n", globs.join(", ")));
        out.push_str(&format!(
            "schema = {{ path = \"{schema_dir}/{}\" }}\n",
            k.file_name()
        ));
    }
    out
}

/// Writes every schema to `dir` (created); returns the files written.
pub fn write_schemas(dir: &Path) -> std::io::Result<Vec<PathBuf>> {
    std::fs::create_dir_all(dir)?;
    let mut out = Vec::new();
    for k in SCHEMA_KINDS {
        let p = dir.join(k.file_name());
        std::fs::write(&p, schema_text(*k))?;
        out.push(p);
    }
    Ok(out)
}

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

    #[test]
    fn every_schema_is_an_object_with_id() {
        for k in SCHEMA_KINDS {
            let v = schema_for(*k);
            assert!(v.is_object(), "{k:?}");
            assert!(v["$id"].as_str().unwrap().ends_with(&k.file_name()));
            assert_eq!(SchemaKind::parse(k.as_str()), Some(*k));
        }
        let theme = schema_text(SchemaKind::Theme);
        assert!(theme.contains("\"selection\""));
        assert!(theme.contains("\"spark\""));
        let km = schema_text(SchemaKind::Keymap);
        assert!(km.contains("\"open:cwd\"") && km.contains("\"details\""));
        let layout = schema_text(SchemaKind::Layout);
        assert!(layout.contains("\"split\"") && layout.contains("\"custom\""));
        let rules = schema_text(SchemaKind::Rules);
        assert!(rules.contains("\"session_key\"") && rules.contains("agent_session"));
    }

    #[test]
    fn rules_mirror_matches_core() {
        // a rule file valid for the mirror is valid for core, and every core field is in the mirror
        let text = r#"
[[group]]
id = "user:studio"
kind = "model_server"
label = "Qwen-Image studio"
match.exe = ["sd-server"]
match.script = ["**/studio.py"]
match.env = ["CLAUDECODE"]
exclude.name = ["sd-cli"]
session_key = "env:CLAUDE_CODE_SESSION_ID"
priority = 5
protected = false

[[group]]
kind = "daemon"
label = "Gradle"
match.cmdline = ["GradleDaemon"]
"#;
        let _: RulesDoc = toml::from_str(text).unwrap();
        let core: oomtop_core::attribution::RuleSet = toml::from_str(text).unwrap();
        assert_eq!(core.rules.len(), 2);
        // A stray top-level key (`[[groups]]`, `[[rule]]`, `version = 1`) is an error for core, so it is one
        // for the mirror and for the published schema too — never a rules file that silently does nothing.
        for stray in [
            "[[groups]]\nkind = \"app\"\nlabel = \"X\"\n",
            "[[rule]]\nkind = \"app\"\nlabel = \"X\"\n",
            "version = 1\n[[group]]\nkind = \"app\"\nlabel = \"X\"\n",
        ] {
            assert!(
                toml::from_str::<oomtop_core::attribution::RuleSet>(stray).is_err(),
                "core: {stray}"
            );
            assert!(toml::from_str::<RulesDoc>(stray).is_err(), "mirror: {stray}");
        }
        let schema = schema_for(SchemaKind::Rules);
        assert_eq!(schema["additionalProperties"], json!(false), "top level");
        assert_eq!(
            schema["properties"]
                .as_object()
                .unwrap()
                .keys()
                .collect::<Vec<_>>(),
            vec!["group"]
        );
        assert_eq!(schema["$defs"]["RuleDoc"]["additionalProperties"], json!(false));
        assert_eq!(
            schema["$defs"]["MatchSpecDoc"]["additionalProperties"],
            json!(false)
        );
        let core_rule = toml::Value::try_from(oomtop_core::attribution::Rule {
            exclude: Some(Default::default()),
            session_key: Some(String::new()),
            id: Some(String::new()),
            ..Default::default()
        })
        .unwrap();
        let mirror_rule = toml::Value::try_from(RuleDoc {
            exclude: Some(Default::default()),
            session_key: Some(String::new()),
            id: Some(String::new()),
            ..Default::default()
        })
        .unwrap();
        let keys = |v: &toml::Value| {
            let mut k: Vec<String> = v.as_table().unwrap().keys().cloned().collect();
            k.sort();
            k
        };
        assert_eq!(keys(&core_rule), keys(&mirror_rule));
        assert_eq!(keys(&core_rule["match"]), keys(&mirror_rule["match"]));
    }

    #[test]
    fn config_schema_carries_the_semantic_rules() {
        // regression: the schema said `minimum: 0` where `config validate` wants ≥ 250, and so on
        let v = config_schema();
        let at = |p: &str| {
            v.pointer(p)
                .cloned()
                .unwrap_or_else(|| panic!("{p} missing from the schema"))
        };
        assert_eq!(at("/$defs/General/properties/refresh_ms/minimum"), json!(250));
        assert_eq!(
            at("/$defs/General/properties/host_refresh_ms/minimum"),
            json!(250)
        );
        assert_eq!(at("/$defs/Format/properties/decimals/maximum"), json!(3));
        assert_eq!(at("/$defs/Adapters/properties/timeout_ms/minimum"), json!(10));
        assert_eq!(at("/$defs/Adapters/properties/timeout_ms/maximum"), json!(2000));
        assert_eq!(
            at("/$defs/HeadroomSection/properties/margin_pct/maximum"),
            json!(100.0)
        );
        assert_eq!(
            at("/$defs/Keys/properties/preset/enum"),
            json!(["default", "vim", "emacs", "htop"])
        );
        assert_eq!(
            at("/$defs/Appearance/properties/header/items/enum"),
            json!(crate::semantic::HEADER_ROWS)
        );
        assert!(at("/$defs/Serve/properties/listen/pattern").is_string());
        assert!(at("/$defs/HeadroomSection/properties/min_margin/pattern").is_string());
        // every default still satisfies what was added
        assert_eq!(at("/$defs/General/properties/refresh_ms/default"), json!(2000));
        assert_eq!(
            schema_text(SchemaKind::Config),
            crate::template::json_schema() + "\n"
        );
    }

    #[test]
    fn writes_all() {
        let d = tempfile::tempdir().unwrap();
        let files = write_schemas(d.path()).unwrap();
        assert_eq!(files.len(), 5);
        for f in files {
            let v: Value = serde_json::from_str(&std::fs::read_to_string(f).unwrap()).unwrap();
            assert!(v.is_object());
        }
        assert!(taplo_config("schemas").contains("themes/*.toml"));
    }
}