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 keys.insert(
124 rule.into(),
125 key_enum_with_env(
126 &modes,
127 builtin,
128 &format!(
129 "Governor rule {rule}: {what}. Unset = built-in default; a governor \
130 install writes on (r3: shadow). LEAN_CTX_GOVERNOR caps every rule"
131 ),
132 env,
133 ),
134 );
135 }
136 keys.insert(
137 "pinned".into(),
138 key(
139 "table",
140 serde_json::json!({}),
141 "Setup mode chosen per host, e.g. claude = \"hybrid\". Written by `lean-ctx init \
142 --agent <host> --mode <mode>`; a pinned host is never switched to the governor \
143 by setup or an update",
144 ),
145 );
146 SectionSchema {
147 description: "Claude Code governor (`hook govern`): rule modes (env \
148 LEAN_CTX_GOVERNOR_* overrides) and per-host setup pins. The governor \
149 is the default Claude Code setup."
150 .into(),
151 keys,
152 }
153}
154
155fn hook_mode_key() -> KeySchema {
158 key_enum_with_env(
159 &["auto", "hybrid", "replace", "mcp"],
160 "auto",
161 "How lean-ctx integrates with agents. auto (default): Hybrid for every \
162 hook-capable agent — native calls are not refused, known commands are \
163 rewritten through lean-ctx; Claude Code's tool list leaves out native \
164 Grep/Glob (no refusals, searches stay compressed). hybrid: the same, \
165 with Grep/Glob back in Claude Code. replace: deny native \
166 Grep/Glob (and non-rewritable shell where the host supports it) so \
167 ctx_* MCP tools are the only path; also set by `lean-ctx harden \
168 --hard`. mcp: MCP server only, no hooks",
169 "LEAN_CTX_HOOK_MODE",
170 )
171}
172
173fn daemon_max_rss_key(cfg: &crate::core::config::Config) -> KeySchema {
176 key_with_env(
177 "u64",
178 serde_json::json!(cfg.daemon_max_rss_mb),
179 "Process RSS target (MB) of the background daemon; the guardian evicts above \
180 the lower of this and max_ram_percent (default 2048, 0 = percent only)",
181 "LEAN_CTX_DAEMON_MAX_RSS_MB",
182 )
183}
184
185fn signer_trust_keys() -> [(&'static str, KeySchema); 2] {
188 [
189 (
190 "a2a_accept_untrusted_signers",
191 key(
192 "bool",
193 serde_json::json!(false),
194 "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",
195 ),
196 ),
197 (
198 "mcp_import_allow_unverified",
199 key(
200 "bool",
201 serde_json::json!(false),
202 "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",
203 ),
204 ),
205 ]
206}
207
208impl ConfigSchema {
209 pub fn generate() -> Self {
210 let mut sections = BTreeMap::new();
211 sections_core::build(&mut sections);
212 sections_features::build(&mut sections);
213 sections_advanced::build(&mut sections);
214 sections.insert("cloud".into(), crate::core::config::cloud::schema_section());
215 sections.insert("intelligence_runtime".into(), SectionSchema {
216 description: "Global-only optional runtime consent and independent staging pins; project overrides never apply".into(),
217 keys: [
218 ("enabled", key("bool", serde_json::json!(false), "Opt in to the verified local runtime")),
219 ("accept_proprietary", key("bool", serde_json::json!(false), "Explicit user acceptance of the separately licensed runtime")),
220 ("staging", key("bool", serde_json::json!(false), "Staging-only delivery; not production release approval")),
221 ("root", key("string", serde_json::json!(""), "Absolute private installation root")),
222 ("manifest_sha256", key("string", serde_json::json!(""), "Independently selected manifest digest")),
223 ("trust_key_hex", key("string", serde_json::json!(""), "Independently provisioned Ed25519 public key, lowercase hex")),
224 ("channel_url", key("string", serde_json::json!(""), "Explicit staging catalog URL; fetched only after consent")),
225 ("channel_signature_url", key("string", serde_json::json!(""), "Detached staging catalog signature URL")),
226 ("channel_root_key_hex", key("string", serde_json::json!(""), "Independently provisioned catalog root; never learned from a download")),
227 ("license_configuration", key("string", serde_json::json!(""), "Explicit user-global path to private license configuration; saved after installed device provisioning")),
228 ("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")),
229 ("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")),
230 ].into_iter().map(|(name, value)| (name.into(), value)).collect(),
231 });
232
233 ConfigSchema {
234 version: 1,
235 sections,
236 }
237 }
238
239 pub fn lookup(&self, key: &str) -> Option<&KeySchema> {
242 if !key.contains('.') {
243 return self.sections.get("root")?.keys.get(key);
244 }
245 for (i, _) in key.rmatch_indices('.') {
250 let section = &key[..i];
251 let field = &key[i + 1..];
252 if let Some(schema) = self.sections.get(section) {
253 if let Some(ks) = schema.keys.get(field) {
254 return Some(ks);
255 }
256 }
257 }
258 None
259 }
260
261 pub fn known_keys(&self) -> Vec<String> {
269 let mut keys = Vec::new();
270 for (section, schema) in &self.sections {
271 if section == "root" {
272 for key_name in schema.keys.keys() {
273 keys.push(key_name.clone());
274 }
275 } else {
276 if schema.keys.is_empty() {
277 keys.push(section.clone());
278 }
279 for key_name in schema.keys.keys() {
280 keys.push(format!("{section}.{key_name}"));
281 }
282 }
283 }
284 keys.extend(config_derived_keys());
285 keys.sort();
286 keys.dedup();
287 keys
288 }
289}
290
291fn config_derived_keys() -> Vec<String> {
301 fn walk(table: &toml::value::Table, prefix: &str, out: &mut Vec<String>) {
302 for (k, v) in table {
303 let full = if prefix.is_empty() {
304 k.clone()
305 } else {
306 format!("{prefix}.{k}")
307 };
308 if let toml::Value::Table(sub) = v {
309 out.push(full.clone());
310 walk(sub, &full, out);
311 } else {
312 out.push(full);
313 }
314 }
315 }
316
317 let mut out = Vec::new();
318 if let Ok(toml::Value::Table(table)) =
319 toml::Value::try_from(crate::core::config::Config::default())
320 {
321 walk(&table, "", &mut out);
322 }
323 out
324}
325
326#[cfg(test)]
327mod tests {
328 use super::*;
329
330 fn accepted(known: &[String], key: &str) -> bool {
333 known.iter().any(|k| k == key) || known.iter().any(|k| key.starts_with(&format!("{k}.")))
334 }
335
336 #[test]
341 fn known_keys_cover_every_config_struct_field() {
342 let known = ConfigSchema::generate().known_keys();
343 let missing: Vec<_> = config_derived_keys()
344 .into_iter()
345 .filter(|k| !accepted(&known, k))
346 .collect();
347 assert!(
348 missing.is_empty(),
349 "config struct fields not recognised by validation (schema drift): {missing:?}"
350 );
351 }
352
353 #[test]
356 fn known_keys_recognise_reported_456_keys() {
357 let known = ConfigSchema::generate().known_keys();
358 for key in [
359 "proxy_require_token",
360 "allow_ide_config_dirs",
361 "memory.episodic",
362 "providers.github",
363 "proxy",
364 ] {
365 assert!(
366 accepted(&known, key),
367 "validation must recognise '{key}' (#456)"
368 );
369 }
370 }
371
372 #[test]
383 fn option_scalar_keys_are_cli_settable() {
384 let schema = ConfigSchema::generate();
385 for key in [
386 "path_jail",
387 "path_jail_scope",
388 "persona",
389 "bypass_hints",
390 "shell_security",
391 "cache_policy",
392 "profile",
393 "tool_profile",
394 "rules_scope",
395 "rules_injection",
396 "permission_inheritance",
397 "proxy_enabled",
398 "proxy_port",
399 "proxy_timeout_ms",
400 ] {
401 assert!(
402 schema.lookup(key).is_some(),
403 "`lean-ctx config set {key} <v>` fails with 'Unknown config key' — \
404 add `{key}` to a sections_*.rs schema"
405 );
406 }
407 }
408
409 #[test]
410 fn proxy_require_token_is_cli_settable() {
411 let schema = ConfigSchema::generate();
412 assert!(
413 schema.lookup("proxy_require_token").is_some(),
414 "`lean-ctx config set proxy_require_token <bool>` must be accepted"
415 );
416 }
417
418 #[test]
419 fn dotted_section_keys_are_cli_settable() {
420 let schema = ConfigSchema::generate();
421 for key in [
422 "memory.lifecycle.stale_days",
423 "memory.knowledge.max_facts",
424 "memory.episodic.max_episodes",
425 "proxy.role_aggressiveness.system",
426 ] {
427 assert!(
428 schema.lookup(key).is_some(),
429 "`lean-ctx config set {key} <v>` fails with \"Unknown config key\" — lookup must handle dotted section names"
430 );
431 }
432 }
433
434 #[test]
435 fn decision_loop_keys_are_cli_settable_with_types_and_defaults() {
436 let schema = ConfigSchema::generate();
437 for (key, ty, default) in [
438 ("decision_loop.enabled", "bool", serde_json::json!(true)),
439 ("decision_loop.max_filter_level", "u8", serde_json::json!(0)),
440 ] {
441 let entry = schema
442 .lookup(key)
443 .unwrap_or_else(|| panic!("config set {key} must be recognized"));
444 assert_eq!(entry.ty, ty, "schema type for {key}");
445 assert_eq!(entry.default, default, "schema default for {key}");
446 }
447 }
448
449 #[test]
450 fn permission_inheritance_defaults_to_on() {
451 let cfg = super::super::Config::default();
452 assert_eq!(
453 cfg.permission_inheritance.as_deref(),
454 Some("on"),
455 "permission_inheritance must default to On so IDE permission rules are honored out of the box"
456 );
457 }
458
459 #[test]
466 fn llm_schema_keys_match_the_llm_config_struct() {
467 let schema = ConfigSchema::generate();
468 let section = schema
469 .sections
470 .get("llm")
471 .expect("[llm] section must exist in the schema");
472 let defaults = serde_json::to_value(crate::core::config::LlmConfig::default())
473 .expect("LlmConfig serialises");
474 let defaults = defaults.as_object().expect("LlmConfig is a struct");
475
476 for (key, entry) in §ion.keys {
477 let actual = defaults.get(key).unwrap_or_else(|| {
478 panic!(
479 "schema key `llm.{key}` has no field on LlmConfig — \
480 `config set llm.{key} <v>` would report a save that serde discards"
481 )
482 });
483 let expected = if actual.is_null() {
485 serde_json::json!("")
486 } else {
487 actual.clone()
488 };
489 assert_eq!(
490 entry.default, expected,
491 "schema default for `llm.{key}` has drifted from LlmConfig::default()"
492 );
493 }
494
495 assert!(
496 schema.lookup("llm.api_key").is_none(),
497 "`llm.api_key` is not a config field — the credential comes from \
498 OPENROUTER_API_KEY / ANTHROPIC_API_KEY, so `config set` must reject it"
499 );
500 assert!(
501 schema.lookup("llm.base_url").is_some(),
502 "`llm.base_url` is a real field and must be settable"
503 );
504 }
505}