1use 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
81fn governor_section() -> SectionSchema {
83 let modes = ["on", "shadow", "off"];
84 let mut keys = BTreeMap::new();
85 for (rule, builtin, env, what) in [
86 (
87 "r1_read",
88 "on",
89 "LEAN_CTX_GOVERNOR_R1_READ",
90 "identical re-read of an unchanged file",
91 ),
92 (
93 "r1_bash",
94 "shadow",
95 "LEAN_CTX_GOVERNOR_R1_BASH",
96 "identical re-run of a viewer command",
97 ),
98 (
99 "r2",
100 "shadow",
101 "LEAN_CTX_GOVERNOR_R2",
102 "lossless repeat collapse of large Bash output",
103 ),
104 (
105 "r3",
106 "shadow",
107 "LEAN_CTX_GOVERNOR_R3",
108 "output already in context (never above shadow)",
109 ),
110 (
111 "r4",
112 "shadow",
113 "LEAN_CTX_GOVERNOR_R4",
114 "template collapse of large Bash output",
115 ),
116 (
117 "r5",
118 "on",
119 "LEAN_CTX_GOVERNOR_R5",
120 "outline instead of a first whole read of a large code file (Read, `cat <file>`, Code Mode script reads)",
121 ),
122 (
123 "r6",
124 "shadow",
125 "LEAN_CTX_GOVERNOR_R6",
126 "large Grep content result grouped by file (ripgrep --heading layout, lossless)",
127 ),
128 ] {
129 keys.insert(
130 rule.into(),
131 key_enum_with_env(
132 &modes,
133 builtin,
134 &format!(
135 "Governor rule {rule}: {what}. Unset = built-in default; a governor \
136 install writes on (r3: shadow). LEAN_CTX_GOVERNOR caps every rule"
137 ),
138 env,
139 ),
140 );
141 }
142 keys.insert(
143 "pinned".into(),
144 key(
145 "table",
146 serde_json::json!({}),
147 "Setup mode chosen per host, e.g. claude = \"hybrid\". Written by `lean-ctx init \
148 --agent <host> --mode <mode>`; a pinned host is never switched to the governor \
149 by setup or an update",
150 ),
151 );
152 SectionSchema {
153 description: "Claude Code governor (`hook govern`): rule modes (env \
154 LEAN_CTX_GOVERNOR_* overrides) and per-host setup pins. The governor \
155 is the default Claude Code setup."
156 .into(),
157 keys,
158 }
159}
160
161fn hook_mode_key() -> KeySchema {
164 key_enum_with_env(
165 &["auto", "hybrid", "replace", "mcp"],
166 "auto",
167 "How lean-ctx integrates with agents. auto (default): Hybrid for every \
168 hook-capable agent — native calls are not refused, known commands are \
169 rewritten through lean-ctx; Claude Code's tool list leaves out native \
170 Grep/Glob (no refusals, searches stay compressed). hybrid: the same, \
171 with Grep/Glob back in Claude Code. replace: deny native \
172 Grep/Glob (and non-rewritable shell where the host supports it) so \
173 ctx_* MCP tools are the only path; also set by `lean-ctx harden \
174 --hard`. mcp: MCP server only, no hooks",
175 "LEAN_CTX_HOOK_MODE",
176 )
177}
178
179fn daemon_max_rss_key(cfg: &crate::core::config::Config) -> KeySchema {
182 key_with_env(
183 "u64",
184 serde_json::json!(cfg.daemon_max_rss_mb),
185 "Process RSS target (MB) of the background daemon; the guardian evicts above \
186 the lower of this and max_ram_percent (default 2048, 0 = percent only)",
187 "LEAN_CTX_DAEMON_MAX_RSS_MB",
188 )
189}
190
191fn signer_trust_keys() -> [(&'static str, KeySchema); 2] {
194 [
195 (
196 "a2a_accept_untrusted_signers",
197 key(
198 "bool",
199 serde_json::json!(false),
200 "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",
201 ),
202 ),
203 (
204 "mcp_import_allow_unverified",
205 key(
206 "bool",
207 serde_json::json!(false),
208 "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",
209 ),
210 ),
211 ]
212}
213
214impl ConfigSchema {
215 pub fn generate() -> Self {
216 let mut sections = BTreeMap::new();
217 sections_core::build(&mut sections);
218 sections_features::build(&mut sections);
219 sections_advanced::build(&mut sections);
220 sections.insert("cloud".into(), crate::core::config::cloud::schema_section());
221 sections.insert("intelligence_runtime".into(), SectionSchema {
222 description: "Global-only optional runtime consent and independent staging pins; project overrides never apply".into(),
223 keys: [
224 ("enabled", key("bool", serde_json::json!(false), "Opt in to the verified local runtime")),
225 ("accept_proprietary", key("bool", serde_json::json!(false), "Explicit user acceptance of the separately licensed runtime")),
226 ("staging", key("bool", serde_json::json!(false), "Staging-only delivery; not production release approval")),
227 ("root", key("string", serde_json::json!(""), "Absolute private installation root")),
228 ("manifest_sha256", key("string", serde_json::json!(""), "Independently selected manifest digest")),
229 ("trust_key_hex", key("string", serde_json::json!(""), "Independently provisioned Ed25519 public key, lowercase hex")),
230 ("channel_url", key("string", serde_json::json!(""), "Explicit staging catalog URL; fetched only after consent")),
231 ("channel_signature_url", key("string", serde_json::json!(""), "Detached staging catalog signature URL")),
232 ("channel_root_key_hex", key("string", serde_json::json!(""), "Independently provisioned catalog root; never learned from a download")),
233 ("license_configuration", key("string", serde_json::json!(""), "Explicit user-global path to private license configuration; saved after installed device provisioning")),
234 ("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")),
235 ("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")),
236 ].into_iter().map(|(name, value)| (name.into(), value)).collect(),
237 });
238
239 ConfigSchema {
240 version: 1,
241 sections,
242 }
243 }
244
245 pub fn lookup(&self, key: &str) -> Option<&KeySchema> {
248 if !key.contains('.') {
249 return self.sections.get("root")?.keys.get(key);
250 }
251 for (i, _) in key.rmatch_indices('.') {
256 let section = &key[..i];
257 let field = &key[i + 1..];
258 if let Some(schema) = self.sections.get(section) {
259 if let Some(ks) = schema.keys.get(field) {
260 return Some(ks);
261 }
262 }
263 }
264 None
265 }
266
267 pub fn known_keys(&self) -> Vec<String> {
275 let mut keys = Vec::new();
276 for (section, schema) in &self.sections {
277 if section == "root" {
278 for key_name in schema.keys.keys() {
279 keys.push(key_name.clone());
280 }
281 } else {
282 if schema.keys.is_empty() {
283 keys.push(section.clone());
284 }
285 for key_name in schema.keys.keys() {
286 keys.push(format!("{section}.{key_name}"));
287 }
288 }
289 }
290 keys.extend(config_derived_keys());
291 keys.sort();
292 keys.dedup();
293 keys
294 }
295}
296
297fn config_derived_keys() -> Vec<String> {
307 fn walk(table: &toml::value::Table, prefix: &str, out: &mut Vec<String>) {
308 for (k, v) in table {
309 let full = if prefix.is_empty() {
310 k.clone()
311 } else {
312 format!("{prefix}.{k}")
313 };
314 if let toml::Value::Table(sub) = v {
315 out.push(full.clone());
316 walk(sub, &full, out);
317 } else {
318 out.push(full);
319 }
320 }
321 }
322
323 let mut out = Vec::new();
324 if let Ok(toml::Value::Table(table)) =
325 toml::Value::try_from(crate::core::config::Config::default())
326 {
327 walk(&table, "", &mut out);
328 }
329 out
330}
331
332#[cfg(test)]
333mod tests {
334 use super::*;
335
336 fn accepted(known: &[String], key: &str) -> bool {
339 known.iter().any(|k| k == key) || known.iter().any(|k| key.starts_with(&format!("{k}.")))
340 }
341
342 #[test]
347 fn known_keys_cover_every_config_struct_field() {
348 let known = ConfigSchema::generate().known_keys();
349 let missing: Vec<_> = config_derived_keys()
350 .into_iter()
351 .filter(|k| !accepted(&known, k))
352 .collect();
353 assert!(
354 missing.is_empty(),
355 "config struct fields not recognised by validation (schema drift): {missing:?}"
356 );
357 }
358
359 #[test]
362 fn known_keys_recognise_reported_456_keys() {
363 let known = ConfigSchema::generate().known_keys();
364 for key in [
365 "proxy_require_token",
366 "allow_ide_config_dirs",
367 "memory.episodic",
368 "providers.github",
369 "proxy",
370 ] {
371 assert!(
372 accepted(&known, key),
373 "validation must recognise '{key}' (#456)"
374 );
375 }
376 }
377
378 #[test]
389 fn option_scalar_keys_are_cli_settable() {
390 let schema = ConfigSchema::generate();
391 for key in [
392 "path_jail",
393 "path_jail_scope",
394 "persona",
395 "bypass_hints",
396 "shell_security",
397 "cache_policy",
398 "profile",
399 "tool_profile",
400 "rules_scope",
401 "rules_injection",
402 "permission_inheritance",
403 "proxy_enabled",
404 "proxy_port",
405 "proxy_timeout_ms",
406 ] {
407 assert!(
408 schema.lookup(key).is_some(),
409 "`lean-ctx config set {key} <v>` fails with 'Unknown config key' — \
410 add `{key}` to a sections_*.rs schema"
411 );
412 }
413 }
414
415 #[test]
416 fn proxy_require_token_is_cli_settable() {
417 let schema = ConfigSchema::generate();
418 assert!(
419 schema.lookup("proxy_require_token").is_some(),
420 "`lean-ctx config set proxy_require_token <bool>` must be accepted"
421 );
422 }
423
424 #[test]
425 fn dotted_section_keys_are_cli_settable() {
426 let schema = ConfigSchema::generate();
427 for key in [
428 "memory.lifecycle.stale_days",
429 "memory.knowledge.max_facts",
430 "memory.episodic.max_episodes",
431 "proxy.role_aggressiveness.system",
432 ] {
433 assert!(
434 schema.lookup(key).is_some(),
435 "`lean-ctx config set {key} <v>` fails with \"Unknown config key\" — lookup must handle dotted section names"
436 );
437 }
438 }
439
440 #[test]
441 fn decision_loop_keys_are_cli_settable_with_types_and_defaults() {
442 let schema = ConfigSchema::generate();
443 for (key, ty, default) in [
444 ("decision_loop.enabled", "bool", serde_json::json!(true)),
445 ("decision_loop.max_filter_level", "u8", serde_json::json!(0)),
446 ] {
447 let entry = schema
448 .lookup(key)
449 .unwrap_or_else(|| panic!("config set {key} must be recognized"));
450 assert_eq!(entry.ty, ty, "schema type for {key}");
451 assert_eq!(entry.default, default, "schema default for {key}");
452 }
453 }
454
455 #[test]
456 fn permission_inheritance_defaults_to_on() {
457 let cfg = super::super::Config::default();
458 assert_eq!(
459 cfg.permission_inheritance.as_deref(),
460 Some("on"),
461 "permission_inheritance must default to On so IDE permission rules are honored out of the box"
462 );
463 }
464
465 #[test]
472 fn llm_schema_keys_match_the_llm_config_struct() {
473 let schema = ConfigSchema::generate();
474 let section = schema
475 .sections
476 .get("llm")
477 .expect("[llm] section must exist in the schema");
478 let defaults = serde_json::to_value(crate::core::config::LlmConfig::default())
479 .expect("LlmConfig serialises");
480 let defaults = defaults.as_object().expect("LlmConfig is a struct");
481
482 for (key, entry) in §ion.keys {
483 let actual = defaults.get(key).unwrap_or_else(|| {
484 panic!(
485 "schema key `llm.{key}` has no field on LlmConfig — \
486 `config set llm.{key} <v>` would report a save that serde discards"
487 )
488 });
489 let expected = if actual.is_null() {
491 serde_json::json!("")
492 } else {
493 actual.clone()
494 };
495 assert_eq!(
496 entry.default, expected,
497 "schema default for `llm.{key}` has drifted from LlmConfig::default()"
498 );
499 }
500
501 assert!(
502 schema.lookup("llm.api_key").is_none(),
503 "`llm.api_key` is not a config field — the credential comes from \
504 OPENROUTER_API_KEY / ANTHROPIC_API_KEY, so `config set` must reject it"
505 );
506 assert!(
507 schema.lookup("llm.base_url").is_some(),
508 "`llm.base_url` is a real field and must be settable"
509 );
510 }
511}