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    pub enabled: bool,
18    pub report_interval: usize,
19    pub report_dir: String,
20}
21
22impl Default for ShadowConfig {
23    fn default() -> Self {
24        Self {
25            enabled: false,
26            report_interval: 10,
27            report_dir: String::new(),
28        }
29    }
30}
31
32/// OCLA settings (`[ocla.delivery]`). The former `[ocla.sidecar]` and
33/// `[ocla.grpc]` sections started no server and are ignored when present.
34#[derive(Debug, Clone, Default, Serialize, Deserialize)]
35#[serde(default)]
36pub struct OclaConfig {
37    pub delivery: DeliveryConfig,
38}
39
40#[derive(Debug, Clone, Serialize, Deserialize)]
41#[serde(default)]
42pub struct DeliveryConfig {
43    pub enabled: bool,
44    /// Allow subagents to receive a cross-agent delivery stub instead of
45    /// forcing a fresh disk read.
46    pub delivery_for_subagents: bool,
47    pub max_entries: usize,
48    pub ttl_minutes: u64,
49}
50
51impl Default for DeliveryConfig {
52    fn default() -> Self {
53        Self {
54            enabled: true,
55            delivery_for_subagents: true,
56            max_entries: 4096,
57            ttl_minutes: 30,
58        }
59    }
60}
61
62impl OclaConfig {
63    pub fn delivery_enabled(&self) -> bool {
64        self.delivery.enabled
65    }
66}
67
68/// Bounds and switches for the cross-agent delivery cache (`[cache]`).
69///
70/// The one source for these values: the former copy under
71/// `[ocla.delivery.cache]` is moved here by the automatic config migration.
72#[derive(Debug, Clone, Serialize, Deserialize)]
73#[serde(default)]
74pub struct CacheConfig {
75    /// Process-local tier lifetime (seconds).
76    pub l1_ttl_secs: u64,
77    /// Daemon tier size (entries).
78    pub l2_max_entries: usize,
79    /// Daemon tier lifetime (seconds).
80    pub l2_ttl_secs: u64,
81    /// Disk tier budget (bytes), enforced when the cache opens.
82    pub l3_max_bytes: u64,
83    /// Reuse a `ctx_compose` result for the same task and path.
84    pub compose_cache_enabled: bool,
85    /// Share pure parse results (BM25 chunks, deep analysis, signatures) by
86    /// content hash across worktrees and data homes (#2247). Off by default;
87    /// `LEAN_CTX_DERIVATION_CACHE=1|0` overrides it.
88    pub derivations_enabled: bool,
89    /// Directory of the shared parse cache; default `<cache dir>/derivations`.
90    /// `LEAN_CTX_DERIVATION_CACHE_DIR` overrides it.
91    pub derivations_dir: Option<String>,
92    /// Size budget of the shared parse cache (bytes); 0 = default 512 MiB.
93    pub derivations_max_bytes: u64,
94}
95
96impl Default for CacheConfig {
97    fn default() -> Self {
98        Self {
99            l1_ttl_secs: 300,
100            l2_max_entries: 10_000,
101            l2_ttl_secs: 3_600,
102            l3_max_bytes: 500_000_000,
103            compose_cache_enabled: true,
104            derivations_enabled: false,
105            derivations_dir: None,
106            derivations_max_bytes: 0,
107        }
108    }
109}
110
111#[cfg(test)]
112mod cache_config_tests {
113    use super::CacheConfig;
114
115    #[test]
116    fn cache_defaults_match_delivery_budget() {
117        assert_eq!(CacheConfig::default().l3_max_bytes, 500_000_000);
118        assert!(CacheConfig::default().compose_cache_enabled);
119    }
120
121    #[test]
122    fn cache_config_deserializes_partial_overrides() {
123        // `shell_cache_enabled` was removed (#1980); configs that still set it
124        // must keep loading.
125        // `l1_max_entries` and `l3_gc_threshold` were retired (never applied).
126        let parsed: CacheConfig = serde_json::from_str(
127            r#"{"l1_max_entries": 12, "l3_gc_threshold": 0.5, "shell_cache_enabled": true, "l2_ttl_secs": 60}"#,
128        )
129        .unwrap();
130        assert_eq!(parsed.l2_ttl_secs, 60);
131        assert_eq!(parsed.l2_max_entries, 10_000);
132    }
133}
134
135/// Agent lifecycle configuration: TTLs, GC intervals, scratchpad limits.
136///
137/// Maps to `[agents]` in config.toml. All fields have sane defaults so existing
138/// configs without this section continue to work.
139#[derive(Debug, Clone, Serialize, Deserialize)]
140#[serde(default)]
141pub struct AgentsConfig {
142    /// How often the background reaper runs (minutes). 0 = disabled.
143    pub gc_interval_minutes: u64,
144    /// Presence registry: remove finished agents older than this (hours).
145    pub presence_ttl_hours: u64,
146    /// Default TTL for scratchpad messages without explicit expiry (hours).
147    pub scratchpad_default_ttl_hours: u64,
148    /// Logical session timeout (seconds).
149    pub logical_session_ttl_seconds: u64,
150    /// Active worker lease. Missing heartbeats release capacity automatically.
151    pub active_worker_lease_seconds: u64,
152    /// Opt-in: let only one cargo/npm build or test run at a time across all
153    /// lean-ctx sessions on this machine (ctx_shell waits for the slot).
154    /// Off by default — it queued every user's builds behind other sessions.
155    pub serialize_build_commands: bool,
156    /// Opt-in: `CARGO_BUILD_JOBS` for builds run through ctx_shell. `0`
157    /// (default) leaves cargo's own setting alone.
158    pub cargo_build_jobs: usize,
159    /// Opt-in: point builds run through ctx_shell at one machine-wide
160    /// `CARGO_TARGET_DIR` (`<data dir>/build-cache/cargo-target`). Off by
161    /// default: when on, `./target` stops receiving the output, so a binary
162    /// run from there is stale.
163    pub shared_cargo_target: bool,
164    /// Max scratchpad entries before oldest are evicted.
165    pub max_scratchpad_entries: usize,
166}
167
168impl Default for AgentsConfig {
169    fn default() -> Self {
170        Self {
171            gc_interval_minutes: 10,
172            presence_ttl_hours: 24,
173            scratchpad_default_ttl_hours: 12,
174            logical_session_ttl_seconds: 180,
175            active_worker_lease_seconds: 120,
176            serialize_build_commands: false,
177            cargo_build_jobs: 0,
178            shared_cargo_target: false,
179            max_scratchpad_entries: 200,
180        }
181    }
182}
183
184#[cfg(test)]
185mod agents_config_tests {
186    use super::AgentsConfig;
187
188    #[test]
189    fn default_values_are_sane() {
190        let cfg = AgentsConfig::default();
191        assert_eq!(cfg.gc_interval_minutes, 10);
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.active_worker_lease_seconds, 120);
196        // Builds are the user's own: lean-ctx neither queues, throttles nor
197        // relocates them unless asked (a shared target made `./target` stale).
198        assert!(!cfg.serialize_build_commands);
199        assert_eq!(cfg.cargo_build_jobs, 0);
200        assert!(!cfg.shared_cargo_target);
201        assert_eq!(cfg.max_scratchpad_entries, 200);
202    }
203
204    #[test]
205    fn deserializes_with_missing_fields() {
206        let json = r"{}";
207        let cfg: AgentsConfig = serde_json::from_str(json).expect("empty object → defaults");
208        assert_eq!(cfg.gc_interval_minutes, 10);
209    }
210
211    #[test]
212    fn partial_override() {
213        let json = r#"{"gc_interval_minutes": 5, "presence_ttl_hours": 12}"#;
214        let cfg: AgentsConfig = serde_json::from_str(json).expect("partial");
215        assert_eq!(cfg.gc_interval_minutes, 5);
216        assert_eq!(cfg.presence_ttl_hours, 12);
217    }
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize)]
221#[serde(default)]
222pub struct SecretDetectionConfig {
223    pub enabled: bool,
224    pub redact: bool,
225    pub custom_patterns: Vec<String>,
226    /// #718: subtractive counterpart to `custom_patterns` — a detected secret
227    /// whose matched text is covered by any of these regexes is neither
228    /// reported nor redacted. Lets users carve out known-safe identifiers or
229    /// repo naming conventions without disabling secret detection wholesale.
230    pub exclude_patterns: Vec<String>,
231}
232
233/// Controls what lean-ctx injects during `setup` and `update --rewire`.
234/// Fresh installs default to non-invasive (rules/skills off, MCP on).
235/// Users who ran setup interactively get explicit true/false.
236/// `None` = undecided (legacy: check if rules already exist and preserve behavior).
237#[derive(Debug, Clone, Serialize, Deserialize)]
238#[serde(default)]
239pub struct SetupConfig {
240    /// Inject agent rule files (CLAUDE.md, .cursor/rules/, etc.).
241    /// None = undecided (legacy compat: inject if rules already present).
242    /// Some(true) = always inject. Some(false) = never inject.
243    pub auto_inject_rules: Option<bool>,
244    /// Install SKILL.md files for supported agents.
245    /// None = undecided. Some(true) = install. Some(false) = skip.
246    pub auto_inject_skills: Option<bool>,
247    /// Register lean-ctx as an MCP server in editor configs.
248    #[serde(default = "serde_defaults::default_true")]
249    pub auto_update_mcp: bool,
250    /// Keep already-installed agent hooks current on MCP server start (#1879).
251    /// `false` leaves hook entries, `permissions.deny` and the status line in
252    /// agent settings exactly as the user wrote them; only an explicit
253    /// `lean-ctx setup` / `init --agent` / `doctor --fix` writes them.
254    #[serde(default = "serde_defaults::default_true")]
255    pub manage_hooks: bool,
256    /// AI tools (agent keys, e.g. `claude`, `cursor`) that `setup`, `onboard`
257    /// and the post-update refresh may configure. Written by the setup
258    /// selection or `--agents`. None = no choice recorded yet: setup offers
259    /// every detected tool, an update refreshes only already-connected ones.
260    #[serde(skip_serializing_if = "Option::is_none")]
261    pub agents: Option<Vec<String>>,
262}
263
264impl Default for SetupConfig {
265    fn default() -> Self {
266        Self {
267            auto_inject_rules: None,
268            auto_inject_skills: None,
269            auto_update_mcp: true,
270            manage_hooks: true,
271            agents: None,
272        }
273    }
274}
275
276impl SetupConfig {
277    /// Returns whether rules should be injected, considering legacy installs.
278    /// If undecided (None), checks if lean-ctx rules markers already exist
279    /// in any agent config — if so, keeps injecting for backward compat.
280    pub fn should_inject_rules(&self) -> bool {
281        match self.auto_inject_rules {
282            Some(v) => v,
283            None => Self::rules_already_present(),
284        }
285    }
286
287    /// Returns whether skills should be installed.
288    pub fn should_inject_skills(&self) -> bool {
289        match self.auto_inject_skills {
290            Some(v) => v,
291            None => Self::rules_already_present(),
292        }
293    }
294
295    /// Returns whether `setup`/`onboard`/`init` may (re)register the lean-ctx
296    /// MCP server in editor configs. Honors `auto_update_mcp` (#281) so locked-
297    /// down environments can keep MCP out of agent settings while still getting
298    /// hooks, rules and skills.
299    pub fn should_update_mcp(&self) -> bool {
300        self.auto_update_mcp
301    }
302
303    /// Check if lean-ctx rules markers exist in any known agent config location.
304    ///
305    /// Delegates the per-agent path catalog to `rules_inject::any_rules_marker_present`
306    /// (derived from the injector's own target list) so this never drifts behind
307    /// newly supported agents again (#442). Claude Code and CodeBuddy have no
308    /// rules *target* (they auto-load an inline block instead), so their legacy
309    /// rule files are checked separately to keep honoring older installs.
310    fn rules_already_present() -> bool {
311        let Some(home) = dirs::home_dir() else {
312            return false;
313        };
314        if crate::rules_inject::any_rules_marker_present(&home) {
315            return true;
316        }
317        let legacy_paths = [
318            crate::core::editor_registry::claude_rules_dir(&home).join("lean-ctx.md"),
319            crate::core::editor_registry::codebuddy_rules_dir(&home).join("lean-ctx.md"),
320        ];
321        legacy_paths.iter().any(|p| {
322            std::fs::read_to_string(p)
323                .is_ok_and(|c| c.contains(crate::core::rules_canonical::START_MARK))
324        })
325    }
326}
327
328impl Default for SecretDetectionConfig {
329    fn default() -> Self {
330        Self {
331            enabled: true,
332            redact: true,
333            custom_patterns: Vec::new(),
334            exclude_patterns: Vec::new(),
335        }
336    }
337}
338
339/// Settings for the zero-loss compression archive (large tool outputs saved to disk).
340#[derive(Debug, Clone, Serialize, Deserialize)]
341#[serde(default)]
342pub struct ArchiveConfig {
343    pub enabled: bool,
344    pub threshold_chars: usize,
345    pub max_age_hours: u64,
346    pub max_disk_mb: u64,
347    pub ephemeral: bool,
348    /// Minimum output tokens before the ephemeral firewall replaces an inline tool
349    /// result with a summary + retrieval ref. Outputs below this stay fully inline.
350    pub ephemeral_min_tokens: usize,
351    /// Maximum output size that `ctx_shell(inline=true)` returns verbatim before
352    /// the archive/firewall path takes over.
353    pub inline_max_bytes: usize,
354    /// Programs whose stdout *is* a dataset (#1260). Head+tail elision does not
355    /// compress those — it drops the interior rows that hold the answer — so a
356    /// `ctx_shell` command running one of these passes through verbatim at any
357    /// size. Set to `[]` to disable the passthrough.
358    pub raw_commands: Vec<String>,
359    /// Context-window guard for *implicitly* verbatim `ctx_shell` deliveries
360    /// (dataset passthrough #1260, `inline=true`): above this many output
361    /// tokens the content is archived losslessly and delivered as a head+tail
362    /// digest with `ctx_expand` drilldown instead of flooding the calling
363    /// agent's context window. Explicit `raw=true`/`bypass=true` and the
364    /// `LEAN_CTX_MINIMAL` escape hatch are never capped. `0` disables the
365    /// cap. Env: LEAN_CTX_VERBATIM_MAX_TOKENS (#1541).
366    pub verbatim_max_tokens: usize,
367}
368
369/// Opt-in conversation-history compression settings (#1123).
370///
371/// The proxy leaves conversation history byte-for-byte unchanged unless
372/// `compression_enabled` is true and the configured token threshold is met.
373/// Each older message is scored; it is kept verbatim at or above
374/// `min_score_to_preserve`, replaced by a stub below `drop_score_below`, and
375/// summarized to one line in between. Neither a summary nor a stub keeps a
376/// recoverable copy, so the proxy leaves history untouched under protection.
377#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
378#[serde(default)]
379pub struct ConversationConfig {
380    /// Enable message-level compression in the proxy. Default: false.
381    pub compression_enabled: bool,
382    /// Number of most recent messages always kept verbatim.
383    pub preserve_last_n_turns: usize,
384    /// Minimum estimated message-array size before compression starts.
385    pub compression_threshold_tokens: usize,
386    /// Minimum score for verbatim preservation.
387    pub min_score_to_preserve: f64,
388    /// Messages scoring below this value are replaced by a one-line stub.
389    pub drop_score_below: f64,
390}
391
392impl Default for ConversationConfig {
393    fn default() -> Self {
394        Self {
395            compression_enabled: false,
396            preserve_last_n_turns: 10,
397            compression_threshold_tokens: 50_000,
398            min_score_to_preserve: 0.5,
399            drop_score_below: 0.2,
400        }
401    }
402}
403
404impl Default for ArchiveConfig {
405    fn default() -> Self {
406        Self {
407            enabled: true,
408            threshold_chars: 800,
409            max_age_hours: 48,
410            max_disk_mb: 500,
411            ephemeral: true,
412            ephemeral_min_tokens: 2000,
413            inline_max_bytes: 32 * 1024,
414            raw_commands: crate::core::firewall::DEFAULT_RAW_COMMANDS
415                .iter()
416                .map(|s| (*s).to_string())
417                .collect(),
418            verbatim_max_tokens: 100_000,
419        }
420    }
421}
422
423impl ArchiveConfig {
424    pub fn ephemeral_effective(&self) -> bool {
425        if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL") {
426            return !matches!(v.trim(), "0" | "false" | "off");
427        }
428        self.ephemeral && self.enabled
429    }
430
431    pub fn ephemeral_min_tokens_effective(&self) -> usize {
432        if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL_MIN_TOKENS")
433            && let Ok(n) = v.trim().parse::<usize>()
434        {
435            return n;
436        }
437        self.ephemeral_min_tokens
438    }
439
440    /// Effective context-window cap for implicitly verbatim deliveries (#1541).
441    pub fn verbatim_max_tokens_effective(&self) -> usize {
442        if let Ok(v) = std::env::var("LEAN_CTX_VERBATIM_MAX_TOKENS")
443            && let Ok(n) = v.trim().parse::<usize>()
444        {
445            return n;
446        }
447        self.verbatim_max_tokens
448    }
449
450    pub fn inline_max_bytes_effective(&self) -> usize {
451        if let Ok(v) = std::env::var("LEAN_CTX_INLINE_MAX_BYTES")
452            && let Ok(n) = v.trim().parse::<usize>()
453        {
454            return n;
455        }
456        self.inline_max_bytes
457    }
458}
459
460/// Configuration for external context providers (GitHub, GitLab, Jira, etc.).
461/// Each provider can be enabled/disabled and configured with auth tokens.
462/// Override individual tokens via env vars (GITHUB_TOKEN, GITLAB_TOKEN, etc.).
463#[derive(Debug, Clone, Serialize, Deserialize)]
464#[serde(default)]
465pub struct ProvidersConfig {
466    /// Master switch for the provider subsystem.
467    pub enabled: bool,
468    /// GitHub provider configuration.
469    pub github: ProviderEntryConfig,
470    /// GitLab provider configuration.
471    pub gitlab: ProviderEntryConfig,
472    /// Auto-ingest provider results into BM25/embedding indexes.
473    pub auto_index: bool,
474    /// Default cache TTL for provider results (seconds).
475    pub cache_ttl_secs: u64,
476    /// MCP Bridge providers: `{ "name" = { url = "...", description = "..." } }`.
477    #[serde(default)]
478    pub mcp_bridges: std::collections::HashMap<String, McpBridgeEntry>,
479}
480
481impl Default for ProvidersConfig {
482    fn default() -> Self {
483        Self {
484            enabled: true,
485            github: ProviderEntryConfig::default(),
486            gitlab: ProviderEntryConfig::default(),
487            auto_index: true,
488            cache_ttl_secs: 120,
489            mcp_bridges: std::collections::HashMap::new(),
490        }
491    }
492}
493
494/// Controls additive KnowledgeRouter hints in Context Gate output.
495#[derive(Debug, Clone, Serialize, Deserialize)]
496#[serde(default)]
497pub struct KnowledgeRoutingConfig {
498    pub enabled: bool,
499    pub max_references: usize,
500    pub hint_prefix: String,
501}
502
503impl Default for KnowledgeRoutingConfig {
504    fn default() -> Self {
505        Self {
506            enabled: true,
507            max_references: 5,
508            hint_prefix: "--- Knowledge Context ---".to_string(),
509        }
510    }
511}
512
513#[derive(Debug, Clone, Serialize, Deserialize)]
514pub struct McpBridgeEntry {
515    /// HTTP/SSE URL for remote MCP servers.
516    #[serde(default)]
517    pub url: Option<String>,
518    /// Command to spawn a local MCP server (stdio transport).
519    #[serde(default)]
520    pub command: Option<String>,
521    /// Arguments for the command.
522    #[serde(default)]
523    pub args: Vec<String>,
524    /// Human-readable description.
525    #[serde(default)]
526    pub description: Option<String>,
527    /// Environment variable name containing an auth token.
528    #[serde(default)]
529    pub auth_env: Option<String>,
530}
531
532/// Per-provider configuration entry.
533#[derive(Debug, Clone, Serialize, Deserialize)]
534#[serde(default)]
535pub struct ProviderEntryConfig {
536    /// Whether this specific provider is enabled.
537    pub enabled: bool,
538    /// Auth token (prefer env var; only use this for project-local overrides).
539    pub token: Option<String>,
540    /// API base URL override (for GitHub Enterprise, self-hosted GitLab, etc.).
541    pub api_url: Option<String>,
542    /// Default project/repo for this provider (auto-detected from git remote if empty).
543    pub project: Option<String>,
544}
545
546impl Default for ProviderEntryConfig {
547    fn default() -> Self {
548        Self {
549            enabled: true,
550            token: None,
551            api_url: None,
552            project: None,
553        }
554    }
555}
556
557/// Controls autonomous background behaviors (preload, dedup, consolidation).
558#[derive(Debug, Clone, Serialize, Deserialize)]
559#[serde(default)]
560pub struct AutonomyConfig {
561    pub enabled: bool,
562    pub auto_consolidate: bool,
563    pub consolidate_every_calls: u32,
564    pub consolidate_cooldown_secs: u64,
565    /// No effect: the background cognition loop is retired (DEPRECATIONS.toml
566    /// `config-autonomy-cognition-loop`). The four `cognition_*` keys stay
567    /// accepted so existing configs keep loading.
568    pub cognition_loop_enabled: bool,
569    #[serde(default = "serde_defaults::default_cognition_loop_interval")]
570    pub cognition_loop_interval_secs: u64,
571    #[serde(default = "serde_defaults::default_cognition_loop_max_steps")]
572    pub cognition_loop_max_steps: u8,
573    #[serde(default = "serde_defaults::default_cognition_synthesis_min_cluster")]
574    pub cognition_synthesis_min_cluster: usize,
575}
576
577impl Default for AutonomyConfig {
578    fn default() -> Self {
579        Self {
580            enabled: true,
581            auto_consolidate: true,
582            consolidate_every_calls: 25,
583            consolidate_cooldown_secs: 120,
584            cognition_loop_enabled: false,
585            cognition_loop_interval_secs: 3600,
586            cognition_loop_max_steps: 9,
587            cognition_synthesis_min_cluster: 3,
588        }
589    }
590}
591
592/// Controls automatic update behavior. All defaults are OFF — auto-updates
593/// require explicit opt-in via `lean-ctx setup` or `lean-ctx update --schedule`.
594#[derive(Debug, Clone, Serialize, Deserialize)]
595#[serde(default)]
596pub struct UpdatesConfig {
597    pub auto_update: bool,
598    pub check_interval_hours: u64,
599    pub notify_only: bool,
600    /// Persistent release pin used by manual and scheduled update checks.
601    /// `None` follows the latest release; values are normalized without `v`.
602    #[serde(default)]
603    pub pinned_version: Option<String>,
604}
605
606impl Default for UpdatesConfig {
607    fn default() -> Self {
608        Self {
609            auto_update: false,
610            check_interval_hours: 6,
611            notify_only: false,
612            pinned_version: None,
613        }
614    }
615}
616
617/// Fixed-context budget accounting (#964). The per-session footprint lean-ctx
618/// adds — tool schemas + MCP instructions + auto-loaded rules files + the wakeup
619/// briefing — is warned about once it crosses `budget_tokens`. The
620/// `LEAN_CTX_CONTEXT_BUDGET_TOKENS` env var overrides it; `lean-ctx doctor
621/// overhead --gate` turns a breach into a non-zero exit for CI.
622#[derive(Debug, Clone, Serialize, Deserialize)]
623#[serde(default)]
624pub struct ContextConfig {
625    pub budget_tokens: usize,
626    /// Inject matching CCR archives into later tool responses.
627    pub proactive_expansion: bool,
628    /// Maximum proactive archive content per tool response.
629    pub proactive_expansion_budget_tokens: usize,
630    /// Minimum normalized BM25 score required for an injection.
631    pub proactive_expansion_threshold: f64,
632    /// Ignore archived content older than this many seconds; 0 disables age expiry.
633    pub proactive_expansion_max_age_secs: u64,
634}
635
636impl Default for ContextConfig {
637    fn default() -> Self {
638        Self {
639            budget_tokens: 8000,
640            proactive_expansion: true,
641            proactive_expansion_budget_tokens: 2000,
642            proactive_expansion_threshold: 0.6,
643            proactive_expansion_max_age_secs: 3600,
644        }
645    }
646}
647
648impl UpdatesConfig {
649    pub fn from_env() -> Self {
650        let mut cfg = Self::default();
651        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_UPDATE") {
652            cfg.auto_update = v == "1" || v.eq_ignore_ascii_case("true");
653        }
654        if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_INTERVAL_HOURS")
655            && let Ok(h) = v.parse::<u64>()
656        {
657            cfg.check_interval_hours = h.clamp(1, 168);
658        }
659        if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_NOTIFY_ONLY") {
660            cfg.notify_only = v == "1" || v.eq_ignore_ascii_case("true");
661        }
662        cfg
663    }
664}
665
666impl AutonomyConfig {
667    /// Creates an autonomy config from env vars, falling back to defaults.
668    pub fn from_env() -> Self {
669        let mut cfg = Self::default();
670        if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
671            && (v == "false" || v == "0")
672        {
673            cfg.enabled = false;
674        }
675        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_CONSOLIDATE") {
676            cfg.auto_consolidate = v != "false" && v != "0";
677        }
678        if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_EVERY_CALLS")
679            && let Ok(n) = v.parse()
680        {
681            cfg.consolidate_every_calls = n;
682        }
683        if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_COOLDOWN_SECS")
684            && let Ok(n) = v.parse()
685        {
686            cfg.consolidate_cooldown_secs = n;
687        }
688        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
689            cfg.cognition_loop_enabled = v != "false" && v != "0";
690        }
691        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
692            && let Ok(n) = v.parse()
693        {
694            cfg.cognition_loop_interval_secs = n;
695        }
696        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
697            && let Ok(n) = v.parse()
698        {
699            cfg.cognition_loop_max_steps = n;
700        }
701        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_SYNTHESIS_MIN_CLUSTER")
702            && let Ok(n) = v.parse()
703        {
704            cfg.cognition_synthesis_min_cluster = n;
705        }
706        cfg
707    }
708
709    /// Loads autonomy config from disk, with env var overrides applied.
710    pub fn load() -> Self {
711        let file_cfg = Config::load().autonomy;
712        let mut cfg = file_cfg;
713        if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
714            && (v == "false" || v == "0")
715        {
716            cfg.enabled = false;
717        }
718        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
719            cfg.cognition_loop_enabled = v != "false" && v != "0";
720        }
721        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
722            && let Ok(n) = v.parse()
723        {
724            cfg.cognition_loop_interval_secs = n;
725        }
726        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
727            && let Ok(n) = v.parse()
728        {
729            cfg.cognition_loop_max_steps = n;
730        }
731        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_SYNTHESIS_MIN_CLUSTER")
732            && let Ok(n) = v.parse()
733        {
734            cfg.cognition_synthesis_min_cluster = n;
735        }
736        cfg
737    }
738}
739
740/// Persisted telemetry choice. This distinguishes the v4 default from a user
741/// choice so upgrades never erase an earlier opt-out.
742#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
743#[serde(rename_all = "snake_case")]
744pub enum TelemetryPreference {
745    #[default]
746    DefaultOn,
747    ExplicitlyEnabled,
748    ExplicitlyDisabled,
749}
750
751/// Privacy-safe product telemetry settings.
752///
753/// When enabled, lean-ctx sends cumulative daily aggregates to `api.leanctx.com`
754/// several times per day: a random installation ID (UUID v4), version, OS,
755/// setup profile and counters. No code, filenames, prompts, or personal data.
756/// Enabled by default (accepted at install); `lean-ctx telemetry off`,
757/// `DO_NOT_TRACK=1` and `LEAN_CTX_TELEMETRY=off` opt out.
758#[derive(Debug, Clone, Serialize, Deserialize)]
759#[serde(default)]
760pub struct TelemetryConfig {
761    /// Master switch for privacy-safe product telemetry.
762    pub enabled: bool,
763    /// Whether the state came from the v4 default or an explicit user choice.
764    pub preference: TelemetryPreference,
765    /// YYYY-MM-DD of the last successful telemetry send.
766    pub last_heartbeat: Option<String>,
767}
768
769impl Default for TelemetryConfig {
770    fn default() -> Self {
771        Self {
772            enabled: true,
773            preference: TelemetryPreference::DefaultOn,
774            last_heartbeat: None,
775        }
776    }
777}
778
779impl TelemetryConfig {
780    #[must_use]
781    pub fn environment_disables(do_not_track: Option<&str>, env_override: Option<&str>) -> bool {
782        do_not_track.is_some_and(|value| value.trim() == "1")
783            || env_override.is_some_and(|value| {
784                matches!(
785                    value.trim().to_ascii_lowercase().as_str(),
786                    "off" | "false" | "0" | "no"
787                )
788            })
789    }
790
791    #[must_use]
792    pub fn explicitly_disabled(&self) -> bool {
793        !self.enabled || self.preference == TelemetryPreference::ExplicitlyDisabled
794    }
795
796    #[must_use]
797    pub fn send_eligible(&self, do_not_track: Option<&str>, env_override: Option<&str>) -> bool {
798        self.enabled
799            && self.preference != TelemetryPreference::ExplicitlyDisabled
800            && !Self::environment_disables(do_not_track, env_override)
801    }
802}
803
804/// Model declaration for **measured-vs-estimated** cost reporting.
805///
806/// Proxy-routed clients (Claude Code, Codex, Pi, Gemini CLI, OpenCode) report
807/// their real model and billed tokens, so lean-ctx prices them *measured* with
808/// no configuration. MCP-only IDEs (Cursor, Copilot, Windsurf, VS Code, Zed)
809/// send their LLM traffic straight to the provider, bypassing lean-ctx — their
810/// real model is invisible. Declaring it here lets those *estimated* turns be
811/// priced with the correct model instead of a blended fallback.
812#[derive(Debug, Clone, Default, Serialize, Deserialize)]
813#[serde(default)]
814pub struct CostConfig {
815    /// Fallback pricing model for any client without a per-client entry.
816    /// Unset/empty → lean-ctx keeps its blended heuristic.
817    #[serde(default, skip_serializing_if = "Option::is_none")]
818    pub default_model: Option<String>,
819    /// Per-client pricing model, keyed by client id (`cursor`, `copilot`,
820    /// `windsurf`, `claude`, `codex`, …). Used for MCP-only IDEs whose real
821    /// model lean-ctx cannot observe. Example:
822    /// `[cost.models]` then `cursor = "claude-opus-4.5"`.
823    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
824    pub models: HashMap<String, String>,
825    /// Operator price overrides (#1189), keyed by model name — for negotiated
826    /// enterprise rates (committed-use discounts, Azure PTU, zero-rated
827    /// internal models) that no public catalog can know. Merged into the
828    /// pricing table as **exact** entries, overriding embedded and live rows;
829    /// only a provider-measured bill beats them. Example:
830    /// `[cost.prices."internal-llm"]` then `input_per_m = 0.10`,
831    /// `output_per_m = 0.40`.
832    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
833    pub prices: HashMap<String, PriceOverride>,
834}
835
836/// User-controlled never-lossy zones (`[protection]`, #1570 P4).
837#[derive(Debug, Clone, Serialize, Deserialize)]
838#[serde(default)]
839pub struct ProtectionConfig {
840    /// Glob patterns matched against a call's path-like arguments (`path`,
841    /// `file_path`, `filePath`). A hit exempts the call's output from every
842    /// lossy filter (triage), same standard as `raw=true`. Lossless paths
843    /// (archive + ctx_expand) are unaffected — protection means "never
844    /// lossy", not "never compressed".
845    pub file_patterns: Vec<String>,
846    /// Honor inline `<protect>` spans: any tool output containing the tag
847    /// bypasses lossy line filtering, and history pruning leaves the
848    /// matching tool result verbatim.
849    pub tags: bool,
850}
851
852impl Default for ProtectionConfig {
853    fn default() -> Self {
854        Self {
855            file_patterns: Vec::new(),
856            tags: true,
857        }
858    }
859}
860
861impl ProtectionConfig {
862    /// Whether `path` matches a protected glob. Invalid patterns are ignored.
863    pub fn path_is_protected(&self, path: &str) -> bool {
864        !path.is_empty()
865            && self
866                .file_patterns
867                .iter()
868                .filter_map(|p| glob::Pattern::new(p).ok())
869                .any(|pattern| pattern.matches(path))
870    }
871}
872
873#[cfg(test)]
874mod protection_tests {
875    use super::ProtectionConfig;
876
877    #[test]
878    fn protected_globs_match_paths_and_ignore_invalid_patterns() {
879        let cfg = ProtectionConfig {
880            file_patterns: vec![
881                "docs/audits/**".into(),
882                "*.secret.md".into(),
883                "[invalid".into(),
884            ],
885            tags: true,
886        };
887        assert!(cfg.path_is_protected("docs/audits/q3/blockers.md"));
888        assert!(cfg.path_is_protected("notes.secret.md"));
889        assert!(!cfg.path_is_protected("src/main.rs"));
890        assert!(!cfg.path_is_protected(""));
891
892        let empty = ProtectionConfig::default();
893        assert!(!empty.path_is_protected("docs/audits/q3/blockers.md"));
894        assert!(empty.tags, "protect tags are honored by default");
895    }
896}
897/// MCP decision-loop runtime settings (`[decision_loop]`).
898#[derive(Debug, Clone, Serialize, Deserialize)]
899#[serde(default)]
900pub struct DecisionLoopConfig {
901    pub enabled: bool,
902    /// Maximum lossy post-dispatch triage level (`0` disables output filtering).
903    /// Classification and decision-loop accounting remain active at level 0.
904    #[serde(default)]
905    pub max_filter_level: u8,
906}
907
908impl Default for DecisionLoopConfig {
909    fn default() -> Self {
910        Self {
911            enabled: true,
912            max_filter_level: 0,
913        }
914    }
915}
916
917/// One `[cost.prices.<model>]` row: USD per million tokens. Omitted cache
918/// rates default to the input rate (the same convention the catalogs use).
919#[derive(Debug, Clone, Default, Serialize, Deserialize)]
920#[serde(default)]
921pub struct PriceOverride {
922    pub input_per_m: Option<f64>,
923    pub output_per_m: Option<f64>,
924    pub cache_write_per_m: Option<f64>,
925    pub cache_read_per_m: Option<f64>,
926}
927
928impl CostConfig {
929    /// Configured pricing model for a client id: the per-client entry first, then
930    /// the global default. `None` when neither is set (the caller then falls back
931    /// to the env override / heuristic). Blank entries are ignored.
932    pub fn model_for_client(&self, client: &str) -> Option<String> {
933        self.models
934            .get(client)
935            .or(self.default_model.as_ref())
936            .map(|s| s.trim().to_string())
937            .filter(|s| !s.is_empty())
938    }
939}
940
941/// Decision layer (`[decisions]`): `.leanctx/decisions/*.toml` records.
942///
943/// `enforce` sets what a pre-edit check does when an edit introduces a
944/// violation of an active decision's `[[check]]`: `"hint"` (report, default),
945/// `"refuse"` (strict: the edit is not written) or `"off"` (no pre-edit check;
946/// reads still name decisions in scope).
947#[derive(Debug, Clone, Serialize, Deserialize)]
948#[serde(default)]
949pub struct DecisionsConfig {
950    pub enforce: String,
951}
952
953impl Default for DecisionsConfig {
954    fn default() -> Self {
955        Self {
956            enforce: "hint".to_string(),
957        }
958    }
959}
960
961impl DecisionsConfig {
962    /// `enforce` normalized: `hint` | `refuse` | `off` (unknown → `hint`).
963    pub fn enforce_mode(&self) -> &'static str {
964        match self.enforce.trim().to_ascii_lowercase().as_str() {
965            "refuse" | "strict" | "block" => "refuse",
966            "off" | "false" | "none" => "off",
967            _ => "hint",
968        }
969    }
970}
971
972/// Code-health engine (`[code_health]`): clean code as a token-cost lever.
973///
974/// Cognitive complexity, naming quality, and coupling are computed once during
975/// indexing and surfaced at read- and edit-time. These switches tune the
976/// thresholds and how assertively findings are surfaced.
977#[derive(Debug, Clone, Serialize, Deserialize)]
978#[serde(default)]
979pub struct CodeHealthConfig {
980    /// Cognitive-complexity threshold above which a function is a hotspot.
981    /// Mirrors `core::code_health::DEFAULT_COGNITIVE_THRESHOLD` (15).
982    pub cognitive_threshold: u32,
983    /// Edit-gate behavior on complexity drift: `"warn"` (annotate, default),
984    /// `"block"` (refuse clean→over-threshold edits), or `"off"`.
985    pub gate: String,
986    /// Annotate over-threshold functions inline in `ctx_read` output.
987    pub annotate_reads: bool,
988    /// Run the naming-quality heuristic.
989    pub naming: bool,
990    /// Inject `[CODE HEALTH]` notices as `additionalContext` in PostToolUse stdout.
991    /// Default: **false** — prevents prompt-cache invalidation on Anthropic models
992    /// (#778: each injection causes 440-520k tokens of cache re-bills when Claude
993    /// Code strips stale system-reminders retroactively).
994    /// When false, notices route to `ctx_knowledge` + dashboard instead.
995    #[serde(default)]
996    pub inject_context: bool,
997}
998
999impl Default for CodeHealthConfig {
1000    fn default() -> Self {
1001        Self {
1002            cognitive_threshold: 15,
1003            gate: "warn".to_string(),
1004            annotate_reads: true,
1005            naming: true,
1006            inject_context: false,
1007        }
1008    }
1009}
1010
1011/// Index-time file filters (#735): declare the retrieval corpus explicitly
1012/// instead of abusing `.gitignore` for retrieval policy.
1013///
1014/// Applies to every index builder through one shared filter layer
1015/// (`core::index_filter`): BM25, graph, and the watch/incremental path; the
1016/// semantic index chunks the BM25 corpus and inherits the same universe.
1017/// Excluded files never produce chunks, graph nodes, or embeddings. Globs are
1018/// matched against the root-relative path (forward slashes); exclude wins
1019/// over include. The empty default preserves today's behavior byte-for-byte.
1020#[derive(Debug, Clone, Serialize, Deserialize)]
1021#[serde(default)]
1022pub struct IndexConfig {
1023    /// Honor `.gitignore` / global gitignore / `.git/info/exclude` during
1024    /// index walks. `false` indexes ignored files too (rarely wanted; the
1025    /// vendor-directory guard still applies).
1026    pub respect_gitignore: bool,
1027    /// Files to drop from the index corpus, e.g. `["**/*.csv", "fixtures/**"]`.
1028    /// Evaluated after `include`; a file matching both is excluded.
1029    pub exclude: Vec<String>,
1030    /// When non-empty, ONLY matching files enter the index corpus, e.g.
1031    /// `["**/*.rs", "**/*.ts"]`. Empty = no restriction.
1032    pub include: Vec<String>,
1033}
1034
1035impl Default for IndexConfig {
1036    fn default() -> Self {
1037        Self {
1038            respect_gitignore: true,
1039            exclude: Vec::new(),
1040            include: Vec::new(),
1041        }
1042    }
1043}
1044
1045/// Skillify (#290): mine the project's session diary + knowledge facts into
1046/// versioned, git-committable `.cursor/rules/skillify-*.mdc` rule files.
1047///
1048/// The miner is precision-biased — it only codifies recurring or high-confidence
1049/// patterns and never invents content. Runs on demand (`ctx_skillify` /
1050/// `lean-ctx skillify`); re-running merges (bumps version) only when the distilled
1051/// content actually changes.
1052#[derive(Debug, Clone, Serialize, Deserialize)]
1053#[serde(default)]
1054pub struct SkillifyConfig {
1055    /// Master switch for the skillify miner. On by default; the miner only ever
1056    /// acts when explicitly invoked, so this never writes files unprompted.
1057    pub enabled: bool,
1058    /// Where generated rules are written: `project` (`<repo>/.cursor/rules`,
1059    /// git-committable, default) or `global` (`~/.cursor/rules`).
1060    pub scope: String,
1061    /// Minimum confidence for a single curated knowledge fact to be codified even
1062    /// without repetition. 0.0..=1.0.
1063    pub min_confidence: f32,
1064    /// Minimum number of reinforcements (confirmations / repeated mentions) before
1065    /// a pattern is codified when its confidence is below `min_confidence`.
1066    pub min_recurrence: u32,
1067}
1068
1069impl Default for SkillifyConfig {
1070    fn default() -> Self {
1071        Self {
1072            enabled: true,
1073            scope: "project".to_string(),
1074            min_confidence: 0.7,
1075            min_recurrence: 2,
1076        }
1077    }
1078}
1079
1080/// AI session summaries (#292): periodically distil the working session into a
1081/// compact, *semantically recallable* summary so a future session can answer
1082/// "what did I do last time on X?". Deterministic and local-first — recall uses
1083/// embeddings when the `embeddings` feature is on, else a lexical fallback.
1084#[derive(Debug, Clone, Serialize, Deserialize)]
1085#[serde(default)]
1086pub struct SummariesConfig {
1087    /// Record periodic session summaries. On by default; recording is cheap and
1088    /// happens at most once per `every_n_turns` tool calls.
1089    pub enabled: bool,
1090    /// Tool calls between automatic summaries. The auto-checkpoint cadence still
1091    /// gates the check, so the effective minimum is the checkpoint interval.
1092    pub every_n_turns: u32,
1093    /// Maximum summaries kept per project (oldest pruned first).
1094    pub max_kept: u32,
1095}
1096
1097impl Default for SummariesConfig {
1098    fn default() -> Self {
1099        Self {
1100            enabled: true,
1101            every_n_turns: 25,
1102            max_kept: 100,
1103        }
1104    }
1105}
1106
1107/// A user-defined command alias mapping for shell compression patterns.
1108#[derive(Debug, Clone, Serialize, Deserialize)]
1109pub struct AliasEntry {
1110    pub command: String,
1111    pub alias: String,
1112}
1113
1114/// Thresholds for detecting and throttling repetitive agent tool call loops.
1115#[derive(Debug, Clone, Serialize, Deserialize)]
1116#[serde(default)]
1117pub struct LoopDetectionConfig {
1118    pub normal_threshold: u32,
1119    pub reduced_threshold: u32,
1120    pub blocked_threshold: u32,
1121    pub window_secs: u64,
1122    pub search_group_limit: u32,
1123    pub tool_total_limits: HashMap<String, u32>,
1124}
1125
1126impl Default for LoopDetectionConfig {
1127    fn default() -> Self {
1128        let mut tool_total_limits = HashMap::new();
1129        tool_total_limits.insert("ctx_read".to_string(), 100);
1130        tool_total_limits.insert("ctx_search".to_string(), 80);
1131        tool_total_limits.insert("ctx_shell".to_string(), 50);
1132        Self {
1133            normal_threshold: 2,
1134            reduced_threshold: 4,
1135            blocked_threshold: 0,
1136            window_secs: 300,
1137            search_group_limit: 10,
1138            tool_total_limits,
1139        }
1140    }
1141}
1142
1143/// Semantic-embedding engine settings.
1144///
1145/// `model` selects which local embedding model lean-ctx downloads and uses for
1146/// `ctx_semantic_search`. Unset, it is `minilm` where ONNX Runtime is installed and
1147/// `potion-code` otherwise (see `model_registry::default_model`). Accepts the same
1148/// aliases as the `LEAN_CTX_EMBEDDING_MODEL` env var: `minilm` (all-MiniLM-L6-v2,
1149/// 384d), `potion-code` (potion-code-16M, 256d static, pure Rust), `nomic` (768d) — or any
1150/// HuggingFace repo with an ONNX export via `hf:org/repo[@revision]` (GL #397), e.g.
1151/// `hf:jinaai/jina-embeddings-v2-base-code` for code-specialized embeddings. When the
1152/// env var is set it takes precedence; an
1153/// unset/`None` value uses the default model. Switching models triggers a one-time
1154/// re-index on the next semantic search (vector dimensions follow from the model).
1155///
1156/// `dimensions` is only consulted for `hf:` custom models as the declared fallback
1157/// width; the real width is probed from the ONNX graph at load time. Built-ins ignore it.
1158/// `[gateway_server]` — deployment parameters of the self-hosted org gateway
1159/// (enterprise#20). Distinct from `[gateway]` (the MCP tool-catalog gateway):
1160/// this section describes the LLM-proxy *server* deployment and its cockpit.
1161///
1162/// All fields optional; an empty section keeps every local behavior unchanged.
1163#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1164#[serde(default)]
1165pub struct GatewayServerConfig {
1166    /// Seats the org-wide projection extrapolates to (e.g. `800`). `None`
1167    /// disables the projection — the cockpit never invents a seat count.
1168    #[serde(default, skip_serializing_if = "Option::is_none")]
1169    pub seats: Option<u32>,
1170    /// Display label for the cockpit header (e.g. `"Zühlke AI Gateway"`).
1171    #[serde(default, skip_serializing_if = "Option::is_none")]
1172    pub org_label: Option<String>,
1173    /// Central admin API base URL (e.g. `https://ai-gateway.example.com`).
1174    /// When set, the local cockpit's usage breakdown reads the org-wide
1175    /// `GET /api/admin/usage` instead of the machine-local snapshot. The
1176    /// bearer token comes from `LEAN_CTX_GATEWAY_ADMIN_TOKEN` (never config).
1177    #[serde(default, skip_serializing_if = "Option::is_none")]
1178    pub admin_url: Option<String>,
1179    /// Replace `person` with a stable keyed pseudonym (`p:<hash>`) before it
1180    /// reaches metering, budgets, dashboards and logs (enterprise#39, GDPR).
1181    /// The salt lives in `<data_dir>/gateway_pii_salt`; `gateway gdpr`
1182    /// re-derives pseudonyms from e-mail input, so DSGVO delete/export keep
1183    /// working. Default `false` (cleartext person tags).
1184    #[serde(default, skip_serializing_if = "Option::is_none")]
1185    pub pseudonymize_persons: Option<bool>,
1186    /// MCP upstream registry (GL#91/#99, Doc 15 §7 — the observe stage of MCP
1187    /// context governance). Each entry publishes a governed reverse-proxy
1188    /// route `/mcp/{id}` on the enterprise gateway server's port (the local
1189    /// proxy mounts no `/mcp/{id}` routes): same per-person key auth as the
1190    /// LLM channel, tool calls metered into `mcp_events`, tool definitions
1191    /// inventoried + hash-tracked (rug-pull detection). Observe-only: the
1192    /// gateway never blocks or rewrites MCP traffic in this stage.
1193    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1194    pub mcp_servers: Vec<McpServerEntry>,
1195}
1196
1197/// One `[[gateway_server.mcp_servers]]` registry entry — an MCP server the org
1198/// gateway fronts. Distinct from `[[gateway.servers]]` (the *local* tool-
1199/// catalog aggregator, #210): this registry is the org-facing reverse proxy.
1200#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
1201pub struct McpServerEntry {
1202    /// Registry id, used in the `/mcp/{id}` route. Lowercase alphanumeric
1203    /// plus `-`/`_` (it becomes a URL path segment).
1204    pub id: String,
1205    /// Upstream Streamable-HTTP endpoint (the server's single MCP endpoint,
1206    /// e.g. `https://mcp.example.com/mcp`). HTTPS for any non-loopback host;
1207    /// plaintext HTTP needs the same explicit opt-in as LLM upstreams
1208    /// (`[proxy] allow_insecure_http_upstream`).
1209    pub url: String,
1210    /// Name of the environment variable holding the upstream credential. When
1211    /// set, the gateway sends `Authorization: Bearer <value>` upstream — the
1212    /// credential lives in the gateway's environment, never on laptops. The
1213    /// caller's own `Authorization` header (their gateway key) is **always**
1214    /// stripped before forwarding, with or without this field.
1215    #[serde(default, skip_serializing_if = "Option::is_none")]
1216    pub auth_env: Option<String>,
1217    /// Set `false` to keep the entry in config but take it out of service.
1218    #[serde(default, skip_serializing_if = "Option::is_none")]
1219    pub enabled: Option<bool>,
1220}
1221
1222/// A validated, ready-to-serve MCP registry entry (runtime view of
1223/// [`McpServerEntry`]).
1224#[derive(Debug, Clone, PartialEq, Eq)]
1225pub struct ResolvedMcpServer {
1226    pub id: String,
1227    pub url: String,
1228    pub auth_env: Option<String>,
1229}
1230
1231impl GatewayServerConfig {
1232    /// Validate + resolve the `[[gateway_server.mcp_servers]]` registry.
1233    /// Same resilience contract as `[[proxy.providers]]`: invalid entries are
1234    /// logged and skipped (one typo never takes the gateway down), duplicates
1235    /// keep the first occurrence. `allow_insecure_http` mirrors the proxy's
1236    /// plaintext-HTTP opt-in so the two registries share one security posture.
1237    #[must_use]
1238    pub fn resolve_mcp_servers(&self, allow_insecure_http: bool) -> Vec<ResolvedMcpServer> {
1239        let mut seen: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
1240        let mut out = Vec::new();
1241        for entry in &self.mcp_servers {
1242            if !entry.enabled.unwrap_or(true) {
1243                continue;
1244            }
1245            let id = entry.id.trim();
1246            if !is_valid_mcp_server_id(id) {
1247                tracing::warn!(
1248                    "[gateway_server.mcp_servers] invalid id '{id}' \
1249                     (lowercase alnum/-/_ only) — entry skipped"
1250                );
1251                continue;
1252            }
1253            if !seen.insert(id) {
1254                tracing::warn!(
1255                    "[gateway_server.mcp_servers] duplicate id '{id}' — keeping first entry"
1256                );
1257                continue;
1258            }
1259            match validate_mcp_upstream_url(&entry.url, allow_insecure_http) {
1260                Ok(url) => out.push(ResolvedMcpServer {
1261                    id: id.to_string(),
1262                    url,
1263                    auth_env: entry
1264                        .auth_env
1265                        .as_deref()
1266                        .map(str::trim)
1267                        .filter(|v| !v.is_empty())
1268                        .map(str::to_string),
1269                }),
1270                Err(e) => {
1271                    tracing::warn!(
1272                        "[gateway_server.mcp_servers] '{id}' has invalid url — skipped: {e}"
1273                    );
1274                }
1275            }
1276        }
1277        out
1278    }
1279}
1280
1281/// True when `id` is usable as an MCP registry id: non-empty, lowercase alnum
1282/// plus `-`/`_` (it becomes a URL path segment). Same shape rule as
1283/// `[[proxy.providers]]` ids; no built-in namespace exists to shadow here.
1284fn is_valid_mcp_server_id(id: &str) -> bool {
1285    !id.is_empty()
1286        && id
1287            .chars()
1288            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
1289}
1290
1291/// Validates an MCP upstream URL. A declared registry entry is itself the
1292/// deliberate custom-host opt-in (same rationale as `[[proxy.providers]]`):
1293/// any HTTPS host is accepted; loopback HTTP is always fine; non-loopback
1294/// plaintext HTTP requires the explicit insecure-HTTP opt-in. This is the
1295/// SSRF boundary — the proxy only ever connects to URLs that passed here.
1296fn validate_mcp_upstream_url(url: &str, allow_insecure_http: bool) -> Result<String, String> {
1297    let trimmed = url.trim().trim_end_matches('/');
1298    if trimmed.is_empty() {
1299        return Err("empty url".into());
1300    }
1301    if crate::core::config::is_local_proxy_url(trimmed) {
1302        return Ok(trimmed.to_string());
1303    }
1304    if trimmed.starts_with("http://") {
1305        if allow_insecure_http {
1306            return Ok(trimmed.to_string());
1307        }
1308        return Err(format!(
1309            "MCP upstream must use HTTPS: {trimmed} (for a trusted local-network HTTP \
1310             upstream opt in with `[proxy] allow_insecure_http_upstream = true`)"
1311        ));
1312    }
1313    if trimmed.starts_with("https://") {
1314        return Ok(trimmed.to_string());
1315    }
1316    Err(format!(
1317        "MCP upstream must start with http:// or https://: {trimmed}"
1318    ))
1319}
1320
1321#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1322#[serde(default)]
1323pub struct EmbeddingConfig {
1324    #[serde(default, skip_serializing_if = "Option::is_none")]
1325    pub model: Option<String>,
1326    #[serde(default, skip_serializing_if = "Option::is_none")]
1327    pub dimensions: Option<usize>,
1328    /// Allow downloading the embedding model on first semantic need (#551).
1329    /// `None` (unset) means **allowed** — the soft default that activates the
1330    /// semantic features without manual setup. Set `false` for air-gapped
1331    /// machines. The `LEAN_CTX_EMBEDDINGS_AUTO_DOWNLOAD` env var, when set,
1332    /// overrides this in either direction.
1333    #[serde(default, skip_serializing_if = "Option::is_none")]
1334    pub auto_download: Option<bool>,
1335    /// Pin embedding inference to a single CPU thread (no GPU EP) so vectors are
1336    /// bit-identical across machines, not just run-to-run on one host (#895).
1337    /// `None`/`false` keeps the multi-threaded GPU-capable path. Extractive prose
1338    /// ranking is already deterministic via score quantization + stable tiebreak;
1339    /// this flag is the extra hardening for cross-machine reproducibility. The
1340    /// `LEAN_CTX_EMBEDDING_DETERMINISTIC` env var overrides this either way.
1341    #[serde(default, skip_serializing_if = "Option::is_none")]
1342    pub deterministic: Option<bool>,
1343}
1344
1345#[cfg(test)]
1346#[path = "sections_tests.rs"]
1347mod gateway_server_tests;
1348
1349#[cfg(test)]
1350mod ocla_tests {
1351    use super::OclaConfig;
1352    use serde::Deserialize;
1353
1354    #[derive(Deserialize)]
1355    struct ConfigFile {
1356        ocla: OclaConfig,
1357    }
1358
1359    /// Configs written for the removed sidecar/gRPC listeners keep loading.
1360    #[test]
1361    fn removed_listener_sections_are_ignored() {
1362        let config: ConfigFile = toml::from_str(
1363            r#"
1364                [ocla.sidecar]
1365                bind_addr = "127.0.0.1:9000"
1366                enabled = true
1367                [ocla.grpc]
1368                enabled = true
1369                listen = "127.0.0.1:60051"
1370                [ocla.delivery]
1371                max_entries = 7
1372            "#,
1373        )
1374        .expect("legacy OCLA config");
1375        assert_eq!(config.ocla.delivery.max_entries, 7);
1376        assert!(config.ocla.delivery.enabled);
1377    }
1378}
1379
1380#[cfg(test)]
1381mod telemetry_tests {
1382    use super::*;
1383
1384    #[test]
1385    fn telemetry_config_defaults_on_and_send_eligible() {
1386        let cfg = TelemetryConfig::default();
1387        assert!(cfg.enabled);
1388        assert_eq!(cfg.preference, TelemetryPreference::DefaultOn);
1389        assert!(cfg.send_eligible(None, None));
1390        assert!(cfg.last_heartbeat.is_none());
1391    }
1392
1393    #[test]
1394    fn telemetry_config_serde_roundtrip() {
1395        let toml_str = r#"
1396[telemetry]
1397enabled = true
1398last_heartbeat = "2026-07-30"
1399"#;
1400        #[derive(serde::Deserialize)]
1401        struct Wrap {
1402            telemetry: TelemetryConfig,
1403        }
1404        let wrap: Wrap = toml::from_str(toml_str).expect("parse telemetry config");
1405        assert!(wrap.telemetry.enabled);
1406        assert_eq!(wrap.telemetry.preference, TelemetryPreference::DefaultOn);
1407        assert_eq!(wrap.telemetry.last_heartbeat.as_deref(), Some("2026-07-30"));
1408    }
1409
1410    #[test]
1411    fn a_retired_notice_key_in_an_existing_config_still_parses() {
1412        let cfg: TelemetryConfig =
1413            toml::from_str("enabled = true\nnotice_shown = false").expect("pre-removal config");
1414        assert!(cfg.send_eligible(None, None));
1415    }
1416
1417    #[test]
1418    fn telemetry_config_missing_section_uses_defaults() {
1419        let toml_str = "";
1420        #[derive(serde::Deserialize, Default)]
1421        #[serde(default)]
1422        struct Wrap {
1423            telemetry: TelemetryConfig,
1424        }
1425        let wrap: Wrap = toml::from_str(toml_str).expect("parse empty config");
1426        assert!(wrap.telemetry.enabled);
1427        assert_eq!(wrap.telemetry.preference, TelemetryPreference::DefaultOn);
1428        assert!(wrap.telemetry.last_heartbeat.is_none());
1429    }
1430
1431    #[test]
1432    fn legacy_false_remains_an_explicit_opt_out() {
1433        let cfg: TelemetryConfig = toml::from_str("enabled = false").expect("legacy config");
1434        assert!(cfg.explicitly_disabled());
1435    }
1436
1437    #[test]
1438    fn send_honors_the_explicit_and_both_environment_opt_outs() {
1439        let mut cfg = TelemetryConfig::default();
1440        assert!(cfg.send_eligible(None, None));
1441        assert!(!cfg.send_eligible(Some("1"), None));
1442        assert!(!cfg.send_eligible(None, Some("OFF")));
1443        cfg.preference = TelemetryPreference::ExplicitlyDisabled;
1444        assert!(!cfg.send_eligible(None, None));
1445    }
1446}