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