Skip to main content

lean_ctx/core/config/
sections.rs

1//! Auxiliary configuration section structs.
2//!
3//! Nested config structs (secret-detection, setup, archive, providers,
4//! autonomy, updates, cloud, gain, loop-detection, embedding, …) split out of
5//! `config/mod.rs` to keep the top-level module focused on `Config` itself.
6//! Re-exported via `pub use sections::*`, so external paths stay stable.
7
8use super::serde_defaults;
9#[allow(clippy::wildcard_imports)]
10use super::*;
11use serde::{Deserialize, Serialize};
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
14#[serde(default)]
15pub struct SecretDetectionConfig {
16    pub enabled: bool,
17    pub redact: bool,
18    pub custom_patterns: Vec<String>,
19}
20
21/// Controls what lean-ctx injects during `setup` and `update --rewire`.
22/// Fresh installs default to non-invasive (rules/skills off, MCP on).
23/// Users who ran setup interactively get explicit true/false.
24/// `None` = undecided (legacy: check if rules already exist and preserve behavior).
25#[derive(Debug, Clone, Serialize, Deserialize)]
26#[serde(default)]
27pub struct SetupConfig {
28    /// Inject agent rule files (CLAUDE.md, .cursor/rules/, etc.).
29    /// None = undecided (legacy compat: inject if rules already present).
30    /// Some(true) = always inject. Some(false) = never inject.
31    pub auto_inject_rules: Option<bool>,
32    /// Install SKILL.md files for supported agents.
33    /// None = undecided. Some(true) = install. Some(false) = skip.
34    pub auto_inject_skills: Option<bool>,
35    /// Register lean-ctx as an MCP server in editor configs.
36    #[serde(default = "serde_defaults::default_true")]
37    pub auto_update_mcp: bool,
38}
39
40impl Default for SetupConfig {
41    fn default() -> Self {
42        Self {
43            auto_inject_rules: None,
44            auto_inject_skills: None,
45            auto_update_mcp: true,
46        }
47    }
48}
49
50impl SetupConfig {
51    /// Returns whether rules should be injected, considering legacy installs.
52    /// If undecided (None), checks if lean-ctx rules markers already exist
53    /// in any agent config — if so, keeps injecting for backward compat.
54    pub fn should_inject_rules(&self) -> bool {
55        match self.auto_inject_rules {
56            Some(v) => v,
57            None => Self::rules_already_present(),
58        }
59    }
60
61    /// Returns whether skills should be installed.
62    pub fn should_inject_skills(&self) -> bool {
63        match self.auto_inject_skills {
64            Some(v) => v,
65            None => Self::rules_already_present(),
66        }
67    }
68
69    /// Returns whether `setup`/`onboard`/`init` may (re)register the lean-ctx
70    /// MCP server in editor configs. Honors `auto_update_mcp` (#281) so locked-
71    /// down environments can keep MCP out of agent settings while still getting
72    /// hooks, rules and skills.
73    pub fn should_update_mcp(&self) -> bool {
74        self.auto_update_mcp
75    }
76
77    /// Check if lean-ctx rules markers exist in any known agent config location.
78    ///
79    /// Delegates the per-agent path catalog to `rules_inject::any_rules_marker_present`
80    /// (derived from the injector's own target list) so this never drifts behind
81    /// newly supported agents again (#442). Claude Code and CodeBuddy have no
82    /// rules *target* (they auto-load an inline block instead), so their legacy
83    /// rule files are checked separately to keep honoring older installs.
84    fn rules_already_present() -> bool {
85        let Some(home) = dirs::home_dir() else {
86            return false;
87        };
88        if crate::rules_inject::any_rules_marker_present(&home) {
89            return true;
90        }
91        let marker = crate::rules_inject::RULES_MARKER;
92        let legacy_paths = [
93            crate::core::editor_registry::claude_rules_dir(&home).join("lean-ctx.md"),
94            crate::core::editor_registry::codebuddy_rules_dir(&home).join("lean-ctx.md"),
95        ];
96        legacy_paths
97            .iter()
98            .any(|p| std::fs::read_to_string(p).is_ok_and(|c| c.contains(marker)))
99    }
100}
101
102impl Default for SecretDetectionConfig {
103    fn default() -> Self {
104        Self {
105            enabled: true,
106            redact: true,
107            custom_patterns: Vec::new(),
108        }
109    }
110}
111
112/// Settings for the zero-loss compression archive (large tool outputs saved to disk).
113#[derive(Debug, Clone, Serialize, Deserialize)]
114#[serde(default)]
115pub struct ArchiveConfig {
116    pub enabled: bool,
117    pub threshold_chars: usize,
118    pub max_age_hours: u64,
119    pub max_disk_mb: u64,
120    pub ephemeral: bool,
121    /// Minimum output tokens before the ephemeral firewall replaces an inline tool
122    /// result with a summary + retrieval ref. Outputs below this stay fully inline.
123    pub ephemeral_min_tokens: usize,
124}
125
126impl Default for ArchiveConfig {
127    fn default() -> Self {
128        Self {
129            enabled: true,
130            threshold_chars: 800,
131            max_age_hours: 48,
132            max_disk_mb: 500,
133            ephemeral: true,
134            ephemeral_min_tokens: 2000,
135        }
136    }
137}
138
139impl ArchiveConfig {
140    pub fn ephemeral_effective(&self) -> bool {
141        if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL") {
142            return !matches!(v.trim(), "0" | "false" | "off");
143        }
144        self.ephemeral && self.enabled
145    }
146
147    pub fn ephemeral_min_tokens_effective(&self) -> usize {
148        if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL_MIN_TOKENS")
149            && let Ok(n) = v.trim().parse::<usize>()
150        {
151            return n;
152        }
153        self.ephemeral_min_tokens
154    }
155}
156
157/// Configuration for external context providers (GitHub, GitLab, Jira, etc.).
158/// Each provider can be enabled/disabled and configured with auth tokens.
159/// Override individual tokens via env vars (GITHUB_TOKEN, GITLAB_TOKEN, etc.).
160#[derive(Debug, Clone, Serialize, Deserialize)]
161#[serde(default)]
162pub struct ProvidersConfig {
163    /// Master switch for the provider subsystem.
164    pub enabled: bool,
165    /// GitHub provider configuration.
166    pub github: ProviderEntryConfig,
167    /// GitLab provider configuration.
168    pub gitlab: ProviderEntryConfig,
169    /// Auto-ingest provider results into BM25/embedding indexes.
170    pub auto_index: bool,
171    /// Default cache TTL for provider results (seconds).
172    pub cache_ttl_secs: u64,
173    /// MCP Bridge providers: `{ "name" = { url = "...", description = "..." } }`.
174    #[serde(default)]
175    pub mcp_bridges: std::collections::HashMap<String, McpBridgeEntry>,
176}
177
178impl Default for ProvidersConfig {
179    fn default() -> Self {
180        Self {
181            enabled: true,
182            github: ProviderEntryConfig::default(),
183            gitlab: ProviderEntryConfig::default(),
184            auto_index: true,
185            cache_ttl_secs: 120,
186            mcp_bridges: std::collections::HashMap::new(),
187        }
188    }
189}
190
191#[derive(Debug, Clone, Serialize, Deserialize)]
192pub struct McpBridgeEntry {
193    /// HTTP/SSE URL for remote MCP servers.
194    #[serde(default)]
195    pub url: Option<String>,
196    /// Command to spawn a local MCP server (stdio transport).
197    #[serde(default)]
198    pub command: Option<String>,
199    /// Arguments for the command.
200    #[serde(default)]
201    pub args: Vec<String>,
202    /// Human-readable description.
203    #[serde(default)]
204    pub description: Option<String>,
205    /// Environment variable name containing an auth token.
206    #[serde(default)]
207    pub auth_env: Option<String>,
208}
209
210/// Per-provider configuration entry.
211#[derive(Debug, Clone, Serialize, Deserialize)]
212#[serde(default)]
213pub struct ProviderEntryConfig {
214    /// Whether this specific provider is enabled.
215    pub enabled: bool,
216    /// Auth token (prefer env var; only use this for project-local overrides).
217    pub token: Option<String>,
218    /// API base URL override (for GitHub Enterprise, self-hosted GitLab, etc.).
219    pub api_url: Option<String>,
220    /// Default project/repo for this provider (auto-detected from git remote if empty).
221    pub project: Option<String>,
222}
223
224impl Default for ProviderEntryConfig {
225    fn default() -> Self {
226        Self {
227            enabled: true,
228            token: None,
229            api_url: None,
230            project: None,
231        }
232    }
233}
234
235/// Controls autonomous background behaviors (preload, dedup, consolidation).
236#[derive(Debug, Clone, Serialize, Deserialize)]
237#[serde(default)]
238pub struct AutonomyConfig {
239    pub enabled: bool,
240    pub auto_preload: bool,
241    pub auto_dedup: bool,
242    pub auto_related: bool,
243    pub auto_consolidate: bool,
244    pub silent_preload: bool,
245    pub dedup_threshold: usize,
246    pub consolidate_every_calls: u32,
247    pub consolidate_cooldown_secs: u64,
248    #[serde(default = "serde_defaults::default_true")]
249    pub cognition_loop_enabled: bool,
250    #[serde(default = "serde_defaults::default_cognition_loop_interval")]
251    pub cognition_loop_interval_secs: u64,
252    #[serde(default = "serde_defaults::default_cognition_loop_max_steps")]
253    pub cognition_loop_max_steps: u8,
254}
255
256impl Default for AutonomyConfig {
257    fn default() -> Self {
258        Self {
259            enabled: true,
260            auto_preload: true,
261            auto_dedup: true,
262            auto_related: true,
263            auto_consolidate: true,
264            silent_preload: true,
265            dedup_threshold: 8,
266            consolidate_every_calls: 25,
267            consolidate_cooldown_secs: 120,
268            cognition_loop_enabled: true,
269            cognition_loop_interval_secs: 3600,
270            cognition_loop_max_steps: 8,
271        }
272    }
273}
274
275/// Controls automatic update behavior. All defaults are OFF — auto-updates
276/// require explicit opt-in via `lean-ctx setup` or `lean-ctx update --schedule`.
277#[derive(Debug, Clone, Serialize, Deserialize)]
278#[serde(default)]
279pub struct UpdatesConfig {
280    pub auto_update: bool,
281    pub check_interval_hours: u64,
282    pub notify_only: bool,
283}
284
285impl Default for UpdatesConfig {
286    fn default() -> Self {
287        Self {
288            auto_update: false,
289            check_interval_hours: 6,
290            notify_only: false,
291        }
292    }
293}
294
295impl UpdatesConfig {
296    pub fn from_env() -> Self {
297        let mut cfg = Self::default();
298        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_UPDATE") {
299            cfg.auto_update = v == "1" || v.eq_ignore_ascii_case("true");
300        }
301        if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_INTERVAL_HOURS")
302            && let Ok(h) = v.parse::<u64>()
303        {
304            cfg.check_interval_hours = h.clamp(1, 168);
305        }
306        if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_NOTIFY_ONLY") {
307            cfg.notify_only = v == "1" || v.eq_ignore_ascii_case("true");
308        }
309        cfg
310    }
311}
312
313impl AutonomyConfig {
314    /// Creates an autonomy config from env vars, falling back to defaults.
315    pub fn from_env() -> Self {
316        let mut cfg = Self::default();
317        if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
318            && (v == "false" || v == "0")
319        {
320            cfg.enabled = false;
321        }
322        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
323            cfg.auto_preload = v != "false" && v != "0";
324        }
325        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
326            cfg.auto_dedup = v != "false" && v != "0";
327        }
328        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
329            cfg.auto_related = v != "false" && v != "0";
330        }
331        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_CONSOLIDATE") {
332            cfg.auto_consolidate = v != "false" && v != "0";
333        }
334        if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
335            cfg.silent_preload = v != "false" && v != "0";
336        }
337        if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD")
338            && let Ok(n) = v.parse()
339        {
340            cfg.dedup_threshold = n;
341        }
342        if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_EVERY_CALLS")
343            && let Ok(n) = v.parse()
344        {
345            cfg.consolidate_every_calls = n;
346        }
347        if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_COOLDOWN_SECS")
348            && let Ok(n) = v.parse()
349        {
350            cfg.consolidate_cooldown_secs = n;
351        }
352        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
353            cfg.cognition_loop_enabled = v != "false" && v != "0";
354        }
355        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
356            && let Ok(n) = v.parse()
357        {
358            cfg.cognition_loop_interval_secs = n;
359        }
360        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
361            && let Ok(n) = v.parse()
362        {
363            cfg.cognition_loop_max_steps = n;
364        }
365        cfg
366    }
367
368    /// Loads autonomy config from disk, with env var overrides applied.
369    pub fn load() -> Self {
370        let file_cfg = Config::load().autonomy;
371        let mut cfg = file_cfg;
372        if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
373            && (v == "false" || v == "0")
374        {
375            cfg.enabled = false;
376        }
377        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_PRELOAD") {
378            cfg.auto_preload = v != "false" && v != "0";
379        }
380        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_DEDUP") {
381            cfg.auto_dedup = v != "false" && v != "0";
382        }
383        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_RELATED") {
384            cfg.auto_related = v != "false" && v != "0";
385        }
386        if let Ok(v) = std::env::var("LEAN_CTX_SILENT_PRELOAD") {
387            cfg.silent_preload = v != "false" && v != "0";
388        }
389        if let Ok(v) = std::env::var("LEAN_CTX_DEDUP_THRESHOLD")
390            && let Ok(n) = v.parse()
391        {
392            cfg.dedup_threshold = n;
393        }
394        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
395            cfg.cognition_loop_enabled = v != "false" && v != "0";
396        }
397        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
398            && let Ok(n) = v.parse()
399        {
400            cfg.cognition_loop_interval_secs = n;
401        }
402        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
403            && let Ok(n) = v.parse()
404        {
405            cfg.cognition_loop_max_steps = n;
406        }
407        cfg
408    }
409}
410
411/// Cloud sync and contribution settings (pattern sharing, model pulls).
412#[derive(Debug, Clone, Serialize, Deserialize, Default)]
413#[serde(default)]
414pub struct CloudConfig {
415    pub contribute_enabled: bool,
416    pub last_contribute: Option<String>,
417    pub last_sync: Option<String>,
418    pub last_gain_sync: Option<String>,
419    pub last_model_pull: Option<String>,
420    /// Auto-push the Pro Personal-Cloud surfaces (knowledge, commands, CEP,
421    /// gotchas, buddy, feedback) from the background task — opt-in, once per
422    /// day, offline-tolerant (GL #384). Toggle: `lean-ctx cloud autosync on`.
423    pub auto_sync: bool,
424    pub last_auto_sync: Option<String>,
425    /// Auto-push the project's encrypted retrieval-index bundle (hosted
426    /// Personal Index, GL #392) alongside the daily auto-sync — separate
427    /// opt-in because index bundles are orders of magnitude larger than the
428    /// other surfaces. Toggle: `lean-ctx cloud autoindex on`.
429    pub auto_index: bool,
430    /// Per-project debounce: `project_hash → YYYY-MM-DD` of the last
431    /// successful background index push.
432    pub last_index_push: std::collections::HashMap<String, String>,
433}
434
435/// Settings for publishing your token-savings recap (`gain --publish` / auto-publish).
436///
437/// Publishing is always opt-in: it sends a small, whitelisted *aggregate* payload (tokens
438/// saved, $ avoided, compression % — never code, paths or counts) to the cloud.
439/// `auto_publish` simply removes the need to re-run `gain --publish` by hand; it stays off
440/// until the user explicitly enables it.
441#[derive(Debug, Clone, Serialize, Deserialize)]
442#[serde(default)]
443pub struct GainConfig {
444    /// When true, `lean-ctx gain` automatically (re)publishes the recap, throttled to
445    /// `auto_publish_interval_hours`. Off by default.
446    pub auto_publish: bool,
447    /// When auto-publishing, also opt into the public leaderboard.
448    pub leaderboard: bool,
449    /// Optional display name for the published card / leaderboard entry.
450    pub display_name: Option<String>,
451    /// Minimum hours between automatic publishes (throttle).
452    pub auto_publish_interval_hours: u64,
453    /// Runtime state — RFC3339 timestamp of the last automatic publish. Managed by the
454    /// tool, not meant to be set by hand.
455    pub last_auto_publish: Option<String>,
456}
457
458impl Default for GainConfig {
459    fn default() -> Self {
460        Self {
461            auto_publish: false,
462            leaderboard: true,
463            display_name: None,
464            auto_publish_interval_hours: 24,
465            last_auto_publish: None,
466        }
467    }
468}
469
470/// Model declaration for **measured-vs-estimated** cost reporting.
471///
472/// Proxy-routed clients (Claude Code, Codex, Pi, Gemini CLI, OpenCode) report
473/// their real model and billed tokens, so lean-ctx prices them *measured* with
474/// no configuration. MCP-only IDEs (Cursor, Copilot, Windsurf, VS Code, Zed)
475/// send their LLM traffic straight to the provider, bypassing lean-ctx — their
476/// real model is invisible. Declaring it here lets those *estimated* turns be
477/// priced with the correct model instead of a blended fallback.
478#[derive(Debug, Clone, Default, Serialize, Deserialize)]
479#[serde(default)]
480pub struct CostConfig {
481    /// Fallback pricing model for any client without a per-client entry.
482    /// Unset/empty → lean-ctx keeps its blended heuristic.
483    #[serde(default, skip_serializing_if = "Option::is_none")]
484    pub default_model: Option<String>,
485    /// Per-client pricing model, keyed by client id (`cursor`, `copilot`,
486    /// `windsurf`, `claude`, `codex`, …). Used for MCP-only IDEs whose real
487    /// model lean-ctx cannot observe. Example:
488    /// `[cost.models]` then `cursor = "claude-opus-4.5"`.
489    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
490    pub models: HashMap<String, String>,
491}
492
493impl CostConfig {
494    /// Configured pricing model for a client id: the per-client entry first, then
495    /// the global default. `None` when neither is set (the caller then falls back
496    /// to the env override / heuristic). Blank entries are ignored.
497    pub fn model_for_client(&self, client: &str) -> Option<String> {
498        self.models
499            .get(client)
500            .or(self.default_model.as_ref())
501            .map(|s| s.trim().to_string())
502            .filter(|s| !s.is_empty())
503    }
504}
505
506/// Settings for the code graph — in particular the *traversal* (co-access) edges
507/// learned from real agent sessions (#289).
508///
509/// The static AST/import graph captures how code is wired structurally; it cannot
510/// see which files an agent actually opens *together* while solving a task.
511/// Traversal edges add that behavioural signal: files surfaced together are
512/// associated with a decaying weight (Hebbian co-access), folded into the graph
513/// as `co_access` edges and mixed into recall. The store is bounded and decays,
514/// so stale associations fade.
515#[derive(Debug, Clone, Serialize, Deserialize)]
516#[serde(default)]
517pub struct GraphConfig {
518    /// Record co-access between files surfaced together in a session, surface them
519    /// as decaying `co_access` edges in the graph, and boost recall by them.
520    /// On by default; set to `false` for a purely static (AST-only) graph.
521    pub traversal_edges: bool,
522}
523
524impl Default for GraphConfig {
525    fn default() -> Self {
526        Self {
527            traversal_edges: true,
528        }
529    }
530}
531
532/// Skillify (#290): mine the project's session diary + knowledge facts into
533/// versioned, git-committable `.cursor/rules/skillify-*.mdc` rule files.
534///
535/// The miner is precision-biased — it only codifies recurring or high-confidence
536/// patterns and never invents content. Runs on demand (`ctx_skillify` /
537/// `lean-ctx skillify`); re-running merges (bumps version) only when the distilled
538/// content actually changes.
539#[derive(Debug, Clone, Serialize, Deserialize)]
540#[serde(default)]
541pub struct SkillifyConfig {
542    /// Master switch for the skillify miner. On by default; the miner only ever
543    /// acts when explicitly invoked, so this never writes files unprompted.
544    pub enabled: bool,
545    /// Where generated rules are written: `project` (`<repo>/.cursor/rules`,
546    /// git-committable, default) or `global` (`~/.cursor/rules`).
547    pub scope: String,
548    /// Minimum confidence for a single curated knowledge fact to be codified even
549    /// without repetition. 0.0..=1.0.
550    pub min_confidence: f32,
551    /// Minimum number of reinforcements (confirmations / repeated mentions) before
552    /// a pattern is codified when its confidence is below `min_confidence`.
553    pub min_recurrence: u32,
554}
555
556impl Default for SkillifyConfig {
557    fn default() -> Self {
558        Self {
559            enabled: true,
560            scope: "project".to_string(),
561            min_confidence: 0.7,
562            min_recurrence: 2,
563        }
564    }
565}
566
567/// AI session summaries (#292): periodically distil the working session into a
568/// compact, *semantically recallable* summary so a future session can answer
569/// "what did I do last time on X?". Deterministic and local-first — recall uses
570/// embeddings when the `embeddings` feature is on, else a lexical fallback.
571#[derive(Debug, Clone, Serialize, Deserialize)]
572#[serde(default)]
573pub struct SummariesConfig {
574    /// Record periodic session summaries. On by default; recording is cheap and
575    /// happens at most once per `every_n_turns` tool calls.
576    pub enabled: bool,
577    /// Tool calls between automatic summaries. The auto-checkpoint cadence still
578    /// gates the check, so the effective minimum is the checkpoint interval.
579    pub every_n_turns: u32,
580    /// Maximum summaries kept per project (oldest pruned first).
581    pub max_kept: u32,
582}
583
584impl Default for SummariesConfig {
585    fn default() -> Self {
586        Self {
587            enabled: true,
588            every_n_turns: 25,
589            max_kept: 100,
590        }
591    }
592}
593
594/// A user-defined command alias mapping for shell compression patterns.
595#[derive(Debug, Clone, Serialize, Deserialize)]
596pub struct AliasEntry {
597    pub command: String,
598    pub alias: String,
599}
600
601/// Thresholds for detecting and throttling repetitive agent tool call loops.
602#[derive(Debug, Clone, Serialize, Deserialize)]
603#[serde(default)]
604pub struct LoopDetectionConfig {
605    pub normal_threshold: u32,
606    pub reduced_threshold: u32,
607    pub blocked_threshold: u32,
608    pub window_secs: u64,
609    pub search_group_limit: u32,
610    pub tool_total_limits: HashMap<String, u32>,
611}
612
613impl Default for LoopDetectionConfig {
614    fn default() -> Self {
615        let mut tool_total_limits = HashMap::new();
616        tool_total_limits.insert("ctx_read".to_string(), 100);
617        tool_total_limits.insert("ctx_search".to_string(), 80);
618        tool_total_limits.insert("ctx_shell".to_string(), 50);
619        tool_total_limits.insert("ctx_semantic_search".to_string(), 60);
620        Self {
621            normal_threshold: 2,
622            reduced_threshold: 4,
623            blocked_threshold: 0,
624            window_secs: 300,
625            search_group_limit: 10,
626            tool_total_limits,
627        }
628    }
629}
630
631/// Semantic-embedding engine settings.
632///
633/// `model` selects which local ONNX embedding model lean-ctx downloads and uses for
634/// `ctx_semantic_search`. Accepts the same aliases as the `LEAN_CTX_EMBEDDING_MODEL` env
635/// var: `minilm` (all-MiniLM-L6-v2, 384d — the default), `jina-code-v2` (768d,
636/// code-optimized), `nomic` (768d) — or any HuggingFace repo with an ONNX export via
637/// `hf:org/repo[@revision]` (GL #397). When the env var is set it takes precedence; an
638/// unset/`None` value uses the default model. Switching models triggers a one-time
639/// re-index on the next semantic search (vector dimensions follow from the model).
640///
641/// `dimensions` is only consulted for `hf:` custom models as the declared fallback
642/// width; the real width is probed from the ONNX graph at load time. Built-ins ignore it.
643#[derive(Debug, Clone, Default, Serialize, Deserialize)]
644#[serde(default)]
645pub struct EmbeddingConfig {
646    #[serde(default, skip_serializing_if = "Option::is_none")]
647    pub model: Option<String>,
648    #[serde(default, skip_serializing_if = "Option::is_none")]
649    pub dimensions: Option<usize>,
650    /// Allow downloading the embedding model on first semantic need (#551).
651    /// `None` (unset) means **allowed** — the soft default that activates the
652    /// semantic features without manual setup. Set `false` for air-gapped
653    /// machines. The `LEAN_CTX_EMBEDDINGS_AUTO_DOWNLOAD` env var, when set,
654    /// overrides this in either direction.
655    #[serde(default, skip_serializing_if = "Option::is_none")]
656    pub auto_download: Option<bool>,
657}