1use super::serde_defaults;
9#[allow(clippy::wildcard_imports)]
10use super::*;
11use serde::{Deserialize, Serialize};
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
15#[serde(default)]
16pub struct ShadowConfig {
17 #[serde(default = "serde_defaults::default_true")]
18 pub auto_record: bool,
19 pub enabled: bool,
20 pub report_interval: usize,
21 pub baseline_model: String,
22 pub report_dir: String,
23}
24
25impl Default for ShadowConfig {
26 fn default() -> Self {
27 Self {
28 auto_record: true,
29 enabled: false,
30 report_interval: 10,
31 baseline_model: "gpt-4o".into(),
32 report_dir: String::new(),
33 }
34 }
35}
36
37#[cfg(test)]
38mod shadow_config_tests {
39 use super::ShadowConfig;
40
41 #[test]
42 fn auto_record_defaults_to_true_and_can_be_disabled() {
43 let defaults: ShadowConfig = serde_json::from_str("{}").expect("valid config");
44 let disabled: ShadowConfig =
45 serde_json::from_str(r#"{"auto_record": false}"#).expect("valid config");
46
47 assert!(defaults.auto_record);
48 assert!(!disabled.auto_record);
49 }
50}
51
52#[derive(Debug, Clone, Default, Serialize, Deserialize)]
57#[serde(default)]
58pub struct OclaConfig {
59 pub sidecar: crate::core::ocla::sidecar::SidecarConfig,
60 pub grpc: crate::core::ocla::grpc_bridge::GrpcConfig,
61 pub delivery: DeliveryConfig,
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
65#[serde(default)]
66pub struct DeliveryConfig {
67 pub enabled: bool,
68 pub delivery_for_subagents: bool,
71 pub max_entries: usize,
72 pub ttl_minutes: u64,
73 pub cache: CacheConfig,
75}
76
77impl Default for DeliveryConfig {
78 fn default() -> Self {
79 Self {
80 enabled: true,
81 delivery_for_subagents: true,
82 max_entries: 4096,
83 ttl_minutes: 30,
84 cache: CacheConfig::default(),
85 }
86 }
87}
88
89impl OclaConfig {
90 pub fn delivery_enabled(&self) -> bool {
91 self.delivery.enabled
92 }
93}
94
95#[derive(Debug, Clone, Serialize, Deserialize)]
97#[serde(default)]
98pub struct CacheConfig {
99 pub l1_max_entries: usize,
100 pub l1_ttl_secs: u64,
101 pub l2_max_entries: usize,
102 pub l2_ttl_secs: u64,
103 pub l3_max_bytes: u64,
104 pub l3_gc_threshold: f64,
105 pub shell_cache_enabled: bool,
106 pub compose_cache_enabled: bool,
107}
108
109impl Default for CacheConfig {
110 fn default() -> Self {
111 Self {
112 l1_max_entries: 1_000,
113 l1_ttl_secs: 300,
114 l2_max_entries: 10_000,
115 l2_ttl_secs: 3_600,
116 l3_max_bytes: 500_000_000,
117 l3_gc_threshold: 0.9,
118 shell_cache_enabled: false,
119 compose_cache_enabled: true,
120 }
121 }
122}
123
124#[cfg(test)]
125mod cache_config_tests {
126 use super::CacheConfig;
127
128 #[test]
129 fn cache_defaults_match_delivery_budget() {
130 assert_eq!(CacheConfig::default().l3_max_bytes, 500_000_000);
131 assert!(!CacheConfig::default().shell_cache_enabled);
132 assert!(CacheConfig::default().compose_cache_enabled);
133 }
134
135 #[test]
136 fn cache_config_deserializes_partial_overrides() {
137 let parsed: CacheConfig =
138 serde_json::from_str(r#"{"l1_max_entries": 12, "shell_cache_enabled": true}"#).unwrap();
139 assert_eq!(parsed.l1_max_entries, 12);
140 assert!(parsed.shell_cache_enabled);
141 assert_eq!(parsed.l2_ttl_secs, 3_600);
142 }
143}
144
145#[derive(Debug, Clone, Serialize, Deserialize)]
150#[serde(default)]
151pub struct AgentsConfig {
152 pub gc_interval_minutes: u64,
154 pub identity_ttl_hours: u64,
156 pub presence_ttl_hours: u64,
158 pub scratchpad_default_ttl_hours: u64,
160 pub logical_session_ttl_seconds: u64,
162 pub max_concurrent_workers: usize,
165 pub max_scratchpad_entries: usize,
167}
168
169impl Default for AgentsConfig {
170 fn default() -> Self {
171 Self {
172 gc_interval_minutes: 10,
173 identity_ttl_hours: 48,
174 presence_ttl_hours: 24,
175 scratchpad_default_ttl_hours: 12,
176 logical_session_ttl_seconds: 180,
177 max_concurrent_workers: 15,
178 max_scratchpad_entries: 200,
179 }
180 }
181}
182
183#[cfg(test)]
184mod agents_config_tests {
185 use super::AgentsConfig;
186
187 #[test]
188 fn default_values_are_sane() {
189 let cfg = AgentsConfig::default();
190 assert_eq!(cfg.gc_interval_minutes, 10);
191 assert_eq!(cfg.identity_ttl_hours, 48);
192 assert_eq!(cfg.presence_ttl_hours, 24);
193 assert_eq!(cfg.scratchpad_default_ttl_hours, 12);
194 assert_eq!(cfg.logical_session_ttl_seconds, 180);
195 assert_eq!(cfg.max_concurrent_workers, 15);
196 assert_eq!(cfg.max_scratchpad_entries, 200);
197 }
198
199 #[test]
200 fn deserializes_with_missing_fields() {
201 let json = r"{}";
202 let cfg: AgentsConfig = serde_json::from_str(json).expect("empty object → defaults");
203 assert_eq!(cfg.gc_interval_minutes, 10);
204 }
205
206 #[test]
207 fn partial_override() {
208 let json = r#"{"gc_interval_minutes": 5, "presence_ttl_hours": 12}"#;
209 let cfg: AgentsConfig = serde_json::from_str(json).expect("partial");
210 assert_eq!(cfg.gc_interval_minutes, 5);
211 assert_eq!(cfg.presence_ttl_hours, 12);
212 assert_eq!(cfg.identity_ttl_hours, 48);
213 }
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize)]
217#[serde(default)]
218pub struct SecretDetectionConfig {
219 pub enabled: bool,
220 pub redact: bool,
221 pub custom_patterns: Vec<String>,
222 pub exclude_patterns: Vec<String>,
227}
228
229#[derive(Debug, Clone, Serialize, Deserialize)]
234#[serde(default)]
235pub struct SetupConfig {
236 pub auto_inject_rules: Option<bool>,
240 pub auto_inject_skills: Option<bool>,
243 #[serde(default = "serde_defaults::default_true")]
245 pub auto_update_mcp: bool,
246}
247
248impl Default for SetupConfig {
249 fn default() -> Self {
250 Self {
251 auto_inject_rules: None,
252 auto_inject_skills: None,
253 auto_update_mcp: true,
254 }
255 }
256}
257
258impl SetupConfig {
259 pub fn should_inject_rules(&self) -> bool {
263 match self.auto_inject_rules {
264 Some(v) => v,
265 None => Self::rules_already_present(),
266 }
267 }
268
269 pub fn should_inject_skills(&self) -> bool {
271 match self.auto_inject_skills {
272 Some(v) => v,
273 None => Self::rules_already_present(),
274 }
275 }
276
277 pub fn should_update_mcp(&self) -> bool {
282 self.auto_update_mcp
283 }
284
285 fn rules_already_present() -> bool {
293 let Some(home) = dirs::home_dir() else {
294 return false;
295 };
296 if crate::rules_inject::any_rules_marker_present(&home) {
297 return true;
298 }
299 let legacy_paths = [
300 crate::core::editor_registry::claude_rules_dir(&home).join("lean-ctx.md"),
301 crate::core::editor_registry::codebuddy_rules_dir(&home).join("lean-ctx.md"),
302 ];
303 legacy_paths.iter().any(|p| {
304 std::fs::read_to_string(p)
305 .is_ok_and(|c| c.contains(crate::core::rules_canonical::START_MARK))
306 })
307 }
308}
309
310impl Default for SecretDetectionConfig {
311 fn default() -> Self {
312 Self {
313 enabled: true,
314 redact: true,
315 custom_patterns: Vec::new(),
316 exclude_patterns: Vec::new(),
317 }
318 }
319}
320
321#[derive(Debug, Clone, Serialize, Deserialize)]
323#[serde(default)]
324pub struct ArchiveConfig {
325 pub enabled: bool,
326 pub threshold_chars: usize,
327 pub max_age_hours: u64,
328 pub max_disk_mb: u64,
329 pub ephemeral: bool,
330 pub ephemeral_min_tokens: usize,
333 pub inline_max_bytes: usize,
336 pub raw_commands: Vec<String>,
341 pub verbatim_max_tokens: usize,
349}
350
351#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
356#[serde(default)]
357pub struct ConversationConfig {
358 pub compression_enabled: bool,
360 pub preserve_last_n_turns: usize,
362 pub compression_threshold_tokens: usize,
364 pub min_score_to_preserve: f64,
366 pub summarize_score_range: [f64; 2],
368 pub drop_score_below: f64,
370 pub ccr_store_dropped: bool,
372}
373
374impl Default for ConversationConfig {
375 fn default() -> Self {
376 Self {
377 compression_enabled: false,
378 preserve_last_n_turns: 10,
379 compression_threshold_tokens: 50_000,
380 min_score_to_preserve: 0.5,
381 summarize_score_range: [0.2, 0.5],
382 drop_score_below: 0.2,
383 ccr_store_dropped: true,
384 }
385 }
386}
387
388impl Default for ArchiveConfig {
389 fn default() -> Self {
390 Self {
391 enabled: true,
392 threshold_chars: 800,
393 max_age_hours: 48,
394 max_disk_mb: 500,
395 ephemeral: true,
396 ephemeral_min_tokens: 2000,
397 inline_max_bytes: 32 * 1024,
398 raw_commands: crate::core::firewall::DEFAULT_RAW_COMMANDS
399 .iter()
400 .map(|s| (*s).to_string())
401 .collect(),
402 verbatim_max_tokens: 100_000,
403 }
404 }
405}
406
407impl ArchiveConfig {
408 pub fn ephemeral_effective(&self) -> bool {
409 if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL") {
410 return !matches!(v.trim(), "0" | "false" | "off");
411 }
412 self.ephemeral && self.enabled
413 }
414
415 pub fn ephemeral_min_tokens_effective(&self) -> usize {
416 if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL_MIN_TOKENS")
417 && let Ok(n) = v.trim().parse::<usize>()
418 {
419 return n;
420 }
421 self.ephemeral_min_tokens
422 }
423
424 pub fn verbatim_max_tokens_effective(&self) -> usize {
426 if let Ok(v) = std::env::var("LEAN_CTX_VERBATIM_MAX_TOKENS")
427 && let Ok(n) = v.trim().parse::<usize>()
428 {
429 return n;
430 }
431 self.verbatim_max_tokens
432 }
433
434 pub fn inline_max_bytes_effective(&self) -> usize {
435 if let Ok(v) = std::env::var("LEAN_CTX_INLINE_MAX_BYTES")
436 && let Ok(n) = v.trim().parse::<usize>()
437 {
438 return n;
439 }
440 self.inline_max_bytes
441 }
442}
443
444#[derive(Debug, Clone, Serialize, Deserialize)]
448#[serde(default)]
449pub struct ProvidersConfig {
450 pub enabled: bool,
452 pub github: ProviderEntryConfig,
454 pub gitlab: ProviderEntryConfig,
456 pub auto_index: bool,
458 pub cache_ttl_secs: u64,
460 #[serde(default)]
462 pub mcp_bridges: std::collections::HashMap<String, McpBridgeEntry>,
463}
464
465impl Default for ProvidersConfig {
466 fn default() -> Self {
467 Self {
468 enabled: true,
469 github: ProviderEntryConfig::default(),
470 gitlab: ProviderEntryConfig::default(),
471 auto_index: true,
472 cache_ttl_secs: 120,
473 mcp_bridges: std::collections::HashMap::new(),
474 }
475 }
476}
477
478#[derive(Debug, Clone, Serialize, Deserialize)]
480#[serde(default)]
481pub struct KnowledgeRoutingConfig {
482 pub enabled: bool,
483 pub max_references: usize,
484 pub hint_prefix: String,
485}
486
487impl Default for KnowledgeRoutingConfig {
488 fn default() -> Self {
489 Self {
490 enabled: true,
491 max_references: 5,
492 hint_prefix: "--- Knowledge Context ---".to_string(),
493 }
494 }
495}
496
497#[derive(Debug, Clone, Serialize, Deserialize)]
498pub struct McpBridgeEntry {
499 #[serde(default)]
501 pub url: Option<String>,
502 #[serde(default)]
504 pub command: Option<String>,
505 #[serde(default)]
507 pub args: Vec<String>,
508 #[serde(default)]
510 pub description: Option<String>,
511 #[serde(default)]
513 pub auth_env: Option<String>,
514}
515
516#[derive(Debug, Clone, Serialize, Deserialize)]
518#[serde(default)]
519pub struct ProviderEntryConfig {
520 pub enabled: bool,
522 pub token: Option<String>,
524 pub api_url: Option<String>,
526 pub project: Option<String>,
528}
529
530impl Default for ProviderEntryConfig {
531 fn default() -> Self {
532 Self {
533 enabled: true,
534 token: None,
535 api_url: None,
536 project: None,
537 }
538 }
539}
540
541#[derive(Debug, Clone, Serialize, Deserialize)]
543#[serde(default)]
544pub struct AutonomyConfig {
545 pub enabled: bool,
546 pub auto_preload: bool,
547 pub auto_dedup: bool,
548 pub auto_related: bool,
549 pub auto_consolidate: bool,
550 pub silent_preload: bool,
551 pub dedup_threshold: usize,
552 pub consolidate_every_calls: u32,
553 pub consolidate_cooldown_secs: u64,
554 #[serde(default = "serde_defaults::default_true")]
555 pub cognition_loop_enabled: bool,
556 #[serde(default = "serde_defaults::default_cognition_loop_interval")]
557 pub cognition_loop_interval_secs: u64,
558 #[serde(default = "serde_defaults::default_cognition_loop_max_steps")]
559 pub cognition_loop_max_steps: u8,
560 #[serde(default = "serde_defaults::default_cognition_synthesis_min_cluster")]
563 pub cognition_synthesis_min_cluster: usize,
564}
565
566impl Default for AutonomyConfig {
567 fn default() -> Self {
568 Self {
569 enabled: true,
570 auto_preload: true,
571 auto_dedup: true,
572 auto_related: true,
573 auto_consolidate: true,
574 silent_preload: true,
575 dedup_threshold: 8,
576 consolidate_every_calls: 25,
577 consolidate_cooldown_secs: 120,
578 cognition_loop_enabled: true,
579 cognition_loop_interval_secs: 3600,
580 cognition_loop_max_steps: 9,
581 cognition_synthesis_min_cluster: 3,
582 }
583 }
584}
585
586#[derive(Debug, Clone, Serialize, Deserialize)]
589#[serde(default)]
590pub struct UpdatesConfig {
591 pub auto_update: bool,
592 pub check_interval_hours: u64,
593 pub notify_only: bool,
594}
595
596impl Default for UpdatesConfig {
597 fn default() -> Self {
598 Self {
599 auto_update: false,
600 check_interval_hours: 6,
601 notify_only: false,
602 }
603 }
604}
605
606#[derive(Debug, Clone, Serialize, Deserialize)]
612#[serde(default)]
613pub struct ContextConfig {
614 pub budget_tokens: usize,
615 pub diet_max_config_tokens: usize,
616 pub diet_relevance_threshold: f64,
617 pub diet_rebalance_on_change: bool,
618 pub diet_staleness_enabled: bool,
619 pub proactive_expansion: bool,
621 pub proactive_expansion_budget_tokens: usize,
623 pub proactive_expansion_threshold: f64,
625 pub proactive_expansion_max_age_secs: u64,
627}
628
629impl Default for ContextConfig {
630 fn default() -> Self {
631 Self {
632 budget_tokens: 8000,
633 diet_max_config_tokens: 800,
634 diet_relevance_threshold: 0.15,
635 diet_rebalance_on_change: true,
636 diet_staleness_enabled: true,
637 proactive_expansion: true,
638 proactive_expansion_budget_tokens: 2000,
639 proactive_expansion_threshold: 0.6,
640 proactive_expansion_max_age_secs: 3600,
641 }
642 }
643}
644
645impl UpdatesConfig {
646 pub fn from_env() -> Self {
647 let mut cfg = Self::default();
648 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_UPDATE") {
649 cfg.auto_update = v == "1" || v.eq_ignore_ascii_case("true");
650 }
651 if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_INTERVAL_HOURS")
652 && let Ok(h) = v.parse::<u64>()
653 {
654 cfg.check_interval_hours = h.clamp(1, 168);
655 }
656 if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_NOTIFY_ONLY") {
657 cfg.notify_only = v == "1" || v.eq_ignore_ascii_case("true");
658 }
659 cfg
660 }
661}
662
663impl AutonomyConfig {
664 pub fn from_env() -> Self {
666 let mut cfg = Self::default();
667 if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
668 && (v == "false" || v == "0")
669 {
670 cfg.enabled = false;
671 }
672 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
673 cfg.auto_preload = v != "false" && v != "0";
674 }
675 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
676 cfg.auto_dedup = v != "false" && v != "0";
677 }
678 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
679 cfg.auto_related = v != "false" && v != "0";
680 }
681 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_CONSOLIDATE") {
682 cfg.auto_consolidate = v != "false" && v != "0";
683 }
684 if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
685 cfg.silent_preload = v != "false" && v != "0";
686 }
687 if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD")
688 && let Ok(n) = v.parse()
689 {
690 cfg.dedup_threshold = n;
691 }
692 if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_EVERY_CALLS")
693 && let Ok(n) = v.parse()
694 {
695 cfg.consolidate_every_calls = n;
696 }
697 if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_COOLDOWN_SECS")
698 && let Ok(n) = v.parse()
699 {
700 cfg.consolidate_cooldown_secs = n;
701 }
702 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
703 cfg.cognition_loop_enabled = v != "false" && v != "0";
704 }
705 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
706 && let Ok(n) = v.parse()
707 {
708 cfg.cognition_loop_interval_secs = n;
709 }
710 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
711 && let Ok(n) = v.parse()
712 {
713 cfg.cognition_loop_max_steps = n;
714 }
715 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_SYNTHESIS_MIN_CLUSTER")
716 && let Ok(n) = v.parse()
717 {
718 cfg.cognition_synthesis_min_cluster = n;
719 }
720 cfg
721 }
722
723 pub fn load() -> Self {
725 let file_cfg = Config::load().autonomy;
726 let mut cfg = file_cfg;
727 if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
728 && (v == "false" || v == "0")
729 {
730 cfg.enabled = false;
731 }
732 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
733 cfg.auto_preload = v != "false" && v != "0";
734 }
735 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
736 cfg.auto_dedup = v != "false" && v != "0";
737 }
738 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
739 cfg.auto_related = v != "false" && v != "0";
740 }
741 if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
742 cfg.silent_preload = v != "false" && v != "0";
743 }
744 if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD")
745 && let Ok(n) = v.parse()
746 {
747 cfg.dedup_threshold = n;
748 }
749 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
750 cfg.cognition_loop_enabled = v != "false" && v != "0";
751 }
752 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
753 && let Ok(n) = v.parse()
754 {
755 cfg.cognition_loop_interval_secs = n;
756 }
757 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
758 && let Ok(n) = v.parse()
759 {
760 cfg.cognition_loop_max_steps = n;
761 }
762 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_SYNTHESIS_MIN_CLUSTER")
763 && let Ok(n) = v.parse()
764 {
765 cfg.cognition_synthesis_min_cluster = n;
766 }
767 cfg
768 }
769}
770
771#[derive(Debug, Clone, Serialize, Deserialize, Default)]
778#[serde(default)]
779pub struct TelemetryConfig {
780 pub enabled: bool,
782 pub last_heartbeat: Option<String>,
784}
785
786#[derive(Debug, Clone, Serialize, Deserialize, Default)]
788#[serde(default)]
789pub struct CloudConfig {
790 pub contribute_enabled: bool,
791 pub last_contribute: Option<String>,
792 #[serde(default)]
794 pub sync_stats_enabled: bool,
795 pub last_sync: Option<String>,
796 #[serde(default)]
798 pub sync_gain_enabled: bool,
799 pub last_gain_sync: Option<String>,
800 #[serde(default)]
802 pub sync_models_enabled: bool,
803 pub last_model_pull: Option<String>,
804 pub auto_sync: bool,
807 pub last_auto_sync: Option<String>,
808 pub auto_index: bool,
811 pub last_index_push: std::collections::HashMap<String, String>,
814}
815
816#[derive(Debug, Clone, Serialize, Deserialize)]
822#[serde(default)]
823pub struct GainConfig {
824 pub auto_publish: bool,
827 pub leaderboard: bool,
829 pub display_name: Option<String>,
831 pub auto_publish_interval_hours: u64,
833 pub last_auto_publish: Option<String>,
836}
837
838impl Default for GainConfig {
839 fn default() -> Self {
840 Self {
841 auto_publish: false,
842 leaderboard: false,
843 display_name: None,
844 auto_publish_interval_hours: 24,
845 last_auto_publish: None,
846 }
847 }
848}
849
850#[derive(Debug, Clone, Default, Serialize, Deserialize)]
859#[serde(default)]
860pub struct CostConfig {
861 #[serde(default)]
866 pub max_session_cost_usd: f64,
867 #[serde(default, skip_serializing_if = "Option::is_none")]
870 pub default_model: Option<String>,
871 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
876 pub models: HashMap<String, String>,
877 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
885 pub prices: HashMap<String, PriceOverride>,
886}
887
888#[derive(Debug, Clone, Serialize, Deserialize)]
890#[serde(default)]
891pub struct DecisionLoopConfig {
892 pub enabled: bool,
893 #[serde(default)]
896 pub max_filter_level: u8,
897}
898
899impl Default for DecisionLoopConfig {
900 fn default() -> Self {
901 Self {
902 enabled: true,
903 max_filter_level: 0,
904 }
905 }
906}
907
908#[derive(Debug, Clone, Default, Serialize, Deserialize)]
911#[serde(default)]
912pub struct PriceOverride {
913 pub input_per_m: Option<f64>,
914 pub output_per_m: Option<f64>,
915 pub cache_write_per_m: Option<f64>,
916 pub cache_read_per_m: Option<f64>,
917}
918
919impl CostConfig {
920 pub fn model_for_client(&self, client: &str) -> Option<String> {
924 self.models
925 .get(client)
926 .or(self.default_model.as_ref())
927 .map(|s| s.trim().to_string())
928 .filter(|s| !s.is_empty())
929 }
930}
931
932#[derive(Debug, Clone, Serialize, Deserialize)]
938#[serde(default)]
939pub struct CodeHealthConfig {
940 pub cognitive_threshold: u32,
943 pub gate: String,
946 pub annotate_reads: bool,
948 pub naming: bool,
950 pub coupling: bool,
952 #[serde(default)]
958 pub inject_context: bool,
959}
960
961impl Default for CodeHealthConfig {
962 fn default() -> Self {
963 Self {
964 cognitive_threshold: 15,
965 gate: "warn".to_string(),
966 annotate_reads: true,
967 naming: true,
968 coupling: true,
969 inject_context: false,
970 }
971 }
972}
973
974#[derive(Debug, Clone, Serialize, Deserialize)]
984#[serde(default)]
985pub struct IndexConfig {
986 pub respect_gitignore: bool,
990 pub exclude: Vec<String>,
993 pub include: Vec<String>,
996}
997
998impl Default for IndexConfig {
999 fn default() -> Self {
1000 Self {
1001 respect_gitignore: true,
1002 exclude: Vec::new(),
1003 include: Vec::new(),
1004 }
1005 }
1006}
1007
1008#[derive(Debug, Clone, Serialize, Deserialize)]
1018#[serde(default)]
1019pub struct GraphConfig {
1020 pub traversal_edges: bool,
1024}
1025
1026impl Default for GraphConfig {
1027 fn default() -> Self {
1028 Self {
1029 traversal_edges: true,
1030 }
1031 }
1032}
1033
1034#[derive(Debug, Clone, Serialize, Deserialize)]
1042#[serde(default)]
1043pub struct SkillifyConfig {
1044 pub enabled: bool,
1047 pub scope: String,
1050 pub min_confidence: f32,
1053 pub min_recurrence: u32,
1056}
1057
1058impl Default for SkillifyConfig {
1059 fn default() -> Self {
1060 Self {
1061 enabled: true,
1062 scope: "project".to_string(),
1063 min_confidence: 0.7,
1064 min_recurrence: 2,
1065 }
1066 }
1067}
1068
1069#[derive(Debug, Clone, Serialize, Deserialize)]
1074#[serde(default)]
1075pub struct SummariesConfig {
1076 pub enabled: bool,
1079 pub every_n_turns: u32,
1082 pub max_kept: u32,
1084}
1085
1086impl Default for SummariesConfig {
1087 fn default() -> Self {
1088 Self {
1089 enabled: true,
1090 every_n_turns: 25,
1091 max_kept: 100,
1092 }
1093 }
1094}
1095
1096#[derive(Debug, Clone, Serialize, Deserialize)]
1098pub struct AliasEntry {
1099 pub command: String,
1100 pub alias: String,
1101}
1102
1103#[derive(Debug, Clone, Serialize, Deserialize)]
1105#[serde(default)]
1106pub struct LoopDetectionConfig {
1107 pub normal_threshold: u32,
1108 pub reduced_threshold: u32,
1109 pub blocked_threshold: u32,
1110 pub window_secs: u64,
1111 pub search_group_limit: u32,
1112 pub tool_total_limits: HashMap<String, u32>,
1113}
1114
1115impl Default for LoopDetectionConfig {
1116 fn default() -> Self {
1117 let mut tool_total_limits = HashMap::new();
1118 tool_total_limits.insert("ctx_read".to_string(), 100);
1119 tool_total_limits.insert("ctx_search".to_string(), 80);
1120 tool_total_limits.insert("ctx_shell".to_string(), 50);
1121 tool_total_limits.insert("ctx_semantic_search".to_string(), 60);
1122 Self {
1123 normal_threshold: 2,
1124 reduced_threshold: 4,
1125 blocked_threshold: 0,
1126 window_secs: 300,
1127 search_group_limit: 10,
1128 tool_total_limits,
1129 }
1130 }
1131}
1132
1133#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1152#[serde(default)]
1153pub struct GatewayServerConfig {
1154 #[serde(default, skip_serializing_if = "Option::is_none")]
1157 pub seats: Option<u32>,
1158 #[serde(default, skip_serializing_if = "Option::is_none")]
1160 pub org_label: Option<String>,
1161 #[serde(default, skip_serializing_if = "Option::is_none")]
1166 pub admin_url: Option<String>,
1167 #[serde(default, skip_serializing_if = "Option::is_none")]
1174 pub admin_bind_host: Option<String>,
1175 #[serde(default, skip_serializing_if = "Option::is_none")]
1180 pub usage_retention_days: Option<u32>,
1181 #[serde(default, skip_serializing_if = "Option::is_none")]
1187 pub pseudonymize_persons: Option<bool>,
1188 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1195 pub mcp_servers: Vec<McpServerEntry>,
1196}
1197
1198#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1202pub struct McpServerEntry {
1203 pub id: String,
1206 pub url: String,
1211 #[serde(default, skip_serializing_if = "Option::is_none")]
1217 pub auth_env: Option<String>,
1218 #[serde(default, skip_serializing_if = "Option::is_none")]
1220 pub enabled: Option<bool>,
1221}
1222
1223#[derive(Debug, Clone, PartialEq, Eq)]
1226pub struct ResolvedMcpServer {
1227 pub id: String,
1228 pub url: String,
1229 pub auth_env: Option<String>,
1230}
1231
1232impl GatewayServerConfig {
1233 #[must_use]
1239 pub fn resolve_mcp_servers(&self, allow_insecure_http: bool) -> Vec<ResolvedMcpServer> {
1240 let mut seen: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
1241 let mut out = Vec::new();
1242 for entry in &self.mcp_servers {
1243 if !entry.enabled.unwrap_or(true) {
1244 continue;
1245 }
1246 let id = entry.id.trim();
1247 if !is_valid_mcp_server_id(id) {
1248 tracing::warn!(
1249 "[gateway_server.mcp_servers] invalid id '{id}' \
1250 (lowercase alnum/-/_ only) — entry skipped"
1251 );
1252 continue;
1253 }
1254 if !seen.insert(id) {
1255 tracing::warn!(
1256 "[gateway_server.mcp_servers] duplicate id '{id}' — keeping first entry"
1257 );
1258 continue;
1259 }
1260 match validate_mcp_upstream_url(&entry.url, allow_insecure_http) {
1261 Ok(url) => out.push(ResolvedMcpServer {
1262 id: id.to_string(),
1263 url,
1264 auth_env: entry
1265 .auth_env
1266 .as_deref()
1267 .map(str::trim)
1268 .filter(|v| !v.is_empty())
1269 .map(str::to_string),
1270 }),
1271 Err(e) => {
1272 tracing::warn!(
1273 "[gateway_server.mcp_servers] '{id}' has invalid url — skipped: {e}"
1274 );
1275 }
1276 }
1277 }
1278 out
1279 }
1280
1281 #[must_use]
1284 pub fn resolved_admin_bind_host(&self) -> std::net::IpAddr {
1285 let raw = std::env::var("LEAN_CTX_GATEWAY_ADMIN_BIND_HOST")
1286 .ok()
1287 .filter(|v| !v.trim().is_empty())
1288 .or_else(|| self.admin_bind_host.clone());
1289 match raw.as_deref().map(str::trim) {
1290 Some(v) if !v.is_empty() => v.parse().unwrap_or_else(|_| {
1291 tracing::warn!(
1292 "gateway_server.admin_bind_host '{v}' is not a valid IP address — binding 127.0.0.1"
1293 );
1294 std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
1295 }),
1296 _ => std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
1297 }
1298 }
1299}
1300
1301fn is_valid_mcp_server_id(id: &str) -> bool {
1305 !id.is_empty()
1306 && id
1307 .chars()
1308 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
1309}
1310
1311fn validate_mcp_upstream_url(url: &str, allow_insecure_http: bool) -> Result<String, String> {
1317 let trimmed = url.trim().trim_end_matches('/');
1318 if trimmed.is_empty() {
1319 return Err("empty url".into());
1320 }
1321 if crate::core::config::is_local_proxy_url(trimmed) {
1322 return Ok(trimmed.to_string());
1323 }
1324 if trimmed.starts_with("http://") {
1325 if allow_insecure_http {
1326 return Ok(trimmed.to_string());
1327 }
1328 return Err(format!(
1329 "MCP upstream must use HTTPS: {trimmed} (for a trusted local-network HTTP \
1330 upstream opt in with `[proxy] allow_insecure_http_upstream = true`)"
1331 ));
1332 }
1333 if trimmed.starts_with("https://") {
1334 return Ok(trimmed.to_string());
1335 }
1336 Err(format!(
1337 "MCP upstream must start with http:// or https://: {trimmed}"
1338 ))
1339}
1340
1341#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1342#[serde(default)]
1343pub struct EmbeddingConfig {
1344 #[serde(default, skip_serializing_if = "Option::is_none")]
1345 pub model: Option<String>,
1346 #[serde(default, skip_serializing_if = "Option::is_none")]
1347 pub dimensions: Option<usize>,
1348 #[serde(default, skip_serializing_if = "Option::is_none")]
1354 pub auto_download: Option<bool>,
1355 #[serde(default, skip_serializing_if = "Option::is_none")]
1362 pub deterministic: Option<bool>,
1363}
1364
1365#[cfg(test)]
1366mod gateway_server_tests {
1367 use super::*;
1368
1369 #[test]
1370 fn admin_bind_defaults_to_loopback_and_rejects_garbage() {
1371 let cfg = GatewayServerConfig::default();
1373 assert!(cfg.resolved_admin_bind_host().is_loopback());
1374
1375 let cfg = GatewayServerConfig {
1376 admin_bind_host: Some("not-an-ip".into()),
1377 ..Default::default()
1378 };
1379 assert!(
1380 cfg.resolved_admin_bind_host().is_loopback(),
1381 "a typo must narrow exposure, never widen it"
1382 );
1383
1384 let cfg = GatewayServerConfig {
1385 admin_bind_host: Some("0.0.0.0".into()),
1386 ..Default::default()
1387 };
1388 assert!(
1389 !cfg.resolved_admin_bind_host().is_loopback(),
1390 "explicit opt-in widens the bind"
1391 );
1392 }
1393
1394 fn mcp_entry(id: &str, url: &str) -> McpServerEntry {
1395 McpServerEntry {
1396 id: id.into(),
1397 url: url.into(),
1398 auth_env: None,
1399 enabled: None,
1400 }
1401 }
1402
1403 #[test]
1404 fn mcp_registry_validates_ids_urls_and_duplicates() {
1405 let cfg = GatewayServerConfig {
1406 mcp_servers: vec![
1407 mcp_entry("github", "https://mcp.example.com/mcp/"),
1408 mcp_entry("GitHub", "https://mcp.example.com/mcp"),
1410 mcp_entry("github", "https://other.example.com/mcp"),
1412 mcp_entry("plain", "http://mcp.example.com/mcp"),
1414 mcp_entry("local", "http://127.0.0.1:9200/mcp"),
1416 McpServerEntry {
1417 enabled: Some(false),
1418 ..mcp_entry("disabled", "https://mcp.example.com/mcp")
1419 },
1420 McpServerEntry {
1421 auth_env: Some(" GITHUB_MCP_PAT ".into()),
1422 ..mcp_entry("authed", "https://api.githubcopilot.com/mcp")
1423 },
1424 ],
1425 ..Default::default()
1426 };
1427 let resolved = cfg.resolve_mcp_servers(false);
1428 let ids: Vec<&str> = resolved.iter().map(|s| s.id.as_str()).collect();
1429 assert_eq!(ids, ["github", "local", "authed"]);
1430 assert_eq!(resolved[0].url, "https://mcp.example.com/mcp");
1432 assert_eq!(resolved[2].auth_env.as_deref(), Some("GITHUB_MCP_PAT"));
1433
1434 let with_optin = cfg.resolve_mcp_servers(true);
1436 assert!(with_optin.iter().any(|s| s.id == "plain"));
1437 }
1438
1439 #[test]
1440 fn mcp_upstream_url_rules_match_the_proxy_posture() {
1441 assert!(validate_mcp_upstream_url("https://mcp.example.com/mcp", false).is_ok());
1442 assert!(validate_mcp_upstream_url("http://localhost:9200/mcp", false).is_ok());
1443 assert!(validate_mcp_upstream_url("http://mcp.example.com/mcp", false).is_err());
1444 assert!(validate_mcp_upstream_url("http://mcp.example.com/mcp", true).is_ok());
1445 assert!(validate_mcp_upstream_url("ftp://mcp.example.com", false).is_err());
1446 assert!(validate_mcp_upstream_url(" ", false).is_err());
1447 }
1448}
1449
1450#[cfg(test)]
1451mod ocla_tests {
1452 use super::OclaConfig;
1453 use crate::core::ocla::grpc_bridge::GrpcConfig;
1454 use crate::core::ocla::sidecar::SidecarConfig;
1455 use serde::Deserialize;
1456
1457 #[derive(Deserialize)]
1458 struct ConfigFile {
1459 ocla: OclaConfig,
1460 }
1461
1462 #[test]
1463 fn sidecar_defaults_are_loopback_and_disabled() {
1464 let config = SidecarConfig::default();
1465 assert_eq!(config.bind_addr, "127.0.0.1:3334");
1466 assert!(!config.enabled);
1467 assert!(config.auth_token.is_none());
1468 }
1469
1470 #[test]
1471 fn nested_sidecar_toml_deserializes() {
1472 let config: ConfigFile = toml::from_str(
1473 r#"
1474 [ocla.sidecar]
1475 bind_addr = "127.0.0.1:9000"
1476 auth_token = "wire-secret"
1477 tls_cert_path = "/etc/lean-ctx/cert.pem"
1478 tls_key_path = "/etc/lean-ctx/key.pem"
1479 enabled = true
1480 "#,
1481 )
1482 .expect("OCLA sidecar config");
1483
1484 let sidecar = config.ocla.sidecar;
1485 assert_eq!(sidecar.bind_addr, "127.0.0.1:9000");
1486 assert_eq!(sidecar.auth_token.as_deref(), Some("wire-secret"));
1487 assert_eq!(
1488 sidecar.tls_cert_path.as_deref().unwrap().to_str(),
1489 Some("/etc/lean-ctx/cert.pem")
1490 );
1491 assert_eq!(
1492 sidecar.tls_key_path.as_deref().unwrap().to_str(),
1493 Some("/etc/lean-ctx/key.pem")
1494 );
1495 assert!(sidecar.enabled);
1496 }
1497
1498 #[test]
1499 fn nested_grpc_toml_deserializes() {
1500 let config: ConfigFile = toml::from_str(
1501 r#"
1502 [ocla.grpc]
1503 enabled = true
1504 listen = "127.0.0.1:60051"
1505 "#,
1506 )
1507 .expect("OCLA gRPC config");
1508
1509 assert_eq!(config.ocla.grpc.listen, "127.0.0.1:60051");
1510 assert!(config.ocla.grpc.enabled);
1511 assert_eq!(GrpcConfig::default().listen, "127.0.0.1:50051");
1512 }
1513}
1514
1515#[cfg(test)]
1516mod telemetry_tests {
1517 use super::*;
1518
1519 #[test]
1520 fn telemetry_config_defaults_to_disabled() {
1521 let cfg = TelemetryConfig::default();
1522 assert!(!cfg.enabled);
1523 assert!(cfg.last_heartbeat.is_none());
1524 }
1525
1526 #[test]
1527 fn telemetry_config_serde_roundtrip() {
1528 let toml_str = r#"
1529[telemetry]
1530enabled = true
1531last_heartbeat = "2026-07-30"
1532"#;
1533 #[derive(serde::Deserialize)]
1534 struct Wrap {
1535 telemetry: TelemetryConfig,
1536 }
1537 let wrap: Wrap = toml::from_str(toml_str).expect("parse telemetry config");
1538 assert!(wrap.telemetry.enabled);
1539 assert_eq!(wrap.telemetry.last_heartbeat.as_deref(), Some("2026-07-30"));
1540 }
1541
1542 #[test]
1543 fn telemetry_config_missing_section_uses_defaults() {
1544 let toml_str = "";
1545 #[derive(serde::Deserialize, Default)]
1546 #[serde(default)]
1547 struct Wrap {
1548 telemetry: TelemetryConfig,
1549 }
1550 let wrap: Wrap = toml::from_str(toml_str).expect("parse empty config");
1551 assert!(!wrap.telemetry.enabled);
1552 assert!(wrap.telemetry.last_heartbeat.is_none());
1553 }
1554}