lean_ctx/core/config/schema/
mod.rs1use 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
88 ConfigSchema {
89 version: 1,
90 sections,
91 }
92 }
93
94 pub fn lookup(&self, key: &str) -> Option<&KeySchema> {
97 if !key.contains('.') {
98 return self.sections.get("root")?.keys.get(key);
99 }
100 for (i, _) in key.rmatch_indices('.') {
105 let section = &key[..i];
106 let field = &key[i + 1..];
107 if let Some(schema) = self.sections.get(section) {
108 if let Some(ks) = schema.keys.get(field) {
109 return Some(ks);
110 }
111 }
112 }
113 None
114 }
115
116 pub fn known_keys(&self) -> Vec<String> {
124 let mut keys = Vec::new();
125 for (section, schema) in &self.sections {
126 if section == "root" {
127 for key_name in schema.keys.keys() {
128 keys.push(key_name.clone());
129 }
130 } else {
131 if schema.keys.is_empty() {
132 keys.push(section.clone());
133 }
134 for key_name in schema.keys.keys() {
135 keys.push(format!("{section}.{key_name}"));
136 }
137 }
138 }
139 keys.extend(config_derived_keys());
140 keys.sort();
141 keys.dedup();
142 keys
143 }
144}
145
146fn config_derived_keys() -> Vec<String> {
156 fn walk(table: &toml::value::Table, prefix: &str, out: &mut Vec<String>) {
157 for (k, v) in table {
158 let full = if prefix.is_empty() {
159 k.clone()
160 } else {
161 format!("{prefix}.{k}")
162 };
163 if let toml::Value::Table(sub) = v {
164 out.push(full.clone());
165 walk(sub, &full, out);
166 } else {
167 out.push(full);
168 }
169 }
170 }
171
172 let mut out = Vec::new();
173 if let Ok(toml::Value::Table(table)) =
174 toml::Value::try_from(crate::core::config::Config::default())
175 {
176 walk(&table, "", &mut out);
177 }
178 out
179}
180
181#[cfg(test)]
182mod tests {
183 use super::*;
184
185 fn accepted(known: &[String], key: &str) -> bool {
188 known.iter().any(|k| k == key) || known.iter().any(|k| key.starts_with(&format!("{k}.")))
189 }
190
191 #[test]
196 fn known_keys_cover_every_config_struct_field() {
197 let known = ConfigSchema::generate().known_keys();
198 let missing: Vec<_> = config_derived_keys()
199 .into_iter()
200 .filter(|k| !accepted(&known, k))
201 .collect();
202 assert!(
203 missing.is_empty(),
204 "config struct fields not recognised by validation (schema drift): {missing:?}"
205 );
206 }
207
208 #[test]
211 fn known_keys_recognise_reported_456_keys() {
212 let known = ConfigSchema::generate().known_keys();
213 for key in [
214 "proxy_require_token",
215 "allow_ide_config_dirs",
216 "memory.episodic",
217 "providers.github",
218 "proxy",
219 ] {
220 assert!(
221 accepted(&known, key),
222 "validation must recognise '{key}' (#456)"
223 );
224 }
225 }
226
227 #[test]
238 fn option_scalar_keys_are_cli_settable() {
239 let schema = ConfigSchema::generate();
240 for key in [
241 "path_jail",
242 "persona",
243 "bypass_hints",
244 "shell_security",
245 "cache_policy",
246 "profile",
247 "tool_profile",
248 "rules_scope",
249 "rules_injection",
250 "permission_inheritance",
251 "proxy_enabled",
252 "proxy_port",
253 "proxy_timeout_ms",
254 ] {
255 assert!(
256 schema.lookup(key).is_some(),
257 "`lean-ctx config set {key} <v>` fails with 'Unknown config key' — \
258 add `{key}` to a sections_*.rs schema"
259 );
260 }
261 }
262
263 #[test]
264 fn proxy_require_token_is_cli_settable() {
265 let schema = ConfigSchema::generate();
266 assert!(
267 schema.lookup("proxy_require_token").is_some(),
268 "`lean-ctx config set proxy_require_token <bool>` must be accepted"
269 );
270 }
271
272 #[test]
273 fn dotted_section_keys_are_cli_settable() {
274 let schema = ConfigSchema::generate();
275 for key in [
276 "memory.lifecycle.stale_days",
277 "memory.knowledge.max_facts",
278 "memory.episodic.max_episodes",
279 "solution.commercial.fingerprints_enabled",
280 "solution.commercial.cross_project_patterns",
281 "solution.commercial.adaptive.enabled",
282 "solution.commercial.adaptive.learning_rate",
283 "solution.commercial.team_policy.enabled",
284 "solution.commercial.team_policy.min_intensity",
285 "proxy.role_aggressiveness.system",
286 ] {
287 assert!(
288 schema.lookup(key).is_some(),
289 "`lean-ctx config set {key} <v>` fails with \"Unknown config key\" — lookup must handle dotted section names"
290 );
291 }
292 }
293
294 #[test]
295 fn decision_loop_keys_are_cli_settable_with_types_and_defaults() {
296 let schema = ConfigSchema::generate();
297 for (key, ty, default) in [
298 ("decision_loop.enabled", "bool", serde_json::json!(true)),
299 ("decision_loop.max_filter_level", "u8", serde_json::json!(0)),
300 ] {
301 let entry = schema
302 .lookup(key)
303 .unwrap_or_else(|| panic!("config set {key} must be recognized"));
304 assert_eq!(entry.ty, ty, "schema type for {key}");
305 assert_eq!(entry.default, default, "schema default for {key}");
306 }
307 }
308
309 #[test]
310 fn permission_inheritance_defaults_to_on() {
311 let cfg = super::super::Config::default();
312 assert_eq!(
313 cfg.permission_inheritance.as_deref(),
314 Some("on"),
315 "permission_inheritance must default to On so IDE permission rules are honored out of the box"
316 );
317 }
318
319 #[test]
326 fn llm_schema_keys_match_the_llm_config_struct() {
327 let schema = ConfigSchema::generate();
328 let section = schema
329 .sections
330 .get("llm")
331 .expect("[llm] section must exist in the schema");
332 let defaults = serde_json::to_value(crate::core::llm_enhance::LlmConfig::default())
333 .expect("LlmConfig serialises");
334 let defaults = defaults.as_object().expect("LlmConfig is a struct");
335
336 for (key, entry) in §ion.keys {
337 let actual = defaults.get(key).unwrap_or_else(|| {
338 panic!(
339 "schema key `llm.{key}` has no field on LlmConfig — \
340 `config set llm.{key} <v>` would report a save that serde discards"
341 )
342 });
343 let expected = if actual.is_null() {
345 serde_json::json!("")
346 } else {
347 actual.clone()
348 };
349 assert_eq!(
350 entry.default, expected,
351 "schema default for `llm.{key}` has drifted from LlmConfig::default()"
352 );
353 }
354
355 assert!(
356 schema.lookup("llm.api_key").is_none(),
357 "`llm.api_key` is not a config field — the credential comes from \
358 OPENROUTER_API_KEY / ANTHROPIC_API_KEY, so `config set` must reject it"
359 );
360 assert!(
361 schema.lookup("llm.base_url").is_some(),
362 "`llm.base_url` is a real field and must be settable"
363 );
364 }
365}