Skip to main content

lean_ctx/core/config/
sections.rs

1//! Auxiliary configuration section structs.
2//!
3//! Nested config structs (secret-detection, setup, archive, providers,
4//! autonomy, updates, cloud, gain, loop-detection, embedding, …) split out of
5//! `config/mod.rs` to keep the top-level module focused on `Config` itself.
6//! Re-exported via `pub use sections::*`, so external paths stay stable.
7
8use super::serde_defaults;
9#[allow(clippy::wildcard_imports)]
10use super::*;
11use serde::{Deserialize, Serialize};
12
13/// Opt-in configuration for counterfactual Shadow Mode reports.
14#[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/// OCLA deployment settings.
53///
54/// This wrapper maps the TOML shape `[ocla.sidecar]` and `[ocla.grpc]`; the
55/// runtime types remain in `core::ocla` so they can be used independently.
56#[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    /// Allow subagents to receive a cross-agent delivery stub instead of
69    /// forcing a fresh disk read.
70    pub delivery_for_subagents: bool,
71    pub max_entries: usize,
72    pub ttl_minutes: u64,
73    /// Generalized cache tier settings.
74    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/// Bounds and feature switches for the generalized cross-agent cache.
96#[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/// Agent lifecycle configuration: TTLs, GC intervals, scratchpad limits.
146///
147/// Maps to `[agents]` in config.toml. All fields have sane defaults so existing
148/// configs without this section continue to work.
149#[derive(Debug, Clone, Serialize, Deserialize)]
150#[serde(default)]
151pub struct AgentsConfig {
152    /// How often the background reaper runs (minutes). 0 = disabled.
153    pub gc_interval_minutes: u64,
154    /// Identity registry: decommission agents not seen for this many hours.
155    pub identity_ttl_hours: u64,
156    /// Presence registry: remove finished agents older than this (hours).
157    pub presence_ttl_hours: u64,
158    /// Default TTL for scratchpad messages without explicit expiry (hours).
159    pub scratchpad_default_ttl_hours: u64,
160    /// Logical session timeout (seconds).
161    pub logical_session_ttl_seconds: u64,
162    /// Hard per-project cap for simultaneously admitted MCP workers (1–15).
163    /// This is admission control, not a queue or scheduler.
164    pub max_concurrent_workers: usize,
165    /// Max scratchpad entries before oldest are evicted.
166    pub max_scratchpad_entries: usize,
167}
168
169impl Default for AgentsConfig {
170    fn default() -> Self {
171        Self {
172            gc_interval_minutes: 10,
173            identity_ttl_hours: 48,
174            presence_ttl_hours: 24,
175            scratchpad_default_ttl_hours: 12,
176            logical_session_ttl_seconds: 180,
177            max_concurrent_workers: 15,
178            max_scratchpad_entries: 200,
179        }
180    }
181}
182
183#[cfg(test)]
184mod agents_config_tests {
185    use super::AgentsConfig;
186
187    #[test]
188    fn default_values_are_sane() {
189        let cfg = AgentsConfig::default();
190        assert_eq!(cfg.gc_interval_minutes, 10);
191        assert_eq!(cfg.identity_ttl_hours, 48);
192        assert_eq!(cfg.presence_ttl_hours, 24);
193        assert_eq!(cfg.scratchpad_default_ttl_hours, 12);
194        assert_eq!(cfg.logical_session_ttl_seconds, 180);
195        assert_eq!(cfg.max_concurrent_workers, 15);
196        assert_eq!(cfg.max_scratchpad_entries, 200);
197    }
198
199    #[test]
200    fn deserializes_with_missing_fields() {
201        let json = r"{}";
202        let cfg: AgentsConfig = serde_json::from_str(json).expect("empty object → defaults");
203        assert_eq!(cfg.gc_interval_minutes, 10);
204    }
205
206    #[test]
207    fn partial_override() {
208        let json = r#"{"gc_interval_minutes": 5, "presence_ttl_hours": 12}"#;
209        let cfg: AgentsConfig = serde_json::from_str(json).expect("partial");
210        assert_eq!(cfg.gc_interval_minutes, 5);
211        assert_eq!(cfg.presence_ttl_hours, 12);
212        assert_eq!(cfg.identity_ttl_hours, 48);
213    }
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize)]
217#[serde(default)]
218pub struct SecretDetectionConfig {
219    pub enabled: bool,
220    pub redact: bool,
221    pub custom_patterns: Vec<String>,
222    /// #718: subtractive counterpart to `custom_patterns` — a detected secret
223    /// whose matched text is covered by any of these regexes is neither
224    /// reported nor redacted. Lets users carve out known-safe identifiers or
225    /// repo naming conventions without disabling secret detection wholesale.
226    pub exclude_patterns: Vec<String>,
227}
228
229/// Controls what lean-ctx injects during `setup` and `update --rewire`.
230/// Fresh installs default to non-invasive (rules/skills off, MCP on).
231/// Users who ran setup interactively get explicit true/false.
232/// `None` = undecided (legacy: check if rules already exist and preserve behavior).
233#[derive(Debug, Clone, Serialize, Deserialize)]
234#[serde(default)]
235pub struct SetupConfig {
236    /// Inject agent rule files (CLAUDE.md, .cursor/rules/, etc.).
237    /// None = undecided (legacy compat: inject if rules already present).
238    /// Some(true) = always inject. Some(false) = never inject.
239    pub auto_inject_rules: Option<bool>,
240    /// Install SKILL.md files for supported agents.
241    /// None = undecided. Some(true) = install. Some(false) = skip.
242    pub auto_inject_skills: Option<bool>,
243    /// Register lean-ctx as an MCP server in editor configs.
244    #[serde(default = "serde_defaults::default_true")]
245    pub auto_update_mcp: bool,
246}
247
248impl Default for SetupConfig {
249    fn default() -> Self {
250        Self {
251            auto_inject_rules: None,
252            auto_inject_skills: None,
253            auto_update_mcp: true,
254        }
255    }
256}
257
258impl SetupConfig {
259    /// Returns whether rules should be injected, considering legacy installs.
260    /// If undecided (None), checks if lean-ctx rules markers already exist
261    /// in any agent config — if so, keeps injecting for backward compat.
262    pub fn should_inject_rules(&self) -> bool {
263        match self.auto_inject_rules {
264            Some(v) => v,
265            None => Self::rules_already_present(),
266        }
267    }
268
269    /// Returns whether skills should be installed.
270    pub fn should_inject_skills(&self) -> bool {
271        match self.auto_inject_skills {
272            Some(v) => v,
273            None => Self::rules_already_present(),
274        }
275    }
276
277    /// Returns whether `setup`/`onboard`/`init` may (re)register the lean-ctx
278    /// MCP server in editor configs. Honors `auto_update_mcp` (#281) so locked-
279    /// down environments can keep MCP out of agent settings while still getting
280    /// hooks, rules and skills.
281    pub fn should_update_mcp(&self) -> bool {
282        self.auto_update_mcp
283    }
284
285    /// Check if lean-ctx rules markers exist in any known agent config location.
286    ///
287    /// Delegates the per-agent path catalog to `rules_inject::any_rules_marker_present`
288    /// (derived from the injector's own target list) so this never drifts behind
289    /// newly supported agents again (#442). Claude Code and CodeBuddy have no
290    /// rules *target* (they auto-load an inline block instead), so their legacy
291    /// rule files are checked separately to keep honoring older installs.
292    fn rules_already_present() -> bool {
293        let Some(home) = dirs::home_dir() else {
294            return false;
295        };
296        if crate::rules_inject::any_rules_marker_present(&home) {
297            return true;
298        }
299        let legacy_paths = [
300            crate::core::editor_registry::claude_rules_dir(&home).join("lean-ctx.md"),
301            crate::core::editor_registry::codebuddy_rules_dir(&home).join("lean-ctx.md"),
302        ];
303        legacy_paths.iter().any(|p| {
304            std::fs::read_to_string(p)
305                .is_ok_and(|c| c.contains(crate::core::rules_canonical::START_MARK))
306        })
307    }
308}
309
310impl Default for SecretDetectionConfig {
311    fn default() -> Self {
312        Self {
313            enabled: true,
314            redact: true,
315            custom_patterns: Vec::new(),
316            exclude_patterns: Vec::new(),
317        }
318    }
319}
320
321/// Settings for the zero-loss compression archive (large tool outputs saved to disk).
322#[derive(Debug, Clone, Serialize, Deserialize)]
323#[serde(default)]
324pub struct ArchiveConfig {
325    pub enabled: bool,
326    pub threshold_chars: usize,
327    pub max_age_hours: u64,
328    pub max_disk_mb: u64,
329    pub ephemeral: bool,
330    /// Minimum output tokens before the ephemeral firewall replaces an inline tool
331    /// result with a summary + retrieval ref. Outputs below this stay fully inline.
332    pub ephemeral_min_tokens: usize,
333    /// Maximum output size that `ctx_shell(inline=true)` returns verbatim before
334    /// the archive/firewall path takes over.
335    pub inline_max_bytes: usize,
336    /// Programs whose stdout *is* a dataset (#1260). Head+tail elision does not
337    /// compress those — it drops the interior rows that hold the answer — so a
338    /// `ctx_shell` command running one of these passes through verbatim at any
339    /// size. Set to `[]` to disable the passthrough.
340    pub raw_commands: Vec<String>,
341    /// Context-window guard for *implicitly* verbatim `ctx_shell` deliveries
342    /// (dataset passthrough #1260, `inline=true`): above this many output
343    /// tokens the content is archived losslessly and delivered as a head+tail
344    /// digest with `ctx_expand` drilldown instead of flooding the calling
345    /// agent's context window. Explicit `raw=true`/`bypass=true` and the
346    /// `LEAN_CTX_MINIMAL` escape hatch are never capped. `0` disables the
347    /// cap. Env: LEAN_CTX_VERBATIM_MAX_TOKENS (#1541).
348    pub verbatim_max_tokens: usize,
349}
350
351/// Opt-in conversation-history compression settings (#1123).
352///
353/// The proxy leaves conversation history byte-for-byte unchanged unless
354/// `compression_enabled` is true and the configured token threshold is met.
355#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
356#[serde(default)]
357pub struct ConversationConfig {
358    /// Enable message-level compression in the proxy. Default: false.
359    pub compression_enabled: bool,
360    /// Number of recent user turns (and their following messages) to preserve.
361    pub preserve_last_n_turns: usize,
362    /// Minimum estimated message-array size before compression starts.
363    pub compression_threshold_tokens: usize,
364    /// Minimum score for verbatim preservation.
365    pub min_score_to_preserve: f64,
366    /// Inclusive lower bound and exclusive upper bound for summaries.
367    pub summarize_score_range: [f64; 2],
368    /// Scores below this value are eligible for drop + CCR.
369    pub drop_score_below: f64,
370    /// Store dropped messages in the content-addressed recovery store.
371    pub ccr_store_dropped: bool,
372}
373
374impl Default for ConversationConfig {
375    fn default() -> Self {
376        Self {
377            compression_enabled: false,
378            preserve_last_n_turns: 10,
379            compression_threshold_tokens: 50_000,
380            min_score_to_preserve: 0.5,
381            summarize_score_range: [0.2, 0.5],
382            drop_score_below: 0.2,
383            ccr_store_dropped: true,
384        }
385    }
386}
387
388impl Default for ArchiveConfig {
389    fn default() -> Self {
390        Self {
391            enabled: true,
392            threshold_chars: 800,
393            max_age_hours: 48,
394            max_disk_mb: 500,
395            ephemeral: true,
396            ephemeral_min_tokens: 2000,
397            inline_max_bytes: 32 * 1024,
398            raw_commands: crate::core::firewall::DEFAULT_RAW_COMMANDS
399                .iter()
400                .map(|s| (*s).to_string())
401                .collect(),
402            verbatim_max_tokens: 100_000,
403        }
404    }
405}
406
407impl ArchiveConfig {
408    pub fn ephemeral_effective(&self) -> bool {
409        if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL") {
410            return !matches!(v.trim(), "0" | "false" | "off");
411        }
412        self.ephemeral && self.enabled
413    }
414
415    pub fn ephemeral_min_tokens_effective(&self) -> usize {
416        if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL_MIN_TOKENS")
417            && let Ok(n) = v.trim().parse::<usize>()
418        {
419            return n;
420        }
421        self.ephemeral_min_tokens
422    }
423
424    /// Effective context-window cap for implicitly verbatim deliveries (#1541).
425    pub fn verbatim_max_tokens_effective(&self) -> usize {
426        if let Ok(v) = std::env::var("LEAN_CTX_VERBATIM_MAX_TOKENS")
427            && let Ok(n) = v.trim().parse::<usize>()
428        {
429            return n;
430        }
431        self.verbatim_max_tokens
432    }
433
434    pub fn inline_max_bytes_effective(&self) -> usize {
435        if let Ok(v) = std::env::var("LEAN_CTX_INLINE_MAX_BYTES")
436            && let Ok(n) = v.trim().parse::<usize>()
437        {
438            return n;
439        }
440        self.inline_max_bytes
441    }
442}
443
444/// Configuration for external context providers (GitHub, GitLab, Jira, etc.).
445/// Each provider can be enabled/disabled and configured with auth tokens.
446/// Override individual tokens via env vars (GITHUB_TOKEN, GITLAB_TOKEN, etc.).
447#[derive(Debug, Clone, Serialize, Deserialize)]
448#[serde(default)]
449pub struct ProvidersConfig {
450    /// Master switch for the provider subsystem.
451    pub enabled: bool,
452    /// GitHub provider configuration.
453    pub github: ProviderEntryConfig,
454    /// GitLab provider configuration.
455    pub gitlab: ProviderEntryConfig,
456    /// Auto-ingest provider results into BM25/embedding indexes.
457    pub auto_index: bool,
458    /// Default cache TTL for provider results (seconds).
459    pub cache_ttl_secs: u64,
460    /// MCP Bridge providers: `{ "name" = { url = "...", description = "..." } }`.
461    #[serde(default)]
462    pub mcp_bridges: std::collections::HashMap<String, McpBridgeEntry>,
463}
464
465impl Default for ProvidersConfig {
466    fn default() -> Self {
467        Self {
468            enabled: true,
469            github: ProviderEntryConfig::default(),
470            gitlab: ProviderEntryConfig::default(),
471            auto_index: true,
472            cache_ttl_secs: 120,
473            mcp_bridges: std::collections::HashMap::new(),
474        }
475    }
476}
477
478/// Controls additive KnowledgeRouter hints in Context Gate output.
479#[derive(Debug, Clone, Serialize, Deserialize)]
480#[serde(default)]
481pub struct KnowledgeRoutingConfig {
482    pub enabled: bool,
483    pub max_references: usize,
484    pub hint_prefix: String,
485}
486
487impl Default for KnowledgeRoutingConfig {
488    fn default() -> Self {
489        Self {
490            enabled: true,
491            max_references: 5,
492            hint_prefix: "--- Knowledge Context ---".to_string(),
493        }
494    }
495}
496
497#[derive(Debug, Clone, Serialize, Deserialize)]
498pub struct McpBridgeEntry {
499    /// HTTP/SSE URL for remote MCP servers.
500    #[serde(default)]
501    pub url: Option<String>,
502    /// Command to spawn a local MCP server (stdio transport).
503    #[serde(default)]
504    pub command: Option<String>,
505    /// Arguments for the command.
506    #[serde(default)]
507    pub args: Vec<String>,
508    /// Human-readable description.
509    #[serde(default)]
510    pub description: Option<String>,
511    /// Environment variable name containing an auth token.
512    #[serde(default)]
513    pub auth_env: Option<String>,
514}
515
516/// Per-provider configuration entry.
517#[derive(Debug, Clone, Serialize, Deserialize)]
518#[serde(default)]
519pub struct ProviderEntryConfig {
520    /// Whether this specific provider is enabled.
521    pub enabled: bool,
522    /// Auth token (prefer env var; only use this for project-local overrides).
523    pub token: Option<String>,
524    /// API base URL override (for GitHub Enterprise, self-hosted GitLab, etc.).
525    pub api_url: Option<String>,
526    /// Default project/repo for this provider (auto-detected from git remote if empty).
527    pub project: Option<String>,
528}
529
530impl Default for ProviderEntryConfig {
531    fn default() -> Self {
532        Self {
533            enabled: true,
534            token: None,
535            api_url: None,
536            project: None,
537        }
538    }
539}
540
541/// Controls autonomous background behaviors (preload, dedup, consolidation).
542#[derive(Debug, Clone, Serialize, Deserialize)]
543#[serde(default)]
544pub struct AutonomyConfig {
545    pub enabled: bool,
546    pub auto_preload: bool,
547    pub auto_dedup: bool,
548    pub auto_related: bool,
549    pub auto_consolidate: bool,
550    pub silent_preload: bool,
551    pub dedup_threshold: usize,
552    pub consolidate_every_calls: u32,
553    pub consolidate_cooldown_secs: u64,
554    #[serde(default = "serde_defaults::default_true")]
555    pub cognition_loop_enabled: bool,
556    #[serde(default = "serde_defaults::default_cognition_loop_interval")]
557    pub cognition_loop_interval_secs: u64,
558    #[serde(default = "serde_defaults::default_cognition_loop_max_steps")]
559    pub cognition_loop_max_steps: u8,
560    /// Minimum facts an entity needs before observation synthesis (#802) writes a
561    /// summary. Synthesis itself is gated by `cognition_loop_max_steps >= 9`.
562    #[serde(default = "serde_defaults::default_cognition_synthesis_min_cluster")]
563    pub cognition_synthesis_min_cluster: usize,
564}
565
566impl Default for AutonomyConfig {
567    fn default() -> Self {
568        Self {
569            enabled: true,
570            auto_preload: true,
571            auto_dedup: true,
572            auto_related: true,
573            auto_consolidate: true,
574            silent_preload: true,
575            dedup_threshold: 8,
576            consolidate_every_calls: 25,
577            consolidate_cooldown_secs: 120,
578            cognition_loop_enabled: true,
579            cognition_loop_interval_secs: 3600,
580            cognition_loop_max_steps: 9,
581            cognition_synthesis_min_cluster: 3,
582        }
583    }
584}
585
586/// Controls automatic update behavior. All defaults are OFF — auto-updates
587/// require explicit opt-in via `lean-ctx setup` or `lean-ctx update --schedule`.
588#[derive(Debug, Clone, Serialize, Deserialize)]
589#[serde(default)]
590pub struct UpdatesConfig {
591    pub auto_update: bool,
592    pub check_interval_hours: u64,
593    pub notify_only: bool,
594}
595
596impl Default for UpdatesConfig {
597    fn default() -> Self {
598        Self {
599            auto_update: false,
600            check_interval_hours: 6,
601            notify_only: false,
602        }
603    }
604}
605
606/// Fixed-context budget accounting (#964). The per-session footprint lean-ctx
607/// adds — tool schemas + MCP instructions + auto-loaded rules files + the wakeup
608/// briefing — is warned about once it crosses `budget_tokens`. The
609/// `LEAN_CTX_CONTEXT_BUDGET_TOKENS` env var overrides it; `lean-ctx doctor
610/// overhead --gate` turns a breach into a non-zero exit for CI.
611#[derive(Debug, Clone, Serialize, Deserialize)]
612#[serde(default)]
613pub struct ContextConfig {
614    pub budget_tokens: usize,
615    pub diet_max_config_tokens: usize,
616    pub diet_relevance_threshold: f64,
617    pub diet_rebalance_on_change: bool,
618    pub diet_staleness_enabled: bool,
619    /// Inject matching CCR archives into later tool responses.
620    pub proactive_expansion: bool,
621    /// Maximum proactive archive content per tool response.
622    pub proactive_expansion_budget_tokens: usize,
623    /// Minimum normalized BM25 score required for an injection.
624    pub proactive_expansion_threshold: f64,
625    /// Ignore archived content older than this many seconds; 0 disables age expiry.
626    pub proactive_expansion_max_age_secs: u64,
627}
628
629impl Default for ContextConfig {
630    fn default() -> Self {
631        Self {
632            budget_tokens: 8000,
633            diet_max_config_tokens: 800,
634            diet_relevance_threshold: 0.15,
635            diet_rebalance_on_change: true,
636            diet_staleness_enabled: true,
637            proactive_expansion: true,
638            proactive_expansion_budget_tokens: 2000,
639            proactive_expansion_threshold: 0.6,
640            proactive_expansion_max_age_secs: 3600,
641        }
642    }
643}
644
645impl UpdatesConfig {
646    pub fn from_env() -> Self {
647        let mut cfg = Self::default();
648        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_UPDATE") {
649            cfg.auto_update = v == "1" || v.eq_ignore_ascii_case("true");
650        }
651        if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_INTERVAL_HOURS")
652            && let Ok(h) = v.parse::<u64>()
653        {
654            cfg.check_interval_hours = h.clamp(1, 168);
655        }
656        if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_NOTIFY_ONLY") {
657            cfg.notify_only = v == "1" || v.eq_ignore_ascii_case("true");
658        }
659        cfg
660    }
661}
662
663impl AutonomyConfig {
664    /// Creates an autonomy config from env vars, falling back to defaults.
665    pub fn from_env() -> Self {
666        let mut cfg = Self::default();
667        if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
668            && (v == "false" || v == "0")
669        {
670            cfg.enabled = false;
671        }
672        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
673            cfg.auto_preload = v != "false" && v != "0";
674        }
675        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
676            cfg.auto_dedup = v != "false" && v != "0";
677        }
678        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
679            cfg.auto_related = v != "false" && v != "0";
680        }
681        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_CONSOLIDATE") {
682            cfg.auto_consolidate = v != "false" && v != "0";
683        }
684        if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
685            cfg.silent_preload = v != "false" && v != "0";
686        }
687        if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD")
688            && let Ok(n) = v.parse()
689        {
690            cfg.dedup_threshold = n;
691        }
692        if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_EVERY_CALLS")
693            && let Ok(n) = v.parse()
694        {
695            cfg.consolidate_every_calls = n;
696        }
697        if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_COOLDOWN_SECS")
698            && let Ok(n) = v.parse()
699        {
700            cfg.consolidate_cooldown_secs = n;
701        }
702        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
703            cfg.cognition_loop_enabled = v != "false" && v != "0";
704        }
705        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
706            && let Ok(n) = v.parse()
707        {
708            cfg.cognition_loop_interval_secs = n;
709        }
710        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
711            && let Ok(n) = v.parse()
712        {
713            cfg.cognition_loop_max_steps = n;
714        }
715        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_SYNTHESIS_MIN_CLUSTER")
716            && let Ok(n) = v.parse()
717        {
718            cfg.cognition_synthesis_min_cluster = n;
719        }
720        cfg
721    }
722
723    /// Loads autonomy config from disk, with env var overrides applied.
724    pub fn load() -> Self {
725        let file_cfg = Config::load().autonomy;
726        let mut cfg = file_cfg;
727        if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
728            && (v == "false" || v == "0")
729        {
730            cfg.enabled = false;
731        }
732        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
733            cfg.auto_preload = v != "false" && v != "0";
734        }
735        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
736            cfg.auto_dedup = v != "false" && v != "0";
737        }
738        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
739            cfg.auto_related = v != "false" && v != "0";
740        }
741        if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
742            cfg.silent_preload = v != "false" && v != "0";
743        }
744        if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD")
745            && let Ok(n) = v.parse()
746        {
747            cfg.dedup_threshold = n;
748        }
749        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
750            cfg.cognition_loop_enabled = v != "false" && v != "0";
751        }
752        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
753            && let Ok(n) = v.parse()
754        {
755            cfg.cognition_loop_interval_secs = n;
756        }
757        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
758            && let Ok(n) = v.parse()
759        {
760            cfg.cognition_loop_max_steps = n;
761        }
762        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_SYNTHESIS_MIN_CLUSTER")
763            && let Ok(n) = v.parse()
764        {
765            cfg.cognition_synthesis_min_cluster = n;
766        }
767        cfg
768    }
769}
770
771/// Anonymous opt-in telemetry heartbeat settings.
772///
773/// When enabled, lean-ctx sends a daily heartbeat to `api.leanctx.com` containing
774/// only: a random installation ID (UUID v4), the lean-ctx version, OS, and CPU
775/// architecture. No code, filenames, usage patterns, or personal data — ever.
776/// Disabled by default; enable during setup or with `lean-ctx telemetry on`.
777#[derive(Debug, Clone, Serialize, Deserialize, Default)]
778#[serde(default)]
779pub struct TelemetryConfig {
780    /// Master switch for the anonymous heartbeat. Off by default (opt-in).
781    pub enabled: bool,
782    /// Daily debounce: YYYY-MM-DD of the last successful heartbeat.
783    pub last_heartbeat: Option<String>,
784}
785
786/// Cloud sync and contribution settings (pattern sharing, model pulls).
787#[derive(Debug, Clone, Serialize, Deserialize, Default)]
788#[serde(default)]
789pub struct CloudConfig {
790    pub contribute_enabled: bool,
791    pub last_contribute: Option<String>,
792    /// Allow background upload of aggregate usage statistics. Disabled by default.
793    #[serde(default)]
794    pub sync_stats_enabled: bool,
795    pub last_sync: Option<String>,
796    /// Research-only background upload of aggregate local observations. Disabled by default.
797    #[serde(default)]
798    pub sync_gain_enabled: bool,
799    pub last_gain_sync: Option<String>,
800    /// Research-only hosted model-data retrieval. Disabled by default.
801    #[serde(default)]
802    pub sync_models_enabled: bool,
803    pub last_model_pull: Option<String>,
804    /// Research-only hosted synchronization switch. Inactive in the public
805    /// local Runtime and off by default.
806    pub auto_sync: bool,
807    pub last_auto_sync: Option<String>,
808    /// Research-only hosted retrieval-index synchronization switch. Inactive
809    /// in the public local Runtime and off by default.
810    pub auto_index: bool,
811    /// Per-project debounce: `project_hash → YYYY-MM-DD` of the last
812    /// successful background index push.
813    pub last_index_push: std::collections::HashMap<String, String>,
814}
815
816/// Settings retained for local development evaluation of hosted publication.
817///
818/// Hosted publication and public rankings are Research, not part of the public
819/// LeanCTX Runtime. Both switches default to `false` and require the explicit
820/// `LEAN_CTX_EXPERIMENTAL_PUBLICATION=1` development flag before they can act.
821#[derive(Debug, Clone, Serialize, Deserialize)]
822#[serde(default)]
823pub struct GainConfig {
824    /// Development-only: automatically publish a local evaluation recap when the
825    /// environment opt-in is present. Off by default.
826    pub auto_publish: bool,
827    /// Development-only: request the Research public-ranking path. Off by default.
828    pub leaderboard: bool,
829    /// Development-only display name for a Research publication evaluation.
830    pub display_name: Option<String>,
831    /// Minimum hours between automatic publishes (throttle).
832    pub auto_publish_interval_hours: u64,
833    /// Runtime state — RFC3339 timestamp of the last automatic publish. Managed by the
834    /// tool, not meant to be set by hand.
835    pub last_auto_publish: Option<String>,
836}
837
838impl Default for GainConfig {
839    fn default() -> Self {
840        Self {
841            auto_publish: false,
842            leaderboard: false,
843            display_name: None,
844            auto_publish_interval_hours: 24,
845            last_auto_publish: None,
846        }
847    }
848}
849
850/// Model declaration for **measured-vs-estimated** cost reporting.
851///
852/// Proxy-routed clients (Claude Code, Codex, Pi, Gemini CLI, OpenCode) report
853/// their real model and billed tokens, so lean-ctx prices them *measured* with
854/// no configuration. MCP-only IDEs (Cursor, Copilot, Windsurf, VS Code, Zed)
855/// send their LLM traffic straight to the provider, bypassing lean-ctx — their
856/// real model is invisible. Declaring it here lets those *estimated* turns be
857/// priced with the correct model instead of a blended fallback.
858#[derive(Debug, Clone, Default, Serialize, Deserialize)]
859#[serde(default)]
860pub struct CostConfig {
861    /// Per-session cost cap in USD. When accumulated cost exceeds this value,
862    /// subsequent tool calls receive a `[COST CAP]` warning instead of the
863    /// normal output (#794). 0 = unlimited (default).
864    /// Override at runtime: `LEAN_CTX_COST_CAP_OVERRIDE=1` bypasses the cap.
865    #[serde(default)]
866    pub max_session_cost_usd: f64,
867    /// Fallback pricing model for any client without a per-client entry.
868    /// Unset/empty → lean-ctx keeps its blended heuristic.
869    #[serde(default, skip_serializing_if = "Option::is_none")]
870    pub default_model: Option<String>,
871    /// Per-client pricing model, keyed by client id (`cursor`, `copilot`,
872    /// `windsurf`, `claude`, `codex`, …). Used for MCP-only IDEs whose real
873    /// model lean-ctx cannot observe. Example:
874    /// `[cost.models]` then `cursor = "claude-opus-4.5"`.
875    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
876    pub models: HashMap<String, String>,
877    /// Operator price overrides (#1189), keyed by model name — for negotiated
878    /// enterprise rates (committed-use discounts, Azure PTU, zero-rated
879    /// internal models) that no public catalog can know. Merged into the
880    /// pricing table as **exact** entries, overriding embedded and live rows;
881    /// only a provider-measured bill beats them. Example:
882    /// `[cost.prices."internal-llm"]` then `input_per_m = 0.10`,
883    /// `output_per_m = 0.40`.
884    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
885    pub prices: HashMap<String, PriceOverride>,
886}
887
888/// MCP decision-loop runtime settings (`[decision_loop]`).
889#[derive(Debug, Clone, Serialize, Deserialize)]
890#[serde(default)]
891pub struct DecisionLoopConfig {
892    pub enabled: bool,
893    /// Maximum lossy post-dispatch triage level (`0` disables output filtering).
894    /// Classification and decision-loop accounting remain active at level 0.
895    #[serde(default)]
896    pub max_filter_level: u8,
897}
898
899impl Default for DecisionLoopConfig {
900    fn default() -> Self {
901        Self {
902            enabled: true,
903            max_filter_level: 0,
904        }
905    }
906}
907
908/// One `[cost.prices.<model>]` row: USD per million tokens. Omitted cache
909/// rates default to the input rate (the same convention the catalogs use).
910#[derive(Debug, Clone, Default, Serialize, Deserialize)]
911#[serde(default)]
912pub struct PriceOverride {
913    pub input_per_m: Option<f64>,
914    pub output_per_m: Option<f64>,
915    pub cache_write_per_m: Option<f64>,
916    pub cache_read_per_m: Option<f64>,
917}
918
919impl CostConfig {
920    /// Configured pricing model for a client id: the per-client entry first, then
921    /// the global default. `None` when neither is set (the caller then falls back
922    /// to the env override / heuristic). Blank entries are ignored.
923    pub fn model_for_client(&self, client: &str) -> Option<String> {
924        self.models
925            .get(client)
926            .or(self.default_model.as_ref())
927            .map(|s| s.trim().to_string())
928            .filter(|s| !s.is_empty())
929    }
930}
931
932/// Code-health engine (`[code_health]`): clean code as a token-cost lever.
933///
934/// Cognitive complexity, naming quality, and coupling are computed once during
935/// indexing and surfaced at read- and edit-time. These switches tune the
936/// thresholds and how assertively findings are surfaced.
937#[derive(Debug, Clone, Serialize, Deserialize)]
938#[serde(default)]
939pub struct CodeHealthConfig {
940    /// Cognitive-complexity threshold above which a function is a hotspot.
941    /// Mirrors `core::code_health::DEFAULT_COGNITIVE_THRESHOLD` (15).
942    pub cognitive_threshold: u32,
943    /// Edit-gate behavior on complexity drift: `"warn"` (annotate, default),
944    /// `"block"` (refuse clean→over-threshold edits), or `"off"`.
945    pub gate: String,
946    /// Annotate over-threshold functions inline in `ctx_read` output.
947    pub annotate_reads: bool,
948    /// Run the naming-quality heuristic.
949    pub naming: bool,
950    /// Compute module-coupling metrics.
951    pub coupling: bool,
952    /// Inject `[CODE HEALTH]` notices as `additionalContext` in PostToolUse stdout.
953    /// Default: **false** — prevents prompt-cache invalidation on Anthropic models
954    /// (#778: each injection causes 440-520k tokens of cache re-bills when Claude
955    /// Code strips stale system-reminders retroactively).
956    /// When false, notices route to `ctx_knowledge` + dashboard instead.
957    #[serde(default)]
958    pub inject_context: bool,
959}
960
961impl Default for CodeHealthConfig {
962    fn default() -> Self {
963        Self {
964            cognitive_threshold: 15,
965            gate: "warn".to_string(),
966            annotate_reads: true,
967            naming: true,
968            coupling: true,
969            inject_context: false,
970        }
971    }
972}
973
974/// Index-time file filters (#735): declare the retrieval corpus explicitly
975/// instead of abusing `.gitignore` for retrieval policy.
976///
977/// Applies to every index builder through one shared filter layer
978/// (`core::index_filter`): BM25, graph, and the watch/incremental path; the
979/// semantic index chunks the BM25 corpus and inherits the same universe.
980/// Excluded files never produce chunks, graph nodes, or embeddings. Globs are
981/// matched against the root-relative path (forward slashes); exclude wins
982/// over include. The empty default preserves today's behavior byte-for-byte.
983#[derive(Debug, Clone, Serialize, Deserialize)]
984#[serde(default)]
985pub struct IndexConfig {
986    /// Honor `.gitignore` / global gitignore / `.git/info/exclude` during
987    /// index walks. `false` indexes ignored files too (rarely wanted; the
988    /// vendor-directory guard still applies).
989    pub respect_gitignore: bool,
990    /// Files to drop from the index corpus, e.g. `["**/*.csv", "fixtures/**"]`.
991    /// Evaluated after `include`; a file matching both is excluded.
992    pub exclude: Vec<String>,
993    /// When non-empty, ONLY matching files enter the index corpus, e.g.
994    /// `["**/*.rs", "**/*.ts"]`. Empty = no restriction.
995    pub include: Vec<String>,
996}
997
998impl Default for IndexConfig {
999    fn default() -> Self {
1000        Self {
1001            respect_gitignore: true,
1002            exclude: Vec::new(),
1003            include: Vec::new(),
1004        }
1005    }
1006}
1007
1008/// Settings for the code graph — in particular the *traversal* (co-access) edges
1009/// learned from real agent sessions (#289).
1010///
1011/// The static AST/import graph captures how code is wired structurally; it cannot
1012/// see which files an agent actually opens *together* while solving a task.
1013/// Traversal edges add that behavioural signal: files surfaced together are
1014/// associated with a decaying weight (Hebbian co-access), folded into the graph
1015/// as `co_access` edges and mixed into recall. The store is bounded and decays,
1016/// so stale associations fade.
1017#[derive(Debug, Clone, Serialize, Deserialize)]
1018#[serde(default)]
1019pub struct GraphConfig {
1020    /// Record co-access between files surfaced together in a session, surface them
1021    /// as decaying `co_access` edges in the graph, and boost recall by them.
1022    /// On by default; set to `false` for a purely static (AST-only) graph.
1023    pub traversal_edges: bool,
1024}
1025
1026impl Default for GraphConfig {
1027    fn default() -> Self {
1028        Self {
1029            traversal_edges: true,
1030        }
1031    }
1032}
1033
1034/// Skillify (#290): mine the project's session diary + knowledge facts into
1035/// versioned, git-committable `.cursor/rules/skillify-*.mdc` rule files.
1036///
1037/// The miner is precision-biased — it only codifies recurring or high-confidence
1038/// patterns and never invents content. Runs on demand (`ctx_skillify` /
1039/// `lean-ctx skillify`); re-running merges (bumps version) only when the distilled
1040/// content actually changes.
1041#[derive(Debug, Clone, Serialize, Deserialize)]
1042#[serde(default)]
1043pub struct SkillifyConfig {
1044    /// Master switch for the skillify miner. On by default; the miner only ever
1045    /// acts when explicitly invoked, so this never writes files unprompted.
1046    pub enabled: bool,
1047    /// Where generated rules are written: `project` (`<repo>/.cursor/rules`,
1048    /// git-committable, default) or `global` (`~/.cursor/rules`).
1049    pub scope: String,
1050    /// Minimum confidence for a single curated knowledge fact to be codified even
1051    /// without repetition. 0.0..=1.0.
1052    pub min_confidence: f32,
1053    /// Minimum number of reinforcements (confirmations / repeated mentions) before
1054    /// a pattern is codified when its confidence is below `min_confidence`.
1055    pub min_recurrence: u32,
1056}
1057
1058impl Default for SkillifyConfig {
1059    fn default() -> Self {
1060        Self {
1061            enabled: true,
1062            scope: "project".to_string(),
1063            min_confidence: 0.7,
1064            min_recurrence: 2,
1065        }
1066    }
1067}
1068
1069/// AI session summaries (#292): periodically distil the working session into a
1070/// compact, *semantically recallable* summary so a future session can answer
1071/// "what did I do last time on X?". Deterministic and local-first — recall uses
1072/// embeddings when the `embeddings` feature is on, else a lexical fallback.
1073#[derive(Debug, Clone, Serialize, Deserialize)]
1074#[serde(default)]
1075pub struct SummariesConfig {
1076    /// Record periodic session summaries. On by default; recording is cheap and
1077    /// happens at most once per `every_n_turns` tool calls.
1078    pub enabled: bool,
1079    /// Tool calls between automatic summaries. The auto-checkpoint cadence still
1080    /// gates the check, so the effective minimum is the checkpoint interval.
1081    pub every_n_turns: u32,
1082    /// Maximum summaries kept per project (oldest pruned first).
1083    pub max_kept: u32,
1084}
1085
1086impl Default for SummariesConfig {
1087    fn default() -> Self {
1088        Self {
1089            enabled: true,
1090            every_n_turns: 25,
1091            max_kept: 100,
1092        }
1093    }
1094}
1095
1096/// A user-defined command alias mapping for shell compression patterns.
1097#[derive(Debug, Clone, Serialize, Deserialize)]
1098pub struct AliasEntry {
1099    pub command: String,
1100    pub alias: String,
1101}
1102
1103/// Thresholds for detecting and throttling repetitive agent tool call loops.
1104#[derive(Debug, Clone, Serialize, Deserialize)]
1105#[serde(default)]
1106pub struct LoopDetectionConfig {
1107    pub normal_threshold: u32,
1108    pub reduced_threshold: u32,
1109    pub blocked_threshold: u32,
1110    pub window_secs: u64,
1111    pub search_group_limit: u32,
1112    pub tool_total_limits: HashMap<String, u32>,
1113}
1114
1115impl Default for LoopDetectionConfig {
1116    fn default() -> Self {
1117        let mut tool_total_limits = HashMap::new();
1118        tool_total_limits.insert("ctx_read".to_string(), 100);
1119        tool_total_limits.insert("ctx_search".to_string(), 80);
1120        tool_total_limits.insert("ctx_shell".to_string(), 50);
1121        tool_total_limits.insert("ctx_semantic_search".to_string(), 60);
1122        Self {
1123            normal_threshold: 2,
1124            reduced_threshold: 4,
1125            blocked_threshold: 0,
1126            window_secs: 300,
1127            search_group_limit: 10,
1128            tool_total_limits,
1129        }
1130    }
1131}
1132
1133/// Semantic-embedding engine settings.
1134///
1135/// `model` selects which local ONNX embedding model lean-ctx downloads and uses for
1136/// `ctx_semantic_search`. Accepts the same aliases as the `LEAN_CTX_EMBEDDING_MODEL` env
1137/// var: `minilm` (all-MiniLM-L6-v2, 384d — the default), `nomic` (768d) — or any
1138/// HuggingFace repo with an ONNX export via `hf:org/repo[@revision]` (GL #397), e.g.
1139/// `hf:jinaai/jina-embeddings-v2-base-code` for code-specialized embeddings. When the
1140/// env var is set it takes precedence; an
1141/// unset/`None` value uses the default model. Switching models triggers a one-time
1142/// re-index on the next semantic search (vector dimensions follow from the model).
1143///
1144/// `dimensions` is only consulted for `hf:` custom models as the declared fallback
1145/// width; the real width is probed from the ONNX graph at load time. Built-ins ignore it.
1146/// `[gateway_server]` — deployment parameters of the self-hosted org gateway
1147/// (enterprise#20). Distinct from `[gateway]` (the MCP tool-catalog gateway):
1148/// this section describes the LLM-proxy *server* deployment and its cockpit.
1149///
1150/// All fields optional; an empty section keeps every local behavior unchanged.
1151#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1152#[serde(default)]
1153pub struct GatewayServerConfig {
1154    /// Seats the org-wide projection extrapolates to (e.g. `800`). `None`
1155    /// disables the projection — the cockpit never invents a seat count.
1156    #[serde(default, skip_serializing_if = "Option::is_none")]
1157    pub seats: Option<u32>,
1158    /// Display label for the cockpit header (e.g. `"Zühlke AI Gateway"`).
1159    #[serde(default, skip_serializing_if = "Option::is_none")]
1160    pub org_label: Option<String>,
1161    /// Central admin API base URL (e.g. `https://ai-gateway.example.com`).
1162    /// When set, the local cockpit's usage breakdown reads the org-wide
1163    /// `GET /api/admin/usage` instead of the machine-local snapshot. The
1164    /// bearer token comes from `LEAN_CTX_GATEWAY_ADMIN_TOKEN` (never config).
1165    #[serde(default, skip_serializing_if = "Option::is_none")]
1166    pub admin_url: Option<String>,
1167    /// Bind address of the admin listener (dashboard + `/api/admin/*` +
1168    /// `/metrics`). Defaults to loopback — **secure by default** (#54/#56):
1169    /// exposing the console is an explicit decision. Container deployments set
1170    /// `"0.0.0.0"` here (the pod/compose port mapping stays the outer guard).
1171    /// `LEAN_CTX_GATEWAY_ADMIN_BIND_HOST` overrides. Invalid values fall back
1172    /// to loopback: a typo can only ever narrow exposure, never open it.
1173    #[serde(default, skip_serializing_if = "Option::is_none")]
1174    pub admin_bind_host: Option<String>,
1175    /// Days to keep `usage_events` rows (enterprise#36). `None`/`0` = keep
1176    /// forever (the local-free default — retention is a deployment decision).
1177    /// A running gateway purges older rows periodically; typical compliance
1178    /// values are `365` or `3650` (EU AI Act evidence horizon).
1179    #[serde(default, skip_serializing_if = "Option::is_none")]
1180    pub usage_retention_days: Option<u32>,
1181    /// Replace `person` with a stable keyed pseudonym (`p:<hash>`) before it
1182    /// reaches metering, budgets, dashboards and logs (enterprise#39, GDPR).
1183    /// The salt lives in `<data_dir>/gateway_pii_salt`; `gateway gdpr`
1184    /// re-derives pseudonyms from e-mail input, so DSGVO delete/export keep
1185    /// working. Default `false` (cleartext person tags).
1186    #[serde(default, skip_serializing_if = "Option::is_none")]
1187    pub pseudonymize_persons: Option<bool>,
1188    /// MCP upstream registry (GL#91/#99, Doc 15 §7 — the observe stage of MCP
1189    /// context governance). Each entry publishes a governed reverse-proxy
1190    /// route `/mcp/{id}` on the proxy port: same per-person key auth as the
1191    /// LLM channel, tool calls metered into `mcp_events`, tool definitions
1192    /// inventoried + hash-tracked (rug-pull detection). Observe-only: the
1193    /// gateway never blocks or rewrites MCP traffic in this stage.
1194    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1195    pub mcp_servers: Vec<McpServerEntry>,
1196}
1197
1198/// One `[[gateway_server.mcp_servers]]` registry entry — an MCP server the org
1199/// gateway fronts. Distinct from `[[gateway.servers]]` (the *local* tool-
1200/// catalog aggregator, #210): this registry is the org-facing reverse proxy.
1201#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1202pub struct McpServerEntry {
1203    /// Registry id, used in the `/mcp/{id}` route. Lowercase alphanumeric
1204    /// plus `-`/`_` (it becomes a URL path segment).
1205    pub id: String,
1206    /// Upstream Streamable-HTTP endpoint (the server's single MCP endpoint,
1207    /// e.g. `https://mcp.example.com/mcp`). HTTPS for any non-loopback host;
1208    /// plaintext HTTP needs the same explicit opt-in as LLM upstreams
1209    /// (`[proxy] allow_insecure_http_upstream`).
1210    pub url: String,
1211    /// Name of the environment variable holding the upstream credential. When
1212    /// set, the gateway sends `Authorization: Bearer <value>` upstream — the
1213    /// credential lives in the gateway's environment, never on laptops. The
1214    /// caller's own `Authorization` header (their gateway key) is **always**
1215    /// stripped before forwarding, with or without this field.
1216    #[serde(default, skip_serializing_if = "Option::is_none")]
1217    pub auth_env: Option<String>,
1218    /// Set `false` to keep the entry in config but take it out of service.
1219    #[serde(default, skip_serializing_if = "Option::is_none")]
1220    pub enabled: Option<bool>,
1221}
1222
1223/// A validated, ready-to-serve MCP registry entry (runtime view of
1224/// [`McpServerEntry`]).
1225#[derive(Debug, Clone, PartialEq, Eq)]
1226pub struct ResolvedMcpServer {
1227    pub id: String,
1228    pub url: String,
1229    pub auth_env: Option<String>,
1230}
1231
1232impl GatewayServerConfig {
1233    /// Validate + resolve the `[[gateway_server.mcp_servers]]` registry.
1234    /// Same resilience contract as `[[proxy.providers]]`: invalid entries are
1235    /// logged and skipped (one typo never takes the gateway down), duplicates
1236    /// keep the first occurrence. `allow_insecure_http` mirrors the proxy's
1237    /// plaintext-HTTP opt-in so the two registries share one security posture.
1238    #[must_use]
1239    pub fn resolve_mcp_servers(&self, allow_insecure_http: bool) -> Vec<ResolvedMcpServer> {
1240        let mut seen: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
1241        let mut out = Vec::new();
1242        for entry in &self.mcp_servers {
1243            if !entry.enabled.unwrap_or(true) {
1244                continue;
1245            }
1246            let id = entry.id.trim();
1247            if !is_valid_mcp_server_id(id) {
1248                tracing::warn!(
1249                    "[gateway_server.mcp_servers] invalid id '{id}' \
1250                     (lowercase alnum/-/_ only) — entry skipped"
1251                );
1252                continue;
1253            }
1254            if !seen.insert(id) {
1255                tracing::warn!(
1256                    "[gateway_server.mcp_servers] duplicate id '{id}' — keeping first entry"
1257                );
1258                continue;
1259            }
1260            match validate_mcp_upstream_url(&entry.url, allow_insecure_http) {
1261                Ok(url) => out.push(ResolvedMcpServer {
1262                    id: id.to_string(),
1263                    url,
1264                    auth_env: entry
1265                        .auth_env
1266                        .as_deref()
1267                        .map(str::trim)
1268                        .filter(|v| !v.is_empty())
1269                        .map(str::to_string),
1270                }),
1271                Err(e) => {
1272                    tracing::warn!(
1273                        "[gateway_server.mcp_servers] '{id}' has invalid url — skipped: {e}"
1274                    );
1275                }
1276            }
1277        }
1278        out
1279    }
1280
1281    /// Effective admin bind address (see `admin_bind_host`). Precedence:
1282    /// `LEAN_CTX_GATEWAY_ADMIN_BIND_HOST` env > config > `127.0.0.1`.
1283    #[must_use]
1284    pub fn resolved_admin_bind_host(&self) -> std::net::IpAddr {
1285        let raw = std::env::var("LEAN_CTX_GATEWAY_ADMIN_BIND_HOST")
1286            .ok()
1287            .filter(|v| !v.trim().is_empty())
1288            .or_else(|| self.admin_bind_host.clone());
1289        match raw.as_deref().map(str::trim) {
1290            Some(v) if !v.is_empty() => v.parse().unwrap_or_else(|_| {
1291                tracing::warn!(
1292                    "gateway_server.admin_bind_host '{v}' is not a valid IP address — binding 127.0.0.1"
1293                );
1294                std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
1295            }),
1296            _ => std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
1297        }
1298    }
1299}
1300
1301/// True when `id` is usable as an MCP registry id: non-empty, lowercase alnum
1302/// plus `-`/`_` (it becomes a URL path segment). Same shape rule as
1303/// `[[proxy.providers]]` ids; no built-in namespace exists to shadow here.
1304fn is_valid_mcp_server_id(id: &str) -> bool {
1305    !id.is_empty()
1306        && id
1307            .chars()
1308            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
1309}
1310
1311/// Validates an MCP upstream URL. A declared registry entry is itself the
1312/// deliberate custom-host opt-in (same rationale as `[[proxy.providers]]`):
1313/// any HTTPS host is accepted; loopback HTTP is always fine; non-loopback
1314/// plaintext HTTP requires the explicit insecure-HTTP opt-in. This is the
1315/// SSRF boundary — the proxy only ever connects to URLs that passed here.
1316fn validate_mcp_upstream_url(url: &str, allow_insecure_http: bool) -> Result<String, String> {
1317    let trimmed = url.trim().trim_end_matches('/');
1318    if trimmed.is_empty() {
1319        return Err("empty url".into());
1320    }
1321    if crate::core::config::is_local_proxy_url(trimmed) {
1322        return Ok(trimmed.to_string());
1323    }
1324    if trimmed.starts_with("http://") {
1325        if allow_insecure_http {
1326            return Ok(trimmed.to_string());
1327        }
1328        return Err(format!(
1329            "MCP upstream must use HTTPS: {trimmed} (for a trusted local-network HTTP \
1330             upstream opt in with `[proxy] allow_insecure_http_upstream = true`)"
1331        ));
1332    }
1333    if trimmed.starts_with("https://") {
1334        return Ok(trimmed.to_string());
1335    }
1336    Err(format!(
1337        "MCP upstream must start with http:// or https://: {trimmed}"
1338    ))
1339}
1340
1341#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1342#[serde(default)]
1343pub struct EmbeddingConfig {
1344    #[serde(default, skip_serializing_if = "Option::is_none")]
1345    pub model: Option<String>,
1346    #[serde(default, skip_serializing_if = "Option::is_none")]
1347    pub dimensions: Option<usize>,
1348    /// Allow downloading the embedding model on first semantic need (#551).
1349    /// `None` (unset) means **allowed** — the soft default that activates the
1350    /// semantic features without manual setup. Set `false` for air-gapped
1351    /// machines. The `LEAN_CTX_EMBEDDINGS_AUTO_DOWNLOAD` env var, when set,
1352    /// overrides this in either direction.
1353    #[serde(default, skip_serializing_if = "Option::is_none")]
1354    pub auto_download: Option<bool>,
1355    /// Pin embedding inference to a single CPU thread (no GPU EP) so vectors are
1356    /// bit-identical across machines, not just run-to-run on one host (#895).
1357    /// `None`/`false` keeps the multi-threaded GPU-capable path. Extractive prose
1358    /// ranking is already deterministic via score quantization + stable tiebreak;
1359    /// this flag is the extra hardening for cross-machine reproducibility. The
1360    /// `LEAN_CTX_EMBEDDING_DETERMINISTIC` env var overrides this either way.
1361    #[serde(default, skip_serializing_if = "Option::is_none")]
1362    pub deterministic: Option<bool>,
1363}
1364
1365#[cfg(test)]
1366mod gateway_server_tests {
1367    use super::*;
1368
1369    #[test]
1370    fn admin_bind_defaults_to_loopback_and_rejects_garbage() {
1371        // Secure by default (#54/#56): unset and invalid both land on loopback.
1372        let cfg = GatewayServerConfig::default();
1373        assert!(cfg.resolved_admin_bind_host().is_loopback());
1374
1375        let cfg = GatewayServerConfig {
1376            admin_bind_host: Some("not-an-ip".into()),
1377            ..Default::default()
1378        };
1379        assert!(
1380            cfg.resolved_admin_bind_host().is_loopback(),
1381            "a typo must narrow exposure, never widen it"
1382        );
1383
1384        let cfg = GatewayServerConfig {
1385            admin_bind_host: Some("0.0.0.0".into()),
1386            ..Default::default()
1387        };
1388        assert!(
1389            !cfg.resolved_admin_bind_host().is_loopback(),
1390            "explicit opt-in widens the bind"
1391        );
1392    }
1393
1394    fn mcp_entry(id: &str, url: &str) -> McpServerEntry {
1395        McpServerEntry {
1396            id: id.into(),
1397            url: url.into(),
1398            auth_env: None,
1399            enabled: None,
1400        }
1401    }
1402
1403    #[test]
1404    fn mcp_registry_validates_ids_urls_and_duplicates() {
1405        let cfg = GatewayServerConfig {
1406            mcp_servers: vec![
1407                mcp_entry("github", "https://mcp.example.com/mcp/"),
1408                // invalid id (uppercase) — skipped, never panics
1409                mcp_entry("GitHub", "https://mcp.example.com/mcp"),
1410                // duplicate — first occurrence wins
1411                mcp_entry("github", "https://other.example.com/mcp"),
1412                // plaintext HTTP on a non-loopback host without the opt-in — skipped
1413                mcp_entry("plain", "http://mcp.example.com/mcp"),
1414                // loopback HTTP is always fine (local/dev)
1415                mcp_entry("local", "http://127.0.0.1:9200/mcp"),
1416                McpServerEntry {
1417                    enabled: Some(false),
1418                    ..mcp_entry("disabled", "https://mcp.example.com/mcp")
1419                },
1420                McpServerEntry {
1421                    auth_env: Some("  GITHUB_MCP_PAT  ".into()),
1422                    ..mcp_entry("authed", "https://api.githubcopilot.com/mcp")
1423                },
1424            ],
1425            ..Default::default()
1426        };
1427        let resolved = cfg.resolve_mcp_servers(false);
1428        let ids: Vec<&str> = resolved.iter().map(|s| s.id.as_str()).collect();
1429        assert_eq!(ids, ["github", "local", "authed"]);
1430        // Trailing slash normalized; the duplicate kept the first URL.
1431        assert_eq!(resolved[0].url, "https://mcp.example.com/mcp");
1432        assert_eq!(resolved[2].auth_env.as_deref(), Some("GITHUB_MCP_PAT"));
1433
1434        // The insecure-HTTP opt-in admits the plaintext entry (trusted LAN).
1435        let with_optin = cfg.resolve_mcp_servers(true);
1436        assert!(with_optin.iter().any(|s| s.id == "plain"));
1437    }
1438
1439    #[test]
1440    fn mcp_upstream_url_rules_match_the_proxy_posture() {
1441        assert!(validate_mcp_upstream_url("https://mcp.example.com/mcp", false).is_ok());
1442        assert!(validate_mcp_upstream_url("http://localhost:9200/mcp", false).is_ok());
1443        assert!(validate_mcp_upstream_url("http://mcp.example.com/mcp", false).is_err());
1444        assert!(validate_mcp_upstream_url("http://mcp.example.com/mcp", true).is_ok());
1445        assert!(validate_mcp_upstream_url("ftp://mcp.example.com", false).is_err());
1446        assert!(validate_mcp_upstream_url("   ", false).is_err());
1447    }
1448}
1449
1450#[cfg(test)]
1451mod ocla_tests {
1452    use super::OclaConfig;
1453    use crate::core::ocla::grpc_bridge::GrpcConfig;
1454    use crate::core::ocla::sidecar::SidecarConfig;
1455    use serde::Deserialize;
1456
1457    #[derive(Deserialize)]
1458    struct ConfigFile {
1459        ocla: OclaConfig,
1460    }
1461
1462    #[test]
1463    fn sidecar_defaults_are_loopback_and_disabled() {
1464        let config = SidecarConfig::default();
1465        assert_eq!(config.bind_addr, "127.0.0.1:3334");
1466        assert!(!config.enabled);
1467        assert!(config.auth_token.is_none());
1468    }
1469
1470    #[test]
1471    fn nested_sidecar_toml_deserializes() {
1472        let config: ConfigFile = toml::from_str(
1473            r#"
1474                [ocla.sidecar]
1475                bind_addr = "127.0.0.1:9000"
1476                auth_token = "wire-secret"
1477                tls_cert_path = "/etc/lean-ctx/cert.pem"
1478                tls_key_path = "/etc/lean-ctx/key.pem"
1479                enabled = true
1480            "#,
1481        )
1482        .expect("OCLA sidecar config");
1483
1484        let sidecar = config.ocla.sidecar;
1485        assert_eq!(sidecar.bind_addr, "127.0.0.1:9000");
1486        assert_eq!(sidecar.auth_token.as_deref(), Some("wire-secret"));
1487        assert_eq!(
1488            sidecar.tls_cert_path.as_deref().unwrap().to_str(),
1489            Some("/etc/lean-ctx/cert.pem")
1490        );
1491        assert_eq!(
1492            sidecar.tls_key_path.as_deref().unwrap().to_str(),
1493            Some("/etc/lean-ctx/key.pem")
1494        );
1495        assert!(sidecar.enabled);
1496    }
1497
1498    #[test]
1499    fn nested_grpc_toml_deserializes() {
1500        let config: ConfigFile = toml::from_str(
1501            r#"
1502                [ocla.grpc]
1503                enabled = true
1504                listen = "127.0.0.1:60051"
1505            "#,
1506        )
1507        .expect("OCLA gRPC config");
1508
1509        assert_eq!(config.ocla.grpc.listen, "127.0.0.1:60051");
1510        assert!(config.ocla.grpc.enabled);
1511        assert_eq!(GrpcConfig::default().listen, "127.0.0.1:50051");
1512    }
1513}
1514
1515#[cfg(test)]
1516mod telemetry_tests {
1517    use super::*;
1518
1519    #[test]
1520    fn telemetry_config_defaults_to_disabled() {
1521        let cfg = TelemetryConfig::default();
1522        assert!(!cfg.enabled);
1523        assert!(cfg.last_heartbeat.is_none());
1524    }
1525
1526    #[test]
1527    fn telemetry_config_serde_roundtrip() {
1528        let toml_str = r#"
1529[telemetry]
1530enabled = true
1531last_heartbeat = "2026-07-30"
1532"#;
1533        #[derive(serde::Deserialize)]
1534        struct Wrap {
1535            telemetry: TelemetryConfig,
1536        }
1537        let wrap: Wrap = toml::from_str(toml_str).expect("parse telemetry config");
1538        assert!(wrap.telemetry.enabled);
1539        assert_eq!(wrap.telemetry.last_heartbeat.as_deref(), Some("2026-07-30"));
1540    }
1541
1542    #[test]
1543    fn telemetry_config_missing_section_uses_defaults() {
1544        let toml_str = "";
1545        #[derive(serde::Deserialize, Default)]
1546        #[serde(default)]
1547        struct Wrap {
1548            telemetry: TelemetryConfig,
1549        }
1550        let wrap: Wrap = toml::from_str(toml_str).expect("parse empty config");
1551        assert!(!wrap.telemetry.enabled);
1552        assert!(wrap.telemetry.last_heartbeat.is_none());
1553    }
1554}