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