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 compose_cache_enabled: bool,
106}
107
108impl Default for CacheConfig {
109 fn default() -> Self {
110 Self {
111 l1_max_entries: 1_000,
112 l1_ttl_secs: 300,
113 l2_max_entries: 10_000,
114 l2_ttl_secs: 3_600,
115 l3_max_bytes: 500_000_000,
116 l3_gc_threshold: 0.9,
117 compose_cache_enabled: true,
118 }
119 }
120}
121
122#[cfg(test)]
123mod cache_config_tests {
124 use super::CacheConfig;
125
126 #[test]
127 fn cache_defaults_match_delivery_budget() {
128 assert_eq!(CacheConfig::default().l3_max_bytes, 500_000_000);
129 assert!(CacheConfig::default().compose_cache_enabled);
130 }
131
132 #[test]
133 fn cache_config_deserializes_partial_overrides() {
134 let parsed: CacheConfig =
137 serde_json::from_str(r#"{"l1_max_entries": 12, "shell_cache_enabled": true}"#).unwrap();
138 assert_eq!(parsed.l1_max_entries, 12);
139 assert_eq!(parsed.l2_ttl_secs, 3_600);
140 }
141}
142
143#[derive(Debug, Clone, Serialize, Deserialize)]
148#[serde(default)]
149pub struct AgentsConfig {
150 pub gc_interval_minutes: u64,
152 pub identity_ttl_hours: u64,
154 pub presence_ttl_hours: u64,
156 pub scratchpad_default_ttl_hours: u64,
158 pub logical_session_ttl_seconds: u64,
160 pub max_concurrent_workers: usize,
164 pub max_concurrent_mutating_workers: usize,
168 pub active_worker_lease_seconds: u64,
170 pub serialize_build_commands: bool,
174 pub cargo_build_jobs: usize,
177 pub shared_cargo_target: bool,
182 pub max_scratchpad_entries: usize,
184}
185
186impl Default for AgentsConfig {
187 fn default() -> Self {
188 Self {
189 gc_interval_minutes: 10,
190 identity_ttl_hours: 48,
191 presence_ttl_hours: 24,
192 scratchpad_default_ttl_hours: 12,
193 logical_session_ttl_seconds: 180,
194 max_concurrent_workers: 12,
195 max_concurrent_mutating_workers: 4,
196 active_worker_lease_seconds: 120,
197 serialize_build_commands: false,
198 cargo_build_jobs: 0,
199 shared_cargo_target: false,
200 max_scratchpad_entries: 200,
201 }
202 }
203}
204
205#[cfg(test)]
206mod agents_config_tests {
207 use super::AgentsConfig;
208
209 #[test]
210 fn default_values_are_sane() {
211 let cfg = AgentsConfig::default();
212 assert_eq!(cfg.gc_interval_minutes, 10);
213 assert_eq!(cfg.identity_ttl_hours, 48);
214 assert_eq!(cfg.presence_ttl_hours, 24);
215 assert_eq!(cfg.scratchpad_default_ttl_hours, 12);
216 assert_eq!(cfg.logical_session_ttl_seconds, 180);
217 assert_eq!(cfg.max_concurrent_workers, 12);
218 assert_eq!(cfg.max_concurrent_mutating_workers, 4);
219 assert_eq!(cfg.active_worker_lease_seconds, 120);
220 assert!(!cfg.serialize_build_commands);
223 assert_eq!(cfg.cargo_build_jobs, 0);
224 assert!(!cfg.shared_cargo_target);
225 assert_eq!(cfg.max_scratchpad_entries, 200);
226 }
227
228 #[test]
229 fn deserializes_with_missing_fields() {
230 let json = r"{}";
231 let cfg: AgentsConfig = serde_json::from_str(json).expect("empty object → defaults");
232 assert_eq!(cfg.gc_interval_minutes, 10);
233 }
234
235 #[test]
236 fn partial_override() {
237 let json = r#"{"gc_interval_minutes": 5, "presence_ttl_hours": 12}"#;
238 let cfg: AgentsConfig = serde_json::from_str(json).expect("partial");
239 assert_eq!(cfg.gc_interval_minutes, 5);
240 assert_eq!(cfg.presence_ttl_hours, 12);
241 assert_eq!(cfg.identity_ttl_hours, 48);
242 }
243}
244
245#[derive(Debug, Clone, Serialize, Deserialize)]
246#[serde(default)]
247pub struct SecretDetectionConfig {
248 pub enabled: bool,
249 pub redact: bool,
250 pub custom_patterns: Vec<String>,
251 pub exclude_patterns: Vec<String>,
256}
257
258#[derive(Debug, Clone, Serialize, Deserialize)]
263#[serde(default)]
264pub struct SetupConfig {
265 pub auto_inject_rules: Option<bool>,
269 pub auto_inject_skills: Option<bool>,
272 #[serde(default = "serde_defaults::default_true")]
274 pub auto_update_mcp: bool,
275 #[serde(default = "serde_defaults::default_true")]
280 pub manage_hooks: bool,
281}
282
283impl Default for SetupConfig {
284 fn default() -> Self {
285 Self {
286 auto_inject_rules: None,
287 auto_inject_skills: None,
288 auto_update_mcp: true,
289 manage_hooks: true,
290 }
291 }
292}
293
294impl SetupConfig {
295 pub fn should_inject_rules(&self) -> bool {
299 match self.auto_inject_rules {
300 Some(v) => v,
301 None => Self::rules_already_present(),
302 }
303 }
304
305 pub fn should_inject_skills(&self) -> bool {
307 match self.auto_inject_skills {
308 Some(v) => v,
309 None => Self::rules_already_present(),
310 }
311 }
312
313 pub fn should_update_mcp(&self) -> bool {
318 self.auto_update_mcp
319 }
320
321 fn rules_already_present() -> bool {
329 let Some(home) = dirs::home_dir() else {
330 return false;
331 };
332 if crate::rules_inject::any_rules_marker_present(&home) {
333 return true;
334 }
335 let legacy_paths = [
336 crate::core::editor_registry::claude_rules_dir(&home).join("lean-ctx.md"),
337 crate::core::editor_registry::codebuddy_rules_dir(&home).join("lean-ctx.md"),
338 ];
339 legacy_paths.iter().any(|p| {
340 std::fs::read_to_string(p)
341 .is_ok_and(|c| c.contains(crate::core::rules_canonical::START_MARK))
342 })
343 }
344}
345
346impl Default for SecretDetectionConfig {
347 fn default() -> Self {
348 Self {
349 enabled: true,
350 redact: true,
351 custom_patterns: Vec::new(),
352 exclude_patterns: Vec::new(),
353 }
354 }
355}
356
357#[derive(Debug, Clone, Serialize, Deserialize)]
359#[serde(default)]
360pub struct ArchiveConfig {
361 pub enabled: bool,
362 pub threshold_chars: usize,
363 pub max_age_hours: u64,
364 pub max_disk_mb: u64,
365 pub ephemeral: bool,
366 pub ephemeral_min_tokens: usize,
369 pub inline_max_bytes: usize,
372 pub raw_commands: Vec<String>,
377 pub verbatim_max_tokens: usize,
385}
386
387#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
392#[serde(default)]
393pub struct ConversationConfig {
394 pub compression_enabled: bool,
396 pub preserve_last_n_turns: usize,
398 pub compression_threshold_tokens: usize,
400 pub min_score_to_preserve: f64,
402 pub summarize_score_range: [f64; 2],
404 pub drop_score_below: f64,
406 pub ccr_store_dropped: bool,
408}
409
410impl Default for ConversationConfig {
411 fn default() -> Self {
412 Self {
413 compression_enabled: false,
414 preserve_last_n_turns: 10,
415 compression_threshold_tokens: 50_000,
416 min_score_to_preserve: 0.5,
417 summarize_score_range: [0.2, 0.5],
418 drop_score_below: 0.2,
419 ccr_store_dropped: true,
420 }
421 }
422}
423
424impl Default for ArchiveConfig {
425 fn default() -> Self {
426 Self {
427 enabled: true,
428 threshold_chars: 800,
429 max_age_hours: 48,
430 max_disk_mb: 500,
431 ephemeral: true,
432 ephemeral_min_tokens: 2000,
433 inline_max_bytes: 32 * 1024,
434 raw_commands: crate::core::firewall::DEFAULT_RAW_COMMANDS
435 .iter()
436 .map(|s| (*s).to_string())
437 .collect(),
438 verbatim_max_tokens: 100_000,
439 }
440 }
441}
442
443impl ArchiveConfig {
444 pub fn ephemeral_effective(&self) -> bool {
445 if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL") {
446 return !matches!(v.trim(), "0" | "false" | "off");
447 }
448 self.ephemeral && self.enabled
449 }
450
451 pub fn ephemeral_min_tokens_effective(&self) -> usize {
452 if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL_MIN_TOKENS")
453 && let Ok(n) = v.trim().parse::<usize>()
454 {
455 return n;
456 }
457 self.ephemeral_min_tokens
458 }
459
460 pub fn verbatim_max_tokens_effective(&self) -> usize {
462 if let Ok(v) = std::env::var("LEAN_CTX_VERBATIM_MAX_TOKENS")
463 && let Ok(n) = v.trim().parse::<usize>()
464 {
465 return n;
466 }
467 self.verbatim_max_tokens
468 }
469
470 pub fn inline_max_bytes_effective(&self) -> usize {
471 if let Ok(v) = std::env::var("LEAN_CTX_INLINE_MAX_BYTES")
472 && let Ok(n) = v.trim().parse::<usize>()
473 {
474 return n;
475 }
476 self.inline_max_bytes
477 }
478}
479
480#[derive(Debug, Clone, Serialize, Deserialize)]
484#[serde(default)]
485pub struct ProvidersConfig {
486 pub enabled: bool,
488 pub github: ProviderEntryConfig,
490 pub gitlab: ProviderEntryConfig,
492 pub auto_index: bool,
494 pub cache_ttl_secs: u64,
496 #[serde(default)]
498 pub mcp_bridges: std::collections::HashMap<String, McpBridgeEntry>,
499}
500
501impl Default for ProvidersConfig {
502 fn default() -> Self {
503 Self {
504 enabled: true,
505 github: ProviderEntryConfig::default(),
506 gitlab: ProviderEntryConfig::default(),
507 auto_index: true,
508 cache_ttl_secs: 120,
509 mcp_bridges: std::collections::HashMap::new(),
510 }
511 }
512}
513
514#[derive(Debug, Clone, Serialize, Deserialize)]
516#[serde(default)]
517pub struct KnowledgeRoutingConfig {
518 pub enabled: bool,
519 pub max_references: usize,
520 pub hint_prefix: String,
521}
522
523impl Default for KnowledgeRoutingConfig {
524 fn default() -> Self {
525 Self {
526 enabled: true,
527 max_references: 5,
528 hint_prefix: "--- Knowledge Context ---".to_string(),
529 }
530 }
531}
532
533#[derive(Debug, Clone, Serialize, Deserialize)]
534pub struct McpBridgeEntry {
535 #[serde(default)]
537 pub url: Option<String>,
538 #[serde(default)]
540 pub command: Option<String>,
541 #[serde(default)]
543 pub args: Vec<String>,
544 #[serde(default)]
546 pub description: Option<String>,
547 #[serde(default)]
549 pub auth_env: Option<String>,
550}
551
552#[derive(Debug, Clone, Serialize, Deserialize)]
554#[serde(default)]
555pub struct ProviderEntryConfig {
556 pub enabled: bool,
558 pub token: Option<String>,
560 pub api_url: Option<String>,
562 pub project: Option<String>,
564}
565
566impl Default for ProviderEntryConfig {
567 fn default() -> Self {
568 Self {
569 enabled: true,
570 token: None,
571 api_url: None,
572 project: None,
573 }
574 }
575}
576
577#[derive(Debug, Clone, Serialize, Deserialize)]
579#[serde(default)]
580pub struct AutonomyConfig {
581 pub enabled: bool,
582 pub auto_preload: bool,
583 pub auto_dedup: bool,
584 pub auto_related: bool,
585 pub auto_consolidate: bool,
586 pub silent_preload: bool,
587 pub dedup_threshold: usize,
588 pub consolidate_every_calls: u32,
589 pub consolidate_cooldown_secs: u64,
590 #[serde(default = "serde_defaults::default_true")]
591 pub cognition_loop_enabled: bool,
592 #[serde(default = "serde_defaults::default_cognition_loop_interval")]
593 pub cognition_loop_interval_secs: u64,
594 #[serde(default = "serde_defaults::default_cognition_loop_max_steps")]
595 pub cognition_loop_max_steps: u8,
596 #[serde(default = "serde_defaults::default_cognition_synthesis_min_cluster")]
599 pub cognition_synthesis_min_cluster: usize,
600}
601
602impl Default for AutonomyConfig {
603 fn default() -> Self {
604 Self {
605 enabled: true,
606 auto_preload: true,
607 auto_dedup: true,
608 auto_related: true,
609 auto_consolidate: true,
610 silent_preload: true,
611 dedup_threshold: 8,
612 consolidate_every_calls: 25,
613 consolidate_cooldown_secs: 120,
614 cognition_loop_enabled: true,
615 cognition_loop_interval_secs: 3600,
616 cognition_loop_max_steps: 9,
617 cognition_synthesis_min_cluster: 3,
618 }
619 }
620}
621
622#[derive(Debug, Clone, Serialize, Deserialize)]
625#[serde(default)]
626pub struct UpdatesConfig {
627 pub auto_update: bool,
628 pub check_interval_hours: u64,
629 pub notify_only: bool,
630 #[serde(default)]
633 pub pinned_version: Option<String>,
634}
635
636impl Default for UpdatesConfig {
637 fn default() -> Self {
638 Self {
639 auto_update: false,
640 check_interval_hours: 6,
641 notify_only: false,
642 pinned_version: None,
643 }
644 }
645}
646
647#[derive(Debug, Clone, Serialize, Deserialize)]
653#[serde(default)]
654pub struct ContextConfig {
655 pub budget_tokens: usize,
656 pub diet_max_config_tokens: usize,
657 pub diet_relevance_threshold: f64,
658 pub diet_rebalance_on_change: bool,
659 pub diet_staleness_enabled: bool,
660 pub proactive_expansion: bool,
662 pub proactive_expansion_budget_tokens: usize,
664 pub proactive_expansion_threshold: f64,
666 pub proactive_expansion_max_age_secs: u64,
668}
669
670impl Default for ContextConfig {
671 fn default() -> Self {
672 Self {
673 budget_tokens: 8000,
674 diet_max_config_tokens: 800,
675 diet_relevance_threshold: 0.15,
676 diet_rebalance_on_change: true,
677 diet_staleness_enabled: true,
678 proactive_expansion: true,
679 proactive_expansion_budget_tokens: 2000,
680 proactive_expansion_threshold: 0.6,
681 proactive_expansion_max_age_secs: 3600,
682 }
683 }
684}
685
686impl UpdatesConfig {
687 pub fn from_env() -> Self {
688 let mut cfg = Self::default();
689 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_UPDATE") {
690 cfg.auto_update = v == "1" || v.eq_ignore_ascii_case("true");
691 }
692 if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_INTERVAL_HOURS")
693 && let Ok(h) = v.parse::<u64>()
694 {
695 cfg.check_interval_hours = h.clamp(1, 168);
696 }
697 if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_NOTIFY_ONLY") {
698 cfg.notify_only = v == "1" || v.eq_ignore_ascii_case("true");
699 }
700 cfg
701 }
702}
703
704impl AutonomyConfig {
705 pub fn from_env() -> Self {
707 let mut cfg = Self::default();
708 if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
709 && (v == "false" || v == "0")
710 {
711 cfg.enabled = false;
712 }
713 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
714 cfg.auto_preload = v != "false" && v != "0";
715 }
716 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
717 cfg.auto_dedup = v != "false" && v != "0";
718 }
719 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
720 cfg.auto_related = v != "false" && v != "0";
721 }
722 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_CONSOLIDATE") {
723 cfg.auto_consolidate = v != "false" && v != "0";
724 }
725 if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
726 cfg.silent_preload = v != "false" && v != "0";
727 }
728 if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD")
729 && let Ok(n) = v.parse()
730 {
731 cfg.dedup_threshold = n;
732 }
733 if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_EVERY_CALLS")
734 && let Ok(n) = v.parse()
735 {
736 cfg.consolidate_every_calls = n;
737 }
738 if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_COOLDOWN_SECS")
739 && let Ok(n) = v.parse()
740 {
741 cfg.consolidate_cooldown_secs = n;
742 }
743 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
744 cfg.cognition_loop_enabled = v != "false" && v != "0";
745 }
746 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
747 && let Ok(n) = v.parse()
748 {
749 cfg.cognition_loop_interval_secs = n;
750 }
751 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
752 && let Ok(n) = v.parse()
753 {
754 cfg.cognition_loop_max_steps = n;
755 }
756 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_SYNTHESIS_MIN_CLUSTER")
757 && let Ok(n) = v.parse()
758 {
759 cfg.cognition_synthesis_min_cluster = n;
760 }
761 cfg
762 }
763
764 pub fn load() -> Self {
766 let file_cfg = Config::load().autonomy;
767 let mut cfg = file_cfg;
768 if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
769 && (v == "false" || v == "0")
770 {
771 cfg.enabled = false;
772 }
773 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
774 cfg.auto_preload = v != "false" && v != "0";
775 }
776 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
777 cfg.auto_dedup = v != "false" && v != "0";
778 }
779 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
780 cfg.auto_related = v != "false" && v != "0";
781 }
782 if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
783 cfg.silent_preload = v != "false" && v != "0";
784 }
785 if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD")
786 && let Ok(n) = v.parse()
787 {
788 cfg.dedup_threshold = n;
789 }
790 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
791 cfg.cognition_loop_enabled = v != "false" && v != "0";
792 }
793 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
794 && let Ok(n) = v.parse()
795 {
796 cfg.cognition_loop_interval_secs = n;
797 }
798 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
799 && let Ok(n) = v.parse()
800 {
801 cfg.cognition_loop_max_steps = n;
802 }
803 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_SYNTHESIS_MIN_CLUSTER")
804 && let Ok(n) = v.parse()
805 {
806 cfg.cognition_synthesis_min_cluster = n;
807 }
808 cfg
809 }
810}
811
812#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
815#[serde(rename_all = "snake_case")]
816pub enum TelemetryPreference {
817 #[default]
818 DefaultOn,
819 ExplicitlyEnabled,
820 ExplicitlyDisabled,
821}
822
823#[derive(Debug, Clone, Serialize, Deserialize)]
831#[serde(default)]
832pub struct TelemetryConfig {
833 pub enabled: bool,
835 pub preference: TelemetryPreference,
837 pub last_heartbeat: Option<String>,
839}
840
841impl Default for TelemetryConfig {
842 fn default() -> Self {
843 Self {
844 enabled: true,
845 preference: TelemetryPreference::DefaultOn,
846 last_heartbeat: None,
847 }
848 }
849}
850
851impl TelemetryConfig {
852 #[must_use]
853 pub fn environment_disables(do_not_track: Option<&str>, env_override: Option<&str>) -> bool {
854 do_not_track.is_some_and(|value| value.trim() == "1")
855 || env_override.is_some_and(|value| {
856 matches!(
857 value.trim().to_ascii_lowercase().as_str(),
858 "off" | "false" | "0" | "no"
859 )
860 })
861 }
862
863 #[must_use]
864 pub fn explicitly_disabled(&self) -> bool {
865 !self.enabled || self.preference == TelemetryPreference::ExplicitlyDisabled
866 }
867
868 #[must_use]
869 pub fn send_eligible(&self, do_not_track: Option<&str>, env_override: Option<&str>) -> bool {
870 self.enabled
871 && self.preference != TelemetryPreference::ExplicitlyDisabled
872 && !Self::environment_disables(do_not_track, env_override)
873 }
874}
875
876#[derive(Debug, Clone, Serialize, Deserialize, Default)]
878#[serde(default)]
879pub struct CloudConfig {
880 pub contribute_enabled: bool,
881 pub last_contribute: Option<String>,
882 #[serde(default)]
884 pub sync_stats_enabled: bool,
885 pub last_sync: Option<String>,
886 #[serde(default)]
888 pub sync_gain_enabled: bool,
889 pub last_gain_sync: Option<String>,
890 #[serde(default)]
892 pub sync_models_enabled: bool,
893 pub last_model_pull: Option<String>,
894 pub auto_sync: bool,
897 pub last_auto_sync: Option<String>,
898 pub auto_index: bool,
901 pub last_index_push: std::collections::HashMap<String, String>,
904}
905
906#[derive(Debug, Clone, Serialize, Deserialize)]
912#[serde(default)]
913pub struct GainConfig {
914 pub auto_publish: bool,
917 pub leaderboard: bool,
919 pub display_name: Option<String>,
921 pub auto_publish_interval_hours: u64,
923 pub last_auto_publish: Option<String>,
926}
927
928impl Default for GainConfig {
929 fn default() -> Self {
930 Self {
931 auto_publish: false,
932 leaderboard: false,
933 display_name: None,
934 auto_publish_interval_hours: 24,
935 last_auto_publish: None,
936 }
937 }
938}
939
940#[derive(Debug, Clone, Default, Serialize, Deserialize)]
949#[serde(default)]
950pub struct CostConfig {
951 #[serde(default)]
956 pub max_session_cost_usd: f64,
957 #[serde(default, skip_serializing_if = "Option::is_none")]
960 pub default_model: Option<String>,
961 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
966 pub models: HashMap<String, String>,
967 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
975 pub prices: HashMap<String, PriceOverride>,
976}
977
978#[derive(Debug, Clone, Serialize, Deserialize)]
980#[serde(default)]
981pub struct ProtectionConfig {
982 pub file_patterns: Vec<String>,
988 pub tags: bool,
992}
993
994impl Default for ProtectionConfig {
995 fn default() -> Self {
996 Self {
997 file_patterns: Vec::new(),
998 tags: true,
999 }
1000 }
1001}
1002
1003impl ProtectionConfig {
1004 pub fn path_is_protected(&self, path: &str) -> bool {
1006 !path.is_empty()
1007 && self
1008 .file_patterns
1009 .iter()
1010 .filter_map(|p| glob::Pattern::new(p).ok())
1011 .any(|pattern| pattern.matches(path))
1012 }
1013}
1014
1015#[cfg(test)]
1016mod protection_tests {
1017 use super::ProtectionConfig;
1018
1019 #[test]
1020 fn protected_globs_match_paths_and_ignore_invalid_patterns() {
1021 let cfg = ProtectionConfig {
1022 file_patterns: vec![
1023 "docs/audits/**".into(),
1024 "*.secret.md".into(),
1025 "[invalid".into(),
1026 ],
1027 tags: true,
1028 };
1029 assert!(cfg.path_is_protected("docs/audits/q3/blockers.md"));
1030 assert!(cfg.path_is_protected("notes.secret.md"));
1031 assert!(!cfg.path_is_protected("src/main.rs"));
1032 assert!(!cfg.path_is_protected(""));
1033
1034 let empty = ProtectionConfig::default();
1035 assert!(!empty.path_is_protected("docs/audits/q3/blockers.md"));
1036 assert!(empty.tags, "protect tags are honored by default");
1037 }
1038}
1039#[derive(Debug, Clone, Serialize, Deserialize)]
1041#[serde(default)]
1042pub struct DecisionLoopConfig {
1043 pub enabled: bool,
1044 #[serde(default)]
1047 pub max_filter_level: u8,
1048}
1049
1050impl Default for DecisionLoopConfig {
1051 fn default() -> Self {
1052 Self {
1053 enabled: true,
1054 max_filter_level: 0,
1055 }
1056 }
1057}
1058
1059#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1062#[serde(default)]
1063pub struct PriceOverride {
1064 pub input_per_m: Option<f64>,
1065 pub output_per_m: Option<f64>,
1066 pub cache_write_per_m: Option<f64>,
1067 pub cache_read_per_m: Option<f64>,
1068}
1069
1070impl CostConfig {
1071 pub fn model_for_client(&self, client: &str) -> Option<String> {
1075 self.models
1076 .get(client)
1077 .or(self.default_model.as_ref())
1078 .map(|s| s.trim().to_string())
1079 .filter(|s| !s.is_empty())
1080 }
1081}
1082
1083#[derive(Debug, Clone, Serialize, Deserialize)]
1089#[serde(default)]
1090pub struct CodeHealthConfig {
1091 pub cognitive_threshold: u32,
1094 pub gate: String,
1097 pub annotate_reads: bool,
1099 pub naming: bool,
1101 pub coupling: bool,
1103 #[serde(default)]
1109 pub inject_context: bool,
1110}
1111
1112impl Default for CodeHealthConfig {
1113 fn default() -> Self {
1114 Self {
1115 cognitive_threshold: 15,
1116 gate: "warn".to_string(),
1117 annotate_reads: true,
1118 naming: true,
1119 coupling: true,
1120 inject_context: false,
1121 }
1122 }
1123}
1124
1125#[derive(Debug, Clone, Serialize, Deserialize)]
1135#[serde(default)]
1136pub struct IndexConfig {
1137 pub respect_gitignore: bool,
1141 pub exclude: Vec<String>,
1144 pub include: Vec<String>,
1147}
1148
1149impl Default for IndexConfig {
1150 fn default() -> Self {
1151 Self {
1152 respect_gitignore: true,
1153 exclude: Vec::new(),
1154 include: Vec::new(),
1155 }
1156 }
1157}
1158
1159#[derive(Debug, Clone, Serialize, Deserialize)]
1169#[serde(default)]
1170pub struct GraphConfig {
1171 pub traversal_edges: bool,
1175}
1176
1177impl Default for GraphConfig {
1178 fn default() -> Self {
1179 Self {
1180 traversal_edges: true,
1181 }
1182 }
1183}
1184
1185#[derive(Debug, Clone, Serialize, Deserialize)]
1193#[serde(default)]
1194pub struct SkillifyConfig {
1195 pub enabled: bool,
1198 pub scope: String,
1201 pub min_confidence: f32,
1204 pub min_recurrence: u32,
1207}
1208
1209impl Default for SkillifyConfig {
1210 fn default() -> Self {
1211 Self {
1212 enabled: true,
1213 scope: "project".to_string(),
1214 min_confidence: 0.7,
1215 min_recurrence: 2,
1216 }
1217 }
1218}
1219
1220#[derive(Debug, Clone, Serialize, Deserialize)]
1225#[serde(default)]
1226pub struct SummariesConfig {
1227 pub enabled: bool,
1230 pub every_n_turns: u32,
1233 pub max_kept: u32,
1235}
1236
1237impl Default for SummariesConfig {
1238 fn default() -> Self {
1239 Self {
1240 enabled: true,
1241 every_n_turns: 25,
1242 max_kept: 100,
1243 }
1244 }
1245}
1246
1247#[derive(Debug, Clone, Serialize, Deserialize)]
1249pub struct AliasEntry {
1250 pub command: String,
1251 pub alias: String,
1252}
1253
1254#[derive(Debug, Clone, Serialize, Deserialize)]
1256#[serde(default)]
1257pub struct LoopDetectionConfig {
1258 pub normal_threshold: u32,
1259 pub reduced_threshold: u32,
1260 pub blocked_threshold: u32,
1261 pub window_secs: u64,
1262 pub search_group_limit: u32,
1263 pub tool_total_limits: HashMap<String, u32>,
1264}
1265
1266impl Default for LoopDetectionConfig {
1267 fn default() -> Self {
1268 let mut tool_total_limits = HashMap::new();
1269 tool_total_limits.insert("ctx_read".to_string(), 100);
1270 tool_total_limits.insert("ctx_search".to_string(), 80);
1271 tool_total_limits.insert("ctx_shell".to_string(), 50);
1272 tool_total_limits.insert("ctx_semantic_search".to_string(), 60);
1273 Self {
1274 normal_threshold: 2,
1275 reduced_threshold: 4,
1276 blocked_threshold: 0,
1277 window_secs: 300,
1278 search_group_limit: 10,
1279 tool_total_limits,
1280 }
1281 }
1282}
1283
1284#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1303#[serde(default)]
1304pub struct GatewayServerConfig {
1305 #[serde(default, skip_serializing_if = "Option::is_none")]
1308 pub seats: Option<u32>,
1309 #[serde(default, skip_serializing_if = "Option::is_none")]
1311 pub org_label: Option<String>,
1312 #[serde(default, skip_serializing_if = "Option::is_none")]
1317 pub admin_url: Option<String>,
1318 #[serde(default, skip_serializing_if = "Option::is_none")]
1325 pub admin_bind_host: Option<String>,
1326 #[serde(default, skip_serializing_if = "Option::is_none")]
1331 pub usage_retention_days: Option<u32>,
1332 #[serde(default, skip_serializing_if = "Option::is_none")]
1338 pub pseudonymize_persons: Option<bool>,
1339 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1346 pub mcp_servers: Vec<McpServerEntry>,
1347}
1348
1349#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1353pub struct McpServerEntry {
1354 pub id: String,
1357 pub url: String,
1362 #[serde(default, skip_serializing_if = "Option::is_none")]
1368 pub auth_env: Option<String>,
1369 #[serde(default, skip_serializing_if = "Option::is_none")]
1371 pub enabled: Option<bool>,
1372}
1373
1374#[derive(Debug, Clone, PartialEq, Eq)]
1377pub struct ResolvedMcpServer {
1378 pub id: String,
1379 pub url: String,
1380 pub auth_env: Option<String>,
1381}
1382
1383impl GatewayServerConfig {
1384 #[must_use]
1390 pub fn resolve_mcp_servers(&self, allow_insecure_http: bool) -> Vec<ResolvedMcpServer> {
1391 let mut seen: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
1392 let mut out = Vec::new();
1393 for entry in &self.mcp_servers {
1394 if !entry.enabled.unwrap_or(true) {
1395 continue;
1396 }
1397 let id = entry.id.trim();
1398 if !is_valid_mcp_server_id(id) {
1399 tracing::warn!(
1400 "[gateway_server.mcp_servers] invalid id '{id}' \
1401 (lowercase alnum/-/_ only) — entry skipped"
1402 );
1403 continue;
1404 }
1405 if !seen.insert(id) {
1406 tracing::warn!(
1407 "[gateway_server.mcp_servers] duplicate id '{id}' — keeping first entry"
1408 );
1409 continue;
1410 }
1411 match validate_mcp_upstream_url(&entry.url, allow_insecure_http) {
1412 Ok(url) => out.push(ResolvedMcpServer {
1413 id: id.to_string(),
1414 url,
1415 auth_env: entry
1416 .auth_env
1417 .as_deref()
1418 .map(str::trim)
1419 .filter(|v| !v.is_empty())
1420 .map(str::to_string),
1421 }),
1422 Err(e) => {
1423 tracing::warn!(
1424 "[gateway_server.mcp_servers] '{id}' has invalid url — skipped: {e}"
1425 );
1426 }
1427 }
1428 }
1429 out
1430 }
1431
1432 #[must_use]
1435 pub fn resolved_admin_bind_host(&self) -> std::net::IpAddr {
1436 let raw = std::env::var("LEAN_CTX_GATEWAY_ADMIN_BIND_HOST")
1437 .ok()
1438 .filter(|v| !v.trim().is_empty())
1439 .or_else(|| self.admin_bind_host.clone());
1440 match raw.as_deref().map(str::trim) {
1441 Some(v) if !v.is_empty() => v.parse().unwrap_or_else(|_| {
1442 tracing::warn!(
1443 "gateway_server.admin_bind_host '{v}' is not a valid IP address — binding 127.0.0.1"
1444 );
1445 std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
1446 }),
1447 _ => std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
1448 }
1449 }
1450}
1451
1452fn is_valid_mcp_server_id(id: &str) -> bool {
1456 !id.is_empty()
1457 && id
1458 .chars()
1459 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
1460}
1461
1462fn validate_mcp_upstream_url(url: &str, allow_insecure_http: bool) -> Result<String, String> {
1468 let trimmed = url.trim().trim_end_matches('/');
1469 if trimmed.is_empty() {
1470 return Err("empty url".into());
1471 }
1472 if crate::core::config::is_local_proxy_url(trimmed) {
1473 return Ok(trimmed.to_string());
1474 }
1475 if trimmed.starts_with("http://") {
1476 if allow_insecure_http {
1477 return Ok(trimmed.to_string());
1478 }
1479 return Err(format!(
1480 "MCP upstream must use HTTPS: {trimmed} (for a trusted local-network HTTP \
1481 upstream opt in with `[proxy] allow_insecure_http_upstream = true`)"
1482 ));
1483 }
1484 if trimmed.starts_with("https://") {
1485 return Ok(trimmed.to_string());
1486 }
1487 Err(format!(
1488 "MCP upstream must start with http:// or https://: {trimmed}"
1489 ))
1490}
1491
1492#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1493#[serde(default)]
1494pub struct EmbeddingConfig {
1495 #[serde(default, skip_serializing_if = "Option::is_none")]
1496 pub model: Option<String>,
1497 #[serde(default, skip_serializing_if = "Option::is_none")]
1498 pub dimensions: Option<usize>,
1499 #[serde(default, skip_serializing_if = "Option::is_none")]
1505 pub auto_download: Option<bool>,
1506 #[serde(default, skip_serializing_if = "Option::is_none")]
1513 pub deterministic: Option<bool>,
1514}
1515
1516#[cfg(test)]
1517mod gateway_server_tests {
1518 use super::*;
1519
1520 #[test]
1521 fn admin_bind_defaults_to_loopback_and_rejects_garbage() {
1522 let cfg = GatewayServerConfig::default();
1524 assert!(cfg.resolved_admin_bind_host().is_loopback());
1525
1526 let cfg = GatewayServerConfig {
1527 admin_bind_host: Some("not-an-ip".into()),
1528 ..Default::default()
1529 };
1530 assert!(
1531 cfg.resolved_admin_bind_host().is_loopback(),
1532 "a typo must narrow exposure, never widen it"
1533 );
1534
1535 let cfg = GatewayServerConfig {
1536 admin_bind_host: Some("0.0.0.0".into()),
1537 ..Default::default()
1538 };
1539 assert!(
1540 !cfg.resolved_admin_bind_host().is_loopback(),
1541 "explicit opt-in widens the bind"
1542 );
1543 }
1544
1545 fn mcp_entry(id: &str, url: &str) -> McpServerEntry {
1546 McpServerEntry {
1547 id: id.into(),
1548 url: url.into(),
1549 auth_env: None,
1550 enabled: None,
1551 }
1552 }
1553
1554 #[test]
1555 fn mcp_registry_validates_ids_urls_and_duplicates() {
1556 let cfg = GatewayServerConfig {
1557 mcp_servers: vec![
1558 mcp_entry("github", "https://mcp.example.com/mcp/"),
1559 mcp_entry("GitHub", "https://mcp.example.com/mcp"),
1561 mcp_entry("github", "https://other.example.com/mcp"),
1563 mcp_entry("plain", "http://mcp.example.com/mcp"),
1565 mcp_entry("local", "http://127.0.0.1:9200/mcp"),
1567 McpServerEntry {
1568 enabled: Some(false),
1569 ..mcp_entry("disabled", "https://mcp.example.com/mcp")
1570 },
1571 McpServerEntry {
1572 auth_env: Some(" GITHUB_MCP_PAT ".into()),
1573 ..mcp_entry("authed", "https://api.githubcopilot.com/mcp")
1574 },
1575 ],
1576 ..Default::default()
1577 };
1578 let resolved = cfg.resolve_mcp_servers(false);
1579 let ids: Vec<&str> = resolved.iter().map(|s| s.id.as_str()).collect();
1580 assert_eq!(ids, ["github", "local", "authed"]);
1581 assert_eq!(resolved[0].url, "https://mcp.example.com/mcp");
1583 assert_eq!(resolved[2].auth_env.as_deref(), Some("GITHUB_MCP_PAT"));
1584
1585 let with_optin = cfg.resolve_mcp_servers(true);
1587 assert!(with_optin.iter().any(|s| s.id == "plain"));
1588 }
1589
1590 #[test]
1591 fn mcp_upstream_url_rules_match_the_proxy_posture() {
1592 assert!(validate_mcp_upstream_url("https://mcp.example.com/mcp", false).is_ok());
1593 assert!(validate_mcp_upstream_url("http://localhost:9200/mcp", false).is_ok());
1594 assert!(validate_mcp_upstream_url("http://mcp.example.com/mcp", false).is_err());
1595 assert!(validate_mcp_upstream_url("http://mcp.example.com/mcp", true).is_ok());
1596 assert!(validate_mcp_upstream_url("ftp://mcp.example.com", false).is_err());
1597 assert!(validate_mcp_upstream_url(" ", false).is_err());
1598 }
1599}
1600
1601#[cfg(test)]
1602mod ocla_tests {
1603 use super::OclaConfig;
1604 use crate::core::ocla::grpc_bridge::GrpcConfig;
1605 use crate::core::ocla::sidecar::SidecarConfig;
1606 use serde::Deserialize;
1607
1608 #[derive(Deserialize)]
1609 struct ConfigFile {
1610 ocla: OclaConfig,
1611 }
1612
1613 #[test]
1614 fn sidecar_defaults_are_loopback_and_disabled() {
1615 let config = SidecarConfig::default();
1616 assert_eq!(config.bind_addr, "127.0.0.1:3334");
1617 assert!(!config.enabled);
1618 assert!(config.auth_token.is_none());
1619 }
1620
1621 #[test]
1622 fn nested_sidecar_toml_deserializes() {
1623 let config: ConfigFile = toml::from_str(
1624 r#"
1625 [ocla.sidecar]
1626 bind_addr = "127.0.0.1:9000"
1627 auth_token = "wire-secret"
1628 tls_cert_path = "/etc/lean-ctx/cert.pem"
1629 tls_key_path = "/etc/lean-ctx/key.pem"
1630 enabled = true
1631 "#,
1632 )
1633 .expect("OCLA sidecar config");
1634
1635 let sidecar = config.ocla.sidecar;
1636 assert_eq!(sidecar.bind_addr, "127.0.0.1:9000");
1637 assert_eq!(sidecar.auth_token.as_deref(), Some("wire-secret"));
1638 assert_eq!(
1639 sidecar.tls_cert_path.as_deref().unwrap().to_str(),
1640 Some("/etc/lean-ctx/cert.pem")
1641 );
1642 assert_eq!(
1643 sidecar.tls_key_path.as_deref().unwrap().to_str(),
1644 Some("/etc/lean-ctx/key.pem")
1645 );
1646 assert!(sidecar.enabled);
1647 }
1648
1649 #[test]
1650 fn nested_grpc_toml_deserializes() {
1651 let config: ConfigFile = toml::from_str(
1652 r#"
1653 [ocla.grpc]
1654 enabled = true
1655 listen = "127.0.0.1:60051"
1656 "#,
1657 )
1658 .expect("OCLA gRPC config");
1659
1660 assert_eq!(config.ocla.grpc.listen, "127.0.0.1:60051");
1661 assert!(config.ocla.grpc.enabled);
1662 assert_eq!(GrpcConfig::default().listen, "127.0.0.1:50051");
1663 }
1664}
1665
1666#[cfg(test)]
1667mod telemetry_tests {
1668 use super::*;
1669
1670 #[test]
1671 fn telemetry_config_defaults_on_and_send_eligible() {
1672 let cfg = TelemetryConfig::default();
1673 assert!(cfg.enabled);
1674 assert_eq!(cfg.preference, TelemetryPreference::DefaultOn);
1675 assert!(cfg.send_eligible(None, None));
1676 assert!(cfg.last_heartbeat.is_none());
1677 }
1678
1679 #[test]
1680 fn telemetry_config_serde_roundtrip() {
1681 let toml_str = r#"
1682[telemetry]
1683enabled = true
1684last_heartbeat = "2026-07-30"
1685"#;
1686 #[derive(serde::Deserialize)]
1687 struct Wrap {
1688 telemetry: TelemetryConfig,
1689 }
1690 let wrap: Wrap = toml::from_str(toml_str).expect("parse telemetry config");
1691 assert!(wrap.telemetry.enabled);
1692 assert_eq!(wrap.telemetry.preference, TelemetryPreference::DefaultOn);
1693 assert_eq!(wrap.telemetry.last_heartbeat.as_deref(), Some("2026-07-30"));
1694 }
1695
1696 #[test]
1697 fn a_retired_notice_key_in_an_existing_config_still_parses() {
1698 let cfg: TelemetryConfig =
1699 toml::from_str("enabled = true\nnotice_shown = false").expect("pre-removal config");
1700 assert!(cfg.send_eligible(None, None));
1701 }
1702
1703 #[test]
1704 fn telemetry_config_missing_section_uses_defaults() {
1705 let toml_str = "";
1706 #[derive(serde::Deserialize, Default)]
1707 #[serde(default)]
1708 struct Wrap {
1709 telemetry: TelemetryConfig,
1710 }
1711 let wrap: Wrap = toml::from_str(toml_str).expect("parse empty config");
1712 assert!(wrap.telemetry.enabled);
1713 assert_eq!(wrap.telemetry.preference, TelemetryPreference::DefaultOn);
1714 assert!(wrap.telemetry.last_heartbeat.is_none());
1715 }
1716
1717 #[test]
1718 fn legacy_false_remains_an_explicit_opt_out() {
1719 let cfg: TelemetryConfig = toml::from_str("enabled = false").expect("legacy config");
1720 assert!(cfg.explicitly_disabled());
1721 }
1722
1723 #[test]
1724 fn send_honors_the_explicit_and_both_environment_opt_outs() {
1725 let mut cfg = TelemetryConfig::default();
1726 assert!(cfg.send_eligible(None, None));
1727 assert!(!cfg.send_eligible(Some("1"), None));
1728 assert!(!cfg.send_eligible(None, Some("OFF")));
1729 cfg.preference = TelemetryPreference::ExplicitlyDisabled;
1730 assert!(!cfg.send_eligible(None, None));
1731 }
1732}