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