Skip to main content

lean_ctx/core/config/
schema.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;
8
9#[derive(Debug, Clone, Serialize)]
10pub struct ConfigSchema {
11    pub version: u32,
12    pub sections: BTreeMap<String, SectionSchema>,
13}
14
15#[derive(Debug, Clone, Serialize)]
16pub struct SectionSchema {
17    pub description: String,
18    pub keys: BTreeMap<String, KeySchema>,
19}
20
21#[derive(Debug, Clone, Serialize)]
22pub struct KeySchema {
23    #[serde(rename = "type")]
24    pub ty: String,
25    pub default: serde_json::Value,
26    pub description: String,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub values: Option<Vec<String>>,
29    #[serde(skip_serializing_if = "Option::is_none")]
30    pub env_override: Option<String>,
31}
32
33fn clean_f32(v: f32) -> serde_json::Value {
34    let clean: f64 = format!("{v}").parse().unwrap_or(v as f64);
35    serde_json::json!(clean)
36}
37
38fn key(ty: &str, default: serde_json::Value, desc: &str) -> KeySchema {
39    KeySchema {
40        ty: ty.to_string(),
41        default,
42        description: desc.to_string(),
43        values: None,
44        env_override: None,
45    }
46}
47
48fn key_enum(values: &[&str], default: &str, desc: &str) -> KeySchema {
49    KeySchema {
50        ty: "enum".to_string(),
51        default: serde_json::Value::String(default.to_string()),
52        description: desc.to_string(),
53        values: Some(values.iter().map(ToString::to_string).collect()),
54        env_override: None,
55    }
56}
57
58fn key_with_env(ty: &str, default: serde_json::Value, desc: &str, env: &str) -> KeySchema {
59    KeySchema {
60        ty: ty.to_string(),
61        default,
62        description: desc.to_string(),
63        values: None,
64        env_override: Some(env.to_string()),
65    }
66}
67
68fn key_enum_with_env(values: &[&str], default: &str, desc: &str, env: &str) -> KeySchema {
69    KeySchema {
70        ty: "enum".to_string(),
71        default: serde_json::Value::String(default.to_string()),
72        description: desc.to_string(),
73        values: Some(values.iter().map(ToString::to_string).collect()),
74        env_override: Some(env.to_string()),
75    }
76}
77
78impl ConfigSchema {
79    pub fn generate() -> Self {
80        let cfg = super::Config::default();
81        let mut sections = BTreeMap::new();
82
83        let mut root = BTreeMap::new();
84        root.insert(
85            "ultra_compact".into(),
86            key(
87                "bool",
88                serde_json::json!(false),
89                "Legacy flag for maximum compression (use compression_level instead)",
90            ),
91        );
92        root.insert(
93            "tee_mode".into(),
94            key_enum(
95                &["never", "failures", "always"],
96                "failures",
97                "Controls when shell output is tee'd to disk for later retrieval",
98            ),
99        );
100        root.insert(
101            "output_density".into(),
102            key_enum_with_env(
103                &["normal", "terse", "ultra"],
104                "normal",
105                "Controls how dense/compact MCP tool output is formatted",
106                "LEAN_CTX_OUTPUT_DENSITY",
107            ),
108        );
109        root.insert(
110            "checkpoint_interval".into(),
111            key(
112                "u32",
113                serde_json::json!(cfg.checkpoint_interval),
114                "Session checkpoint interval in minutes",
115            ),
116        );
117        root.insert(
118            "excluded_commands".into(),
119            key(
120                "string[]",
121                serde_json::json!(cfg.excluded_commands),
122                "Commands to exclude from shell hook interception",
123            ),
124        );
125        root.insert(
126            "passthrough_urls".into(),
127            key(
128                "string[]",
129                serde_json::json!(cfg.passthrough_urls),
130                "URLs to pass through without proxy interception",
131            ),
132        );
133        root.insert("slow_command_threshold_ms".into(), key("u64", serde_json::json!(cfg.slow_command_threshold_ms), "Commands taking longer than this (ms) are recorded in the slow log. Set to 0 to disable"));
134        root.insert(
135            "theme".into(),
136            key(
137                "string",
138                serde_json::json!(cfg.theme),
139                "Dashboard color theme",
140            ),
141        );
142        root.insert(
143            "buddy_enabled".into(),
144            key(
145                "bool",
146                serde_json::json!(cfg.buddy_enabled),
147                "Enable the buddy system for multi-agent coordination",
148            ),
149        );
150        root.insert(
151            "enable_wakeup_ctx".into(),
152            key(
153                "bool",
154                serde_json::json!(cfg.enable_wakeup_ctx),
155                "Append wakeup briefing (facts, session summary) to ctx_overview output. Set false to reduce context bloat when calling ctx_overview frequently.",
156            ),
157        );
158        root.insert(
159            "redirect_exclude".into(),
160            key(
161                "string[]",
162                serde_json::json!(cfg.redirect_exclude),
163                "URL patterns to exclude from proxy redirection",
164            ),
165        );
166        root.insert(
167            "disabled_tools".into(),
168            key(
169                "string[]",
170                serde_json::json!(cfg.disabled_tools),
171                "Tools to exclude from the MCP tool list",
172            ),
173        );
174        root.insert(
175            "rules_scope".into(),
176            key_enum(
177                &["both", "global", "project"],
178                "both",
179                "Where agent rule files are installed. Override via LEAN_CTX_RULES_SCOPE",
180            ),
181        );
182        root.insert(
183            "extra_ignore_patterns".into(),
184            key(
185                "string[]",
186                serde_json::json!(cfg.extra_ignore_patterns),
187                "Extra glob patterns to ignore in graph/overview/preload",
188            ),
189        );
190        root.insert(
191            "terse_agent".into(),
192            key_enum_with_env(
193                &["off", "lite", "full", "ultra"],
194                "off",
195                "Controls agent output verbosity via instructions injection",
196                "LEAN_CTX_TERSE_AGENT",
197            ),
198        );
199        root.insert(
200            "compression_level".into(),
201            key_enum_with_env(
202                &["off", "lite", "standard", "max"],
203                "off",
204                "Unified compression level for all output",
205                "LEAN_CTX_COMPRESSION",
206            ),
207        );
208        root.insert(
209            "allow_paths".into(),
210            key_with_env(
211                "string[]",
212                serde_json::json!(cfg.allow_paths),
213                "Additional paths allowed by PathJail (absolute)",
214                "LEAN_CTX_ALLOW_PATH",
215            ),
216        );
217        root.insert(
218            "content_defined_chunking".into(),
219            key(
220                "bool",
221                serde_json::json!(false),
222                "Enable Rabin-Karp chunking for cache-optimal output ordering",
223            ),
224        );
225        root.insert(
226            "minimal_overhead".into(),
227            key_with_env(
228                "bool",
229                serde_json::json!(false),
230                "Skip session/knowledge/gotcha blocks in MCP instructions",
231                "LEAN_CTX_MINIMAL",
232            ),
233        );
234        root.insert(
235            "shell_hook_disabled".into(),
236            key_with_env(
237                "bool",
238                serde_json::json!(false),
239                "Disable shell hook injection",
240                "LEAN_CTX_NO_HOOK",
241            ),
242        );
243        root.insert(
244            "shell_activation".into(),
245            key_enum_with_env(
246                &["always", "agents-only", "off"],
247                "always",
248                "Controls when the shell hook auto-activates aliases",
249                "LEAN_CTX_SHELL_ACTIVATION",
250            ),
251        );
252        root.insert(
253            "update_check_disabled".into(),
254            key_with_env(
255                "bool",
256                serde_json::json!(false),
257                "Disable the daily version check",
258                "LEAN_CTX_NO_UPDATE_CHECK",
259            ),
260        );
261        root.insert(
262            "bm25_max_cache_mb".into(),
263            key_with_env(
264                "u64",
265                serde_json::json!(cfg.bm25_max_cache_mb),
266                "Maximum BM25 cache file size in MB",
267                "LEAN_CTX_BM25_MAX_CACHE_MB",
268            ),
269        );
270        root.insert(
271            "graph_index_max_files".into(),
272            key(
273                "u64",
274                serde_json::json!(cfg.graph_index_max_files),
275                "Maximum files in graph index. 0 = unlimited (default). Set >0 to cap for constrained systems",
276            ),
277        );
278        root.insert(
279            "memory_profile".into(),
280            key_enum_with_env(
281                &["low", "balanced", "performance"],
282                "balanced",
283                "Controls RAM vs feature trade-off",
284                "LEAN_CTX_MEMORY_PROFILE",
285            ),
286        );
287        root.insert(
288            "memory_cleanup".into(),
289            key_enum_with_env(
290                &["aggressive", "shared"],
291                "aggressive",
292                "Controls how aggressively memory is freed when idle",
293                "LEAN_CTX_MEMORY_CLEANUP",
294            ),
295        );
296        root.insert(
297            "savings_footer".into(),
298            key_enum_with_env(
299                &["auto", "always", "never"],
300                "never",
301                "Controls visibility of token savings footers: never (default, suppress everywhere), always, auto (context-dependent)",
302                "LEAN_CTX_SAVINGS_FOOTER",
303            ),
304        );
305        root.insert(
306            "max_ram_percent".into(),
307            key_with_env(
308                "u8",
309                serde_json::json!(cfg.max_ram_percent),
310                "Maximum percentage of system RAM that lean-ctx may use (1-50, default 5)",
311                "LEAN_CTX_MAX_RAM_PERCENT",
312            ),
313        );
314        root.insert(
315            "project_root".into(),
316            key_with_env(
317                "string?",
318                serde_json::json!(null),
319                "Explicit project root directory. Prevents accidental home-directory scans",
320                "LEAN_CTX_PROJECT_ROOT",
321            ),
322        );
323        root.insert(
324            "proxy_enabled".into(),
325            key(
326                "bool?",
327                serde_json::json!(null),
328                "Enable/disable the proxy layer. null = auto-detect, true = force on, false = force off",
329            ),
330        );
331        root.insert(
332            "response_verbosity".into(),
333            key_enum_with_env(
334                &["normal", "compact", "minimal"],
335                "normal",
336                "Controls how verbose tool responses are",
337                "LEAN_CTX_RESPONSE_VERBOSITY",
338            ),
339        );
340        root.insert(
341            "allow_auto_reroot".into(),
342            key_with_env(
343                "bool",
344                serde_json::json!(false),
345                "Allow automatic project-root re-rooting when absolute paths outside the jail are seen",
346                "LEAN_CTX_ALLOW_REROOT",
347            ),
348        );
349        root.insert(
350            "sandbox_level".into(),
351            key_with_env(
352                "u8",
353                serde_json::json!(0),
354                "Sandbox strictness level (0=default, 1=strict, 2=paranoid)",
355                "LEAN_CTX_SANDBOX_LEVEL",
356            ),
357        );
358        root.insert(
359            "reference_results".into(),
360            key_with_env(
361                "bool",
362                serde_json::json!(false),
363                "Store large tool outputs as references instead of inline content",
364                "LEAN_CTX_REFERENCE_RESULTS",
365            ),
366        );
367        root.insert(
368            "agent_token_budget".into(),
369            key(
370                "usize",
371                serde_json::json!(0),
372                "Default per-agent token budget. 0 = unlimited",
373            ),
374        );
375        root.insert(
376            "shell_allowlist".into(),
377            key_with_env(
378                "array",
379                serde_json::json!([]),
380                "Optional shell command allowlist. When non-empty, only listed binaries are permitted",
381                "LEAN_CTX_SHELL_ALLOWLIST",
382            ),
383        );
384
385        sections.insert(
386            "root".into(),
387            SectionSchema {
388                description: "Top-level configuration keys".into(),
389                keys: root,
390            },
391        );
392
393        sections.insert(
394            "ide_paths".into(),
395            SectionSchema {
396                description: "Per-IDE allowed paths. Keys are agent names (cursor, codex, opencode, antigravity, etc.), values are arrays of paths to index for that agent".into(),
397                keys: BTreeMap::new(),
398            },
399        );
400
401        let mut lsp_keys = BTreeMap::new();
402        lsp_keys.insert(
403            "rust".into(),
404            key(
405                "string?",
406                serde_json::json!(null),
407                "Custom path to rust-analyzer binary",
408            ),
409        );
410        lsp_keys.insert(
411            "typescript".into(),
412            key(
413                "string?",
414                serde_json::json!(null),
415                "Custom path to typescript-language-server binary",
416            ),
417        );
418        lsp_keys.insert(
419            "python".into(),
420            key(
421                "string?",
422                serde_json::json!(null),
423                "Custom path to pylsp binary",
424            ),
425        );
426        lsp_keys.insert(
427            "go".into(),
428            key(
429                "string?",
430                serde_json::json!(null),
431                "Custom path to gopls binary",
432            ),
433        );
434        sections.insert(
435            "lsp".into(),
436            SectionSchema {
437                description: "LSP server binary overrides. Map language name to custom binary path"
438                    .into(),
439                keys: lsp_keys,
440            },
441        );
442
443        let mut archive = BTreeMap::new();
444        archive.insert(
445            "enabled".into(),
446            key(
447                "bool",
448                serde_json::json!(cfg.archive.enabled),
449                "Enable zero-loss compression archive",
450            ),
451        );
452        archive.insert(
453            "threshold_chars".into(),
454            key(
455                "usize",
456                serde_json::json!(cfg.archive.threshold_chars),
457                "Minimum output size (chars) to trigger archiving",
458            ),
459        );
460        archive.insert(
461            "max_age_hours".into(),
462            key(
463                "u64",
464                serde_json::json!(cfg.archive.max_age_hours),
465                "Maximum age of archived entries before cleanup",
466            ),
467        );
468        archive.insert(
469            "max_disk_mb".into(),
470            key(
471                "u64",
472                serde_json::json!(cfg.archive.max_disk_mb),
473                "Maximum total disk usage for the archive",
474            ),
475        );
476        sections.insert("archive".into(), SectionSchema {
477            description: "Settings for the zero-loss compression archive (large tool outputs saved to disk)".into(),
478            keys: archive,
479        });
480
481        let mut autonomy = BTreeMap::new();
482        autonomy.insert(
483            "enabled".into(),
484            key(
485                "bool",
486                serde_json::json!(cfg.autonomy.enabled),
487                "Enable autonomous background behaviors",
488            ),
489        );
490        autonomy.insert(
491            "auto_preload".into(),
492            key(
493                "bool",
494                serde_json::json!(cfg.autonomy.auto_preload),
495                "Auto-preload related files on first read",
496            ),
497        );
498        autonomy.insert(
499            "auto_dedup".into(),
500            key(
501                "bool",
502                serde_json::json!(cfg.autonomy.auto_dedup),
503                "Auto-deduplicate repeated reads",
504            ),
505        );
506        autonomy.insert(
507            "auto_related".into(),
508            key(
509                "bool",
510                serde_json::json!(cfg.autonomy.auto_related),
511                "Auto-load graph-related files",
512            ),
513        );
514        autonomy.insert(
515            "auto_consolidate".into(),
516            key(
517                "bool",
518                serde_json::json!(cfg.autonomy.auto_consolidate),
519                "Auto-consolidate knowledge periodically",
520            ),
521        );
522        autonomy.insert(
523            "silent_preload".into(),
524            key(
525                "bool",
526                serde_json::json!(cfg.autonomy.silent_preload),
527                "Suppress preload notifications in output",
528            ),
529        );
530        autonomy.insert(
531            "dedup_threshold".into(),
532            key(
533                "usize",
534                serde_json::json!(cfg.autonomy.dedup_threshold),
535                "Number of repeated reads before dedup triggers",
536            ),
537        );
538        autonomy.insert(
539            "consolidate_every_calls".into(),
540            key(
541                "u32",
542                serde_json::json!(cfg.autonomy.consolidate_every_calls),
543                "Consolidate knowledge every N tool calls",
544            ),
545        );
546        autonomy.insert(
547            "consolidate_cooldown_secs".into(),
548            key(
549                "u64",
550                serde_json::json!(cfg.autonomy.consolidate_cooldown_secs),
551                "Minimum seconds between consolidation runs",
552            ),
553        );
554        sections.insert(
555            "autonomy".into(),
556            SectionSchema {
557                description:
558                    "Controls autonomous background behaviors (preload, dedup, consolidation)"
559                        .into(),
560                keys: autonomy,
561            },
562        );
563
564        let mut loop_det = BTreeMap::new();
565        loop_det.insert(
566            "normal_threshold".into(),
567            key(
568                "u32",
569                serde_json::json!(cfg.loop_detection.normal_threshold),
570                "Repetitions before reducing output",
571            ),
572        );
573        loop_det.insert(
574            "reduced_threshold".into(),
575            key(
576                "u32",
577                serde_json::json!(cfg.loop_detection.reduced_threshold),
578                "Repetitions before further reducing output",
579            ),
580        );
581        loop_det.insert(
582            "blocked_threshold".into(),
583            key(
584                "u32",
585                serde_json::json!(cfg.loop_detection.blocked_threshold),
586                "Repetitions before blocking. 0 = disabled",
587            ),
588        );
589        loop_det.insert(
590            "window_secs".into(),
591            key(
592                "u64",
593                serde_json::json!(cfg.loop_detection.window_secs),
594                "Time window in seconds for loop detection",
595            ),
596        );
597        loop_det.insert(
598            "search_group_limit".into(),
599            key(
600                "u32",
601                serde_json::json!(cfg.loop_detection.search_group_limit),
602                "Maximum unique searches within a loop window",
603            ),
604        );
605        loop_det.insert(
606            "tool_total_limits".into(),
607            key(
608                "table",
609                serde_json::json!({"ctx_read": 100, "ctx_search": 80, "ctx_shell": 50, "ctx_semantic_search": 60}),
610                "Per-tool total call limits within a session. Keys are tool names, values are max calls",
611            ),
612        );
613        sections.insert(
614            "loop_detection".into(),
615            SectionSchema {
616                description: "Loop detection settings for preventing repeated identical tool calls"
617                    .into(),
618                keys: loop_det,
619            },
620        );
621
622        let mut updates = BTreeMap::new();
623        updates.insert(
624            "auto_update".into(),
625            key(
626                "bool",
627                serde_json::json!(cfg.updates.auto_update),
628                "Enable automatic updates (requires explicit opt-in)",
629            ),
630        );
631        updates.insert(
632            "check_interval_hours".into(),
633            key(
634                "u64",
635                serde_json::json!(cfg.updates.check_interval_hours),
636                "How often to check for updates (hours)",
637            ),
638        );
639        updates.insert(
640            "notify_only".into(),
641            key(
642                "bool",
643                serde_json::json!(cfg.updates.notify_only),
644                "Only notify about updates, don't install automatically",
645            ),
646        );
647        sections.insert(
648            "updates".into(),
649            SectionSchema {
650                description: "Automatic update configuration".into(),
651                keys: updates,
652            },
653        );
654
655        let mut boundary = BTreeMap::new();
656        boundary.insert(
657            "cross_project_search".into(),
658            key(
659                "bool",
660                serde_json::json!(cfg.boundary_policy.cross_project_search),
661                "Allow searching across project boundaries",
662            ),
663        );
664        boundary.insert(
665            "cross_project_import".into(),
666            key(
667                "bool",
668                serde_json::json!(cfg.boundary_policy.cross_project_import),
669                "Allow importing knowledge from other projects",
670            ),
671        );
672        boundary.insert(
673            "audit_cross_access".into(),
674            key(
675                "bool",
676                serde_json::json!(cfg.boundary_policy.audit_cross_access),
677                "Log audit events when cross-project access occurs",
678            ),
679        );
680        boundary.insert(
681            "universal_gotchas_enabled".into(),
682            key(
683                "bool",
684                serde_json::json!(cfg.boundary_policy.universal_gotchas_enabled),
685                "Load universal (cross-project) gotchas",
686            ),
687        );
688        sections.insert(
689            "boundary_policy".into(),
690            SectionSchema {
691                description: "Cross-project boundary and access control policies".into(),
692                keys: boundary,
693            },
694        );
695
696        let mut secret_det = BTreeMap::new();
697        secret_det.insert(
698            "enabled".into(),
699            key(
700                "bool",
701                serde_json::json!(cfg.secret_detection.enabled),
702                "Enable secret/credential detection in tool outputs",
703            ),
704        );
705        secret_det.insert(
706            "redact".into(),
707            key(
708                "bool",
709                serde_json::json!(cfg.secret_detection.redact),
710                "Redact detected secrets from output",
711            ),
712        );
713        secret_det.insert(
714            "custom_patterns".into(),
715            key(
716                "array",
717                serde_json::json!(cfg.secret_detection.custom_patterns),
718                "Additional regex patterns to detect as secrets",
719            ),
720        );
721        sections.insert(
722            "secret_detection".into(),
723            SectionSchema {
724                description: "Secret/credential detection and redaction settings".into(),
725                keys: secret_det,
726            },
727        );
728
729        let mut cloud = BTreeMap::new();
730        cloud.insert(
731            "contribute_enabled".into(),
732            key(
733                "bool",
734                serde_json::json!(cfg.cloud.contribute_enabled),
735                "Enable contributing anonymized stats to lean-ctx cloud",
736            ),
737        );
738        sections.insert(
739            "cloud".into(),
740            SectionSchema {
741                description: "Cloud feature settings".into(),
742                keys: cloud,
743            },
744        );
745
746        let mut proxy = BTreeMap::new();
747        proxy.insert(
748            "anthropic_upstream".into(),
749            key(
750                "string?",
751                serde_json::json!(cfg.proxy.anthropic_upstream),
752                "Custom upstream URL for Anthropic API proxy",
753            ),
754        );
755        proxy.insert(
756            "openai_upstream".into(),
757            key(
758                "string?",
759                serde_json::json!(cfg.proxy.openai_upstream),
760                "Custom upstream URL for OpenAI API proxy",
761            ),
762        );
763        proxy.insert(
764            "gemini_upstream".into(),
765            key(
766                "string?",
767                serde_json::json!(cfg.proxy.gemini_upstream),
768                "Custom upstream URL for Gemini API proxy",
769            ),
770        );
771        sections.insert(
772            "proxy".into(),
773            SectionSchema {
774                description: "Proxy upstream configuration for API routing".into(),
775                keys: proxy,
776            },
777        );
778
779        let mem = &cfg.memory;
780        let mut mem_knowledge = BTreeMap::new();
781        mem_knowledge.insert(
782            "max_facts".into(),
783            key(
784                "usize",
785                serde_json::json!(mem.knowledge.max_facts),
786                "Maximum number of knowledge facts stored per project",
787            ),
788        );
789        mem_knowledge.insert(
790            "max_patterns".into(),
791            key(
792                "usize",
793                serde_json::json!(mem.knowledge.max_patterns),
794                "Maximum number of patterns stored",
795            ),
796        );
797        mem_knowledge.insert(
798            "max_history".into(),
799            key(
800                "usize",
801                serde_json::json!(mem.knowledge.max_history),
802                "Maximum history entries retained",
803            ),
804        );
805        mem_knowledge.insert(
806            "contradiction_threshold".into(),
807            key(
808                "f32",
809                clean_f32(mem.knowledge.contradiction_threshold),
810                "Confidence threshold for contradiction detection",
811            ),
812        );
813        mem_knowledge.insert(
814            "recall_facts_limit".into(),
815            key(
816                "usize",
817                serde_json::json!(mem.knowledge.recall_facts_limit),
818                "Maximum facts returned per recall query",
819            ),
820        );
821        mem_knowledge.insert(
822            "rooms_limit".into(),
823            key(
824                "usize",
825                serde_json::json!(mem.knowledge.rooms_limit),
826                "Maximum number of rooms returned",
827            ),
828        );
829        mem_knowledge.insert(
830            "timeline_limit".into(),
831            key(
832                "usize",
833                serde_json::json!(mem.knowledge.timeline_limit),
834                "Maximum number of timeline entries returned",
835            ),
836        );
837        mem_knowledge.insert(
838            "relations_limit".into(),
839            key(
840                "usize",
841                serde_json::json!(mem.knowledge.relations_limit),
842                "Maximum number of relations returned",
843            ),
844        );
845        sections.insert(
846            "memory.knowledge".into(),
847            SectionSchema {
848                description: "Knowledge memory budgets (facts, patterns, gotchas)".into(),
849                keys: mem_knowledge,
850            },
851        );
852
853        let mut mem_episodic = BTreeMap::new();
854        mem_episodic.insert(
855            "max_episodes".into(),
856            key(
857                "usize",
858                serde_json::json!(mem.episodic.max_episodes),
859                "Maximum number of episodes retained",
860            ),
861        );
862        mem_episodic.insert(
863            "max_actions_per_episode".into(),
864            key(
865                "usize",
866                serde_json::json!(mem.episodic.max_actions_per_episode),
867                "Maximum actions tracked per episode",
868            ),
869        );
870        mem_episodic.insert(
871            "summary_max_chars".into(),
872            key(
873                "usize",
874                serde_json::json!(mem.episodic.summary_max_chars),
875                "Maximum characters in episode summary",
876            ),
877        );
878        sections.insert(
879            "memory.episodic".into(),
880            SectionSchema {
881                description: "Episodic memory budgets (session episodes)".into(),
882                keys: mem_episodic,
883            },
884        );
885
886        let mut mem_procedural = BTreeMap::new();
887        mem_procedural.insert(
888            "max_procedures".into(),
889            key(
890                "usize",
891                serde_json::json!(mem.procedural.max_procedures),
892                "Maximum number of learned procedures stored",
893            ),
894        );
895        mem_procedural.insert(
896            "min_repetitions".into(),
897            key(
898                "usize",
899                serde_json::json!(mem.procedural.min_repetitions),
900                "Minimum repetitions before a pattern is stored",
901            ),
902        );
903        mem_procedural.insert(
904            "min_sequence_len".into(),
905            key(
906                "usize",
907                serde_json::json!(mem.procedural.min_sequence_len),
908                "Minimum sequence length for procedure detection",
909            ),
910        );
911        mem_procedural.insert(
912            "max_window_size".into(),
913            key(
914                "usize",
915                serde_json::json!(mem.procedural.max_window_size),
916                "Maximum window size for pattern analysis",
917            ),
918        );
919        sections.insert(
920            "memory.procedural".into(),
921            SectionSchema {
922                description: "Procedural memory budgets (learned patterns)".into(),
923                keys: mem_procedural,
924            },
925        );
926
927        let mut mem_lifecycle = BTreeMap::new();
928        mem_lifecycle.insert(
929            "decay_rate".into(),
930            key(
931                "f32",
932                clean_f32(mem.lifecycle.decay_rate),
933                "Rate at which knowledge confidence decays over time",
934            ),
935        );
936        mem_lifecycle.insert(
937            "low_confidence_threshold".into(),
938            key(
939                "f32",
940                clean_f32(mem.lifecycle.low_confidence_threshold),
941                "Threshold below which facts are considered low-confidence",
942            ),
943        );
944        mem_lifecycle.insert(
945            "stale_days".into(),
946            key(
947                "i64",
948                serde_json::json!(mem.lifecycle.stale_days),
949                "Days after which unused facts are considered stale",
950            ),
951        );
952        mem_lifecycle.insert(
953            "similarity_threshold".into(),
954            key(
955                "f32",
956                clean_f32(mem.lifecycle.similarity_threshold),
957                "Similarity threshold for deduplication",
958            ),
959        );
960        sections.insert(
961            "memory.lifecycle".into(),
962            SectionSchema {
963                description: "Knowledge lifecycle policy (decay, staleness, dedup)".into(),
964                keys: mem_lifecycle,
965            },
966        );
967
968        let mut mem_gotcha = BTreeMap::new();
969        mem_gotcha.insert(
970            "max_gotchas_per_project".into(),
971            key(
972                "usize",
973                serde_json::json!(mem.gotcha.max_gotchas_per_project),
974                "Maximum gotchas stored per project",
975            ),
976        );
977        mem_gotcha.insert(
978            "retrieval_budget_per_room".into(),
979            key(
980                "usize",
981                serde_json::json!(mem.gotcha.retrieval_budget_per_room),
982                "Maximum gotchas retrieved per room per query",
983            ),
984        );
985        mem_gotcha.insert(
986            "default_decay_rate".into(),
987            key(
988                "f32",
989                clean_f32(mem.gotcha.default_decay_rate),
990                "Default decay rate for gotcha importance",
991            ),
992        );
993        sections.insert(
994            "memory.gotcha".into(),
995            SectionSchema {
996                description: "Gotcha memory settings (project-specific warnings and pitfalls)"
997                    .into(),
998                keys: mem_gotcha,
999            },
1000        );
1001
1002        let mut mem_embeddings = BTreeMap::new();
1003        mem_embeddings.insert(
1004            "max_facts".into(),
1005            key(
1006                "usize",
1007                serde_json::json!(mem.embeddings.max_facts),
1008                "Maximum number of embedding facts stored",
1009            ),
1010        );
1011        sections.insert(
1012            "memory.embeddings".into(),
1013            SectionSchema {
1014                description: "Embeddings memory settings for semantic search".into(),
1015                keys: mem_embeddings,
1016            },
1017        );
1018
1019        let mut aliases = BTreeMap::new();
1020        aliases.insert(
1021            "command".into(),
1022            key(
1023                "string",
1024                serde_json::json!(""),
1025                "The command pattern to match (e.g. 'deploy')",
1026            ),
1027        );
1028        aliases.insert(
1029            "alias".into(),
1030            key(
1031                "string",
1032                serde_json::json!(""),
1033                "The alias definition to execute",
1034            ),
1035        );
1036        sections.insert("custom_aliases".into(), SectionSchema {
1037            description: "Custom command aliases (array of {command, alias} entries). Note: field names are 'command' and 'alias' (not 'name')".into(),
1038            keys: aliases,
1039        });
1040
1041        if let Some(root_section) = sections.get_mut("root") {
1042            root_section.keys.insert(
1043                "custom_aliases".into(),
1044                key(
1045                    "array",
1046                    serde_json::json!([]),
1047                    "Custom command aliases (array of {command, alias} entries)",
1048                ),
1049            );
1050        }
1051
1052        ConfigSchema {
1053            version: 1,
1054            sections,
1055        }
1056    }
1057
1058    /// All known TOML keys (dot-separated) for validation.
1059    pub fn known_keys(&self) -> Vec<String> {
1060        let mut keys = Vec::new();
1061        for (section, schema) in &self.sections {
1062            if section == "root" {
1063                for key_name in schema.keys.keys() {
1064                    keys.push(key_name.clone());
1065                }
1066            } else {
1067                if schema.keys.is_empty() {
1068                    keys.push(section.clone());
1069                }
1070                for key_name in schema.keys.keys() {
1071                    keys.push(format!("{section}.{key_name}"));
1072                }
1073            }
1074        }
1075        keys
1076    }
1077}