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,
164 pub max_concurrent_mutating_workers: usize,
166 pub active_worker_lease_seconds: u64,
168 pub serialize_build_commands: bool,
170 pub cargo_build_jobs: usize,
172 pub shared_cargo_target: bool,
174 pub max_scratchpad_entries: usize,
176}
177
178impl Default for AgentsConfig {
179 fn default() -> Self {
180 Self {
181 gc_interval_minutes: 10,
182 identity_ttl_hours: 48,
183 presence_ttl_hours: 24,
184 scratchpad_default_ttl_hours: 12,
185 logical_session_ttl_seconds: 180,
186 max_concurrent_workers: 12,
187 max_concurrent_mutating_workers: 4,
188 active_worker_lease_seconds: 120,
189 serialize_build_commands: true,
190 cargo_build_jobs: 3,
191 shared_cargo_target: true,
192 max_scratchpad_entries: 200,
193 }
194 }
195}
196
197#[cfg(test)]
198mod agents_config_tests {
199 use super::AgentsConfig;
200
201 #[test]
202 fn default_values_are_sane() {
203 let cfg = AgentsConfig::default();
204 assert_eq!(cfg.gc_interval_minutes, 10);
205 assert_eq!(cfg.identity_ttl_hours, 48);
206 assert_eq!(cfg.presence_ttl_hours, 24);
207 assert_eq!(cfg.scratchpad_default_ttl_hours, 12);
208 assert_eq!(cfg.logical_session_ttl_seconds, 180);
209 assert_eq!(cfg.max_concurrent_workers, 12);
210 assert_eq!(cfg.max_concurrent_mutating_workers, 4);
211 assert_eq!(cfg.active_worker_lease_seconds, 120);
212 assert!(cfg.serialize_build_commands);
213 assert_eq!(cfg.cargo_build_jobs, 3);
214 assert!(cfg.shared_cargo_target);
215 assert_eq!(cfg.max_scratchpad_entries, 200);
216 }
217
218 #[test]
219 fn deserializes_with_missing_fields() {
220 let json = r"{}";
221 let cfg: AgentsConfig = serde_json::from_str(json).expect("empty object → defaults");
222 assert_eq!(cfg.gc_interval_minutes, 10);
223 }
224
225 #[test]
226 fn partial_override() {
227 let json = r#"{"gc_interval_minutes": 5, "presence_ttl_hours": 12}"#;
228 let cfg: AgentsConfig = serde_json::from_str(json).expect("partial");
229 assert_eq!(cfg.gc_interval_minutes, 5);
230 assert_eq!(cfg.presence_ttl_hours, 12);
231 assert_eq!(cfg.identity_ttl_hours, 48);
232 }
233}
234
235#[derive(Debug, Clone, Serialize, Deserialize)]
236#[serde(default)]
237pub struct SecretDetectionConfig {
238 pub enabled: bool,
239 pub redact: bool,
240 pub custom_patterns: Vec<String>,
241 pub exclude_patterns: Vec<String>,
246}
247
248#[derive(Debug, Clone, Serialize, Deserialize)]
253#[serde(default)]
254pub struct SetupConfig {
255 pub auto_inject_rules: Option<bool>,
259 pub auto_inject_skills: Option<bool>,
262 #[serde(default = "serde_defaults::default_true")]
264 pub auto_update_mcp: bool,
265}
266
267impl Default for SetupConfig {
268 fn default() -> Self {
269 Self {
270 auto_inject_rules: None,
271 auto_inject_skills: None,
272 auto_update_mcp: true,
273 }
274 }
275}
276
277impl SetupConfig {
278 pub fn should_inject_rules(&self) -> bool {
282 match self.auto_inject_rules {
283 Some(v) => v,
284 None => Self::rules_already_present(),
285 }
286 }
287
288 pub fn should_inject_skills(&self) -> bool {
290 match self.auto_inject_skills {
291 Some(v) => v,
292 None => Self::rules_already_present(),
293 }
294 }
295
296 pub fn should_update_mcp(&self) -> bool {
301 self.auto_update_mcp
302 }
303
304 fn rules_already_present() -> bool {
312 let Some(home) = dirs::home_dir() else {
313 return false;
314 };
315 if crate::rules_inject::any_rules_marker_present(&home) {
316 return true;
317 }
318 let legacy_paths = [
319 crate::core::editor_registry::claude_rules_dir(&home).join("lean-ctx.md"),
320 crate::core::editor_registry::codebuddy_rules_dir(&home).join("lean-ctx.md"),
321 ];
322 legacy_paths.iter().any(|p| {
323 std::fs::read_to_string(p)
324 .is_ok_and(|c| c.contains(crate::core::rules_canonical::START_MARK))
325 })
326 }
327}
328
329impl Default for SecretDetectionConfig {
330 fn default() -> Self {
331 Self {
332 enabled: true,
333 redact: true,
334 custom_patterns: Vec::new(),
335 exclude_patterns: Vec::new(),
336 }
337 }
338}
339
340#[derive(Debug, Clone, Serialize, Deserialize)]
342#[serde(default)]
343pub struct ArchiveConfig {
344 pub enabled: bool,
345 pub threshold_chars: usize,
346 pub max_age_hours: u64,
347 pub max_disk_mb: u64,
348 pub ephemeral: bool,
349 pub ephemeral_min_tokens: usize,
352 pub inline_max_bytes: usize,
355 pub raw_commands: Vec<String>,
360 pub verbatim_max_tokens: usize,
368}
369
370#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
375#[serde(default)]
376pub struct ConversationConfig {
377 pub compression_enabled: bool,
379 pub preserve_last_n_turns: usize,
381 pub compression_threshold_tokens: usize,
383 pub min_score_to_preserve: f64,
385 pub summarize_score_range: [f64; 2],
387 pub drop_score_below: f64,
389 pub ccr_store_dropped: bool,
391}
392
393impl Default for ConversationConfig {
394 fn default() -> Self {
395 Self {
396 compression_enabled: false,
397 preserve_last_n_turns: 10,
398 compression_threshold_tokens: 50_000,
399 min_score_to_preserve: 0.5,
400 summarize_score_range: [0.2, 0.5],
401 drop_score_below: 0.2,
402 ccr_store_dropped: true,
403 }
404 }
405}
406
407impl Default for ArchiveConfig {
408 fn default() -> Self {
409 Self {
410 enabled: true,
411 threshold_chars: 800,
412 max_age_hours: 48,
413 max_disk_mb: 500,
414 ephemeral: true,
415 ephemeral_min_tokens: 2000,
416 inline_max_bytes: 32 * 1024,
417 raw_commands: crate::core::firewall::DEFAULT_RAW_COMMANDS
418 .iter()
419 .map(|s| (*s).to_string())
420 .collect(),
421 verbatim_max_tokens: 100_000,
422 }
423 }
424}
425
426impl ArchiveConfig {
427 pub fn ephemeral_effective(&self) -> bool {
428 if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL") {
429 return !matches!(v.trim(), "0" | "false" | "off");
430 }
431 self.ephemeral && self.enabled
432 }
433
434 pub fn ephemeral_min_tokens_effective(&self) -> usize {
435 if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL_MIN_TOKENS")
436 && let Ok(n) = v.trim().parse::<usize>()
437 {
438 return n;
439 }
440 self.ephemeral_min_tokens
441 }
442
443 pub fn verbatim_max_tokens_effective(&self) -> usize {
445 if let Ok(v) = std::env::var("LEAN_CTX_VERBATIM_MAX_TOKENS")
446 && let Ok(n) = v.trim().parse::<usize>()
447 {
448 return n;
449 }
450 self.verbatim_max_tokens
451 }
452
453 pub fn inline_max_bytes_effective(&self) -> usize {
454 if let Ok(v) = std::env::var("LEAN_CTX_INLINE_MAX_BYTES")
455 && let Ok(n) = v.trim().parse::<usize>()
456 {
457 return n;
458 }
459 self.inline_max_bytes
460 }
461}
462
463#[derive(Debug, Clone, Serialize, Deserialize)]
467#[serde(default)]
468pub struct ProvidersConfig {
469 pub enabled: bool,
471 pub github: ProviderEntryConfig,
473 pub gitlab: ProviderEntryConfig,
475 pub auto_index: bool,
477 pub cache_ttl_secs: u64,
479 #[serde(default)]
481 pub mcp_bridges: std::collections::HashMap<String, McpBridgeEntry>,
482}
483
484impl Default for ProvidersConfig {
485 fn default() -> Self {
486 Self {
487 enabled: true,
488 github: ProviderEntryConfig::default(),
489 gitlab: ProviderEntryConfig::default(),
490 auto_index: true,
491 cache_ttl_secs: 120,
492 mcp_bridges: std::collections::HashMap::new(),
493 }
494 }
495}
496
497#[derive(Debug, Clone, Serialize, Deserialize)]
499#[serde(default)]
500pub struct KnowledgeRoutingConfig {
501 pub enabled: bool,
502 pub max_references: usize,
503 pub hint_prefix: String,
504}
505
506impl Default for KnowledgeRoutingConfig {
507 fn default() -> Self {
508 Self {
509 enabled: true,
510 max_references: 5,
511 hint_prefix: "--- Knowledge Context ---".to_string(),
512 }
513 }
514}
515
516#[derive(Debug, Clone, Serialize, Deserialize)]
517pub struct McpBridgeEntry {
518 #[serde(default)]
520 pub url: Option<String>,
521 #[serde(default)]
523 pub command: Option<String>,
524 #[serde(default)]
526 pub args: Vec<String>,
527 #[serde(default)]
529 pub description: Option<String>,
530 #[serde(default)]
532 pub auth_env: Option<String>,
533}
534
535#[derive(Debug, Clone, Serialize, Deserialize)]
537#[serde(default)]
538pub struct ProviderEntryConfig {
539 pub enabled: bool,
541 pub token: Option<String>,
543 pub api_url: Option<String>,
545 pub project: Option<String>,
547}
548
549impl Default for ProviderEntryConfig {
550 fn default() -> Self {
551 Self {
552 enabled: true,
553 token: None,
554 api_url: None,
555 project: None,
556 }
557 }
558}
559
560#[derive(Debug, Clone, Serialize, Deserialize)]
562#[serde(default)]
563pub struct AutonomyConfig {
564 pub enabled: bool,
565 pub auto_preload: bool,
566 pub auto_dedup: bool,
567 pub auto_related: bool,
568 pub auto_consolidate: bool,
569 pub silent_preload: bool,
570 pub dedup_threshold: usize,
571 pub consolidate_every_calls: u32,
572 pub consolidate_cooldown_secs: u64,
573 #[serde(default = "serde_defaults::default_true")]
574 pub cognition_loop_enabled: bool,
575 #[serde(default = "serde_defaults::default_cognition_loop_interval")]
576 pub cognition_loop_interval_secs: u64,
577 #[serde(default = "serde_defaults::default_cognition_loop_max_steps")]
578 pub cognition_loop_max_steps: u8,
579 #[serde(default = "serde_defaults::default_cognition_synthesis_min_cluster")]
582 pub cognition_synthesis_min_cluster: usize,
583}
584
585impl Default for AutonomyConfig {
586 fn default() -> Self {
587 Self {
588 enabled: true,
589 auto_preload: true,
590 auto_dedup: true,
591 auto_related: true,
592 auto_consolidate: true,
593 silent_preload: true,
594 dedup_threshold: 8,
595 consolidate_every_calls: 25,
596 consolidate_cooldown_secs: 120,
597 cognition_loop_enabled: true,
598 cognition_loop_interval_secs: 3600,
599 cognition_loop_max_steps: 9,
600 cognition_synthesis_min_cluster: 3,
601 }
602 }
603}
604
605#[derive(Debug, Clone, Serialize, Deserialize)]
608#[serde(default)]
609pub struct UpdatesConfig {
610 pub auto_update: bool,
611 pub check_interval_hours: u64,
612 pub notify_only: bool,
613}
614
615impl Default for UpdatesConfig {
616 fn default() -> Self {
617 Self {
618 auto_update: false,
619 check_interval_hours: 6,
620 notify_only: false,
621 }
622 }
623}
624
625#[derive(Debug, Clone, Serialize, Deserialize)]
631#[serde(default)]
632pub struct ContextConfig {
633 pub budget_tokens: usize,
634 pub diet_max_config_tokens: usize,
635 pub diet_relevance_threshold: f64,
636 pub diet_rebalance_on_change: bool,
637 pub diet_staleness_enabled: bool,
638 pub proactive_expansion: bool,
640 pub proactive_expansion_budget_tokens: usize,
642 pub proactive_expansion_threshold: f64,
644 pub proactive_expansion_max_age_secs: u64,
646}
647
648impl Default for ContextConfig {
649 fn default() -> Self {
650 Self {
651 budget_tokens: 8000,
652 diet_max_config_tokens: 800,
653 diet_relevance_threshold: 0.15,
654 diet_rebalance_on_change: true,
655 diet_staleness_enabled: true,
656 proactive_expansion: true,
657 proactive_expansion_budget_tokens: 2000,
658 proactive_expansion_threshold: 0.6,
659 proactive_expansion_max_age_secs: 3600,
660 }
661 }
662}
663
664impl UpdatesConfig {
665 pub fn from_env() -> Self {
666 let mut cfg = Self::default();
667 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_UPDATE") {
668 cfg.auto_update = v == "1" || v.eq_ignore_ascii_case("true");
669 }
670 if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_INTERVAL_HOURS")
671 && let Ok(h) = v.parse::<u64>()
672 {
673 cfg.check_interval_hours = h.clamp(1, 168);
674 }
675 if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_NOTIFY_ONLY") {
676 cfg.notify_only = v == "1" || v.eq_ignore_ascii_case("true");
677 }
678 cfg
679 }
680}
681
682impl AutonomyConfig {
683 pub fn from_env() -> Self {
685 let mut cfg = Self::default();
686 if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
687 && (v == "false" || v == "0")
688 {
689 cfg.enabled = false;
690 }
691 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
692 cfg.auto_preload = v != "false" && v != "0";
693 }
694 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
695 cfg.auto_dedup = v != "false" && v != "0";
696 }
697 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
698 cfg.auto_related = v != "false" && v != "0";
699 }
700 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_CONSOLIDATE") {
701 cfg.auto_consolidate = v != "false" && v != "0";
702 }
703 if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
704 cfg.silent_preload = v != "false" && v != "0";
705 }
706 if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD")
707 && let Ok(n) = v.parse()
708 {
709 cfg.dedup_threshold = n;
710 }
711 if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_EVERY_CALLS")
712 && let Ok(n) = v.parse()
713 {
714 cfg.consolidate_every_calls = n;
715 }
716 if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_COOLDOWN_SECS")
717 && let Ok(n) = v.parse()
718 {
719 cfg.consolidate_cooldown_secs = n;
720 }
721 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
722 cfg.cognition_loop_enabled = v != "false" && v != "0";
723 }
724 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
725 && let Ok(n) = v.parse()
726 {
727 cfg.cognition_loop_interval_secs = n;
728 }
729 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
730 && let Ok(n) = v.parse()
731 {
732 cfg.cognition_loop_max_steps = n;
733 }
734 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_SYNTHESIS_MIN_CLUSTER")
735 && let Ok(n) = v.parse()
736 {
737 cfg.cognition_synthesis_min_cluster = n;
738 }
739 cfg
740 }
741
742 pub fn load() -> Self {
744 let file_cfg = Config::load().autonomy;
745 let mut cfg = file_cfg;
746 if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
747 && (v == "false" || v == "0")
748 {
749 cfg.enabled = false;
750 }
751 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
752 cfg.auto_preload = v != "false" && v != "0";
753 }
754 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
755 cfg.auto_dedup = v != "false" && v != "0";
756 }
757 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
758 cfg.auto_related = v != "false" && v != "0";
759 }
760 if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
761 cfg.silent_preload = v != "false" && v != "0";
762 }
763 if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD")
764 && let Ok(n) = v.parse()
765 {
766 cfg.dedup_threshold = n;
767 }
768 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
769 cfg.cognition_loop_enabled = v != "false" && v != "0";
770 }
771 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
772 && let Ok(n) = v.parse()
773 {
774 cfg.cognition_loop_interval_secs = n;
775 }
776 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
777 && let Ok(n) = v.parse()
778 {
779 cfg.cognition_loop_max_steps = n;
780 }
781 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_SYNTHESIS_MIN_CLUSTER")
782 && let Ok(n) = v.parse()
783 {
784 cfg.cognition_synthesis_min_cluster = n;
785 }
786 cfg
787 }
788}
789
790#[derive(Debug, Clone, Serialize, Deserialize, Default)]
797#[serde(default)]
798pub struct TelemetryConfig {
799 pub enabled: bool,
801 pub last_heartbeat: Option<String>,
803}
804
805#[derive(Debug, Clone, Serialize, Deserialize, Default)]
807#[serde(default)]
808pub struct CloudConfig {
809 pub contribute_enabled: bool,
810 pub last_contribute: Option<String>,
811 #[serde(default)]
813 pub sync_stats_enabled: bool,
814 pub last_sync: Option<String>,
815 #[serde(default)]
817 pub sync_gain_enabled: bool,
818 pub last_gain_sync: Option<String>,
819 #[serde(default)]
821 pub sync_models_enabled: bool,
822 pub last_model_pull: Option<String>,
823 pub auto_sync: bool,
826 pub last_auto_sync: Option<String>,
827 pub auto_index: bool,
830 pub last_index_push: std::collections::HashMap<String, String>,
833}
834
835#[derive(Debug, Clone, Serialize, Deserialize)]
841#[serde(default)]
842pub struct GainConfig {
843 pub auto_publish: bool,
846 pub leaderboard: bool,
848 pub display_name: Option<String>,
850 pub auto_publish_interval_hours: u64,
852 pub last_auto_publish: Option<String>,
855}
856
857impl Default for GainConfig {
858 fn default() -> Self {
859 Self {
860 auto_publish: false,
861 leaderboard: false,
862 display_name: None,
863 auto_publish_interval_hours: 24,
864 last_auto_publish: None,
865 }
866 }
867}
868
869#[derive(Debug, Clone, Default, Serialize, Deserialize)]
878#[serde(default)]
879pub struct CostConfig {
880 #[serde(default)]
885 pub max_session_cost_usd: f64,
886 #[serde(default, skip_serializing_if = "Option::is_none")]
889 pub default_model: Option<String>,
890 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
895 pub models: HashMap<String, String>,
896 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
904 pub prices: HashMap<String, PriceOverride>,
905}
906
907#[derive(Debug, Clone, Serialize, Deserialize)]
909#[serde(default)]
910pub struct ProtectionConfig {
911 pub file_patterns: Vec<String>,
917 pub tags: bool,
921}
922
923impl Default for ProtectionConfig {
924 fn default() -> Self {
925 Self {
926 file_patterns: Vec::new(),
927 tags: true,
928 }
929 }
930}
931
932impl ProtectionConfig {
933 pub fn path_is_protected(&self, path: &str) -> bool {
935 !path.is_empty()
936 && self
937 .file_patterns
938 .iter()
939 .filter_map(|p| glob::Pattern::new(p).ok())
940 .any(|pattern| pattern.matches(path))
941 }
942}
943
944#[cfg(test)]
945mod protection_tests {
946 use super::ProtectionConfig;
947
948 #[test]
949 fn protected_globs_match_paths_and_ignore_invalid_patterns() {
950 let cfg = ProtectionConfig {
951 file_patterns: vec![
952 "docs/audits/**".into(),
953 "*.secret.md".into(),
954 "[invalid".into(),
955 ],
956 tags: true,
957 };
958 assert!(cfg.path_is_protected("docs/audits/q3/blockers.md"));
959 assert!(cfg.path_is_protected("notes.secret.md"));
960 assert!(!cfg.path_is_protected("src/main.rs"));
961 assert!(!cfg.path_is_protected(""));
962
963 let empty = ProtectionConfig::default();
964 assert!(!empty.path_is_protected("docs/audits/q3/blockers.md"));
965 assert!(empty.tags, "protect tags are honored by default");
966 }
967}
968#[derive(Debug, Clone, Serialize, Deserialize)]
970#[serde(default)]
971pub struct DecisionLoopConfig {
972 pub enabled: bool,
973 #[serde(default)]
976 pub max_filter_level: u8,
977}
978
979impl Default for DecisionLoopConfig {
980 fn default() -> Self {
981 Self {
982 enabled: true,
983 max_filter_level: 0,
984 }
985 }
986}
987
988#[derive(Debug, Clone, Default, Serialize, Deserialize)]
991#[serde(default)]
992pub struct PriceOverride {
993 pub input_per_m: Option<f64>,
994 pub output_per_m: Option<f64>,
995 pub cache_write_per_m: Option<f64>,
996 pub cache_read_per_m: Option<f64>,
997}
998
999impl CostConfig {
1000 pub fn model_for_client(&self, client: &str) -> Option<String> {
1004 self.models
1005 .get(client)
1006 .or(self.default_model.as_ref())
1007 .map(|s| s.trim().to_string())
1008 .filter(|s| !s.is_empty())
1009 }
1010}
1011
1012#[derive(Debug, Clone, Serialize, Deserialize)]
1018#[serde(default)]
1019pub struct CodeHealthConfig {
1020 pub cognitive_threshold: u32,
1023 pub gate: String,
1026 pub annotate_reads: bool,
1028 pub naming: bool,
1030 pub coupling: bool,
1032 #[serde(default)]
1038 pub inject_context: bool,
1039}
1040
1041impl Default for CodeHealthConfig {
1042 fn default() -> Self {
1043 Self {
1044 cognitive_threshold: 15,
1045 gate: "warn".to_string(),
1046 annotate_reads: true,
1047 naming: true,
1048 coupling: true,
1049 inject_context: false,
1050 }
1051 }
1052}
1053
1054#[derive(Debug, Clone, Serialize, Deserialize)]
1064#[serde(default)]
1065pub struct IndexConfig {
1066 pub respect_gitignore: bool,
1070 pub exclude: Vec<String>,
1073 pub include: Vec<String>,
1076}
1077
1078impl Default for IndexConfig {
1079 fn default() -> Self {
1080 Self {
1081 respect_gitignore: true,
1082 exclude: Vec::new(),
1083 include: Vec::new(),
1084 }
1085 }
1086}
1087
1088#[derive(Debug, Clone, Serialize, Deserialize)]
1098#[serde(default)]
1099pub struct GraphConfig {
1100 pub traversal_edges: bool,
1104}
1105
1106impl Default for GraphConfig {
1107 fn default() -> Self {
1108 Self {
1109 traversal_edges: true,
1110 }
1111 }
1112}
1113
1114#[derive(Debug, Clone, Serialize, Deserialize)]
1122#[serde(default)]
1123pub struct SkillifyConfig {
1124 pub enabled: bool,
1127 pub scope: String,
1130 pub min_confidence: f32,
1133 pub min_recurrence: u32,
1136}
1137
1138impl Default for SkillifyConfig {
1139 fn default() -> Self {
1140 Self {
1141 enabled: true,
1142 scope: "project".to_string(),
1143 min_confidence: 0.7,
1144 min_recurrence: 2,
1145 }
1146 }
1147}
1148
1149#[derive(Debug, Clone, Serialize, Deserialize)]
1154#[serde(default)]
1155pub struct SummariesConfig {
1156 pub enabled: bool,
1159 pub every_n_turns: u32,
1162 pub max_kept: u32,
1164}
1165
1166impl Default for SummariesConfig {
1167 fn default() -> Self {
1168 Self {
1169 enabled: true,
1170 every_n_turns: 25,
1171 max_kept: 100,
1172 }
1173 }
1174}
1175
1176#[derive(Debug, Clone, Serialize, Deserialize)]
1178pub struct AliasEntry {
1179 pub command: String,
1180 pub alias: String,
1181}
1182
1183#[derive(Debug, Clone, Serialize, Deserialize)]
1185#[serde(default)]
1186pub struct LoopDetectionConfig {
1187 pub normal_threshold: u32,
1188 pub reduced_threshold: u32,
1189 pub blocked_threshold: u32,
1190 pub window_secs: u64,
1191 pub search_group_limit: u32,
1192 pub tool_total_limits: HashMap<String, u32>,
1193}
1194
1195impl Default for LoopDetectionConfig {
1196 fn default() -> Self {
1197 let mut tool_total_limits = HashMap::new();
1198 tool_total_limits.insert("ctx_read".to_string(), 100);
1199 tool_total_limits.insert("ctx_search".to_string(), 80);
1200 tool_total_limits.insert("ctx_shell".to_string(), 50);
1201 tool_total_limits.insert("ctx_semantic_search".to_string(), 60);
1202 Self {
1203 normal_threshold: 2,
1204 reduced_threshold: 4,
1205 blocked_threshold: 0,
1206 window_secs: 300,
1207 search_group_limit: 10,
1208 tool_total_limits,
1209 }
1210 }
1211}
1212
1213#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1232#[serde(default)]
1233pub struct GatewayServerConfig {
1234 #[serde(default, skip_serializing_if = "Option::is_none")]
1237 pub seats: Option<u32>,
1238 #[serde(default, skip_serializing_if = "Option::is_none")]
1240 pub org_label: Option<String>,
1241 #[serde(default, skip_serializing_if = "Option::is_none")]
1246 pub admin_url: Option<String>,
1247 #[serde(default, skip_serializing_if = "Option::is_none")]
1254 pub admin_bind_host: Option<String>,
1255 #[serde(default, skip_serializing_if = "Option::is_none")]
1260 pub usage_retention_days: Option<u32>,
1261 #[serde(default, skip_serializing_if = "Option::is_none")]
1267 pub pseudonymize_persons: Option<bool>,
1268 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1275 pub mcp_servers: Vec<McpServerEntry>,
1276}
1277
1278#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1282pub struct McpServerEntry {
1283 pub id: String,
1286 pub url: String,
1291 #[serde(default, skip_serializing_if = "Option::is_none")]
1297 pub auth_env: Option<String>,
1298 #[serde(default, skip_serializing_if = "Option::is_none")]
1300 pub enabled: Option<bool>,
1301}
1302
1303#[derive(Debug, Clone, PartialEq, Eq)]
1306pub struct ResolvedMcpServer {
1307 pub id: String,
1308 pub url: String,
1309 pub auth_env: Option<String>,
1310}
1311
1312impl GatewayServerConfig {
1313 #[must_use]
1319 pub fn resolve_mcp_servers(&self, allow_insecure_http: bool) -> Vec<ResolvedMcpServer> {
1320 let mut seen: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
1321 let mut out = Vec::new();
1322 for entry in &self.mcp_servers {
1323 if !entry.enabled.unwrap_or(true) {
1324 continue;
1325 }
1326 let id = entry.id.trim();
1327 if !is_valid_mcp_server_id(id) {
1328 tracing::warn!(
1329 "[gateway_server.mcp_servers] invalid id '{id}' \
1330 (lowercase alnum/-/_ only) — entry skipped"
1331 );
1332 continue;
1333 }
1334 if !seen.insert(id) {
1335 tracing::warn!(
1336 "[gateway_server.mcp_servers] duplicate id '{id}' — keeping first entry"
1337 );
1338 continue;
1339 }
1340 match validate_mcp_upstream_url(&entry.url, allow_insecure_http) {
1341 Ok(url) => out.push(ResolvedMcpServer {
1342 id: id.to_string(),
1343 url,
1344 auth_env: entry
1345 .auth_env
1346 .as_deref()
1347 .map(str::trim)
1348 .filter(|v| !v.is_empty())
1349 .map(str::to_string),
1350 }),
1351 Err(e) => {
1352 tracing::warn!(
1353 "[gateway_server.mcp_servers] '{id}' has invalid url — skipped: {e}"
1354 );
1355 }
1356 }
1357 }
1358 out
1359 }
1360
1361 #[must_use]
1364 pub fn resolved_admin_bind_host(&self) -> std::net::IpAddr {
1365 let raw = std::env::var("LEAN_CTX_GATEWAY_ADMIN_BIND_HOST")
1366 .ok()
1367 .filter(|v| !v.trim().is_empty())
1368 .or_else(|| self.admin_bind_host.clone());
1369 match raw.as_deref().map(str::trim) {
1370 Some(v) if !v.is_empty() => v.parse().unwrap_or_else(|_| {
1371 tracing::warn!(
1372 "gateway_server.admin_bind_host '{v}' is not a valid IP address — binding 127.0.0.1"
1373 );
1374 std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
1375 }),
1376 _ => std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
1377 }
1378 }
1379}
1380
1381fn is_valid_mcp_server_id(id: &str) -> bool {
1385 !id.is_empty()
1386 && id
1387 .chars()
1388 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
1389}
1390
1391fn validate_mcp_upstream_url(url: &str, allow_insecure_http: bool) -> Result<String, String> {
1397 let trimmed = url.trim().trim_end_matches('/');
1398 if trimmed.is_empty() {
1399 return Err("empty url".into());
1400 }
1401 if crate::core::config::is_local_proxy_url(trimmed) {
1402 return Ok(trimmed.to_string());
1403 }
1404 if trimmed.starts_with("http://") {
1405 if allow_insecure_http {
1406 return Ok(trimmed.to_string());
1407 }
1408 return Err(format!(
1409 "MCP upstream must use HTTPS: {trimmed} (for a trusted local-network HTTP \
1410 upstream opt in with `[proxy] allow_insecure_http_upstream = true`)"
1411 ));
1412 }
1413 if trimmed.starts_with("https://") {
1414 return Ok(trimmed.to_string());
1415 }
1416 Err(format!(
1417 "MCP upstream must start with http:// or https://: {trimmed}"
1418 ))
1419}
1420
1421#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1422#[serde(default)]
1423pub struct EmbeddingConfig {
1424 #[serde(default, skip_serializing_if = "Option::is_none")]
1425 pub model: Option<String>,
1426 #[serde(default, skip_serializing_if = "Option::is_none")]
1427 pub dimensions: Option<usize>,
1428 #[serde(default, skip_serializing_if = "Option::is_none")]
1434 pub auto_download: Option<bool>,
1435 #[serde(default, skip_serializing_if = "Option::is_none")]
1442 pub deterministic: Option<bool>,
1443}
1444
1445#[cfg(test)]
1446mod gateway_server_tests {
1447 use super::*;
1448
1449 #[test]
1450 fn admin_bind_defaults_to_loopback_and_rejects_garbage() {
1451 let cfg = GatewayServerConfig::default();
1453 assert!(cfg.resolved_admin_bind_host().is_loopback());
1454
1455 let cfg = GatewayServerConfig {
1456 admin_bind_host: Some("not-an-ip".into()),
1457 ..Default::default()
1458 };
1459 assert!(
1460 cfg.resolved_admin_bind_host().is_loopback(),
1461 "a typo must narrow exposure, never widen it"
1462 );
1463
1464 let cfg = GatewayServerConfig {
1465 admin_bind_host: Some("0.0.0.0".into()),
1466 ..Default::default()
1467 };
1468 assert!(
1469 !cfg.resolved_admin_bind_host().is_loopback(),
1470 "explicit opt-in widens the bind"
1471 );
1472 }
1473
1474 fn mcp_entry(id: &str, url: &str) -> McpServerEntry {
1475 McpServerEntry {
1476 id: id.into(),
1477 url: url.into(),
1478 auth_env: None,
1479 enabled: None,
1480 }
1481 }
1482
1483 #[test]
1484 fn mcp_registry_validates_ids_urls_and_duplicates() {
1485 let cfg = GatewayServerConfig {
1486 mcp_servers: vec![
1487 mcp_entry("github", "https://mcp.example.com/mcp/"),
1488 mcp_entry("GitHub", "https://mcp.example.com/mcp"),
1490 mcp_entry("github", "https://other.example.com/mcp"),
1492 mcp_entry("plain", "http://mcp.example.com/mcp"),
1494 mcp_entry("local", "http://127.0.0.1:9200/mcp"),
1496 McpServerEntry {
1497 enabled: Some(false),
1498 ..mcp_entry("disabled", "https://mcp.example.com/mcp")
1499 },
1500 McpServerEntry {
1501 auth_env: Some(" GITHUB_MCP_PAT ".into()),
1502 ..mcp_entry("authed", "https://api.githubcopilot.com/mcp")
1503 },
1504 ],
1505 ..Default::default()
1506 };
1507 let resolved = cfg.resolve_mcp_servers(false);
1508 let ids: Vec<&str> = resolved.iter().map(|s| s.id.as_str()).collect();
1509 assert_eq!(ids, ["github", "local", "authed"]);
1510 assert_eq!(resolved[0].url, "https://mcp.example.com/mcp");
1512 assert_eq!(resolved[2].auth_env.as_deref(), Some("GITHUB_MCP_PAT"));
1513
1514 let with_optin = cfg.resolve_mcp_servers(true);
1516 assert!(with_optin.iter().any(|s| s.id == "plain"));
1517 }
1518
1519 #[test]
1520 fn mcp_upstream_url_rules_match_the_proxy_posture() {
1521 assert!(validate_mcp_upstream_url("https://mcp.example.com/mcp", false).is_ok());
1522 assert!(validate_mcp_upstream_url("http://localhost:9200/mcp", false).is_ok());
1523 assert!(validate_mcp_upstream_url("http://mcp.example.com/mcp", false).is_err());
1524 assert!(validate_mcp_upstream_url("http://mcp.example.com/mcp", true).is_ok());
1525 assert!(validate_mcp_upstream_url("ftp://mcp.example.com", false).is_err());
1526 assert!(validate_mcp_upstream_url(" ", false).is_err());
1527 }
1528}
1529
1530#[cfg(test)]
1531mod ocla_tests {
1532 use super::OclaConfig;
1533 use crate::core::ocla::grpc_bridge::GrpcConfig;
1534 use crate::core::ocla::sidecar::SidecarConfig;
1535 use serde::Deserialize;
1536
1537 #[derive(Deserialize)]
1538 struct ConfigFile {
1539 ocla: OclaConfig,
1540 }
1541
1542 #[test]
1543 fn sidecar_defaults_are_loopback_and_disabled() {
1544 let config = SidecarConfig::default();
1545 assert_eq!(config.bind_addr, "127.0.0.1:3334");
1546 assert!(!config.enabled);
1547 assert!(config.auth_token.is_none());
1548 }
1549
1550 #[test]
1551 fn nested_sidecar_toml_deserializes() {
1552 let config: ConfigFile = toml::from_str(
1553 r#"
1554 [ocla.sidecar]
1555 bind_addr = "127.0.0.1:9000"
1556 auth_token = "wire-secret"
1557 tls_cert_path = "/etc/lean-ctx/cert.pem"
1558 tls_key_path = "/etc/lean-ctx/key.pem"
1559 enabled = true
1560 "#,
1561 )
1562 .expect("OCLA sidecar config");
1563
1564 let sidecar = config.ocla.sidecar;
1565 assert_eq!(sidecar.bind_addr, "127.0.0.1:9000");
1566 assert_eq!(sidecar.auth_token.as_deref(), Some("wire-secret"));
1567 assert_eq!(
1568 sidecar.tls_cert_path.as_deref().unwrap().to_str(),
1569 Some("/etc/lean-ctx/cert.pem")
1570 );
1571 assert_eq!(
1572 sidecar.tls_key_path.as_deref().unwrap().to_str(),
1573 Some("/etc/lean-ctx/key.pem")
1574 );
1575 assert!(sidecar.enabled);
1576 }
1577
1578 #[test]
1579 fn nested_grpc_toml_deserializes() {
1580 let config: ConfigFile = toml::from_str(
1581 r#"
1582 [ocla.grpc]
1583 enabled = true
1584 listen = "127.0.0.1:60051"
1585 "#,
1586 )
1587 .expect("OCLA gRPC config");
1588
1589 assert_eq!(config.ocla.grpc.listen, "127.0.0.1:60051");
1590 assert!(config.ocla.grpc.enabled);
1591 assert_eq!(GrpcConfig::default().listen, "127.0.0.1:50051");
1592 }
1593}
1594
1595#[cfg(test)]
1596mod telemetry_tests {
1597 use super::*;
1598
1599 #[test]
1600 fn telemetry_config_defaults_to_disabled() {
1601 let cfg = TelemetryConfig::default();
1602 assert!(!cfg.enabled);
1603 assert!(cfg.last_heartbeat.is_none());
1604 }
1605
1606 #[test]
1607 fn telemetry_config_serde_roundtrip() {
1608 let toml_str = r#"
1609[telemetry]
1610enabled = true
1611last_heartbeat = "2026-07-30"
1612"#;
1613 #[derive(serde::Deserialize)]
1614 struct Wrap {
1615 telemetry: TelemetryConfig,
1616 }
1617 let wrap: Wrap = toml::from_str(toml_str).expect("parse telemetry config");
1618 assert!(wrap.telemetry.enabled);
1619 assert_eq!(wrap.telemetry.last_heartbeat.as_deref(), Some("2026-07-30"));
1620 }
1621
1622 #[test]
1623 fn telemetry_config_missing_section_uses_defaults() {
1624 let toml_str = "";
1625 #[derive(serde::Deserialize, Default)]
1626 #[serde(default)]
1627 struct Wrap {
1628 telemetry: TelemetryConfig,
1629 }
1630 let wrap: Wrap = toml::from_str(toml_str).expect("parse empty config");
1631 assert!(!wrap.telemetry.enabled);
1632 assert!(wrap.telemetry.last_heartbeat.is_none());
1633 }
1634}