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
81/// `hook_mode` (root section); kept here so `sections_core.rs` stays under the
82/// LOC gate.
83fn hook_mode_key() -> KeySchema {
84    key_enum_with_env(
85        &["auto", "hybrid", "replace", "mcp"],
86        "auto",
87        "How lean-ctx integrates with agents. auto (default): Hybrid for every \
88         hook-capable agent — native calls are not refused, known commands are \
89         rewritten through lean-ctx; Claude Code's tool list leaves out native \
90         Grep/Glob (no refusals, searches stay compressed). hybrid: the same, \
91         with Grep/Glob back in Claude Code. replace: deny native \
92         Grep/Glob (and non-rewritable shell where the host supports it) so \
93         ctx_* MCP tools are the only path; also set by `lean-ctx harden \
94         --hard`. mcp: MCP server only, no hooks",
95        "LEAN_CTX_HOOK_MODE",
96    )
97}
98
99/// `daemon_max_rss_mb` (root section); kept here so `sections_core.rs` stays
100/// under the LOC gate.
101fn daemon_max_rss_key(cfg: &crate::core::config::Config) -> KeySchema {
102    key_with_env(
103        "u64",
104        serde_json::json!(cfg.daemon_max_rss_mb),
105        "Process RSS target (MB) of the background daemon; the guardian evicts above \
106         the lower of this and max_ram_percent (default 2048, 0 = percent only)",
107        "LEAN_CTX_DAEMON_MAX_RSS_MB",
108    )
109}
110
111/// The global-only signer-trust opt-ins (root section); kept here so
112/// `sections_core.rs` stays under the LOC gate.
113fn signer_trust_keys() -> [(&'static str, KeySchema); 2] {
114    [
115        (
116            "a2a_accept_untrusted_signers",
117            key(
118                "bool",
119                serde_json::json!(false),
120                "Accept A2A handoff bundles and context packages (/v1/a2a/handoff, /a2a/deliver) signed by a key that is not pinned in trusted-signers.toml. Off by default: such signatures prove integrity, not who sent them, so they are rejected with 403 untrusted_signer. Global-only",
121            ),
122        ),
123        (
124            "mcp_import_allow_unverified",
125            key(
126                "bool",
127                serde_json::json!(false),
128                "Let MCP tools (ctx_handoff import, ctx_pack import) import bundles and packages that are unsigned or signed by a key not pinned in trusted-signers.toml. A tool argument cannot grant this (prompt injection); CLI imports keep --allow-unsigned. Global-only",
129            ),
130        ),
131    ]
132}
133
134impl ConfigSchema {
135    pub fn generate() -> Self {
136        let mut sections = BTreeMap::new();
137        sections_core::build(&mut sections);
138        sections_features::build(&mut sections);
139        sections_advanced::build(&mut sections);
140        sections.insert("hive".into(), crate::core::hive::config::schema_section());
141        sections.insert("intelligence_runtime".into(), SectionSchema {
142            description: "Global-only optional runtime consent and independent staging pins; project overrides never apply".into(),
143            keys: [
144                ("enabled", key("bool", serde_json::json!(false), "Opt in to the verified local runtime")),
145                ("accept_proprietary", key("bool", serde_json::json!(false), "Explicit user acceptance of the separately licensed runtime")),
146                ("staging", key("bool", serde_json::json!(false), "Staging-only delivery; not production release approval")),
147                ("root", key("string", serde_json::json!(""), "Absolute private installation root")),
148                ("manifest_sha256", key("string", serde_json::json!(""), "Independently selected manifest digest")),
149                ("trust_key_hex", key("string", serde_json::json!(""), "Independently provisioned Ed25519 public key, lowercase hex")),
150                ("channel_url", key("string", serde_json::json!(""), "Explicit staging catalog URL; fetched only after consent")),
151                ("channel_signature_url", key("string", serde_json::json!(""), "Detached staging catalog signature URL")),
152                ("channel_root_key_hex", key("string", serde_json::json!(""), "Independently provisioned catalog root; never learned from a download")),
153                ("license_configuration", key("string", serde_json::json!(""), "Explicit user-global path to private license configuration; saved after installed device provisioning")),
154                ("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")),
155                ("team_artifact_projects", key("array", serde_json::json!([]), "Projects that read shared team artifacts: tables of root (absolute), organization_id, project_id and repository_id. Empty: no project uses an artifact")),
156            ].into_iter().map(|(name, value)| (name.into(), value)).collect(),
157        });
158
159        ConfigSchema {
160            version: 1,
161            sections,
162        }
163    }
164
165    /// Looks up a key schema by its dot-separated TOML path.
166    /// Returns `None` if the key is not part of the schema.
167    pub fn lookup(&self, key: &str) -> Option<&KeySchema> {
168        if !key.contains('.') {
169            return self.sections.get("root")?.keys.get(key);
170        }
171        // Try progressively longer section prefixes so that dotted sections
172        // like `memory.lifecycle` or `proxy.role_aggressiveness` resolve
173        // correctly: `memory.lifecycle.stale_days` → section=`memory.lifecycle`,
174        // field=`stale_days`.
175        for (i, _) in key.rmatch_indices('.') {
176            let section = &key[..i];
177            let field = &key[i + 1..];
178            if let Some(schema) = self.sections.get(section) {
179                if let Some(ks) = schema.keys.get(field) {
180                    return Some(ks);
181                }
182            }
183        }
184        None
185    }
186
187    /// All known TOML keys (dot-separated) for validation.
188    ///
189    /// Combines the hand-written schema (which carries descriptions, types and
190    /// help text) with the keys derived from the live `Config` struct. The
191    /// struct is the source of truth for *what is valid*, so a field added to
192    /// `Config` is recognised by `config apply` / `config validate` immediately,
193    /// without anyone remembering to mirror it into `sections_*.rs` (#456).
194    pub fn known_keys(&self) -> Vec<String> {
195        let mut keys = Vec::new();
196        for (section, schema) in &self.sections {
197            if section == "root" {
198                for key_name in schema.keys.keys() {
199                    keys.push(key_name.clone());
200                }
201            } else {
202                if schema.keys.is_empty() {
203                    keys.push(section.clone());
204                }
205                for key_name in schema.keys.keys() {
206                    keys.push(format!("{section}.{key_name}"));
207                }
208            }
209        }
210        keys.extend(config_derived_keys());
211        keys.sort();
212        keys.dedup();
213        keys
214    }
215}
216
217/// Every TOML key the `Config` struct serialises to, in dot-separated form
218/// (e.g. `proxy_require_token`, `memory`, `memory.episodic`). Derived from
219/// `Config::default()` so validation tracks the struct automatically (#456).
220///
221/// Option fields that default to `None` are omitted by serde and therefore not
222/// listed here; those keys still come from the hand-written schema. Emitting the
223/// bare section name (e.g. `memory`) lets the `starts_with("section.")` rule in
224/// the validators accept the whole section, matching how empty schema sections
225/// already behave.
226fn config_derived_keys() -> Vec<String> {
227    fn walk(table: &toml::value::Table, prefix: &str, out: &mut Vec<String>) {
228        for (k, v) in table {
229            let full = if prefix.is_empty() {
230                k.clone()
231            } else {
232                format!("{prefix}.{k}")
233            };
234            if let toml::Value::Table(sub) = v {
235                out.push(full.clone());
236                walk(sub, &full, out);
237            } else {
238                out.push(full);
239            }
240        }
241    }
242
243    let mut out = Vec::new();
244    if let Ok(toml::Value::Table(table)) =
245        toml::Value::try_from(crate::core::config::Config::default())
246    {
247        walk(&table, "", &mut out);
248    }
249    out
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255
256    /// Mirrors the acceptance rule used by `config validate` / `config apply`:
257    /// a key is valid if it is listed verbatim or sits under a known section.
258    fn accepted(known: &[String], key: &str) -> bool {
259        known.iter().any(|k| k == key) || known.iter().any(|k| key.starts_with(&format!("{k}.")))
260    }
261
262    /// #456: every field the `Config` struct actually serialises must be
263    /// accepted by validation. Before the fix, 38 real keys/sections
264    /// (`proxy_require_token`, `memory.*`, `providers.*`, `proxy`, …) were
265    /// flagged "unknown" because the hand-written schema had drifted.
266    #[test]
267    fn known_keys_cover_every_config_struct_field() {
268        let known = ConfigSchema::generate().known_keys();
269        let missing: Vec<_> = config_derived_keys()
270            .into_iter()
271            .filter(|k| !accepted(&known, k))
272            .collect();
273        assert!(
274            missing.is_empty(),
275            "config struct fields not recognised by validation (schema drift): {missing:?}"
276        );
277    }
278
279    /// Spot-check the concrete keys from the #456 report so a future schema/struct
280    /// refactor that reintroduces the drift fails loudly.
281    #[test]
282    fn known_keys_recognise_reported_456_keys() {
283        let known = ConfigSchema::generate().known_keys();
284        for key in [
285            "proxy_require_token",
286            "allow_ide_config_dirs",
287            "memory.episodic",
288            "providers.github",
289            "proxy",
290        ] {
291            assert!(
292                accepted(&known, key),
293                "validation must recognise '{key}' (#456)"
294            );
295        }
296    }
297
298    /// `config set` resolves keys via [`ConfigSchema::lookup`] — the hand-written
299    /// schema only, NOT `known_keys()` (which also folds in `config_derived_keys`).
300    /// An `Option<_>` scalar field defaults to `None`, so serde omits it from
301    /// `Config::default()` and it never appears in `config_derived_keys`: such a
302    /// field is settable via `config set` **only** if it was hand-added to a
303    /// `sections_*.rs` schema. Forgetting that is the `Unknown config key: <x>`
304    /// regression a user hit for `path_jail` before #507 (and `persona` /
305    /// `bypass_hints` here). Guard the whole class so a new `Option` knob can't
306    /// silently become un-settable again — if you add an `Option` scalar to
307    /// `Config`, register it in `sections_*.rs` and list it here.
308    #[test]
309    fn option_scalar_keys_are_cli_settable() {
310        let schema = ConfigSchema::generate();
311        for key in [
312            "path_jail",
313            "path_jail_scope",
314            "persona",
315            "bypass_hints",
316            "shell_security",
317            "cache_policy",
318            "profile",
319            "tool_profile",
320            "rules_scope",
321            "rules_injection",
322            "permission_inheritance",
323            "proxy_enabled",
324            "proxy_port",
325            "proxy_timeout_ms",
326        ] {
327            assert!(
328                schema.lookup(key).is_some(),
329                "`lean-ctx config set {key} <v>` fails with 'Unknown config key' — \
330                 add `{key}` to a sections_*.rs schema"
331            );
332        }
333    }
334
335    #[test]
336    fn proxy_require_token_is_cli_settable() {
337        let schema = ConfigSchema::generate();
338        assert!(
339            schema.lookup("proxy_require_token").is_some(),
340            "`lean-ctx config set proxy_require_token <bool>` must be accepted"
341        );
342    }
343
344    #[test]
345    fn dotted_section_keys_are_cli_settable() {
346        let schema = ConfigSchema::generate();
347        for key in [
348            "memory.lifecycle.stale_days",
349            "memory.knowledge.max_facts",
350            "memory.episodic.max_episodes",
351            "proxy.role_aggressiveness.system",
352        ] {
353            assert!(
354                schema.lookup(key).is_some(),
355                "`lean-ctx config set {key} <v>` fails with \"Unknown config key\" — lookup must handle dotted section names"
356            );
357        }
358    }
359
360    #[test]
361    fn decision_loop_keys_are_cli_settable_with_types_and_defaults() {
362        let schema = ConfigSchema::generate();
363        for (key, ty, default) in [
364            ("decision_loop.enabled", "bool", serde_json::json!(true)),
365            ("decision_loop.max_filter_level", "u8", serde_json::json!(0)),
366        ] {
367            let entry = schema
368                .lookup(key)
369                .unwrap_or_else(|| panic!("config set {key} must be recognized"));
370            assert_eq!(entry.ty, ty, "schema type for {key}");
371            assert_eq!(entry.default, default, "schema default for {key}");
372        }
373    }
374
375    #[test]
376    fn permission_inheritance_defaults_to_on() {
377        let cfg = super::super::Config::default();
378        assert_eq!(
379            cfg.permission_inheritance.as_deref(),
380            Some("on"),
381            "permission_inheritance must default to On so IDE permission rules are honored out of the box"
382        );
383    }
384
385    /// #1605: the `[llm]` schema was hand-written with literal defaults and had
386    /// drifted from `LlmConfig` — it named an `api_key` key that no field backs
387    /// (so `config set llm.api_key <secret>` printed "Updated" and then dropped
388    /// the value in the serde round-trip), advertised `llama3.2` as the model
389    /// default, and omitted `base_url` entirely. Every `[llm]` schema key must
390    /// name a real serialised field, and its default must be the struct's.
391    #[test]
392    fn llm_schema_keys_match_the_llm_config_struct() {
393        let schema = ConfigSchema::generate();
394        let section = schema
395            .sections
396            .get("llm")
397            .expect("[llm] section must exist in the schema");
398        let defaults = serde_json::to_value(crate::core::llm_enhance::LlmConfig::default())
399            .expect("LlmConfig serialises");
400        let defaults = defaults.as_object().expect("LlmConfig is a struct");
401
402        for (key, entry) in &section.keys {
403            let actual = defaults.get(key).unwrap_or_else(|| {
404                panic!(
405                    "schema key `llm.{key}` has no field on LlmConfig — \
406                     `config set llm.{key} <v>` would report a save that serde discards"
407                )
408            });
409            // `Option<String>` serialises as null; the schema shows an empty string.
410            let expected = if actual.is_null() {
411                serde_json::json!("")
412            } else {
413                actual.clone()
414            };
415            assert_eq!(
416                entry.default, expected,
417                "schema default for `llm.{key}` has drifted from LlmConfig::default()"
418            );
419        }
420
421        assert!(
422            schema.lookup("llm.api_key").is_none(),
423            "`llm.api_key` is not a config field — the credential comes from \
424             OPENROUTER_API_KEY / ANTHROPIC_API_KEY, so `config set` must reject it"
425        );
426        assert!(
427            schema.lookup("llm.base_url").is_some(),
428            "`llm.base_url` is a real field and must be settable"
429        );
430    }
431}