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