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,
172 pub cargo_build_jobs: usize,
174 pub shared_cargo_target: bool,
176 pub max_scratchpad_entries: usize,
178}
179
180impl Default for AgentsConfig {
181 fn default() -> Self {
182 Self {
183 gc_interval_minutes: 10,
184 identity_ttl_hours: 48,
185 presence_ttl_hours: 24,
186 scratchpad_default_ttl_hours: 12,
187 logical_session_ttl_seconds: 180,
188 max_concurrent_workers: 12,
189 max_concurrent_mutating_workers: 4,
190 active_worker_lease_seconds: 120,
191 serialize_build_commands: true,
192 cargo_build_jobs: 3,
193 shared_cargo_target: true,
194 max_scratchpad_entries: 200,
195 }
196 }
197}
198
199#[cfg(test)]
200mod agents_config_tests {
201 use super::AgentsConfig;
202
203 #[test]
204 fn default_values_are_sane() {
205 let cfg = AgentsConfig::default();
206 assert_eq!(cfg.gc_interval_minutes, 10);
207 assert_eq!(cfg.identity_ttl_hours, 48);
208 assert_eq!(cfg.presence_ttl_hours, 24);
209 assert_eq!(cfg.scratchpad_default_ttl_hours, 12);
210 assert_eq!(cfg.logical_session_ttl_seconds, 180);
211 assert_eq!(cfg.max_concurrent_workers, 12);
212 assert_eq!(cfg.max_concurrent_mutating_workers, 4);
213 assert_eq!(cfg.active_worker_lease_seconds, 120);
214 assert!(cfg.serialize_build_commands);
215 assert_eq!(cfg.cargo_build_jobs, 3);
216 assert!(cfg.shared_cargo_target);
217 assert_eq!(cfg.max_scratchpad_entries, 200);
218 }
219
220 #[test]
221 fn deserializes_with_missing_fields() {
222 let json = r"{}";
223 let cfg: AgentsConfig = serde_json::from_str(json).expect("empty object → defaults");
224 assert_eq!(cfg.gc_interval_minutes, 10);
225 }
226
227 #[test]
228 fn partial_override() {
229 let json = r#"{"gc_interval_minutes": 5, "presence_ttl_hours": 12}"#;
230 let cfg: AgentsConfig = serde_json::from_str(json).expect("partial");
231 assert_eq!(cfg.gc_interval_minutes, 5);
232 assert_eq!(cfg.presence_ttl_hours, 12);
233 assert_eq!(cfg.identity_ttl_hours, 48);
234 }
235}
236
237#[derive(Debug, Clone, Serialize, Deserialize)]
238#[serde(default)]
239pub struct SecretDetectionConfig {
240 pub enabled: bool,
241 pub redact: bool,
242 pub custom_patterns: Vec<String>,
243 pub exclude_patterns: Vec<String>,
248}
249
250#[derive(Debug, Clone, Serialize, Deserialize)]
255#[serde(default)]
256pub struct SetupConfig {
257 pub auto_inject_rules: Option<bool>,
261 pub auto_inject_skills: Option<bool>,
264 #[serde(default = "serde_defaults::default_true")]
266 pub auto_update_mcp: bool,
267 #[serde(default = "serde_defaults::default_true")]
272 pub manage_hooks: bool,
273}
274
275impl Default for SetupConfig {
276 fn default() -> Self {
277 Self {
278 auto_inject_rules: None,
279 auto_inject_skills: None,
280 auto_update_mcp: true,
281 manage_hooks: true,
282 }
283 }
284}
285
286impl SetupConfig {
287 pub fn should_inject_rules(&self) -> bool {
291 match self.auto_inject_rules {
292 Some(v) => v,
293 None => Self::rules_already_present(),
294 }
295 }
296
297 pub fn should_inject_skills(&self) -> bool {
299 match self.auto_inject_skills {
300 Some(v) => v,
301 None => Self::rules_already_present(),
302 }
303 }
304
305 pub fn should_update_mcp(&self) -> bool {
310 self.auto_update_mcp
311 }
312
313 fn rules_already_present() -> bool {
321 let Some(home) = dirs::home_dir() else {
322 return false;
323 };
324 if crate::rules_inject::any_rules_marker_present(&home) {
325 return true;
326 }
327 let legacy_paths = [
328 crate::core::editor_registry::claude_rules_dir(&home).join("lean-ctx.md"),
329 crate::core::editor_registry::codebuddy_rules_dir(&home).join("lean-ctx.md"),
330 ];
331 legacy_paths.iter().any(|p| {
332 std::fs::read_to_string(p)
333 .is_ok_and(|c| c.contains(crate::core::rules_canonical::START_MARK))
334 })
335 }
336}
337
338impl Default for SecretDetectionConfig {
339 fn default() -> Self {
340 Self {
341 enabled: true,
342 redact: true,
343 custom_patterns: Vec::new(),
344 exclude_patterns: Vec::new(),
345 }
346 }
347}
348
349#[derive(Debug, Clone, Serialize, Deserialize)]
351#[serde(default)]
352pub struct ArchiveConfig {
353 pub enabled: bool,
354 pub threshold_chars: usize,
355 pub max_age_hours: u64,
356 pub max_disk_mb: u64,
357 pub ephemeral: bool,
358 pub ephemeral_min_tokens: usize,
361 pub inline_max_bytes: usize,
364 pub raw_commands: Vec<String>,
369 pub verbatim_max_tokens: usize,
377}
378
379#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
384#[serde(default)]
385pub struct ConversationConfig {
386 pub compression_enabled: bool,
388 pub preserve_last_n_turns: usize,
390 pub compression_threshold_tokens: usize,
392 pub min_score_to_preserve: f64,
394 pub summarize_score_range: [f64; 2],
396 pub drop_score_below: f64,
398 pub ccr_store_dropped: bool,
400}
401
402impl Default for ConversationConfig {
403 fn default() -> Self {
404 Self {
405 compression_enabled: false,
406 preserve_last_n_turns: 10,
407 compression_threshold_tokens: 50_000,
408 min_score_to_preserve: 0.5,
409 summarize_score_range: [0.2, 0.5],
410 drop_score_below: 0.2,
411 ccr_store_dropped: true,
412 }
413 }
414}
415
416impl Default for ArchiveConfig {
417 fn default() -> Self {
418 Self {
419 enabled: true,
420 threshold_chars: 800,
421 max_age_hours: 48,
422 max_disk_mb: 500,
423 ephemeral: true,
424 ephemeral_min_tokens: 2000,
425 inline_max_bytes: 32 * 1024,
426 raw_commands: crate::core::firewall::DEFAULT_RAW_COMMANDS
427 .iter()
428 .map(|s| (*s).to_string())
429 .collect(),
430 verbatim_max_tokens: 100_000,
431 }
432 }
433}
434
435impl ArchiveConfig {
436 pub fn ephemeral_effective(&self) -> bool {
437 if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL") {
438 return !matches!(v.trim(), "0" | "false" | "off");
439 }
440 self.ephemeral && self.enabled
441 }
442
443 pub fn ephemeral_min_tokens_effective(&self) -> usize {
444 if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL_MIN_TOKENS")
445 && let Ok(n) = v.trim().parse::<usize>()
446 {
447 return n;
448 }
449 self.ephemeral_min_tokens
450 }
451
452 pub fn verbatim_max_tokens_effective(&self) -> usize {
454 if let Ok(v) = std::env::var("LEAN_CTX_VERBATIM_MAX_TOKENS")
455 && let Ok(n) = v.trim().parse::<usize>()
456 {
457 return n;
458 }
459 self.verbatim_max_tokens
460 }
461
462 pub fn inline_max_bytes_effective(&self) -> usize {
463 if let Ok(v) = std::env::var("LEAN_CTX_INLINE_MAX_BYTES")
464 && let Ok(n) = v.trim().parse::<usize>()
465 {
466 return n;
467 }
468 self.inline_max_bytes
469 }
470}
471
472#[derive(Debug, Clone, Serialize, Deserialize)]
476#[serde(default)]
477pub struct ProvidersConfig {
478 pub enabled: bool,
480 pub github: ProviderEntryConfig,
482 pub gitlab: ProviderEntryConfig,
484 pub auto_index: bool,
486 pub cache_ttl_secs: u64,
488 #[serde(default)]
490 pub mcp_bridges: std::collections::HashMap<String, McpBridgeEntry>,
491}
492
493impl Default for ProvidersConfig {
494 fn default() -> Self {
495 Self {
496 enabled: true,
497 github: ProviderEntryConfig::default(),
498 gitlab: ProviderEntryConfig::default(),
499 auto_index: true,
500 cache_ttl_secs: 120,
501 mcp_bridges: std::collections::HashMap::new(),
502 }
503 }
504}
505
506#[derive(Debug, Clone, Serialize, Deserialize)]
508#[serde(default)]
509pub struct KnowledgeRoutingConfig {
510 pub enabled: bool,
511 pub max_references: usize,
512 pub hint_prefix: String,
513}
514
515impl Default for KnowledgeRoutingConfig {
516 fn default() -> Self {
517 Self {
518 enabled: true,
519 max_references: 5,
520 hint_prefix: "--- Knowledge Context ---".to_string(),
521 }
522 }
523}
524
525#[derive(Debug, Clone, Serialize, Deserialize)]
526pub struct McpBridgeEntry {
527 #[serde(default)]
529 pub url: Option<String>,
530 #[serde(default)]
532 pub command: Option<String>,
533 #[serde(default)]
535 pub args: Vec<String>,
536 #[serde(default)]
538 pub description: Option<String>,
539 #[serde(default)]
541 pub auth_env: Option<String>,
542}
543
544#[derive(Debug, Clone, Serialize, Deserialize)]
546#[serde(default)]
547pub struct ProviderEntryConfig {
548 pub enabled: bool,
550 pub token: Option<String>,
552 pub api_url: Option<String>,
554 pub project: Option<String>,
556}
557
558impl Default for ProviderEntryConfig {
559 fn default() -> Self {
560 Self {
561 enabled: true,
562 token: None,
563 api_url: None,
564 project: None,
565 }
566 }
567}
568
569#[derive(Debug, Clone, Serialize, Deserialize)]
571#[serde(default)]
572pub struct AutonomyConfig {
573 pub enabled: bool,
574 pub auto_preload: bool,
575 pub auto_dedup: bool,
576 pub auto_related: bool,
577 pub auto_consolidate: bool,
578 pub silent_preload: bool,
579 pub dedup_threshold: usize,
580 pub consolidate_every_calls: u32,
581 pub consolidate_cooldown_secs: u64,
582 #[serde(default = "serde_defaults::default_true")]
583 pub cognition_loop_enabled: bool,
584 #[serde(default = "serde_defaults::default_cognition_loop_interval")]
585 pub cognition_loop_interval_secs: u64,
586 #[serde(default = "serde_defaults::default_cognition_loop_max_steps")]
587 pub cognition_loop_max_steps: u8,
588 #[serde(default = "serde_defaults::default_cognition_synthesis_min_cluster")]
591 pub cognition_synthesis_min_cluster: usize,
592}
593
594impl Default for AutonomyConfig {
595 fn default() -> Self {
596 Self {
597 enabled: true,
598 auto_preload: true,
599 auto_dedup: true,
600 auto_related: true,
601 auto_consolidate: true,
602 silent_preload: true,
603 dedup_threshold: 8,
604 consolidate_every_calls: 25,
605 consolidate_cooldown_secs: 120,
606 cognition_loop_enabled: true,
607 cognition_loop_interval_secs: 3600,
608 cognition_loop_max_steps: 9,
609 cognition_synthesis_min_cluster: 3,
610 }
611 }
612}
613
614#[derive(Debug, Clone, Serialize, Deserialize)]
617#[serde(default)]
618pub struct UpdatesConfig {
619 pub auto_update: bool,
620 pub check_interval_hours: u64,
621 pub notify_only: bool,
622 #[serde(default)]
625 pub pinned_version: Option<String>,
626}
627
628impl Default for UpdatesConfig {
629 fn default() -> Self {
630 Self {
631 auto_update: false,
632 check_interval_hours: 6,
633 notify_only: false,
634 pinned_version: None,
635 }
636 }
637}
638
639#[derive(Debug, Clone, Serialize, Deserialize)]
645#[serde(default)]
646pub struct ContextConfig {
647 pub budget_tokens: usize,
648 pub diet_max_config_tokens: usize,
649 pub diet_relevance_threshold: f64,
650 pub diet_rebalance_on_change: bool,
651 pub diet_staleness_enabled: bool,
652 pub proactive_expansion: bool,
654 pub proactive_expansion_budget_tokens: usize,
656 pub proactive_expansion_threshold: f64,
658 pub proactive_expansion_max_age_secs: u64,
660}
661
662impl Default for ContextConfig {
663 fn default() -> Self {
664 Self {
665 budget_tokens: 8000,
666 diet_max_config_tokens: 800,
667 diet_relevance_threshold: 0.15,
668 diet_rebalance_on_change: true,
669 diet_staleness_enabled: true,
670 proactive_expansion: true,
671 proactive_expansion_budget_tokens: 2000,
672 proactive_expansion_threshold: 0.6,
673 proactive_expansion_max_age_secs: 3600,
674 }
675 }
676}
677
678impl UpdatesConfig {
679 pub fn from_env() -> Self {
680 let mut cfg = Self::default();
681 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_UPDATE") {
682 cfg.auto_update = v == "1" || v.eq_ignore_ascii_case("true");
683 }
684 if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_INTERVAL_HOURS")
685 && let Ok(h) = v.parse::<u64>()
686 {
687 cfg.check_interval_hours = h.clamp(1, 168);
688 }
689 if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_NOTIFY_ONLY") {
690 cfg.notify_only = v == "1" || v.eq_ignore_ascii_case("true");
691 }
692 cfg
693 }
694}
695
696impl AutonomyConfig {
697 pub fn from_env() -> Self {
699 let mut cfg = Self::default();
700 if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
701 && (v == "false" || v == "0")
702 {
703 cfg.enabled = false;
704 }
705 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
706 cfg.auto_preload = v != "false" && v != "0";
707 }
708 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
709 cfg.auto_dedup = v != "false" && v != "0";
710 }
711 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
712 cfg.auto_related = v != "false" && v != "0";
713 }
714 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_CONSOLIDATE") {
715 cfg.auto_consolidate = v != "false" && v != "0";
716 }
717 if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
718 cfg.silent_preload = v != "false" && v != "0";
719 }
720 if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD")
721 && let Ok(n) = v.parse()
722 {
723 cfg.dedup_threshold = n;
724 }
725 if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_EVERY_CALLS")
726 && let Ok(n) = v.parse()
727 {
728 cfg.consolidate_every_calls = n;
729 }
730 if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_COOLDOWN_SECS")
731 && let Ok(n) = v.parse()
732 {
733 cfg.consolidate_cooldown_secs = n;
734 }
735 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
736 cfg.cognition_loop_enabled = v != "false" && v != "0";
737 }
738 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
739 && let Ok(n) = v.parse()
740 {
741 cfg.cognition_loop_interval_secs = n;
742 }
743 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
744 && let Ok(n) = v.parse()
745 {
746 cfg.cognition_loop_max_steps = n;
747 }
748 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_SYNTHESIS_MIN_CLUSTER")
749 && let Ok(n) = v.parse()
750 {
751 cfg.cognition_synthesis_min_cluster = n;
752 }
753 cfg
754 }
755
756 pub fn load() -> Self {
758 let file_cfg = Config::load().autonomy;
759 let mut cfg = file_cfg;
760 if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
761 && (v == "false" || v == "0")
762 {
763 cfg.enabled = false;
764 }
765 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
766 cfg.auto_preload = v != "false" && v != "0";
767 }
768 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
769 cfg.auto_dedup = v != "false" && v != "0";
770 }
771 if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
772 cfg.auto_related = v != "false" && v != "0";
773 }
774 if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
775 cfg.silent_preload = v != "false" && v != "0";
776 }
777 if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD")
778 && let Ok(n) = v.parse()
779 {
780 cfg.dedup_threshold = n;
781 }
782 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
783 cfg.cognition_loop_enabled = v != "false" && v != "0";
784 }
785 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
786 && let Ok(n) = v.parse()
787 {
788 cfg.cognition_loop_interval_secs = n;
789 }
790 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
791 && let Ok(n) = v.parse()
792 {
793 cfg.cognition_loop_max_steps = n;
794 }
795 if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_SYNTHESIS_MIN_CLUSTER")
796 && let Ok(n) = v.parse()
797 {
798 cfg.cognition_synthesis_min_cluster = n;
799 }
800 cfg
801 }
802}
803
804#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
807#[serde(rename_all = "snake_case")]
808pub enum TelemetryPreference {
809 #[default]
810 DefaultOn,
811 ExplicitlyEnabled,
812 ExplicitlyDisabled,
813}
814
815#[derive(Debug, Clone, Serialize, Deserialize)]
823#[serde(default)]
824pub struct TelemetryConfig {
825 pub enabled: bool,
827 pub preference: TelemetryPreference,
829 pub last_heartbeat: Option<String>,
831}
832
833impl Default for TelemetryConfig {
834 fn default() -> Self {
835 Self {
836 enabled: true,
837 preference: TelemetryPreference::DefaultOn,
838 last_heartbeat: None,
839 }
840 }
841}
842
843impl TelemetryConfig {
844 #[must_use]
845 pub fn environment_disables(do_not_track: Option<&str>, env_override: Option<&str>) -> bool {
846 do_not_track.is_some_and(|value| value.trim() == "1")
847 || env_override.is_some_and(|value| {
848 matches!(
849 value.trim().to_ascii_lowercase().as_str(),
850 "off" | "false" | "0" | "no"
851 )
852 })
853 }
854
855 #[must_use]
856 pub fn explicitly_disabled(&self) -> bool {
857 !self.enabled || self.preference == TelemetryPreference::ExplicitlyDisabled
858 }
859
860 #[must_use]
861 pub fn send_eligible(&self, do_not_track: Option<&str>, env_override: Option<&str>) -> bool {
862 self.enabled
863 && self.preference != TelemetryPreference::ExplicitlyDisabled
864 && !Self::environment_disables(do_not_track, env_override)
865 }
866}
867
868#[derive(Debug, Clone, Serialize, Deserialize, Default)]
870#[serde(default)]
871pub struct CloudConfig {
872 pub contribute_enabled: bool,
873 pub last_contribute: Option<String>,
874 #[serde(default)]
876 pub sync_stats_enabled: bool,
877 pub last_sync: Option<String>,
878 #[serde(default)]
880 pub sync_gain_enabled: bool,
881 pub last_gain_sync: Option<String>,
882 #[serde(default)]
884 pub sync_models_enabled: bool,
885 pub last_model_pull: Option<String>,
886 pub auto_sync: bool,
889 pub last_auto_sync: Option<String>,
890 pub auto_index: bool,
893 pub last_index_push: std::collections::HashMap<String, String>,
896}
897
898#[derive(Debug, Clone, Serialize, Deserialize)]
904#[serde(default)]
905pub struct GainConfig {
906 pub auto_publish: bool,
909 pub leaderboard: bool,
911 pub display_name: Option<String>,
913 pub auto_publish_interval_hours: u64,
915 pub last_auto_publish: Option<String>,
918}
919
920impl Default for GainConfig {
921 fn default() -> Self {
922 Self {
923 auto_publish: false,
924 leaderboard: false,
925 display_name: None,
926 auto_publish_interval_hours: 24,
927 last_auto_publish: None,
928 }
929 }
930}
931
932#[derive(Debug, Clone, Default, Serialize, Deserialize)]
941#[serde(default)]
942pub struct CostConfig {
943 #[serde(default)]
948 pub max_session_cost_usd: f64,
949 #[serde(default, skip_serializing_if = "Option::is_none")]
952 pub default_model: Option<String>,
953 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
958 pub models: HashMap<String, String>,
959 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
967 pub prices: HashMap<String, PriceOverride>,
968}
969
970#[derive(Debug, Clone, Serialize, Deserialize)]
972#[serde(default)]
973pub struct ProtectionConfig {
974 pub file_patterns: Vec<String>,
980 pub tags: bool,
984}
985
986impl Default for ProtectionConfig {
987 fn default() -> Self {
988 Self {
989 file_patterns: Vec::new(),
990 tags: true,
991 }
992 }
993}
994
995impl ProtectionConfig {
996 pub fn path_is_protected(&self, path: &str) -> bool {
998 !path.is_empty()
999 && self
1000 .file_patterns
1001 .iter()
1002 .filter_map(|p| glob::Pattern::new(p).ok())
1003 .any(|pattern| pattern.matches(path))
1004 }
1005}
1006
1007#[cfg(test)]
1008mod protection_tests {
1009 use super::ProtectionConfig;
1010
1011 #[test]
1012 fn protected_globs_match_paths_and_ignore_invalid_patterns() {
1013 let cfg = ProtectionConfig {
1014 file_patterns: vec![
1015 "docs/audits/**".into(),
1016 "*.secret.md".into(),
1017 "[invalid".into(),
1018 ],
1019 tags: true,
1020 };
1021 assert!(cfg.path_is_protected("docs/audits/q3/blockers.md"));
1022 assert!(cfg.path_is_protected("notes.secret.md"));
1023 assert!(!cfg.path_is_protected("src/main.rs"));
1024 assert!(!cfg.path_is_protected(""));
1025
1026 let empty = ProtectionConfig::default();
1027 assert!(!empty.path_is_protected("docs/audits/q3/blockers.md"));
1028 assert!(empty.tags, "protect tags are honored by default");
1029 }
1030}
1031#[derive(Debug, Clone, Serialize, Deserialize)]
1033#[serde(default)]
1034pub struct DecisionLoopConfig {
1035 pub enabled: bool,
1036 #[serde(default)]
1039 pub max_filter_level: u8,
1040}
1041
1042impl Default for DecisionLoopConfig {
1043 fn default() -> Self {
1044 Self {
1045 enabled: true,
1046 max_filter_level: 0,
1047 }
1048 }
1049}
1050
1051#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1054#[serde(default)]
1055pub struct PriceOverride {
1056 pub input_per_m: Option<f64>,
1057 pub output_per_m: Option<f64>,
1058 pub cache_write_per_m: Option<f64>,
1059 pub cache_read_per_m: Option<f64>,
1060}
1061
1062impl CostConfig {
1063 pub fn model_for_client(&self, client: &str) -> Option<String> {
1067 self.models
1068 .get(client)
1069 .or(self.default_model.as_ref())
1070 .map(|s| s.trim().to_string())
1071 .filter(|s| !s.is_empty())
1072 }
1073}
1074
1075#[derive(Debug, Clone, Serialize, Deserialize)]
1081#[serde(default)]
1082pub struct CodeHealthConfig {
1083 pub cognitive_threshold: u32,
1086 pub gate: String,
1089 pub annotate_reads: bool,
1091 pub naming: bool,
1093 pub coupling: bool,
1095 #[serde(default)]
1101 pub inject_context: bool,
1102}
1103
1104impl Default for CodeHealthConfig {
1105 fn default() -> Self {
1106 Self {
1107 cognitive_threshold: 15,
1108 gate: "warn".to_string(),
1109 annotate_reads: true,
1110 naming: true,
1111 coupling: true,
1112 inject_context: false,
1113 }
1114 }
1115}
1116
1117#[derive(Debug, Clone, Serialize, Deserialize)]
1127#[serde(default)]
1128pub struct IndexConfig {
1129 pub respect_gitignore: bool,
1133 pub exclude: Vec<String>,
1136 pub include: Vec<String>,
1139}
1140
1141impl Default for IndexConfig {
1142 fn default() -> Self {
1143 Self {
1144 respect_gitignore: true,
1145 exclude: Vec::new(),
1146 include: Vec::new(),
1147 }
1148 }
1149}
1150
1151#[derive(Debug, Clone, Serialize, Deserialize)]
1161#[serde(default)]
1162pub struct GraphConfig {
1163 pub traversal_edges: bool,
1167}
1168
1169impl Default for GraphConfig {
1170 fn default() -> Self {
1171 Self {
1172 traversal_edges: true,
1173 }
1174 }
1175}
1176
1177#[derive(Debug, Clone, Serialize, Deserialize)]
1185#[serde(default)]
1186pub struct SkillifyConfig {
1187 pub enabled: bool,
1190 pub scope: String,
1193 pub min_confidence: f32,
1196 pub min_recurrence: u32,
1199}
1200
1201impl Default for SkillifyConfig {
1202 fn default() -> Self {
1203 Self {
1204 enabled: true,
1205 scope: "project".to_string(),
1206 min_confidence: 0.7,
1207 min_recurrence: 2,
1208 }
1209 }
1210}
1211
1212#[derive(Debug, Clone, Serialize, Deserialize)]
1217#[serde(default)]
1218pub struct SummariesConfig {
1219 pub enabled: bool,
1222 pub every_n_turns: u32,
1225 pub max_kept: u32,
1227}
1228
1229impl Default for SummariesConfig {
1230 fn default() -> Self {
1231 Self {
1232 enabled: true,
1233 every_n_turns: 25,
1234 max_kept: 100,
1235 }
1236 }
1237}
1238
1239#[derive(Debug, Clone, Serialize, Deserialize)]
1241pub struct AliasEntry {
1242 pub command: String,
1243 pub alias: String,
1244}
1245
1246#[derive(Debug, Clone, Serialize, Deserialize)]
1248#[serde(default)]
1249pub struct LoopDetectionConfig {
1250 pub normal_threshold: u32,
1251 pub reduced_threshold: u32,
1252 pub blocked_threshold: u32,
1253 pub window_secs: u64,
1254 pub search_group_limit: u32,
1255 pub tool_total_limits: HashMap<String, u32>,
1256}
1257
1258impl Default for LoopDetectionConfig {
1259 fn default() -> Self {
1260 let mut tool_total_limits = HashMap::new();
1261 tool_total_limits.insert("ctx_read".to_string(), 100);
1262 tool_total_limits.insert("ctx_search".to_string(), 80);
1263 tool_total_limits.insert("ctx_shell".to_string(), 50);
1264 tool_total_limits.insert("ctx_semantic_search".to_string(), 60);
1265 Self {
1266 normal_threshold: 2,
1267 reduced_threshold: 4,
1268 blocked_threshold: 0,
1269 window_secs: 300,
1270 search_group_limit: 10,
1271 tool_total_limits,
1272 }
1273 }
1274}
1275
1276#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1295#[serde(default)]
1296pub struct GatewayServerConfig {
1297 #[serde(default, skip_serializing_if = "Option::is_none")]
1300 pub seats: Option<u32>,
1301 #[serde(default, skip_serializing_if = "Option::is_none")]
1303 pub org_label: Option<String>,
1304 #[serde(default, skip_serializing_if = "Option::is_none")]
1309 pub admin_url: Option<String>,
1310 #[serde(default, skip_serializing_if = "Option::is_none")]
1317 pub admin_bind_host: Option<String>,
1318 #[serde(default, skip_serializing_if = "Option::is_none")]
1323 pub usage_retention_days: Option<u32>,
1324 #[serde(default, skip_serializing_if = "Option::is_none")]
1330 pub pseudonymize_persons: Option<bool>,
1331 #[serde(default, skip_serializing_if = "Vec::is_empty")]
1338 pub mcp_servers: Vec<McpServerEntry>,
1339}
1340
1341#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1345pub struct McpServerEntry {
1346 pub id: String,
1349 pub url: String,
1354 #[serde(default, skip_serializing_if = "Option::is_none")]
1360 pub auth_env: Option<String>,
1361 #[serde(default, skip_serializing_if = "Option::is_none")]
1363 pub enabled: Option<bool>,
1364}
1365
1366#[derive(Debug, Clone, PartialEq, Eq)]
1369pub struct ResolvedMcpServer {
1370 pub id: String,
1371 pub url: String,
1372 pub auth_env: Option<String>,
1373}
1374
1375impl GatewayServerConfig {
1376 #[must_use]
1382 pub fn resolve_mcp_servers(&self, allow_insecure_http: bool) -> Vec<ResolvedMcpServer> {
1383 let mut seen: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
1384 let mut out = Vec::new();
1385 for entry in &self.mcp_servers {
1386 if !entry.enabled.unwrap_or(true) {
1387 continue;
1388 }
1389 let id = entry.id.trim();
1390 if !is_valid_mcp_server_id(id) {
1391 tracing::warn!(
1392 "[gateway_server.mcp_servers] invalid id '{id}' \
1393 (lowercase alnum/-/_ only) — entry skipped"
1394 );
1395 continue;
1396 }
1397 if !seen.insert(id) {
1398 tracing::warn!(
1399 "[gateway_server.mcp_servers] duplicate id '{id}' — keeping first entry"
1400 );
1401 continue;
1402 }
1403 match validate_mcp_upstream_url(&entry.url, allow_insecure_http) {
1404 Ok(url) => out.push(ResolvedMcpServer {
1405 id: id.to_string(),
1406 url,
1407 auth_env: entry
1408 .auth_env
1409 .as_deref()
1410 .map(str::trim)
1411 .filter(|v| !v.is_empty())
1412 .map(str::to_string),
1413 }),
1414 Err(e) => {
1415 tracing::warn!(
1416 "[gateway_server.mcp_servers] '{id}' has invalid url — skipped: {e}"
1417 );
1418 }
1419 }
1420 }
1421 out
1422 }
1423
1424 #[must_use]
1427 pub fn resolved_admin_bind_host(&self) -> std::net::IpAddr {
1428 let raw = std::env::var("LEAN_CTX_GATEWAY_ADMIN_BIND_HOST")
1429 .ok()
1430 .filter(|v| !v.trim().is_empty())
1431 .or_else(|| self.admin_bind_host.clone());
1432 match raw.as_deref().map(str::trim) {
1433 Some(v) if !v.is_empty() => v.parse().unwrap_or_else(|_| {
1434 tracing::warn!(
1435 "gateway_server.admin_bind_host '{v}' is not a valid IP address — binding 127.0.0.1"
1436 );
1437 std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
1438 }),
1439 _ => std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
1440 }
1441 }
1442}
1443
1444fn is_valid_mcp_server_id(id: &str) -> bool {
1448 !id.is_empty()
1449 && id
1450 .chars()
1451 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
1452}
1453
1454fn validate_mcp_upstream_url(url: &str, allow_insecure_http: bool) -> Result<String, String> {
1460 let trimmed = url.trim().trim_end_matches('/');
1461 if trimmed.is_empty() {
1462 return Err("empty url".into());
1463 }
1464 if crate::core::config::is_local_proxy_url(trimmed) {
1465 return Ok(trimmed.to_string());
1466 }
1467 if trimmed.starts_with("http://") {
1468 if allow_insecure_http {
1469 return Ok(trimmed.to_string());
1470 }
1471 return Err(format!(
1472 "MCP upstream must use HTTPS: {trimmed} (for a trusted local-network HTTP \
1473 upstream opt in with `[proxy] allow_insecure_http_upstream = true`)"
1474 ));
1475 }
1476 if trimmed.starts_with("https://") {
1477 return Ok(trimmed.to_string());
1478 }
1479 Err(format!(
1480 "MCP upstream must start with http:// or https://: {trimmed}"
1481 ))
1482}
1483
1484#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1485#[serde(default)]
1486pub struct EmbeddingConfig {
1487 #[serde(default, skip_serializing_if = "Option::is_none")]
1488 pub model: Option<String>,
1489 #[serde(default, skip_serializing_if = "Option::is_none")]
1490 pub dimensions: Option<usize>,
1491 #[serde(default, skip_serializing_if = "Option::is_none")]
1497 pub auto_download: Option<bool>,
1498 #[serde(default, skip_serializing_if = "Option::is_none")]
1505 pub deterministic: Option<bool>,
1506}
1507
1508#[cfg(test)]
1509mod gateway_server_tests {
1510 use super::*;
1511
1512 #[test]
1513 fn admin_bind_defaults_to_loopback_and_rejects_garbage() {
1514 let cfg = GatewayServerConfig::default();
1516 assert!(cfg.resolved_admin_bind_host().is_loopback());
1517
1518 let cfg = GatewayServerConfig {
1519 admin_bind_host: Some("not-an-ip".into()),
1520 ..Default::default()
1521 };
1522 assert!(
1523 cfg.resolved_admin_bind_host().is_loopback(),
1524 "a typo must narrow exposure, never widen it"
1525 );
1526
1527 let cfg = GatewayServerConfig {
1528 admin_bind_host: Some("0.0.0.0".into()),
1529 ..Default::default()
1530 };
1531 assert!(
1532 !cfg.resolved_admin_bind_host().is_loopback(),
1533 "explicit opt-in widens the bind"
1534 );
1535 }
1536
1537 fn mcp_entry(id: &str, url: &str) -> McpServerEntry {
1538 McpServerEntry {
1539 id: id.into(),
1540 url: url.into(),
1541 auth_env: None,
1542 enabled: None,
1543 }
1544 }
1545
1546 #[test]
1547 fn mcp_registry_validates_ids_urls_and_duplicates() {
1548 let cfg = GatewayServerConfig {
1549 mcp_servers: vec![
1550 mcp_entry("github", "https://mcp.example.com/mcp/"),
1551 mcp_entry("GitHub", "https://mcp.example.com/mcp"),
1553 mcp_entry("github", "https://other.example.com/mcp"),
1555 mcp_entry("plain", "http://mcp.example.com/mcp"),
1557 mcp_entry("local", "http://127.0.0.1:9200/mcp"),
1559 McpServerEntry {
1560 enabled: Some(false),
1561 ..mcp_entry("disabled", "https://mcp.example.com/mcp")
1562 },
1563 McpServerEntry {
1564 auth_env: Some(" GITHUB_MCP_PAT ".into()),
1565 ..mcp_entry("authed", "https://api.githubcopilot.com/mcp")
1566 },
1567 ],
1568 ..Default::default()
1569 };
1570 let resolved = cfg.resolve_mcp_servers(false);
1571 let ids: Vec<&str> = resolved.iter().map(|s| s.id.as_str()).collect();
1572 assert_eq!(ids, ["github", "local", "authed"]);
1573 assert_eq!(resolved[0].url, "https://mcp.example.com/mcp");
1575 assert_eq!(resolved[2].auth_env.as_deref(), Some("GITHUB_MCP_PAT"));
1576
1577 let with_optin = cfg.resolve_mcp_servers(true);
1579 assert!(with_optin.iter().any(|s| s.id == "plain"));
1580 }
1581
1582 #[test]
1583 fn mcp_upstream_url_rules_match_the_proxy_posture() {
1584 assert!(validate_mcp_upstream_url("https://mcp.example.com/mcp", false).is_ok());
1585 assert!(validate_mcp_upstream_url("http://localhost:9200/mcp", false).is_ok());
1586 assert!(validate_mcp_upstream_url("http://mcp.example.com/mcp", false).is_err());
1587 assert!(validate_mcp_upstream_url("http://mcp.example.com/mcp", true).is_ok());
1588 assert!(validate_mcp_upstream_url("ftp://mcp.example.com", false).is_err());
1589 assert!(validate_mcp_upstream_url(" ", false).is_err());
1590 }
1591}
1592
1593#[cfg(test)]
1594mod ocla_tests {
1595 use super::OclaConfig;
1596 use crate::core::ocla::grpc_bridge::GrpcConfig;
1597 use crate::core::ocla::sidecar::SidecarConfig;
1598 use serde::Deserialize;
1599
1600 #[derive(Deserialize)]
1601 struct ConfigFile {
1602 ocla: OclaConfig,
1603 }
1604
1605 #[test]
1606 fn sidecar_defaults_are_loopback_and_disabled() {
1607 let config = SidecarConfig::default();
1608 assert_eq!(config.bind_addr, "127.0.0.1:3334");
1609 assert!(!config.enabled);
1610 assert!(config.auth_token.is_none());
1611 }
1612
1613 #[test]
1614 fn nested_sidecar_toml_deserializes() {
1615 let config: ConfigFile = toml::from_str(
1616 r#"
1617 [ocla.sidecar]
1618 bind_addr = "127.0.0.1:9000"
1619 auth_token = "wire-secret"
1620 tls_cert_path = "/etc/lean-ctx/cert.pem"
1621 tls_key_path = "/etc/lean-ctx/key.pem"
1622 enabled = true
1623 "#,
1624 )
1625 .expect("OCLA sidecar config");
1626
1627 let sidecar = config.ocla.sidecar;
1628 assert_eq!(sidecar.bind_addr, "127.0.0.1:9000");
1629 assert_eq!(sidecar.auth_token.as_deref(), Some("wire-secret"));
1630 assert_eq!(
1631 sidecar.tls_cert_path.as_deref().unwrap().to_str(),
1632 Some("/etc/lean-ctx/cert.pem")
1633 );
1634 assert_eq!(
1635 sidecar.tls_key_path.as_deref().unwrap().to_str(),
1636 Some("/etc/lean-ctx/key.pem")
1637 );
1638 assert!(sidecar.enabled);
1639 }
1640
1641 #[test]
1642 fn nested_grpc_toml_deserializes() {
1643 let config: ConfigFile = toml::from_str(
1644 r#"
1645 [ocla.grpc]
1646 enabled = true
1647 listen = "127.0.0.1:60051"
1648 "#,
1649 )
1650 .expect("OCLA gRPC config");
1651
1652 assert_eq!(config.ocla.grpc.listen, "127.0.0.1:60051");
1653 assert!(config.ocla.grpc.enabled);
1654 assert_eq!(GrpcConfig::default().listen, "127.0.0.1:50051");
1655 }
1656}
1657
1658#[cfg(test)]
1659mod telemetry_tests {
1660 use super::*;
1661
1662 #[test]
1663 fn telemetry_config_defaults_on_and_send_eligible() {
1664 let cfg = TelemetryConfig::default();
1665 assert!(cfg.enabled);
1666 assert_eq!(cfg.preference, TelemetryPreference::DefaultOn);
1667 assert!(cfg.send_eligible(None, None));
1668 assert!(cfg.last_heartbeat.is_none());
1669 }
1670
1671 #[test]
1672 fn telemetry_config_serde_roundtrip() {
1673 let toml_str = r#"
1674[telemetry]
1675enabled = true
1676last_heartbeat = "2026-07-30"
1677"#;
1678 #[derive(serde::Deserialize)]
1679 struct Wrap {
1680 telemetry: TelemetryConfig,
1681 }
1682 let wrap: Wrap = toml::from_str(toml_str).expect("parse telemetry config");
1683 assert!(wrap.telemetry.enabled);
1684 assert_eq!(wrap.telemetry.preference, TelemetryPreference::DefaultOn);
1685 assert_eq!(wrap.telemetry.last_heartbeat.as_deref(), Some("2026-07-30"));
1686 }
1687
1688 #[test]
1689 fn a_retired_notice_key_in_an_existing_config_still_parses() {
1690 let cfg: TelemetryConfig =
1691 toml::from_str("enabled = true\nnotice_shown = false").expect("pre-removal config");
1692 assert!(cfg.send_eligible(None, None));
1693 }
1694
1695 #[test]
1696 fn telemetry_config_missing_section_uses_defaults() {
1697 let toml_str = "";
1698 #[derive(serde::Deserialize, Default)]
1699 #[serde(default)]
1700 struct Wrap {
1701 telemetry: TelemetryConfig,
1702 }
1703 let wrap: Wrap = toml::from_str(toml_str).expect("parse empty config");
1704 assert!(wrap.telemetry.enabled);
1705 assert_eq!(wrap.telemetry.preference, TelemetryPreference::DefaultOn);
1706 assert!(wrap.telemetry.last_heartbeat.is_none());
1707 }
1708
1709 #[test]
1710 fn legacy_false_remains_an_explicit_opt_out() {
1711 let cfg: TelemetryConfig = toml::from_str("enabled = false").expect("legacy config");
1712 assert!(cfg.explicitly_disabled());
1713 }
1714
1715 #[test]
1716 fn send_honors_the_explicit_and_both_environment_opt_outs() {
1717 let mut cfg = TelemetryConfig::default();
1718 assert!(cfg.send_eligible(None, None));
1719 assert!(!cfg.send_eligible(Some("1"), None));
1720 assert!(!cfg.send_eligible(None, Some("OFF")));
1721 cfg.preference = TelemetryPreference::ExplicitlyDisabled;
1722 assert!(!cfg.send_eligible(None, None));
1723 }
1724}