1use serde::Serialize;
7use std::collections::BTreeMap;
8#[cfg(test)]
9mod drift_tests;
10mod sections_advanced;
11mod sections_core;
12mod sections_features;
13
14#[derive(Debug, Clone, Serialize)]
15pub struct ConfigSchema {
16 pub version: u32,
17 pub sections: BTreeMap<String, SectionSchema>,
18}
19
20#[derive(Debug, Clone, Serialize)]
21pub struct SectionSchema {
22 pub description: String,
23 pub keys: BTreeMap<String, KeySchema>,
24}
25
26#[derive(Debug, Clone, Serialize)]
27pub struct KeySchema {
28 #[serde(rename = "type")]
29 pub ty: String,
30 pub default: serde_json::Value,
31 pub description: String,
32 #[serde(skip_serializing_if = "Option::is_none")]
33 pub values: Option<Vec<String>>,
34 #[serde(skip_serializing_if = "Option::is_none")]
35 pub env_override: Option<String>,
36}
37
38fn clean_f32(v: f32) -> serde_json::Value {
39 let clean: f64 = format!("{v}").parse().unwrap_or(v as f64);
40 serde_json::json!(clean)
41}
42
43fn key(ty: &str, default: serde_json::Value, desc: &str) -> KeySchema {
44 KeySchema {
45 ty: ty.to_string(),
46 default,
47 description: desc.to_string(),
48 values: None,
49 env_override: None,
50 }
51}
52
53fn key_enum(values: &[&str], default: &str, desc: &str) -> KeySchema {
54 KeySchema {
55 ty: "enum".to_string(),
56 default: serde_json::Value::String(default.to_string()),
57 description: desc.to_string(),
58 values: Some(values.iter().map(ToString::to_string).collect()),
59 env_override: None,
60 }
61}
62
63fn key_with_env(ty: &str, default: serde_json::Value, desc: &str, env: &str) -> KeySchema {
64 KeySchema {
65 ty: ty.to_string(),
66 default,
67 description: desc.to_string(),
68 values: None,
69 env_override: Some(env.to_string()),
70 }
71}
72
73fn key_enum_with_env(values: &[&str], default: &str, desc: &str, env: &str) -> KeySchema {
74 KeySchema {
75 ty: "enum".to_string(),
76 default: serde_json::Value::String(default.to_string()),
77 description: desc.to_string(),
78 values: Some(values.iter().map(ToString::to_string).collect()),
79 env_override: Some(env.to_string()),
80 }
81}
82
83fn governor_section() -> SectionSchema {
85 let modes = ["on", "shadow", "off"];
86 let mut keys = BTreeMap::new();
87 for (rule, builtin, env, what) in [
88 (
89 "r1_read",
90 "on",
91 "LEAN_CTX_GOVERNOR_R1_READ",
92 "identical re-read of an unchanged file",
93 ),
94 (
95 "r1_bash",
96 "shadow",
97 "LEAN_CTX_GOVERNOR_R1_BASH",
98 "identical re-run of a viewer command",
99 ),
100 (
101 "r2",
102 "shadow",
103 "LEAN_CTX_GOVERNOR_R2",
104 "lossless repeat collapse of large Bash output",
105 ),
106 (
107 "r3",
108 "shadow",
109 "LEAN_CTX_GOVERNOR_R3",
110 "output already in context (never above shadow)",
111 ),
112 (
113 "r4",
114 "shadow",
115 "LEAN_CTX_GOVERNOR_R4",
116 "template collapse of large Bash output",
117 ),
118 (
119 "r5",
120 "on",
121 "LEAN_CTX_GOVERNOR_R5",
122 "outline instead of a first whole read of a large code file (Read, `cat <file>`, Code Mode script reads)",
123 ),
124 (
125 "r6",
126 "shadow",
127 "LEAN_CTX_GOVERNOR_R6",
128 "large Grep content result grouped by file (ripgrep --heading layout, lossless)",
129 ),
130 ] {
131 keys.insert(
132 rule.into(),
133 key_enum_with_env(
134 &modes,
135 builtin,
136 &format!(
137 "Governor rule {rule}: {what}. Unset = built-in default; a governor \
138 install writes on (r3: shadow). LEAN_CTX_GOVERNOR caps every rule"
139 ),
140 env,
141 ),
142 );
143 }
144 keys.insert(
145 "pinned".into(),
146 key(
147 "table",
148 serde_json::json!({}),
149 "Setup mode chosen per host, e.g. claude = \"hybrid\". Written by `lean-ctx init \
150 --agent <host> --mode <mode>`; a pinned host is never switched to the governor \
151 by setup or an update",
152 ),
153 );
154 SectionSchema {
155 description: "Claude Code governor (`hook govern`): rule modes (env \
156 LEAN_CTX_GOVERNOR_* overrides) and per-host setup pins. The governor \
157 is the default Claude Code setup."
158 .into(),
159 keys,
160 }
161}
162
163fn hook_mode_key() -> KeySchema {
166 key_enum_with_env(
167 &["auto", "hybrid", "replace", "mcp"],
168 "auto",
169 "How lean-ctx integrates with agents. auto (default): Hybrid for every \
170 hook-capable agent — native calls are not refused, known commands are \
171 rewritten through lean-ctx; Claude Code's tool list leaves out native \
172 Grep/Glob (no refusals, searches stay compressed). hybrid: the same, \
173 with Grep/Glob back in Claude Code. replace: deny native \
174 Grep/Glob (and non-rewritable shell where the host supports it) so \
175 ctx_* MCP tools are the only path; also set by `lean-ctx harden \
176 --hard`. mcp: MCP server only, no hooks",
177 "LEAN_CTX_HOOK_MODE",
178 )
179}
180
181fn daemon_max_rss_key(cfg: &crate::core::config::Config) -> KeySchema {
184 key_with_env(
185 "u64",
186 serde_json::json!(cfg.daemon_max_rss_mb),
187 "Process RSS target (MB) of the background daemon; the guardian evicts above \
188 the lower of this and max_ram_percent (default 2048, 0 = percent only)",
189 "LEAN_CTX_DAEMON_MAX_RSS_MB",
190 )
191}
192
193fn signer_trust_keys() -> [(&'static str, KeySchema); 2] {
196 [
197 (
198 "a2a_accept_untrusted_signers",
199 key(
200 "bool",
201 serde_json::json!(false),
202 "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",
203 ),
204 ),
205 (
206 "mcp_import_allow_unverified",
207 key(
208 "bool",
209 serde_json::json!(false),
210 "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",
211 ),
212 ),
213 ]
214}
215
216impl ConfigSchema {
217 pub fn generate() -> Self {
218 let mut sections = BTreeMap::new();
219 sections_core::build(&mut sections);
220 sections_features::build(&mut sections);
221 sections_advanced::build(&mut sections);
222 sections.insert("cloud".into(), crate::core::config::cloud::schema_section());
223 sections.insert("intelligence_runtime".into(), SectionSchema {
224 description: "Global-only optional runtime consent and independent staging pins; project overrides never apply".into(),
225 keys: [
226 ("enabled", key("bool", serde_json::json!(false), "Opt in to the verified local runtime")),
227 ("accept_proprietary", key("bool", serde_json::json!(false), "Explicit user acceptance of the separately licensed runtime")),
228 ("staging", key("bool", serde_json::json!(false), "Staging-only delivery; not production release approval")),
229 ("root", key("string", serde_json::json!(""), "Absolute private installation root")),
230 ("manifest_sha256", key("string", serde_json::json!(""), "Independently selected manifest digest")),
231 ("trust_key_hex", key("string", serde_json::json!(""), "Independently provisioned Ed25519 public key, lowercase hex")),
232 ("channel_url", key("string", serde_json::json!(""), "Explicit staging catalog URL; fetched only after consent")),
233 ("channel_signature_url", key("string", serde_json::json!(""), "Detached staging catalog signature URL")),
234 ("channel_root_key_hex", key("string", serde_json::json!(""), "Independently provisioned catalog root; never learned from a download")),
235 ("license_configuration", key("string", serde_json::json!(""), "Explicit user-global path to private license configuration; saved after installed device provisioning")),
236 ("context_policy_apply", key("bool", serde_json::json!(false), "No effect (kept so existing configs load): read-strategy policies are no longer learned by a runtime; planning always uses the local modes")),
237 ("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")),
238 ].into_iter().map(|(name, value)| (name.into(), value)).collect(),
239 });
240
241 ConfigSchema {
242 version: 1,
243 sections,
244 }
245 }
246
247 pub fn lookup(&self, key: &str) -> Option<&KeySchema> {
250 if !key.contains('.') {
251 return self.sections.get("root")?.keys.get(key);
252 }
253 for (i, _) in key.rmatch_indices('.') {
258 let section = &key[..i];
259 let field = &key[i + 1..];
260 if let Some(schema) = self.sections.get(section) {
261 if let Some(ks) = schema.keys.get(field) {
262 return Some(ks);
263 }
264 }
265 }
266 None
267 }
268
269 pub fn known_keys(&self) -> Vec<String> {
277 let mut keys = Vec::new();
278 for (section, schema) in &self.sections {
279 if section == "root" {
280 for key_name in schema.keys.keys() {
281 keys.push(key_name.clone());
282 }
283 } else {
284 if schema.keys.is_empty() {
285 keys.push(section.clone());
286 }
287 for key_name in schema.keys.keys() {
288 keys.push(format!("{section}.{key_name}"));
289 }
290 }
291 }
292 keys.extend(config_derived_keys());
293 keys.sort();
294 keys.dedup();
295 keys
296 }
297}
298
299impl ConfigSchema {
300 pub fn undocumented_keys(&self) -> Vec<(String, toml::Value)> {
305 fn walk(
306 schema: &ConfigSchema,
307 table: &toml::value::Table,
308 prefix: &str,
309 out: &mut Vec<(String, toml::Value)>,
310 ) {
311 for (k, v) in table {
312 let full = if prefix.is_empty() {
313 k.clone()
314 } else {
315 format!("{prefix}.{k}")
316 };
317 match v {
318 toml::Value::Table(sub) if !sub.is_empty() => walk(schema, sub, &full, out),
319 toml::Value::Table(_) if schema.sections.contains_key(&full) => {}
321 _ if schema.lookup(&full).is_none() => out.push((full, v.clone())),
322 _ => {}
323 }
324 }
325 }
326 let mut out = Vec::new();
327 if let Ok(toml::Value::Table(table)) =
328 toml::Value::try_from(crate::core::config::Config::default())
329 {
330 walk(self, &table, "", &mut out);
331 }
332 out.sort_by(|a, b| a.0.cmp(&b.0));
333 out
334 }
335}
336
337fn config_derived_keys() -> Vec<String> {
347 fn walk(table: &toml::value::Table, prefix: &str, out: &mut Vec<String>) {
348 for (k, v) in table {
349 let full = if prefix.is_empty() {
350 k.clone()
351 } else {
352 format!("{prefix}.{k}")
353 };
354 if let toml::Value::Table(sub) = v {
355 out.push(full.clone());
356 walk(sub, &full, out);
357 } else {
358 out.push(full);
359 }
360 }
361 }
362
363 let mut out = Vec::new();
364 if let Ok(toml::Value::Table(table)) =
365 toml::Value::try_from(crate::core::config::Config::default())
366 {
367 walk(&table, "", &mut out);
368 }
369 out
370}
371
372#[cfg(test)]
373mod tests {
374 use super::*;
375
376 fn accepted(known: &[String], key: &str) -> bool {
379 known.iter().any(|k| k == key) || known.iter().any(|k| key.starts_with(&format!("{k}.")))
380 }
381
382 #[test]
387 fn known_keys_cover_every_config_struct_field() {
388 let known = ConfigSchema::generate().known_keys();
389 let missing: Vec<_> = config_derived_keys()
390 .into_iter()
391 .filter(|k| !accepted(&known, k))
392 .collect();
393 assert!(
394 missing.is_empty(),
395 "config struct fields not recognised by validation (schema drift): {missing:?}"
396 );
397 }
398
399 #[test]
402 fn known_keys_recognise_reported_456_keys() {
403 let known = ConfigSchema::generate().known_keys();
404 for key in [
405 "proxy_require_token",
406 "allow_ide_config_dirs",
407 "memory.episodic",
408 "providers.github",
409 "proxy",
410 ] {
411 assert!(
412 accepted(&known, key),
413 "validation must recognise '{key}' (#456)"
414 );
415 }
416 }
417
418 #[test]
429 fn option_scalar_keys_are_cli_settable() {
430 let schema = ConfigSchema::generate();
431 for key in [
432 "path_jail",
433 "path_jail_scope",
434 "persona",
435 "bypass_hints",
436 "shell_security",
437 "cache_policy",
438 "profile",
439 "tool_profile",
440 "rules_scope",
441 "rules_injection",
442 "permission_inheritance",
443 "proxy_enabled",
444 "proxy_port",
445 "proxy_timeout_ms",
446 ] {
447 assert!(
448 schema.lookup(key).is_some(),
449 "`lean-ctx config set {key} <v>` fails with 'Unknown config key' — \
450 add `{key}` to a sections_*.rs schema"
451 );
452 }
453 }
454
455 #[test]
456 fn proxy_require_token_is_cli_settable() {
457 let schema = ConfigSchema::generate();
458 assert!(
459 schema.lookup("proxy_require_token").is_some(),
460 "`lean-ctx config set proxy_require_token <bool>` must be accepted"
461 );
462 }
463
464 #[test]
465 fn dotted_section_keys_are_cli_settable() {
466 let schema = ConfigSchema::generate();
467 for key in [
468 "memory.lifecycle.stale_days",
469 "memory.knowledge.max_facts",
470 "memory.episodic.max_episodes",
471 "proxy.role_aggressiveness.system",
472 ] {
473 assert!(
474 schema.lookup(key).is_some(),
475 "`lean-ctx config set {key} <v>` fails with \"Unknown config key\" — lookup must handle dotted section names"
476 );
477 }
478 }
479
480 #[test]
481 fn decision_loop_keys_are_cli_settable_with_types_and_defaults() {
482 let schema = ConfigSchema::generate();
483 for (key, ty, default) in [
484 ("decision_loop.enabled", "bool", serde_json::json!(true)),
485 ("decision_loop.max_filter_level", "u8", serde_json::json!(0)),
486 ] {
487 let entry = schema
488 .lookup(key)
489 .unwrap_or_else(|| panic!("config set {key} must be recognized"));
490 assert_eq!(entry.ty, ty, "schema type for {key}");
491 assert_eq!(entry.default, default, "schema default for {key}");
492 }
493 }
494
495 #[test]
496 fn permission_inheritance_defaults_to_on() {
497 let cfg = super::super::Config::default();
498 assert_eq!(
499 cfg.permission_inheritance.as_deref(),
500 Some("on"),
501 "permission_inheritance must default to On so IDE permission rules are honored out of the box"
502 );
503 }
504
505 #[test]
512 fn llm_schema_keys_match_the_llm_config_struct() {
513 let schema = ConfigSchema::generate();
514 let section = schema
515 .sections
516 .get("llm")
517 .expect("[llm] section must exist in the schema");
518 let defaults = serde_json::to_value(crate::core::config::LlmConfig::default())
519 .expect("LlmConfig serialises");
520 let defaults = defaults.as_object().expect("LlmConfig is a struct");
521
522 for (key, entry) in §ion.keys {
523 let actual = defaults.get(key).unwrap_or_else(|| {
524 panic!(
525 "schema key `llm.{key}` has no field on LlmConfig — \
526 `config set llm.{key} <v>` would report a save that serde discards"
527 )
528 });
529 let expected = if actual.is_null() {
531 serde_json::json!("")
532 } else {
533 actual.clone()
534 };
535 assert_eq!(
536 entry.default, expected,
537 "schema default for `llm.{key}` has drifted from LlmConfig::default()"
538 );
539 }
540
541 assert!(
542 schema.lookup("llm.api_key").is_none(),
543 "`llm.api_key` is not a config field — the credential comes from \
544 OPENROUTER_API_KEY / ANTHROPIC_API_KEY, so `config set` must reject it"
545 );
546 assert!(
547 schema.lookup("llm.base_url").is_some(),
548 "`llm.base_url` is a real field and must be settable"
549 );
550 }
551}