Skip to main content

lean_ctx/core/config/schema/
mod.rs

1//! Auto-generated config schema from `Config` struct metadata.
2//!
3//! Used by `lean-ctx config schema` to emit JSON and by
4//! `lean-ctx config validate` to check user config.toml files.
5
6use serde::Serialize;
7use std::collections::BTreeMap;
8mod sections_advanced;
9mod sections_core;
10mod sections_features;
11
12#[derive(Debug, Clone, Serialize)]
13pub struct ConfigSchema {
14    pub version: u32,
15    pub sections: BTreeMap<String, SectionSchema>,
16}
17
18#[derive(Debug, Clone, Serialize)]
19pub struct SectionSchema {
20    pub description: String,
21    pub keys: BTreeMap<String, KeySchema>,
22}
23
24#[derive(Debug, Clone, Serialize)]
25pub struct KeySchema {
26    #[serde(rename = "type")]
27    pub ty: String,
28    pub default: serde_json::Value,
29    pub description: String,
30    #[serde(skip_serializing_if = "Option::is_none")]
31    pub values: Option<Vec<String>>,
32    #[serde(skip_serializing_if = "Option::is_none")]
33    pub env_override: Option<String>,
34}
35
36fn clean_f32(v: f32) -> serde_json::Value {
37    let clean: f64 = format!("{v}").parse().unwrap_or(v as f64);
38    serde_json::json!(clean)
39}
40
41fn key(ty: &str, default: serde_json::Value, desc: &str) -> KeySchema {
42    KeySchema {
43        ty: ty.to_string(),
44        default,
45        description: desc.to_string(),
46        values: None,
47        env_override: None,
48    }
49}
50
51fn key_enum(values: &[&str], default: &str, desc: &str) -> KeySchema {
52    KeySchema {
53        ty: "enum".to_string(),
54        default: serde_json::Value::String(default.to_string()),
55        description: desc.to_string(),
56        values: Some(values.iter().map(ToString::to_string).collect()),
57        env_override: None,
58    }
59}
60
61fn key_with_env(ty: &str, default: serde_json::Value, desc: &str, env: &str) -> KeySchema {
62    KeySchema {
63        ty: ty.to_string(),
64        default,
65        description: desc.to_string(),
66        values: None,
67        env_override: Some(env.to_string()),
68    }
69}
70
71fn key_enum_with_env(values: &[&str], default: &str, desc: &str, env: &str) -> KeySchema {
72    KeySchema {
73        ty: "enum".to_string(),
74        default: serde_json::Value::String(default.to_string()),
75        description: desc.to_string(),
76        values: Some(values.iter().map(ToString::to_string).collect()),
77        env_override: Some(env.to_string()),
78    }
79}
80
81impl ConfigSchema {
82    pub fn generate() -> Self {
83        let mut sections = BTreeMap::new();
84        sections_core::build(&mut sections);
85        sections_features::build(&mut sections);
86        sections_advanced::build(&mut sections);
87        sections.insert("intelligence_runtime".into(), SectionSchema {
88            description: "Global-only optional runtime consent and independent staging pins; project overrides never apply".into(),
89            keys: [
90                ("enabled", key("bool", serde_json::json!(false), "Opt in to the verified local runtime")),
91                ("accept_proprietary", key("bool", serde_json::json!(false), "Explicit user acceptance of the separately licensed runtime")),
92                ("staging", key("bool", serde_json::json!(false), "Staging-only delivery; not production release approval")),
93                ("root", key("string", serde_json::json!(""), "Absolute private installation root")),
94                ("manifest_sha256", key("string", serde_json::json!(""), "Independently selected manifest digest")),
95                ("trust_key_hex", key("string", serde_json::json!(""), "Independently provisioned Ed25519 public key, lowercase hex")),
96                ("channel_url", key("string", serde_json::json!(""), "Explicit staging catalog URL; fetched only after consent")),
97                ("channel_signature_url", key("string", serde_json::json!(""), "Detached staging catalog signature URL")),
98                ("channel_root_key_hex", key("string", serde_json::json!(""), "Independently provisioned catalog root; never learned from a download")),
99                ("license_configuration", key("string", serde_json::json!(""), "Explicit user-global path to private license configuration; saved after installed device provisioning")),
100                ("context_policy_apply", key("bool", serde_json::json!(false), "Apply the promoted read-strategy policy in planning instead of recording it in shadow; security and explicit choices still win")),
101            ].into_iter().map(|(name, value)| (name.into(), value)).collect(),
102        });
103
104        ConfigSchema {
105            version: 1,
106            sections,
107        }
108    }
109
110    /// Looks up a key schema by its dot-separated TOML path.
111    /// Returns `None` if the key is not part of the schema.
112    pub fn lookup(&self, key: &str) -> Option<&KeySchema> {
113        if !key.contains('.') {
114            return self.sections.get("root")?.keys.get(key);
115        }
116        // Try progressively longer section prefixes so that dotted sections
117        // like `memory.lifecycle` or `solution.commercial.team_policy` resolve
118        // correctly: `memory.lifecycle.stale_days` → section=`memory.lifecycle`,
119        // field=`stale_days`.
120        for (i, _) in key.rmatch_indices('.') {
121            let section = &key[..i];
122            let field = &key[i + 1..];
123            if let Some(schema) = self.sections.get(section) {
124                if let Some(ks) = schema.keys.get(field) {
125                    return Some(ks);
126                }
127            }
128        }
129        None
130    }
131
132    /// All known TOML keys (dot-separated) for validation.
133    ///
134    /// Combines the hand-written schema (which carries descriptions, types and
135    /// help text) with the keys derived from the live `Config` struct. The
136    /// struct is the source of truth for *what is valid*, so a field added to
137    /// `Config` is recognised by `config apply` / `config validate` immediately,
138    /// without anyone remembering to mirror it into `sections_*.rs` (#456).
139    pub fn known_keys(&self) -> Vec<String> {
140        let mut keys = Vec::new();
141        for (section, schema) in &self.sections {
142            if section == "root" {
143                for key_name in schema.keys.keys() {
144                    keys.push(key_name.clone());
145                }
146            } else {
147                if schema.keys.is_empty() {
148                    keys.push(section.clone());
149                }
150                for key_name in schema.keys.keys() {
151                    keys.push(format!("{section}.{key_name}"));
152                }
153            }
154        }
155        keys.extend(config_derived_keys());
156        keys.sort();
157        keys.dedup();
158        keys
159    }
160}
161
162/// Every TOML key the `Config` struct serialises to, in dot-separated form
163/// (e.g. `proxy_require_token`, `memory`, `memory.episodic`). Derived from
164/// `Config::default()` so validation tracks the struct automatically (#456).
165///
166/// Option fields that default to `None` are omitted by serde and therefore not
167/// listed here; those keys still come from the hand-written schema. Emitting the
168/// bare section name (e.g. `memory`) lets the `starts_with("section.")` rule in
169/// the validators accept the whole section, matching how empty schema sections
170/// already behave.
171fn config_derived_keys() -> Vec<String> {
172    fn walk(table: &toml::value::Table, prefix: &str, out: &mut Vec<String>) {
173        for (k, v) in table {
174            let full = if prefix.is_empty() {
175                k.clone()
176            } else {
177                format!("{prefix}.{k}")
178            };
179            if let toml::Value::Table(sub) = v {
180                out.push(full.clone());
181                walk(sub, &full, out);
182            } else {
183                out.push(full);
184            }
185        }
186    }
187
188    let mut out = Vec::new();
189    if let Ok(toml::Value::Table(table)) =
190        toml::Value::try_from(crate::core::config::Config::default())
191    {
192        walk(&table, "", &mut out);
193    }
194    out
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    /// Mirrors the acceptance rule used by `config validate` / `config apply`:
202    /// a key is valid if it is listed verbatim or sits under a known section.
203    fn accepted(known: &[String], key: &str) -> bool {
204        known.iter().any(|k| k == key) || known.iter().any(|k| key.starts_with(&format!("{k}.")))
205    }
206
207    /// #456: every field the `Config` struct actually serialises must be
208    /// accepted by validation. Before the fix, 38 real keys/sections
209    /// (`proxy_require_token`, `memory.*`, `providers.*`, `proxy`, …) were
210    /// flagged "unknown" because the hand-written schema had drifted.
211    #[test]
212    fn known_keys_cover_every_config_struct_field() {
213        let known = ConfigSchema::generate().known_keys();
214        let missing: Vec<_> = config_derived_keys()
215            .into_iter()
216            .filter(|k| !accepted(&known, k))
217            .collect();
218        assert!(
219            missing.is_empty(),
220            "config struct fields not recognised by validation (schema drift): {missing:?}"
221        );
222    }
223
224    /// Spot-check the concrete keys from the #456 report so a future schema/struct
225    /// refactor that reintroduces the drift fails loudly.
226    #[test]
227    fn known_keys_recognise_reported_456_keys() {
228        let known = ConfigSchema::generate().known_keys();
229        for key in [
230            "proxy_require_token",
231            "allow_ide_config_dirs",
232            "memory.episodic",
233            "providers.github",
234            "proxy",
235        ] {
236            assert!(
237                accepted(&known, key),
238                "validation must recognise '{key}' (#456)"
239            );
240        }
241    }
242
243    /// `config set` resolves keys via [`ConfigSchema::lookup`] — the hand-written
244    /// schema only, NOT `known_keys()` (which also folds in `config_derived_keys`).
245    /// An `Option<_>` scalar field defaults to `None`, so serde omits it from
246    /// `Config::default()` and it never appears in `config_derived_keys`: such a
247    /// field is settable via `config set` **only** if it was hand-added to a
248    /// `sections_*.rs` schema. Forgetting that is the `Unknown config key: <x>`
249    /// regression a user hit for `path_jail` before #507 (and `persona` /
250    /// `bypass_hints` here). Guard the whole class so a new `Option` knob can't
251    /// silently become un-settable again — if you add an `Option` scalar to
252    /// `Config`, register it in `sections_*.rs` and list it here.
253    #[test]
254    fn option_scalar_keys_are_cli_settable() {
255        let schema = ConfigSchema::generate();
256        for key in [
257            "path_jail",
258            "persona",
259            "bypass_hints",
260            "shell_security",
261            "cache_policy",
262            "profile",
263            "tool_profile",
264            "rules_scope",
265            "rules_injection",
266            "permission_inheritance",
267            "proxy_enabled",
268            "proxy_port",
269            "proxy_timeout_ms",
270        ] {
271            assert!(
272                schema.lookup(key).is_some(),
273                "`lean-ctx config set {key} <v>` fails with 'Unknown config key' — \
274                 add `{key}` to a sections_*.rs schema"
275            );
276        }
277    }
278
279    #[test]
280    fn proxy_require_token_is_cli_settable() {
281        let schema = ConfigSchema::generate();
282        assert!(
283            schema.lookup("proxy_require_token").is_some(),
284            "`lean-ctx config set proxy_require_token <bool>` must be accepted"
285        );
286    }
287
288    #[test]
289    fn dotted_section_keys_are_cli_settable() {
290        let schema = ConfigSchema::generate();
291        for key in [
292            "memory.lifecycle.stale_days",
293            "memory.knowledge.max_facts",
294            "memory.episodic.max_episodes",
295            "solution.commercial.fingerprints_enabled",
296            "solution.commercial.cross_project_patterns",
297            "solution.commercial.adaptive.enabled",
298            "solution.commercial.adaptive.learning_rate",
299            "solution.commercial.team_policy.enabled",
300            "solution.commercial.team_policy.min_intensity",
301            "proxy.role_aggressiveness.system",
302        ] {
303            assert!(
304                schema.lookup(key).is_some(),
305                "`lean-ctx config set {key} <v>` fails with \"Unknown config key\" — lookup must handle dotted section names"
306            );
307        }
308    }
309
310    #[test]
311    fn decision_loop_keys_are_cli_settable_with_types_and_defaults() {
312        let schema = ConfigSchema::generate();
313        for (key, ty, default) in [
314            ("decision_loop.enabled", "bool", serde_json::json!(true)),
315            ("decision_loop.max_filter_level", "u8", serde_json::json!(0)),
316        ] {
317            let entry = schema
318                .lookup(key)
319                .unwrap_or_else(|| panic!("config set {key} must be recognized"));
320            assert_eq!(entry.ty, ty, "schema type for {key}");
321            assert_eq!(entry.default, default, "schema default for {key}");
322        }
323    }
324
325    #[test]
326    fn permission_inheritance_defaults_to_on() {
327        let cfg = super::super::Config::default();
328        assert_eq!(
329            cfg.permission_inheritance.as_deref(),
330            Some("on"),
331            "permission_inheritance must default to On so IDE permission rules are honored out of the box"
332        );
333    }
334
335    /// #1605: the `[llm]` schema was hand-written with literal defaults and had
336    /// drifted from `LlmConfig` — it named an `api_key` key that no field backs
337    /// (so `config set llm.api_key <secret>` printed "Updated" and then dropped
338    /// the value in the serde round-trip), advertised `llama3.2` as the model
339    /// default, and omitted `base_url` entirely. Every `[llm]` schema key must
340    /// name a real serialised field, and its default must be the struct's.
341    #[test]
342    fn llm_schema_keys_match_the_llm_config_struct() {
343        let schema = ConfigSchema::generate();
344        let section = schema
345            .sections
346            .get("llm")
347            .expect("[llm] section must exist in the schema");
348        let defaults = serde_json::to_value(crate::core::llm_enhance::LlmConfig::default())
349            .expect("LlmConfig serialises");
350        let defaults = defaults.as_object().expect("LlmConfig is a struct");
351
352        for (key, entry) in &section.keys {
353            let actual = defaults.get(key).unwrap_or_else(|| {
354                panic!(
355                    "schema key `llm.{key}` has no field on LlmConfig — \
356                     `config set llm.{key} <v>` would report a save that serde discards"
357                )
358            });
359            // `Option<String>` serialises as null; the schema shows an empty string.
360            let expected = if actual.is_null() {
361                serde_json::json!("")
362            } else {
363                actual.clone()
364            };
365            assert_eq!(
366                entry.default, expected,
367                "schema default for `llm.{key}` has drifted from LlmConfig::default()"
368            );
369        }
370
371        assert!(
372            schema.lookup("llm.api_key").is_none(),
373            "`llm.api_key` is not a config field — the credential comes from \
374             OPENROUTER_API_KEY / ANTHROPIC_API_KEY, so `config set` must reject it"
375        );
376        assert!(
377            schema.lookup("llm.base_url").is_some(),
378            "`llm.base_url` is a real field and must be settable"
379        );
380    }
381}