lean_ctx/core/config/mod.rs
1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3use std::path::{Path, PathBuf};
4use std::sync::Mutex;
5
6use super::memory_policy::MemoryPolicy;
7
8mod defaults_allowlist;
9mod enums;
10mod memory;
11mod provenance;
12mod proxy;
13mod render;
14pub mod risk;
15pub mod schema;
16mod sections;
17mod serde_defaults;
18pub mod setter;
19mod shell_activation;
20pub use render::render_annotated_config;
21pub use sections::*;
22#[cfg(test)]
23mod tests;
24
25pub(crate) use defaults_allowlist::{cloud_infra_commands, default_shell_allowlist};
26pub use enums::{
27 CompressionLevel, Effort, OutputDensity, PermissionInheritance, ResponseVerbosity,
28 RulesInjection, RulesScope, TeeMode, TerseAgent,
29};
30pub use memory::{MemoryCleanup, MemoryGuardConfig, MemoryProfile, SavingsFooter};
31pub use provenance::{ConfigProvenance, EnvOverride};
32pub use proxy::{
33 HistoryMode, ProseRanker, ProseRole, ProxyConfig, ProxyProvider, RoleAggressiveness,
34 UpstreamDrift, Upstreams, diagnose_drift, env_upstream_override, is_local_proxy_url,
35 normalize_url, normalize_url_opt,
36};
37pub use shell_activation::ShellActivation;
38
39/// Default BM25 cache cap from config (also used by `bm25_index` heuristics).
40pub fn default_bm25_max_cache_mb() -> u64 {
41 serde_defaults::default_bm25_max_cache_mb()
42}
43
44/// Effective on-disk ceiling (MB) for the persisted BM25 index when nothing is
45/// explicitly configured (no `bm25_max_cache_mb`, no `max_disk_mb` budget).
46///
47/// Deliberately decoupled from the RAM `MemoryProfile` (64/128/512 MB): this is
48/// a *disk* file, and tying it to the profile silently refused persistence on
49/// large repos under Low/Balanced, forcing a cold rebuild on every call (the
50/// perpetual "index warming" of issue #249). 512 MB compressed covers
51/// essentially every real repo; RAM pressure is governed separately by the
52/// eviction orchestrator (which measures real heap).
53pub const DEFAULT_BM25_PERSIST_MB: u64 = 512;
54
55// Compile-time regression guard (#249): the default disk ceiling must stay well
56// above the old RAM-profile caps (64/128 MB) that starved large repos.
57const _: () = assert!(DEFAULT_BM25_PERSIST_MB >= 512);
58
59/// lean-ctx tools whose sole purpose is editing the user's source files. When
60/// `prefer_native_editor` is set (#454) these are hidden from `list_tools` and
61/// refused at dispatch so the host's native editor handles edits instead.
62///
63/// Deliberately narrow: only the dedicated edit tool is blocked. LSP refactor
64/// (`ctx_refactor`) also exposes read-only sub-actions (references/definition),
65/// so it is left available; users wanting it gone can add it to `disabled_tools`.
66pub const EDIT_TOOL_NAMES: &[&str] = &["ctx_edit"];
67
68/// Global lean-ctx configuration loaded from `config.toml`, merged with project-local overrides.
69#[derive(Debug, Clone, Serialize, Deserialize)]
70#[serde(default)]
71pub struct Config {
72 pub ultra_compact: bool,
73 #[serde(default, deserialize_with = "serde_defaults::deserialize_tee_mode")]
74 pub tee_mode: TeeMode,
75 #[serde(default)]
76 pub output_density: OutputDensity,
77 pub checkpoint_interval: u32,
78 pub excluded_commands: Vec<String>,
79 pub passthrough_urls: Vec<String>,
80 pub custom_aliases: Vec<AliasEntry>,
81 /// Output formats that are already compact/token-oriented and must be
82 /// preserved verbatim instead of being recompressed (#342). Matched against
83 /// the *output shape* (not the command name), so any tool emitting the
84 /// format is covered without enumerating commands in `excluded_commands`.
85 /// Default: `["toon"]`. Set to `[]` to disable and always recompress.
86 #[serde(default = "serde_defaults::default_preserve_compact_formats")]
87 pub preserve_compact_formats: Vec<String>,
88 /// Commands taking longer than this threshold (ms) are recorded in the slow log.
89 /// Set to 0 to disable slow logging.
90 pub slow_command_threshold_ms: u64,
91 #[serde(default = "serde_defaults::default_theme")]
92 pub theme: String,
93 #[serde(default)]
94 pub cloud: CloudConfig,
95 #[serde(default)]
96 pub gain: GainConfig,
97 /// Model declaration for measured-vs-estimated cost reporting (MCP-only IDEs).
98 #[serde(default)]
99 pub cost: CostConfig,
100 #[serde(default)]
101 pub autonomy: AutonomyConfig,
102 #[serde(default)]
103 pub providers: ProvidersConfig,
104 #[serde(default)]
105 pub proxy: ProxyConfig,
106 /// Whether the API proxy is enabled. Tri-state:
107 /// - None: undecided (fresh install, will prompt on interactive setup)
108 /// - Some(true): user opted in, proxy managed by lean-ctx
109 /// - Some(false): user opted out, never touch proxy or endpoints
110 #[serde(default)]
111 pub proxy_enabled: Option<bool>,
112 #[serde(default)]
113 pub proxy_port: Option<u16>,
114 /// Proxy reachability timeout in milliseconds. Default: 200.
115 /// Override via LEAN_CTX_PROXY_TIMEOUT_MS env var.
116 #[serde(default)]
117 pub proxy_timeout_ms: Option<u64>,
118 /// Strict proxy auth: when true, authenticate ONLY via the Bearer token
119 /// (`LEAN_CTX_PROXY_TOKEN`) and disable the provider-API-key fallback. Default
120 /// false keeps the loopback-friendly behavior where any local AI tool's own
121 /// provider key authenticates (the proxy never injects upstream credentials —
122 /// it forwards the caller's key verbatim). Enable on shared/multi-user hosts to
123 /// require the token; clients must then send `Authorization: Bearer <token>`.
124 #[serde(default)]
125 pub proxy_require_token: bool,
126 #[serde(default = "serde_defaults::default_buddy_enabled")]
127 pub buddy_enabled: bool,
128 #[serde(default = "serde_defaults::default_true")]
129 pub enable_wakeup_ctx: bool,
130 #[serde(default)]
131 pub redirect_exclude: Vec<String>,
132 /// Tools to exclude from the MCP tool list returned by list_tools.
133 /// Accepts exact tool names (e.g. `["ctx_graph", "ctx_agent"]`).
134 /// Empty by default — all tools listed, no behaviour change.
135 #[serde(default)]
136 pub disabled_tools: Vec<String>,
137 /// Prefer the host agent's native editor over lean-ctx edit operations (#454).
138 /// When true, the lean-ctx edit tool(s) (see [`EDIT_TOOL_NAMES`]) are neither
139 /// advertised in `list_tools` nor dispatchable (direct or via `ctx_call`), so
140 /// the agent falls back to the host's built-in editing UI. Reads / search /
141 /// shell / memory tools are unaffected. Override via
142 /// `LEAN_CTX_PREFER_NATIVE_EDITOR=1`.
143 #[serde(default)]
144 pub prefer_native_editor: bool,
145 /// Tool categories to activate by default for dynamic-tool-capable clients.
146 /// Values: "core" (always on), "arch", "debug", "memory", "metrics", "session".
147 /// Example: `default_tool_categories = ["core", "arch", "memory"]`
148 /// Override via LCTX_DEFAULT_CATEGORIES env var (comma-separated).
149 /// Empty = lean-ctx default (core + session).
150 #[serde(default)]
151 pub default_tool_categories: Vec<String>,
152 /// Disable all automatic read-mode degradation (auto_degrade + context_gate pressure).
153 /// When true, lean-ctx never downgrades requested read modes regardless of pressure.
154 /// Override via LCTX_NO_DEGRADE=1 env var.
155 #[serde(default)]
156 pub no_degrade: bool,
157 /// Serve explicit `full`/`lines:N-M` re-reads of session-cached files as
158 /// deltas: when the file changed on disk since it was cached, the read
159 /// returns `mode=diff` instead of re-emitting content the model already
160 /// holds. First reads are unaffected; `fresh=true` always bypasses.
161 /// Opt-in. Override via LCTX_DELTA_EXPLICIT=1/0 env var.
162 #[serde(default)]
163 pub delta_explicit: bool,
164 /// Persistent profile name. Checked after LEAN_CTX_PROFILE env var.
165 /// Set via `lean-ctx config set profile passthrough` or editing config.toml.
166 #[serde(default)]
167 pub profile: Option<String>,
168 /// Tool visibility profile: "minimal" (10), "standard" (19), or "power" (all).
169 /// Override via LEAN_CTX_TOOL_PROFILE env var.
170 /// Existing installs default to "power" (backward compat).
171 #[serde(default)]
172 pub tool_profile: Option<String>,
173 /// Explicit list of enabled tool names (overrides tool_profile when non-empty).
174 /// Example: `tools_enabled = ["ctx_read", "ctx_shell", "ctx_search"]`
175 #[serde(default)]
176 pub tools_enabled: Vec<String>,
177 /// Active context persona (`persona-spec-v1`). Selects the domain bundle —
178 /// tool surface, read-mode/compressor/chunker defaults, intent taxonomy,
179 /// sensitivity floor. Override via `LEAN_CTX_PERSONA`. Defaults to `coding`.
180 #[serde(default)]
181 pub persona: Option<String>,
182 #[serde(default)]
183 pub loop_detection: LoopDetectionConfig,
184 /// Controls where lean-ctx installs agent rule files.
185 /// Values: "both" (default), "global" (home-dir only), "project" (repo-local only).
186 /// Override via LEAN_CTX_RULES_SCOPE env var.
187 #[serde(default)]
188 pub rules_scope: Option<String>,
189 /// Controls how rules are injected for shared-instruction-file agents.
190 /// Values: "shared" (default, marker block in CLAUDE.md/CODEBUDDY.md/AGENTS.md/GEMINI.md),
191 /// "dedicated" (never touch those files; use each agent's config-driven
192 /// auto-load: SessionStart hook / instructions[] / context.fileName, #343), or
193 /// "off" (write no rules file at all — for hosts that supply their own
194 /// tool-steering workflow or phase-isolated/non-caching harnesses, #361).
195 /// Override via LEAN_CTX_RULES_INJECTION env var.
196 #[serde(default)]
197 pub rules_injection: Option<String>,
198 /// Mirror the host IDE's tool-permission rules onto lean-ctx's own MCP tools.
199 /// Values: "off" (default) or "on". When "on", lean-ctx reads the active
200 /// IDE's permission config (v1: OpenCode) and applies the equivalent
201 /// deny/ask/allow decision to the matching lean-ctx tool — so `ctx_shell`
202 /// honors your `bash`/`rm *` rules instead of bypassing them.
203 /// Override via LEAN_CTX_PERMISSION_INHERITANCE env var.
204 #[serde(default)]
205 pub permission_inheritance: Option<String>,
206 /// Extra glob patterns to ignore in graph/overview/preload (repo-local).
207 /// Example: `["externals/**", "target/**", "temp/**"]`
208 #[serde(default)]
209 pub extra_ignore_patterns: Vec<String>,
210 /// Controls agent output verbosity via instructions injection.
211 /// Values: "off" (default), "lite", "full", "ultra".
212 /// Override via LEAN_CTX_TERSE_AGENT env var.
213 #[serde(default)]
214 pub terse_agent: TerseAgent,
215 /// Unified compression level (replaces separate terse_agent + output_density).
216 /// Values: "off" (default), "lite", "standard", "max".
217 /// Override via LEAN_CTX_COMPRESSION env var.
218 #[serde(default)]
219 pub compression_level: CompressionLevel,
220 /// Global compression intensity 0.0 (lossless) – 1.0 (max), mapped onto the
221 /// read modes / entropy / IB stages (see `core::aggressiveness`). `None`
222 /// (default) keeps each mode's built-in default. Override via the
223 /// `LEAN_CTX_AGGRESSIVENESS` env var or the `ctx_read` `aggressiveness` arg.
224 #[serde(default)]
225 pub compression_aggressiveness: Option<f64>,
226 /// Archive configuration for zero-loss compression.
227 #[serde(default)]
228 pub archive: ArchiveConfig,
229 /// Memory policy (knowledge/episodic/procedural/lifecycle budgets & thresholds).
230 #[serde(default)]
231 pub memory: MemoryPolicy,
232 /// Additional paths allowed by PathJail (absolute).
233 /// Useful for multi-project workspaces where the jail root is a parent directory.
234 /// Override via LEAN_CTX_ALLOW_PATH env var (path-list separator).
235 #[serde(default)]
236 pub allow_paths: Vec<String>,
237 /// Allow jailed tool access to home-level IDE config dirs (~/.cursor, VS Code,
238 /// Cline/Roo, JetBrains, …). Tri-state: `None` = not asked yet (setup prompts
239 /// once), `Some(false)` = declined, `Some(true)` = opted in. Those dirs can
240 /// expose other agents' sessions, MCP configs and credentials, so the effective
241 /// default is off. `~/.lean-ctx` (own data dir) is always allowed. The opt-in
242 /// set is registry-derived, covering every supported editor. Override via
243 /// LEAN_CTX_ALLOW_IDE_DIRS=1.
244 #[serde(default)]
245 pub allow_ide_config_dirs: Option<bool>,
246 /// Extra project roots for multi-root workspaces.
247 /// Tools like ctx_tree and ctx_search can scan across all roots in a single call.
248 /// These paths are automatically added to PathJail's allow-list.
249 /// Override via LEAN_CTX_EXTRA_ROOTS env var (path-list separator).
250 #[serde(default)]
251 pub extra_roots: Vec<String>,
252 /// Read-only roots: sibling subtrees the agent may READ but never WRITE.
253 /// Reads resolve as if they were extra_roots; every write tool (edit, refactor,
254 /// handoff/session export, memory compaction) is default-denied inside these
255 /// paths. Useful for reference repos mounted next to the project.
256 /// Override via LEAN_CTX_READ_ONLY_ROOTS env var (path-list separator).
257 #[serde(default)]
258 pub read_only_roots: Vec<String>,
259 /// Enable content-defined chunking (Rabin-Karp) for cache-optimal output ordering.
260 /// Stable chunks are emitted first to maximize prompt cache hits.
261 #[serde(default)]
262 pub content_defined_chunking: bool,
263 /// Skip session/knowledge/gotcha blocks in MCP instructions to minimize token overhead.
264 /// Override via LEAN_CTX_MINIMAL env var.
265 #[serde(default)]
266 pub minimal_overhead: bool,
267 /// Opt-in: substitute long identifiers with short α-codes (+ a `§MAP` table)
268 /// in `aggressive` reads for projects with >50 source files. Off by default —
269 /// the abbreviated form is confusing for editing/refactoring, where the agent
270 /// needs the real package and symbol names. Enable for max exploration savings.
271 #[serde(default)]
272 pub symbol_map_auto: bool,
273 /// Opt-in: bias `auto` toward structure-first reads (`map`) for medium code
274 /// files on a cold read. Off by default — interactive sessions keep the
275 /// conservative `full` floor that avoids a follow-up body read. Enable for
276 /// phase-isolated harnesses (no warm-session cache payback), where a cold
277 /// `full` read is pure overhead and structure-first reads aid localization.
278 /// Override via the LEAN_CTX_STRUCTURE_FIRST env var.
279 #[serde(default)]
280 pub structure_first: bool,
281 /// Opt-in: let the adaptive *learning* signals (predictor, bandit, heatmap,
282 /// adaptive policy, bounce/path memory) participate in `auto` mode
283 /// resolution. Off by default (#683): the default cascade is a deterministic
284 /// function of (file, task) — only capability guards and the size/task
285 /// heuristic decide — which keeps output byte-stable for provider prompt
286 /// caching (#498) and avoids per-read disk I/O from the learning stores.
287 /// Override via the LEAN_CTX_AUTO_MODE_LEARNING env var.
288 #[serde(default)]
289 pub auto_mode_learning: bool,
290 /// Team server URL for opt-in savings roll-up.
291 /// Set via `lean-ctx config set team_url https://...` or `[team] url` in config.toml.
292 /// Override via LEAN_CTX_TEAM_URL env var.
293 #[serde(default)]
294 pub team_url: Option<String>,
295 /// Bearer token for the team server (Authorization header on savings push /
296 /// pull). Set via `lean-ctx config set team_token <tok>` or `team_token` in
297 /// config.toml. Override via the LEAN_CTX_TEAM_TOKEN env var.
298 #[serde(default)]
299 pub team_token: Option<String>,
300 /// Opt-in: when true, the running daemon periodically pushes this machine's
301 /// signed savings batch to `team_url` so the team roll-up fills itself (no
302 /// manual `savings push` per dev). Off by default; requires `team_url` +
303 /// `team_token`. Set via `lean-ctx config set team_auto_push true`.
304 #[serde(default)]
305 pub team_auto_push: bool,
306 /// Enable human-readable activity journal (~/.lean-ctx/journal.md).
307 #[serde(default)]
308 pub journal_enabled: bool,
309 /// Opt-in: auto-persist interesting findings as knowledge facts.
310 #[serde(default)]
311 pub auto_capture: bool,
312 /// Hybrid search weights (BM25/dense/candidates).
313 #[serde(default)]
314 pub search: crate::core::hybrid_search::HybridConfig,
315 /// Code-graph settings, including traversal (co-access) edges (#289).
316 #[serde(default)]
317 pub graph: GraphConfig,
318 /// Skillify miner settings (#290): codify recurring patterns into rules.
319 #[serde(default)]
320 pub skillify: SkillifyConfig,
321 /// AI session-summary settings (#292): periodic, semantically-recallable summaries.
322 #[serde(default)]
323 pub summaries: SummariesConfig,
324 /// Optional LLM enhancement (query expansion, contradiction explanation).
325 #[serde(default)]
326 pub llm: crate::core::llm_enhance::LlmConfig,
327 /// Semantic-embedding engine settings (which local ONNX model to use).
328 #[serde(default)]
329 pub embedding: EmbeddingConfig,
330 /// Disable shell hook injection (the _lc() function that wraps CLI commands).
331 /// Override via LEAN_CTX_NO_HOOK env var.
332 #[serde(default)]
333 pub shell_hook_disabled: bool,
334 /// Shadow mode: transparently intercepts native tool calls (Read/Grep/Shell)
335 /// via hooks, strengthens MCP instructions to MUST-level, and activates
336 /// immediate bypass hints on first native tool use. Enables "transparent
337 /// replacement" so agents use ctx_* without explicit opt-in.
338 #[serde(default)]
339 pub shadow_mode: bool,
340 /// Opt-in (#520): write a human-readable debug log of intercepted MCP tool
341 /// calls and hook routing decisions (lean-ctx vs native, with reasons) to
342 /// `<state_dir>/logs/debug.log`. Override via the LEAN_CTX_DEBUG_LOG env var.
343 #[serde(default)]
344 pub debug_log: bool,
345 /// Controls when the shell hook auto-activates aliases.
346 /// - `always`: (Default) Aliases active in every interactive shell.
347 /// - `agents-only`: Aliases only active when an AI agent env var is detected.
348 /// - `off`: Aliases never auto-activate (user must call `lean-ctx-on` manually).
349 ///
350 /// Override via `LEAN_CTX_SHELL_ACTIVATION` env var.
351 #[serde(default)]
352 pub shell_activation: ShellActivation,
353 /// Disable the daily version check against leanctx.com/version.txt.
354 /// Override via LEAN_CTX_NO_UPDATE_CHECK env var.
355 #[serde(default)]
356 pub update_check_disabled: bool,
357 #[serde(default)]
358 pub updates: UpdatesConfig,
359 /// Maximum BM25 cache file size in MB. Indexes exceeding this are quarantined on load
360 /// and refused on save. Override via LEAN_CTX_BM25_MAX_CACHE_MB env var.
361 #[serde(default = "serde_defaults::default_bm25_max_cache_mb")]
362 pub bm25_max_cache_mb: u64,
363 /// Maximum number of files scanned by the lightweight JSON graph index.
364 /// 0 = unlimited (default). Set >0 to cap for constrained systems.
365 #[serde(default = "serde_defaults::default_graph_index_max_files")]
366 pub graph_index_max_files: u64,
367 /// Controls RAM vs feature trade-off. Values: "low", "balanced" (default), "performance".
368 /// Override via LEAN_CTX_MEMORY_PROFILE env var.
369 #[serde(default)]
370 pub memory_profile: MemoryProfile,
371 /// Controls how aggressively memory is freed when idle.
372 /// Values: "aggressive" (default, 5 min TTL), "shared" (30 min TTL for multi-IDE use).
373 /// Override via LEAN_CTX_MEMORY_CLEANUP env var.
374 #[serde(default)]
375 pub memory_cleanup: MemoryCleanup,
376 /// Maximum percentage of system RAM that lean-ctx may use (default: 5).
377 /// Override via LEAN_CTX_MAX_RAM_PERCENT env var.
378 #[serde(default = "serde_defaults::default_max_ram_percent")]
379 pub max_ram_percent: u8,
380 /// Simplified disk budget (MB). When set and detail values are at defaults,
381 /// distributes proportionally: archive=25%, bm25=10%, remainder for stores.
382 /// 0 = disabled (use individual settings). Override via LEAN_CTX_MAX_DISK_MB.
383 #[serde(default)]
384 pub max_disk_mb: u64,
385 /// Auto-purge data older than this many days. 0 = disabled.
386 /// Flows into archive.max_age_hours and lifecycle idle TTL.
387 #[serde(default)]
388 pub max_staleness_days: u32,
389 /// Cap on the rayon worker threads used by the CPU-heavy index build
390 /// (call graph etc.). 0 = rayon default (all cores). Set >0 to bound
391 /// per-instance CPU so a fleet of concurrent sessions can't saturate the
392 /// host on startup. Override via LEANCTX_INDEX_THREADS env var.
393 #[serde(default)]
394 pub max_index_threads: usize,
395 /// Controls visibility of token savings footers in tool output.
396 /// Values: "always" (default, show on every response), "never", "auto" (legacy compatibility).
397 /// Override via LEAN_CTX_SAVINGS_FOOTER or LEAN_CTX_SHOW_SAVINGS=1|0 env var.
398 #[serde(default)]
399 pub savings_footer: SavingsFooter,
400 /// Explicit project root override. When set, lean-ctx uses this instead of auto-detection.
401 /// This prevents accidental home-directory scans when running from $HOME.
402 /// Override via LEAN_CTX_PROJECT_ROOT env var.
403 #[serde(default)]
404 pub project_root: Option<String>,
405 /// LSP server overrides. Map language name to custom binary path.
406 /// Example: `[lsp]\nrust = "/opt/rust-analyzer"\npython = "~/.venvs/main/bin/pylsp"`
407 #[serde(default)]
408 pub lsp: std::collections::HashMap<String, String>,
409 /// Per-IDE allowed paths. Restricts which directories lean-ctx will scan/index for each IDE.
410 /// Example: `[ide_paths]\ncursor = ["/home/user/projects/app1"]\ncodex = ["/home/user/codex"]`
411 /// When set, only these paths are indexed for the matching agent. Global `allow_paths` still applies.
412 #[serde(default)]
413 pub ide_paths: HashMap<String, Vec<String>>,
414 /// Custom model context window overrides.
415 /// Example: `[model_context_windows]\n"my-custom-model" = 500000`
416 #[serde(default)]
417 pub model_context_windows: HashMap<String, usize>,
418 /// Controls how much detail tool responses include.
419 ///
420 /// - `full` (default): complete compressed output
421 /// - `headers_only`: metadata line only (path, mode, token count)
422 ///
423 /// Override via `LEAN_CTX_RESPONSE_VERBOSITY` env var.
424 #[serde(default)]
425 pub response_verbosity: ResponseVerbosity,
426 /// Bypass hint mode. When agents use native Read/Grep instead of lean-ctx tools,
427 /// a hint is appended to the next tool response.
428 /// Values: "on" (default), "off", "aggressive" (hint on every call, no cooldown).
429 /// Override via LEAN_CTX_BYPASS_HINTS env var.
430 #[serde(default)]
431 pub bypass_hints: Option<String>,
432 /// Cache policy for ctx_read. Controls behavior on cache hits.
433 /// Values: "aggressive" (default, 13-tok stubs + compaction-aware reset),
434 /// "safe" (delivers map instead of stub), "off" (no caching, always disk read).
435 /// Override via LEAN_CTX_CACHE_POLICY env var.
436 #[serde(default)]
437 pub cache_policy: Option<String>,
438 /// Token budget for the in-memory `ctx_read` cache. When the cached total
439 /// plus an incoming read would exceed this, lean-ctx evicts the least-valuable
440 /// entries *immediately* (RRF: recency × frequency × size) so the read always
441 /// proceeds — eviction is never deferred to the staleness TTL. `0` uses the
442 /// built-in default (500k). `LEAN_CTX_CACHE_MAX_TOKENS` env var overrides this.
443 #[serde(default)]
444 pub cache_max_tokens: usize,
445 /// Cross-project boundary policy.
446 /// Controls whether cross-project search/import is allowed and whether access is audited.
447 #[serde(default)]
448 pub boundary_policy: crate::core::memory_boundary::BoundaryPolicy,
449 #[serde(default)]
450 pub secret_detection: SecretDetectionConfig,
451 /// Per-item sensitivity model with a uniform policy floor (#212).
452 /// Disabled by default → fully no-op until `sensitivity.enabled = true`.
453 #[serde(default)]
454 pub sensitivity: crate::core::sensitivity::SensitivityConfig,
455 /// MCP Tool-Catalog Gateway (#210): aggregate + query-route downstream MCP
456 /// servers. Global-only (never merged from project-local config) and a full
457 /// no-op until `gateway.enabled = true`.
458 #[serde(default)]
459 pub gateway: crate::core::gateway::GatewayConfig,
460 /// Addon ecosystem security floor (#863): install policy, registry-signature
461 /// requirement and sandboxing for spawned addon servers. Global-only (never
462 /// merged from project-local config) and fully permissive by default.
463 #[serde(default)]
464 pub addons: crate::core::addons::AddonsConfig,
465 /// Allow automatic project-root re-rooting when absolute paths outside the jail are seen.
466 /// When false (default), absolute paths outside the jail are rejected without re-rooting.
467 /// Override via LEAN_CTX_ALLOW_REROOT env var.
468 #[serde(default)]
469 pub allow_auto_reroot: bool,
470 /// Disable PathJail entirely by setting `path_jail = false` in config.toml.
471 /// Useful in container/Docker environments where the sandbox is the boundary.
472 /// (The former `LEAN_CTX_NO_JAIL=1` env override was removed in v3.7.3.)
473 #[serde(default)]
474 pub path_jail: Option<bool>,
475 /// Sandbox level for code execution (ctx_exec).
476 /// 0 = subprocess only (current), 1 = OS-level restriction (Seatbelt/Landlock).
477 /// Override via LEAN_CTX_SANDBOX_LEVEL env var.
478 #[serde(default)]
479 pub sandbox_level: u8,
480 /// When true, large tool outputs (>4000 chars) are stored as references
481 /// and a short URI is returned instead of the full content.
482 /// Override via LEAN_CTX_REFERENCE_RESULTS env var.
483 #[serde(default)]
484 pub reference_results: bool,
485 /// Default per-agent token budget. 0 means unlimited.
486 /// Override per-agent via ctx_session or programmatically.
487 #[serde(default)]
488 pub agent_token_budget: usize,
489 /// Optional shell command allowlist. When non-empty, only commands whose base binary
490 /// is in this list are permitted by ctx_shell. Empty = disable allowlist (allow all).
491 /// Default includes common dev tools. Set to `[]` to disable.
492 /// Override via LEAN_CTX_SHELL_ALLOWLIST env var (comma-separated).
493 #[serde(default = "default_shell_allowlist")]
494 pub shell_allowlist: Vec<String>,
495
496 /// Extra commands MERGED on top of the effective `shell_allowlist` without replacing
497 /// the defaults. Setting `shell_allowlist` replaces the whole built-in list (a common
498 /// footgun); entries here are purely additive, which is what `lean-ctx allow <cmd>`
499 /// writes. Only applied in restricted mode (when the base allowlist is non-empty).
500 #[serde(default)]
501 pub shell_allowlist_extra: Vec<String>,
502
503 /// When true, block command substitution ($(), backticks) and process substitution
504 /// (<(), >()) in shell arguments. When false (default), only warn via tracing.
505 /// Default false preserves backward compatibility — set true for maximum security.
506 #[serde(default)]
507 pub shell_strict_mode: bool,
508
509 /// Shell-security mode for ctx_shell / `lean-ctx -c` command gating (GL #788):
510 /// `enforce` (default, secure), `warn` (run checks, log violations, never
511 /// block) or `off` (skip the allowlist + dangerous-pattern blocks entirely —
512 /// a deliberate opt-out; compression stays active). Override via
513 /// LEAN_CTX_SHELL_SECURITY. `None` resolves to `enforce`.
514 #[serde(default)]
515 pub shell_security: Option<String>,
516
517 /// Default shell-command timeout in seconds for *normal* commands. `None`
518 /// resolves to the built-in 2-minute default; heavy builds/tests use
519 /// [`Config::shell_heavy_timeout_secs`]. Override via
520 /// `LEAN_CTX_SHELL_TIMEOUT_SECS` (`LEAN_CTX_SHELL_TIMEOUT_MS` still wins over
521 /// both, in milliseconds).
522 #[serde(default)]
523 pub shell_timeout_secs: Option<u64>,
524
525 /// Shell-command timeout in seconds for *heavy* commands (cargo build/test,
526 /// make, docker build, git commit/push, …). `None` resolves to the built-in
527 /// 10-minute ceiling. Override via `LEAN_CTX_SHELL_HEAVY_TIMEOUT_SECS`.
528 #[serde(default)]
529 pub shell_heavy_timeout_secs: Option<u64>,
530
531 /// When true, `ctx_shell` accepts shell file-write redirects (`>`, `>>`,
532 /// `tee`, heredoc-to-file, `curl -o`, `wget` default mode). Default false —
533 /// the native Write/Edit tool is preferred. Opt-in for power users who want
534 /// classic shell syntax; the real command gating (allowlist,
535 /// dangerous-pattern and interpreter-eval blocks) still applies. Override
536 /// via `LEAN_CTX_SHELL_ALLOW_WRITES=1`.
537 #[serde(default)]
538 pub shell_allow_writes: bool,
539
540 /// Setup behavior: controls what gets injected during setup and updates.
541 #[serde(default)]
542 pub setup: SetupConfig,
543}
544
545impl Default for Config {
546 fn default() -> Self {
547 Self {
548 ultra_compact: false,
549 tee_mode: TeeMode::default(),
550 output_density: OutputDensity::default(),
551 checkpoint_interval: 15,
552 excluded_commands: Vec::new(),
553 passthrough_urls: Vec::new(),
554 custom_aliases: Vec::new(),
555 preserve_compact_formats: serde_defaults::default_preserve_compact_formats(),
556 slow_command_threshold_ms: 5000,
557 theme: serde_defaults::default_theme(),
558 cloud: CloudConfig::default(),
559 gain: GainConfig::default(),
560 cost: CostConfig::default(),
561 autonomy: AutonomyConfig::default(),
562 providers: ProvidersConfig::default(),
563 proxy: ProxyConfig::default(),
564 proxy_enabled: None,
565 proxy_port: None,
566 proxy_timeout_ms: None,
567 proxy_require_token: false,
568 buddy_enabled: serde_defaults::default_buddy_enabled(),
569 enable_wakeup_ctx: true,
570 redirect_exclude: Vec::new(),
571 disabled_tools: Vec::new(),
572 prefer_native_editor: false,
573 default_tool_categories: Vec::new(),
574 no_degrade: false,
575 delta_explicit: false,
576 profile: None,
577 tool_profile: None,
578 tools_enabled: Vec::new(),
579 persona: None,
580 loop_detection: LoopDetectionConfig::default(),
581 rules_scope: None,
582 rules_injection: None,
583 permission_inheritance: None,
584 extra_ignore_patterns: Vec::new(),
585 terse_agent: TerseAgent::default(),
586 compression_level: CompressionLevel::default(),
587 compression_aggressiveness: None,
588 archive: ArchiveConfig::default(),
589 memory: MemoryPolicy::default(),
590 allow_paths: Vec::new(),
591 allow_ide_config_dirs: None,
592 extra_roots: Vec::new(),
593 read_only_roots: Vec::new(),
594 content_defined_chunking: false,
595 minimal_overhead: true,
596 symbol_map_auto: false,
597 structure_first: false,
598 auto_mode_learning: false,
599 team_url: None,
600 team_token: None,
601 team_auto_push: false,
602 journal_enabled: true,
603 auto_capture: true,
604 search: crate::core::hybrid_search::HybridConfig::default(),
605 graph: GraphConfig::default(),
606 skillify: SkillifyConfig::default(),
607 summaries: SummariesConfig::default(),
608 llm: crate::core::llm_enhance::LlmConfig::default(),
609 embedding: EmbeddingConfig::default(),
610 shell_hook_disabled: false,
611 shadow_mode: false,
612 debug_log: false,
613 shell_activation: ShellActivation::default(),
614 update_check_disabled: false,
615 updates: UpdatesConfig::default(),
616 graph_index_max_files: serde_defaults::default_graph_index_max_files(),
617 bm25_max_cache_mb: serde_defaults::default_bm25_max_cache_mb(),
618 memory_profile: MemoryProfile::default(),
619 memory_cleanup: MemoryCleanup::default(),
620 max_ram_percent: serde_defaults::default_max_ram_percent(),
621 max_disk_mb: 0,
622 max_staleness_days: 0,
623 max_index_threads: 0,
624 savings_footer: SavingsFooter::default(),
625 project_root: None,
626 lsp: std::collections::HashMap::new(),
627 ide_paths: HashMap::new(),
628 model_context_windows: HashMap::new(),
629 response_verbosity: ResponseVerbosity::default(),
630 bypass_hints: None,
631 cache_policy: None,
632 cache_max_tokens: 0,
633 boundary_policy: crate::core::memory_boundary::BoundaryPolicy::default(),
634 secret_detection: SecretDetectionConfig::default(),
635 sensitivity: crate::core::sensitivity::SensitivityConfig::default(),
636 gateway: crate::core::gateway::GatewayConfig::default(),
637 addons: crate::core::addons::AddonsConfig::default(),
638 allow_auto_reroot: false,
639 path_jail: None,
640 sandbox_level: 0,
641 reference_results: false,
642 agent_token_budget: 0,
643 shell_allowlist: default_shell_allowlist(),
644 shell_allowlist_extra: Vec::new(),
645 shell_strict_mode: false,
646 shell_security: None,
647 shell_timeout_secs: None,
648 shell_heavy_timeout_secs: None,
649 shell_allow_writes: false,
650 setup: SetupConfig::default(),
651 }
652 }
653}
654
655/// Holds the most recent global `config.toml` parse error, if the file currently
656/// fails to parse. When that happens `Config::load()` silently falls back to the
657/// built-in defaults and only logs to stderr — which is invisible over an MCP/stdio
658/// transport. Recording it here lets callers (e.g. the shell-allowlist diagnostic
659/// and `lean-ctx doctor`) surface "you're on defaults because your config is broken".
660static LAST_PARSE_ERROR: Mutex<Option<String>> = Mutex::new(None);
661
662/// Returns the most recent global config parse error, or `None` if the current
663/// `config.toml` parsed successfully (or no config file exists).
664#[must_use]
665pub fn last_config_parse_error() -> Option<String> {
666 LAST_PARSE_ERROR.lock().ok().and_then(|g| g.clone())
667}
668
669fn record_parse_error(err: Option<String>) {
670 if let Ok(mut guard) = LAST_PARSE_ERROR.lock() {
671 *guard = err;
672 }
673}
674
675/// Reset every SECURITY-sensitive field of a parsed project-local `Config` back
676/// to its default, returning the names of the ones that actually carried an
677/// override. Used by [`Config::merge_local`] for untrusted workspaces: clearing a
678/// field to its default makes the downstream "== default ⇒ no override" merge
679/// guards skip it automatically, so a single list here gates every sensitive key
680/// without touching the per-field merge arms (security audit #4).
681///
682/// Sensitive = anything that can widen lean-ctx's own boundaries or steer the
683/// agent: the shell allowlist, path-jail roots, proxy upstreams, command
684/// aliases, network passthrough, rules scope/injection, tool disabling and
685/// permission inheritance. Comfort/perf knobs are intentionally NOT listed.
686fn strip_sensitive_overrides(local: &mut Config) -> Vec<&'static str> {
687 let mut withheld: Vec<&'static str> = Vec::new();
688
689 if local.shell_allowlist != default_shell_allowlist() {
690 local.shell_allowlist = default_shell_allowlist();
691 withheld.push("shell_allowlist");
692 }
693 if !local.shell_allowlist_extra.is_empty() {
694 local.shell_allowlist_extra.clear();
695 withheld.push("shell_allowlist_extra");
696 }
697 if !local.allow_paths.is_empty() {
698 local.allow_paths.clear();
699 withheld.push("allow_paths");
700 }
701 if !local.extra_roots.is_empty() {
702 local.extra_roots.clear();
703 withheld.push("extra_roots");
704 }
705 if !local.custom_aliases.is_empty() {
706 local.custom_aliases.clear();
707 withheld.push("custom_aliases");
708 }
709 if !local.passthrough_urls.is_empty() {
710 local.passthrough_urls.clear();
711 withheld.push("passthrough_urls");
712 }
713 if local.proxy.anthropic_upstream.is_some()
714 || local.proxy.openai_upstream.is_some()
715 || local.proxy.chatgpt_upstream.is_some()
716 || local.proxy.gemini_upstream.is_some()
717 {
718 local.proxy.anthropic_upstream = None;
719 local.proxy.openai_upstream = None;
720 local.proxy.chatgpt_upstream = None;
721 local.proxy.gemini_upstream = None;
722 withheld.push("proxy.*_upstream");
723 }
724 if local.rules_scope.is_some() {
725 local.rules_scope = None;
726 withheld.push("rules_scope");
727 }
728 if local.rules_injection.is_some() {
729 local.rules_injection = None;
730 withheld.push("rules_injection");
731 }
732 if local.permission_inheritance.is_some() {
733 local.permission_inheritance = None;
734 withheld.push("permission_inheritance");
735 }
736 if !local.disabled_tools.is_empty() {
737 local.disabled_tools.clear();
738 withheld.push("disabled_tools");
739 }
740
741 withheld
742}
743
744/// Names of the SECURITY-sensitive overrides a project-local `.lean-ctx.toml`
745/// carries — the keys `strip_sensitive_overrides` would withhold for an
746/// untrusted workspace. Read-only (parses a throwaway `Config`); used by
747/// `lean-ctx trust` to tell the user exactly what trusting will enable.
748#[must_use]
749pub fn local_sensitive_overrides(local_toml: &str) -> Vec<&'static str> {
750 match toml::from_str::<Config>(local_toml) {
751 Ok(mut parsed) => strip_sensitive_overrides(&mut parsed),
752 Err(_) => Vec::new(),
753 }
754}
755
756impl Config {
757 /// Returns the effective rules scope, preferring env var over config file.
758 pub fn rules_scope_effective(&self) -> RulesScope {
759 let raw = std::env::var("LEAN_CTX_RULES_SCOPE")
760 .ok()
761 .or_else(|| self.rules_scope.clone())
762 .unwrap_or_default();
763 match raw.trim().to_lowercase().as_str() {
764 "global" => RulesScope::Global,
765 "project" => RulesScope::Project,
766 _ => RulesScope::Both,
767 }
768 }
769
770 /// Returns the effective rules injection mode, preferring env var over config.
771 /// Default is `Shared` (zero-config discovery via a CLAUDE.md/CODEBUDDY.md/AGENTS.md block).
772 pub fn rules_injection_effective(&self) -> RulesInjection {
773 let raw = std::env::var("LEAN_CTX_RULES_INJECTION")
774 .ok()
775 .or_else(|| self.rules_injection.clone())
776 .unwrap_or_default();
777 match raw.trim().to_lowercase().as_str() {
778 "dedicated" => RulesInjection::Dedicated,
779 "off" | "none" | "disabled" => RulesInjection::Off,
780 _ => RulesInjection::Shared,
781 }
782 }
783
784 /// Returns the effective permission-inheritance mode, preferring the
785 /// `LEAN_CTX_PERMISSION_INHERITANCE` env var over config. Default is `Off`.
786 /// Accepts `on`/`true`/`1` as enabled.
787 #[must_use]
788 pub fn permission_inheritance_effective(&self) -> PermissionInheritance {
789 let raw = std::env::var("LEAN_CTX_PERMISSION_INHERITANCE")
790 .ok()
791 .or_else(|| self.permission_inheritance.clone())
792 .unwrap_or_default();
793 match raw.trim().to_lowercase().as_str() {
794 "on" | "true" | "1" | "inherit" => PermissionInheritance::On,
795 _ => PermissionInheritance::Off,
796 }
797 }
798
799 /// True when lean-ctx should inject its rules via each agent's dedicated,
800 /// non-polluting auto-load path *and* global rules are in scope.
801 ///
802 /// Gates the Claude/Codex `SessionStart` `additionalContext` summary: it
803 /// stands in for the (now-skipped) shared CLAUDE.md/CODEBUDDY.md/AGENTS.md block, so it
804 /// only fires when injection is `Dedicated` and the scope isn't project-only.
805 #[must_use]
806 pub fn dedicated_session_context_active(&self) -> bool {
807 self.rules_injection_effective() == RulesInjection::Dedicated
808 && self.rules_scope_effective() != RulesScope::Project
809 }
810
811 fn parse_disabled_tools_env(val: &str) -> Vec<String> {
812 val.split(',')
813 .map(|s| s.trim().to_string())
814 .filter(|s| !s.is_empty())
815 .collect()
816 }
817
818 /// Returns the effective disabled tools list, preferring env var over config
819 /// file. When `prefer_native_editor` is active, the lean-ctx edit tools are
820 /// folded in so they are hidden from `list_tools` (#454).
821 pub fn disabled_tools_effective(&self) -> Vec<String> {
822 let mut list = if let Ok(val) = std::env::var("LEAN_CTX_DISABLED_TOOLS") {
823 Self::parse_disabled_tools_env(&val)
824 } else {
825 self.disabled_tools.clone()
826 };
827 if self.prefer_native_editor_effective() {
828 for name in EDIT_TOOL_NAMES {
829 if !list.iter().any(|t| t == name) {
830 list.push((*name).to_string());
831 }
832 }
833 }
834 list
835 }
836
837 /// Whether lean-ctx edit operations are disabled in favour of the host's
838 /// native editor (#454). `LEAN_CTX_PREFER_NATIVE_EDITOR` wins over config.
839 pub fn prefer_native_editor_effective(&self) -> bool {
840 match std::env::var("LEAN_CTX_PREFER_NATIVE_EDITOR") {
841 Ok(raw) => matches!(
842 raw.trim().to_lowercase().as_str(),
843 "1" | "true" | "yes" | "on"
844 ),
845 Err(_) => self.prefer_native_editor,
846 }
847 }
848
849 /// Cap on the rayon index-build worker threads. `LEANCTX_INDEX_THREADS` wins
850 /// over config; `0` means "no cap" — rayon's all-cores default is kept.
851 pub fn max_index_threads_effective(&self) -> usize {
852 std::env::var("LEANCTX_INDEX_THREADS")
853 .ok()
854 .and_then(|raw| raw.trim().parse::<usize>().ok())
855 .unwrap_or(self.max_index_threads)
856 }
857
858 /// Whether `name` is a lean-ctx edit operation that must be blocked from
859 /// dispatch (direct and via `ctx_call`) when [`Self::prefer_native_editor_effective`]
860 /// is set (#454). Read/search/shell/memory tools are never blocked.
861 pub fn edit_tool_blocked(&self, name: &str) -> bool {
862 self.prefer_native_editor_effective() && EDIT_TOOL_NAMES.contains(&name)
863 }
864
865 /// Returns `true` if minimal overhead is enabled via env var or config.
866 pub fn minimal_overhead_effective(&self) -> bool {
867 std::env::var("LEAN_CTX_MINIMAL").is_ok() || self.minimal_overhead
868 }
869
870 /// Returns `true` if structure-first auto reads are enabled.
871 ///
872 /// The `LEAN_CTX_STRUCTURE_FIRST` env var wins over the config field, and
873 /// accepts the usual truthy/falsy spellings so a harness can flip it per run
874 /// (`LEAN_CTX_STRUCTURE_FIRST=0` forces it off even if config enables it).
875 pub fn structure_first_effective(&self) -> bool {
876 match std::env::var("LEAN_CTX_STRUCTURE_FIRST") {
877 Ok(raw) => matches!(
878 raw.trim().to_lowercase().as_str(),
879 "1" | "true" | "yes" | "on"
880 ),
881 Err(_) => self.structure_first,
882 }
883 }
884
885 /// Returns `true` when the adaptive learning signals may participate in
886 /// `auto` mode resolution (#683). Off by default for a deterministic,
887 /// I/O-light cascade; the `LEAN_CTX_AUTO_MODE_LEARNING` env var wins over the
888 /// config field and accepts the usual truthy/falsy spellings.
889 pub fn auto_mode_learning_effective(&self) -> bool {
890 match std::env::var("LEAN_CTX_AUTO_MODE_LEARNING") {
891 Ok(raw) => matches!(
892 raw.trim().to_lowercase().as_str(),
893 "1" | "true" | "yes" | "on"
894 ),
895 Err(_) => self.auto_mode_learning,
896 }
897 }
898
899 /// Returns `true` when probabilistic exploration (Thompson sampling,
900 /// Boltzmann-temperature eviction, simulated annealing) may influence
901 /// decisions. Off by default so tool output stays a deterministic, byte-
902 /// stable function of (content, mode, task) — the determinism contract
903 /// (#498) that lets provider prompt caching apply. The `LEAN_CTX_STOCHASTIC`
904 /// env var wins (the usual truthy/falsy spellings); otherwise it follows
905 /// [`Self::auto_mode_learning_effective`], which is itself off by default.
906 pub fn is_stochastic_enabled(&self) -> bool {
907 match std::env::var("LEAN_CTX_STOCHASTIC") {
908 Ok(raw) => matches!(
909 raw.trim().to_lowercase().as_str(),
910 "1" | "true" | "yes" | "on"
911 ),
912 Err(_) => self.auto_mode_learning_effective(),
913 }
914 }
915
916 /// Returns `true` if minimal overhead should be enabled for this MCP client.
917 ///
918 /// This is a superset of `minimal_overhead_effective()`:
919 /// - `LEAN_CTX_OVERHEAD_MODE=minimal` forces minimal overhead
920 /// - `LEAN_CTX_OVERHEAD_MODE=full` disables client/model heuristics (still honors LEAN_CTX_MINIMAL / config)
921 /// - In auto mode (default), certain low-context clients/models are treated as minimal to prevent
922 /// large metadata blocks from destabilizing smaller context windows (e.g. Hermes + MiniMax).
923 pub fn minimal_overhead_effective_for_client(&self, client_name: &str) -> bool {
924 if let Ok(raw) = std::env::var("LEAN_CTX_OVERHEAD_MODE") {
925 match raw.trim().to_lowercase().as_str() {
926 "minimal" => return true,
927 "full" => return self.minimal_overhead_effective(),
928 _ => {}
929 }
930 }
931
932 if self.minimal_overhead_effective() {
933 return true;
934 }
935
936 let client_lower = client_name.trim().to_lowercase();
937 if !client_lower.is_empty() {
938 if let Ok(list) = std::env::var("LEAN_CTX_MINIMAL_CLIENTS") {
939 for needle in list.split(',').map(|s| s.trim().to_lowercase()) {
940 if !needle.is_empty() && client_lower.contains(&needle) {
941 return true;
942 }
943 }
944 } else if client_lower.contains("hermes") || client_lower.contains("minimax") {
945 return true;
946 }
947 }
948
949 let model = std::env::var("LEAN_CTX_MODEL")
950 .or_else(|_| std::env::var("LCTX_MODEL"))
951 .unwrap_or_default();
952 let model = model.trim().to_lowercase();
953 if !model.is_empty() {
954 let m = model.replace(['_', ' '], "-");
955 if m.contains("minimax")
956 || m.contains("mini-max")
957 || m.contains("m2.7")
958 || m.contains("m2-7")
959 {
960 return true;
961 }
962 }
963
964 false
965 }
966
967 /// Returns `true` if shell hook injection is disabled via env var or config.
968 pub fn shell_hook_disabled_effective(&self) -> bool {
969 std::env::var("LEAN_CTX_NO_HOOK").is_ok() || self.shell_hook_disabled
970 }
971
972 /// Returns the effective shell activation mode (env var > config > default).
973 pub fn shell_activation_effective(&self) -> ShellActivation {
974 ShellActivation::effective(self)
975 }
976
977 /// Returns `true` if `ctx_shell` may accept shell file-write redirects.
978 /// `LEAN_CTX_SHELL_ALLOW_WRITES` (`1`/`true`/`yes`/`on`) overrides
979 /// `config.toml`. The real command gating still applies either way.
980 pub fn shell_allow_writes_effective(&self) -> bool {
981 match std::env::var("LEAN_CTX_SHELL_ALLOW_WRITES") {
982 Ok(raw) => matches!(
983 raw.trim().to_ascii_lowercase().as_str(),
984 "1" | "true" | "yes" | "on"
985 ),
986 Err(_) => self.shell_allow_writes,
987 }
988 }
989
990 /// Returns `true` if the daily update check is disabled via env var or config.
991 pub fn update_check_disabled_effective(&self) -> bool {
992 std::env::var("LEAN_CTX_NO_UPDATE_CHECK").is_ok() || self.update_check_disabled
993 }
994
995 pub fn memory_policy_effective(&self) -> Result<MemoryPolicy, String> {
996 let mut policy = self.memory.clone();
997 policy.apply_env_overrides();
998
999 let budget = self.max_disk_mb_effective();
1000 if budget > 0 {
1001 let scale_factor = (budget as f64 / 500.0).clamp(0.5, 10.0);
1002 let default_policy = MemoryPolicy::default();
1003 if policy.knowledge.max_facts == default_policy.knowledge.max_facts {
1004 policy.knowledge.max_facts = (200.0 * scale_factor) as usize;
1005 }
1006 if policy.knowledge.max_patterns == default_policy.knowledge.max_patterns {
1007 policy.knowledge.max_patterns = (50.0 * scale_factor) as usize;
1008 }
1009 if policy.episodic.max_episodes == default_policy.episodic.max_episodes {
1010 policy.episodic.max_episodes = (500.0 * scale_factor) as usize;
1011 }
1012 if policy.procedural.max_procedures == default_policy.procedural.max_procedures {
1013 policy.procedural.max_procedures = (100.0 * scale_factor) as usize;
1014 }
1015 }
1016
1017 policy.validate()?;
1018 Ok(policy)
1019 }
1020
1021 /// Returns the effective set of default tool categories.
1022 /// Priority: LCTX_DEFAULT_CATEGORIES env var > config.toml > hardcoded default.
1023 pub fn default_tool_categories_effective(&self) -> Vec<String> {
1024 if let Ok(val) = std::env::var("LCTX_DEFAULT_CATEGORIES") {
1025 return val
1026 .split(',')
1027 .map(|s| s.trim().to_lowercase())
1028 .filter(|s| !s.is_empty())
1029 .collect();
1030 }
1031 if !self.default_tool_categories.is_empty() {
1032 return self
1033 .default_tool_categories
1034 .iter()
1035 .map(|s| s.to_lowercase())
1036 .collect();
1037 }
1038 vec!["core".to_string(), "session".to_string()]
1039 }
1040
1041 /// Returns the effective tool profile.
1042 /// Priority: LEAN_CTX_TOOL_PROFILE env > config tool_profile > config
1043 /// tools_enabled > active persona's tool surface > power.
1044 ///
1045 /// Explicit settings win (backward compatible); when none are set, the
1046 /// active persona supplies the tool surface (the `coding` default resolves
1047 /// to `power`, so existing installs are unaffected).
1048 pub fn tool_profile_effective(&self) -> super::tool_profiles::ToolProfile {
1049 super::persona::Persona::resolve(self).effective_tool_profile(self)
1050 }
1051
1052 /// Returns `true` if all automatic read-mode degradation is disabled.
1053 /// Checks LCTX_NO_DEGRADE env var first, then config.toml field.
1054 pub fn no_degrade_effective(&self) -> bool {
1055 if let Ok(val) = std::env::var("LCTX_NO_DEGRADE") {
1056 return val == "1" || val.eq_ignore_ascii_case("true");
1057 }
1058 self.no_degrade
1059 }
1060
1061 /// Returns `true` if explicit `full`/`lines:N-M` re-reads of
1062 /// cached-but-changed files should be served as deltas (`mode=diff`)
1063 /// instead of re-emitting full content.
1064 ///
1065 /// Checks the `LCTX_DELTA_EXPLICIT` env var first, then the config.toml
1066 /// field. Unlike a presence-only knob, an explicit `0`/`false` in the env
1067 /// forces the feature OFF even when the config field is `true`, so the env
1068 /// can fully override config in both directions.
1069 pub fn delta_explicit_effective(&self) -> bool {
1070 if let Ok(val) = std::env::var("LCTX_DELTA_EXPLICIT") {
1071 return val == "1" || val.eq_ignore_ascii_case("true");
1072 }
1073 self.delta_explicit
1074 }
1075
1076 /// Effective max_disk_mb from env or config.
1077 pub fn max_disk_mb_effective(&self) -> u64 {
1078 std::env::var("LEAN_CTX_MAX_DISK_MB")
1079 .ok()
1080 .and_then(|v| v.parse().ok())
1081 .unwrap_or(self.max_disk_mb)
1082 }
1083
1084 /// Effective max_staleness_days from env or config.
1085 pub fn max_staleness_days_effective(&self) -> u32 {
1086 std::env::var("LEAN_CTX_MAX_STALENESS_DAYS")
1087 .ok()
1088 .and_then(|v| v.parse().ok())
1089 .unwrap_or(self.max_staleness_days)
1090 }
1091
1092 /// Archive max_disk_mb derived from simplified max_disk_mb if the detail
1093 /// value is still at its default. Explicit overrides take priority.
1094 pub fn archive_max_disk_mb_effective(&self) -> u64 {
1095 let budget = self.max_disk_mb_effective();
1096 if budget > 0 && self.archive.max_disk_mb == ArchiveConfig::default().max_disk_mb {
1097 budget * 25 / 100
1098 } else {
1099 self.archive.max_disk_mb
1100 }
1101 }
1102
1103 /// Archive max_age_hours derived from max_staleness_days if the detail
1104 /// value is still at its default. Explicit overrides take priority.
1105 pub fn archive_max_age_hours_effective(&self) -> u64 {
1106 let staleness = self.max_staleness_days_effective();
1107 if staleness > 0 && self.archive.max_age_hours == ArchiveConfig::default().max_age_hours {
1108 staleness as u64 * 24
1109 } else {
1110 self.archive.max_age_hours
1111 }
1112 }
1113
1114 /// Effective on-disk ceiling (MB) for the persisted BM25 index. Single source
1115 /// of truth for `save`/`load`, `cache prune`, and the doctor health check.
1116 ///
1117 /// Priority: explicit `bm25_max_cache_mb` › `max_disk_mb` budget (10%) ›
1118 /// generous default ([`DEFAULT_BM25_PERSIST_MB`]). The default is decoupled
1119 /// from the RAM profile so large repos persist instead of rebuilding forever
1120 /// (issue #249).
1121 pub fn bm25_max_cache_mb_effective(&self) -> u64 {
1122 if self.bm25_max_cache_mb != serde_defaults::default_bm25_max_cache_mb() {
1123 return self.bm25_max_cache_mb;
1124 }
1125 let budget = self.max_disk_mb_effective();
1126 if budget > 0 {
1127 return budget * 10 / 100;
1128 }
1129 DEFAULT_BM25_PERSIST_MB
1130 }
1131}
1132
1133impl Config {
1134 /// Returns the path to the global config file (`$XDG_CONFIG_HOME/lean-ctx/config.toml`).
1135 ///
1136 /// Resolves via [`crate::core::paths::config_dir`] so config lives in the
1137 /// RO-safe config category. Behavior-neutral today: `config_dir()` equals the
1138 /// legacy data dir for existing/single-dir installs (GH #408 / GL #602).
1139 pub fn path() -> Option<PathBuf> {
1140 crate::core::paths::config_dir()
1141 .ok()
1142 .map(|d| d.join("config.toml"))
1143 }
1144
1145 /// `Some(path)` when the global config the runtime *resolves* does not exist,
1146 /// so lean-ctx is silently on built-in defaults. `None` when a config file is
1147 /// present (or HOME is unresolvable).
1148 ///
1149 /// The directory is layout-dependent (XDG `~/.config/lean-ctx` vs legacy
1150 /// `~/.lean-ctx` vs `$LEAN_CTX_DATA_DIR`) and an MCP client may launch the
1151 /// server in a sandbox/container with a different `$HOME`. An edit made to a
1152 /// *different* `config.toml` than this one is silently ignored; the block
1153 /// messages use this to say so out loud over MCP, where the stderr path is
1154 /// invisible (#540).
1155 #[must_use]
1156 pub fn missing_config_path() -> Option<PathBuf> {
1157 match Self::path() {
1158 Some(p) if !p.exists() => Some(p),
1159 _ => None,
1160 }
1161 }
1162
1163 /// Returns the path to the project-local config override file.
1164 pub fn local_path(project_root: &str) -> PathBuf {
1165 PathBuf::from(project_root).join(".lean-ctx.toml")
1166 }
1167
1168 /// Resolves the active project root (env override → session → git toplevel →
1169 /// cwd), cached for the process. Exposed crate-wide so workspace-trust and the
1170 /// CLI agree with config loading on *which* directory a `.lean-ctx.toml`
1171 /// belongs to (GH security audit, finding 4).
1172 pub(crate) fn find_project_root() -> Option<String> {
1173 static ROOT_CACHE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
1174 ROOT_CACHE
1175 .get_or_init(Self::find_project_root_inner)
1176 .clone()
1177 }
1178
1179 fn find_project_root_inner() -> Option<String> {
1180 if let Ok(env_root) = std::env::var("LEAN_CTX_PROJECT_ROOT")
1181 && !env_root.is_empty()
1182 {
1183 return Some(env_root);
1184 }
1185
1186 let cwd = std::env::current_dir().ok();
1187
1188 if let Some(root) =
1189 crate::core::session::SessionState::load_latest().and_then(|s| s.project_root)
1190 {
1191 let root_path = std::path::Path::new(&root);
1192 let cwd_is_under_root = cwd.as_ref().is_some_and(|c| c.starts_with(root_path));
1193 // Route the marker probe through the TCC-guarded helper and never
1194 // adopt a ~/Documents project root from a launchd-standalone process
1195 // (#356): doing so would later stat its `.lean-ctx.toml`/markers and
1196 // pop the macOS privacy prompt in lean-ctx's own name.
1197 let has_marker = crate::core::pathutil::has_project_marker(root_path);
1198
1199 if (cwd_is_under_root || has_marker) && crate::core::pathutil::may_probe_path(root_path)
1200 {
1201 return Some(root);
1202 }
1203 }
1204
1205 if let Some(ref cwd) = cwd {
1206 // A launchd-standalone process must not shell out to `git` (which
1207 // stats the working tree) or adopt cwd as the project root when cwd
1208 // is under a TCC-protected dir (#356).
1209 let may_probe_cwd = crate::core::pathutil::may_probe_path(cwd);
1210 let git_root = if may_probe_cwd {
1211 std::process::Command::new("git")
1212 .args(["rev-parse", "--show-toplevel"])
1213 .current_dir(cwd)
1214 .stdout(std::process::Stdio::piped())
1215 .stderr(std::process::Stdio::null())
1216 .output()
1217 .ok()
1218 .and_then(|o| {
1219 if o.status.success() {
1220 String::from_utf8(o.stdout)
1221 .ok()
1222 .map(|s| s.trim().to_string())
1223 } else {
1224 None
1225 }
1226 })
1227 } else {
1228 None
1229 };
1230 if let Some(root) = git_root {
1231 return Some(root);
1232 }
1233 if may_probe_cwd && !crate::core::pathutil::is_broad_or_unsafe_root(cwd) {
1234 return Some(cwd.to_string_lossy().to_string());
1235 }
1236 }
1237 None
1238 }
1239
1240 /// Loads config from disk with caching, merging global + project-local overrides.
1241 ///
1242 /// The cache is keyed on a **content hash** of the global + project-local
1243 /// files, not their mtime. mtime-only invalidation silently served a stale
1244 /// `Config` whenever a content edit preserved the mtime (coarse filesystem
1245 /// mtime resolution, `cp -p`, atomic save-then-rename, two edits within the
1246 /// same second). A long-lived MCP server then kept the old value (e.g.
1247 /// `path_jail`) while a fresh `lean-ctx doctor` process — with an empty
1248 /// cache — saw the new one (#406). Config files are tiny, so reading +
1249 /// hashing them on every load is negligible and guarantees liveness.
1250 pub fn load() -> Self {
1251 static CACHE: Mutex<Option<(Config, Option<String>, Option<String>)>> = Mutex::new(None);
1252
1253 let Some(path) = Self::path() else {
1254 return Self::default();
1255 };
1256
1257 let project_root = Self::find_project_root();
1258 let local_path = project_root.as_deref().map(Self::local_path);
1259
1260 // Read raw content up front so the cache key is a content hash.
1261 let global_content = std::fs::read_to_string(&path).ok();
1262 // TCC (#356): never read a project-local `.lean-ctx.toml` under
1263 // ~/Documents from a launchd-standalone process — the read pops the
1264 // macOS privacy prompt. `find_project_root` already avoids returning
1265 // such roots; this also guards the explicit `LEAN_CTX_PROJECT_ROOT` path.
1266 let local_content = local_path
1267 .as_ref()
1268 .filter(|p| crate::core::pathutil::may_probe_path(p.as_path()))
1269 .and_then(|p| std::fs::read_to_string(p).ok());
1270
1271 let global_hash = global_content.as_deref().map(crate::core::hasher::hash_str);
1272 let local_hash = local_content.as_deref().map(crate::core::hasher::hash_str);
1273
1274 if let Ok(guard) = CACHE.lock()
1275 && let Some((ref cfg, ref cached_global, ref cached_local)) = *guard
1276 && *cached_global == global_hash
1277 && *cached_local == local_hash
1278 {
1279 return cfg.clone();
1280 }
1281
1282 let mut cfg: Config = if let Some(ref content) = global_content {
1283 match toml::from_str(content) {
1284 Ok(c) => {
1285 record_parse_error(None);
1286 c
1287 }
1288 Err(e) => {
1289 record_parse_error(Some(format!("{e}")));
1290 tracing::warn!("config parse error in {}: {e}", path.display());
1291 eprintln!(
1292 "\x1b[33m[lean-ctx] WARNING: config parse error in {}: {e}\n \
1293 Using defaults. Run `lean-ctx doctor --fix` to repair.\x1b[0m",
1294 path.display()
1295 );
1296 Self::default()
1297 }
1298 }
1299 } else {
1300 record_parse_error(None);
1301 Self::default()
1302 };
1303
1304 if let Some(ref local) = local_content {
1305 // Finding 4: a project-local `.lean-ctx.toml`'s SECURITY-sensitive
1306 // overrides (shell allowlist, path-jail widening, proxy upstream, …)
1307 // are honoured only for a workspace the user has explicitly trusted.
1308 // `local_hash` is exactly the content hash workspace-trust pins, so
1309 // editing the file after trust re-gates it (see `workspace_trust`).
1310 let trusted = project_root.as_deref().is_some_and(|r| {
1311 crate::core::workspace_trust::is_trusted_for(
1312 std::path::Path::new(r),
1313 local_hash.as_deref().unwrap_or_default(),
1314 )
1315 });
1316 cfg.merge_local(local, trusted);
1317 }
1318
1319 if let Ok(mut guard) = CACHE.lock() {
1320 *guard = Some((cfg.clone(), global_hash, local_hash));
1321 }
1322
1323 cfg
1324 }
1325
1326 /// Merge a project-local `.lean-ctx.toml` onto `self`.
1327 ///
1328 /// `trusted` reflects [`crate::core::workspace_trust`]: when `false`, the
1329 /// security-sensitive overrides (shell allowlist, path-jail widening, proxy
1330 /// upstream, command aliases, rules scope, …) are withheld and a warning is
1331 /// emitted — comfort-only overrides (compression, theme, memory tuning) still
1332 /// apply. This stops a cloned, untrusted repo from silently weakening
1333 /// lean-ctx's own boundaries through its bundled config (security audit #4).
1334 fn merge_local(&mut self, local_toml: &str, trusted: bool) {
1335 let mut local: Config = match toml::from_str(local_toml) {
1336 Ok(c) => c,
1337 Err(e) => {
1338 tracing::warn!("local config parse error: {e}");
1339 eprintln!(
1340 "\x1b[33m[lean-ctx] WARNING: local .lean-ctx.toml parse error: {e}\n \
1341 Local overrides skipped.\x1b[0m"
1342 );
1343 return;
1344 }
1345 };
1346 if !trusted {
1347 let withheld = strip_sensitive_overrides(&mut local);
1348 if !withheld.is_empty() {
1349 tracing::warn!(
1350 "[SECURITY] untrusted workspace: ignoring {} security-sensitive \
1351 .lean-ctx.toml override(s): {} — run `lean-ctx trust` to apply them",
1352 withheld.len(),
1353 withheld.join(", ")
1354 );
1355 }
1356 }
1357 if local.ultra_compact {
1358 self.ultra_compact = true;
1359 }
1360 if local.tee_mode != TeeMode::default() {
1361 self.tee_mode = local.tee_mode;
1362 }
1363 if local.output_density != OutputDensity::default() {
1364 self.output_density = local.output_density;
1365 }
1366 if local.checkpoint_interval != 15 {
1367 self.checkpoint_interval = local.checkpoint_interval;
1368 }
1369 if !local.excluded_commands.is_empty() {
1370 self.excluded_commands.extend(local.excluded_commands);
1371 }
1372 if !local.passthrough_urls.is_empty() {
1373 self.passthrough_urls.extend(local.passthrough_urls);
1374 }
1375 if !local.custom_aliases.is_empty() {
1376 self.custom_aliases.extend(local.custom_aliases);
1377 }
1378 // Additive merge with dedup: project-local config can add formats on top
1379 // of the global default (`["toon"]`) without re-listing it.
1380 for fmt in local.preserve_compact_formats {
1381 if !self
1382 .preserve_compact_formats
1383 .iter()
1384 .any(|f| f.eq_ignore_ascii_case(&fmt))
1385 {
1386 self.preserve_compact_formats.push(fmt);
1387 }
1388 }
1389 if local.slow_command_threshold_ms != 5000 {
1390 self.slow_command_threshold_ms = local.slow_command_threshold_ms;
1391 }
1392 if local.theme != "default" {
1393 self.theme = local.theme;
1394 }
1395 if !local.buddy_enabled {
1396 self.buddy_enabled = false;
1397 }
1398 if !local.enable_wakeup_ctx {
1399 self.enable_wakeup_ctx = false;
1400 }
1401 if !local.redirect_exclude.is_empty() {
1402 self.redirect_exclude.extend(local.redirect_exclude);
1403 }
1404 if !local.disabled_tools.is_empty() {
1405 self.disabled_tools.extend(local.disabled_tools);
1406 }
1407 if local.prefer_native_editor {
1408 self.prefer_native_editor = true;
1409 }
1410 if !local.extra_ignore_patterns.is_empty() {
1411 self.extra_ignore_patterns
1412 .extend(local.extra_ignore_patterns);
1413 }
1414 if local.rules_scope.is_some() {
1415 self.rules_scope = local.rules_scope;
1416 }
1417 if local.rules_injection.is_some() {
1418 self.rules_injection = local.rules_injection;
1419 }
1420 if local.permission_inheritance.is_some() {
1421 self.permission_inheritance = local.permission_inheritance;
1422 }
1423 if local.proxy.anthropic_upstream.is_some() {
1424 self.proxy.anthropic_upstream = local.proxy.anthropic_upstream;
1425 }
1426 if local.proxy.openai_upstream.is_some() {
1427 self.proxy.openai_upstream = local.proxy.openai_upstream;
1428 }
1429 if local.proxy.chatgpt_upstream.is_some() {
1430 self.proxy.chatgpt_upstream = local.proxy.chatgpt_upstream;
1431 }
1432 if local.proxy.gemini_upstream.is_some() {
1433 self.proxy.gemini_upstream = local.proxy.gemini_upstream;
1434 }
1435 if !local.autonomy.enabled {
1436 self.autonomy.enabled = false;
1437 }
1438 if !local.autonomy.auto_preload {
1439 self.autonomy.auto_preload = false;
1440 }
1441 if !local.autonomy.auto_dedup {
1442 self.autonomy.auto_dedup = false;
1443 }
1444 if !local.autonomy.auto_related {
1445 self.autonomy.auto_related = false;
1446 }
1447 if !local.autonomy.auto_consolidate {
1448 self.autonomy.auto_consolidate = false;
1449 }
1450 if local.autonomy.silent_preload {
1451 self.autonomy.silent_preload = true;
1452 }
1453 if !local.autonomy.silent_preload && self.autonomy.silent_preload {
1454 self.autonomy.silent_preload = false;
1455 }
1456 if local.autonomy.dedup_threshold != AutonomyConfig::default().dedup_threshold {
1457 self.autonomy.dedup_threshold = local.autonomy.dedup_threshold;
1458 }
1459 if local.autonomy.consolidate_every_calls
1460 != AutonomyConfig::default().consolidate_every_calls
1461 {
1462 self.autonomy.consolidate_every_calls = local.autonomy.consolidate_every_calls;
1463 }
1464 if local.autonomy.consolidate_cooldown_secs
1465 != AutonomyConfig::default().consolidate_cooldown_secs
1466 {
1467 self.autonomy.consolidate_cooldown_secs = local.autonomy.consolidate_cooldown_secs;
1468 }
1469 if !local.autonomy.cognition_loop_enabled {
1470 self.autonomy.cognition_loop_enabled = false;
1471 }
1472 if local.autonomy.cognition_loop_interval_secs
1473 != AutonomyConfig::default().cognition_loop_interval_secs
1474 {
1475 self.autonomy.cognition_loop_interval_secs =
1476 local.autonomy.cognition_loop_interval_secs;
1477 }
1478 if local.autonomy.cognition_loop_max_steps
1479 != AutonomyConfig::default().cognition_loop_max_steps
1480 {
1481 self.autonomy.cognition_loop_max_steps = local.autonomy.cognition_loop_max_steps;
1482 }
1483 if local_toml.contains("compression_level") {
1484 self.compression_level = local.compression_level;
1485 }
1486 if local_toml.contains("compression_aggressiveness") {
1487 self.compression_aggressiveness = local.compression_aggressiveness;
1488 }
1489 if local_toml.contains("terse_agent") {
1490 self.terse_agent = local.terse_agent;
1491 }
1492 if !local.archive.enabled {
1493 self.archive.enabled = false;
1494 }
1495 if local.archive.threshold_chars != ArchiveConfig::default().threshold_chars {
1496 self.archive.threshold_chars = local.archive.threshold_chars;
1497 }
1498 if local.archive.max_age_hours != ArchiveConfig::default().max_age_hours {
1499 self.archive.max_age_hours = local.archive.max_age_hours;
1500 }
1501 if local.archive.max_disk_mb != ArchiveConfig::default().max_disk_mb {
1502 self.archive.max_disk_mb = local.archive.max_disk_mb;
1503 }
1504 if !local.archive.ephemeral {
1505 self.archive.ephemeral = false;
1506 }
1507 if local.archive.ephemeral_min_tokens != ArchiveConfig::default().ephemeral_min_tokens {
1508 self.archive.ephemeral_min_tokens = local.archive.ephemeral_min_tokens;
1509 }
1510 let mem_def = MemoryPolicy::default();
1511 if local.memory.knowledge.max_facts != mem_def.knowledge.max_facts {
1512 self.memory.knowledge.max_facts = local.memory.knowledge.max_facts;
1513 }
1514 if local.memory.knowledge.max_patterns != mem_def.knowledge.max_patterns {
1515 self.memory.knowledge.max_patterns = local.memory.knowledge.max_patterns;
1516 }
1517 if local.memory.knowledge.max_history != mem_def.knowledge.max_history {
1518 self.memory.knowledge.max_history = local.memory.knowledge.max_history;
1519 }
1520 if local.memory.knowledge.contradiction_threshold
1521 != mem_def.knowledge.contradiction_threshold
1522 {
1523 self.memory.knowledge.contradiction_threshold =
1524 local.memory.knowledge.contradiction_threshold;
1525 }
1526
1527 if local.memory.episodic.max_episodes != mem_def.episodic.max_episodes {
1528 self.memory.episodic.max_episodes = local.memory.episodic.max_episodes;
1529 }
1530 if local.memory.episodic.max_actions_per_episode != mem_def.episodic.max_actions_per_episode
1531 {
1532 self.memory.episodic.max_actions_per_episode =
1533 local.memory.episodic.max_actions_per_episode;
1534 }
1535 if local.memory.episodic.summary_max_chars != mem_def.episodic.summary_max_chars {
1536 self.memory.episodic.summary_max_chars = local.memory.episodic.summary_max_chars;
1537 }
1538
1539 if local.memory.procedural.min_repetitions != mem_def.procedural.min_repetitions {
1540 self.memory.procedural.min_repetitions = local.memory.procedural.min_repetitions;
1541 }
1542 if local.memory.procedural.min_sequence_len != mem_def.procedural.min_sequence_len {
1543 self.memory.procedural.min_sequence_len = local.memory.procedural.min_sequence_len;
1544 }
1545 if local.memory.procedural.max_procedures != mem_def.procedural.max_procedures {
1546 self.memory.procedural.max_procedures = local.memory.procedural.max_procedures;
1547 }
1548 if local.memory.procedural.max_window_size != mem_def.procedural.max_window_size {
1549 self.memory.procedural.max_window_size = local.memory.procedural.max_window_size;
1550 }
1551
1552 if local.memory.lifecycle.decay_rate != mem_def.lifecycle.decay_rate {
1553 self.memory.lifecycle.decay_rate = local.memory.lifecycle.decay_rate;
1554 }
1555 if local.memory.lifecycle.low_confidence_threshold
1556 != mem_def.lifecycle.low_confidence_threshold
1557 {
1558 self.memory.lifecycle.low_confidence_threshold =
1559 local.memory.lifecycle.low_confidence_threshold;
1560 }
1561 if local.memory.lifecycle.stale_days != mem_def.lifecycle.stale_days {
1562 self.memory.lifecycle.stale_days = local.memory.lifecycle.stale_days;
1563 }
1564 if local.memory.lifecycle.similarity_threshold != mem_def.lifecycle.similarity_threshold {
1565 self.memory.lifecycle.similarity_threshold =
1566 local.memory.lifecycle.similarity_threshold;
1567 }
1568
1569 if local.memory.embeddings.max_facts != mem_def.embeddings.max_facts {
1570 self.memory.embeddings.max_facts = local.memory.embeddings.max_facts;
1571 }
1572 if !local.allow_paths.is_empty() {
1573 self.allow_paths.extend(local.allow_paths);
1574 }
1575 if !local.extra_roots.is_empty() {
1576 self.extra_roots.extend(local.extra_roots);
1577 }
1578 // Project-local config may only ADD read-only roots (tighten the write
1579 // boundary), never remove them — merge mirrors extra_roots (#475).
1580 if !local.read_only_roots.is_empty() {
1581 self.read_only_roots.extend(local.read_only_roots);
1582 }
1583 if local.minimal_overhead {
1584 self.minimal_overhead = true;
1585 }
1586 if local.shell_hook_disabled {
1587 self.shell_hook_disabled = true;
1588 }
1589 if local.shell_activation != ShellActivation::default() {
1590 self.shell_activation = local.shell_activation.clone();
1591 }
1592 if local.bm25_max_cache_mb != default_bm25_max_cache_mb() {
1593 self.bm25_max_cache_mb = local.bm25_max_cache_mb;
1594 }
1595 if local.memory_profile != MemoryProfile::default() {
1596 self.memory_profile = local.memory_profile;
1597 }
1598 if local.memory_cleanup != MemoryCleanup::default() {
1599 self.memory_cleanup = local.memory_cleanup;
1600 }
1601 // Only override when the local file actually defines `shell_allowlist`.
1602 // The field carries `#[serde(default = "default_shell_allowlist")]`, so a
1603 // local `.lean-ctx.toml` that omits the key still deserializes to the full
1604 // 201-entry built-in list — an `is_empty()` guard would then silently clobber
1605 // a deliberately shorter global allowlist with the defaults. Comparing against
1606 // the default (the same pattern used for every other merged field) treats
1607 // "omitted" as "no override".
1608 if local.shell_allowlist != default_shell_allowlist() {
1609 self.shell_allowlist = local.shell_allowlist;
1610 }
1611 if !local.shell_allowlist_extra.is_empty() {
1612 self.shell_allowlist_extra
1613 .extend(local.shell_allowlist_extra);
1614 }
1615 if !local.default_tool_categories.is_empty() {
1616 self.default_tool_categories = local.default_tool_categories;
1617 }
1618 if local.tool_profile.is_some() {
1619 self.tool_profile = local.tool_profile;
1620 }
1621 if !local.tools_enabled.is_empty() {
1622 self.tools_enabled = local.tools_enabled;
1623 }
1624 if local.no_degrade {
1625 self.no_degrade = true;
1626 }
1627 if local.delta_explicit {
1628 self.delta_explicit = true;
1629 }
1630 if local.profile.is_some() {
1631 self.profile = local.profile;
1632 }
1633 if local.proxy_timeout_ms.is_some() {
1634 self.proxy_timeout_ms = local.proxy_timeout_ms;
1635 }
1636 }
1637
1638 /// Loads ONLY the global config file — never merging project-local
1639 /// `.lean-ctx.toml` overrides, and bypassing the in-memory cache. Every
1640 /// PERSIST path must use this (or [`Config::update_global`]): [`Config::load`]
1641 /// folds per-project overrides into the struct, and [`Config::save`] writes
1642 /// the whole struct back to the GLOBAL file — so a `load → mutate → save`
1643 /// round-trip silently leaks per-project values (and, historically, reset
1644 /// customized keys) into the global config (#443). Reading global-only makes
1645 /// the save leak-free by construction.
1646 pub fn load_global() -> Self {
1647 Self::path().map_or_else(Self::default, |p| Self::load_global_from(&p))
1648 }
1649
1650 /// Path-parameterized core of [`Config::load_global`] (unit-testable without
1651 /// the real config dir). Missing, empty, or unparseable files yield
1652 /// defaults; persisting callers that must not clobber a corrupt file use
1653 /// [`Config::update_global`], which refuses instead.
1654 fn load_global_from(path: &Path) -> Self {
1655 match std::fs::read_to_string(path) {
1656 Ok(raw) if !raw.trim().is_empty() => toml::from_str(&raw).unwrap_or_default(),
1657 _ => Self::default(),
1658 }
1659 }
1660
1661 /// Safely mutate and persist the GLOBAL config. Reads the global file only
1662 /// (no project-local merge), applies `f`, then writes minimally. Refuses
1663 /// (returns `Err`) when the file exists but is unparseable, so a typo can
1664 /// never clobber a customized config (#443). Returns the saved `Config`.
1665 ///
1666 /// This is the canonical persistence entry point: prefer it over
1667 /// `Config::load()` followed by `save()`, which leaks project-local
1668 /// overrides into the global file.
1669 pub fn update_global<F>(f: F) -> std::result::Result<Self, super::error::LeanCtxError>
1670 where
1671 F: FnOnce(&mut Self),
1672 {
1673 let path = Self::path().ok_or_else(|| {
1674 super::error::LeanCtxError::Config("cannot determine home directory".into())
1675 })?;
1676 Self::update_global_at(&path, f)
1677 }
1678
1679 /// Path-parameterized core of [`Config::update_global`] (unit-testable).
1680 fn update_global_at<F>(
1681 path: &Path,
1682 f: F,
1683 ) -> std::result::Result<Self, super::error::LeanCtxError>
1684 where
1685 F: FnOnce(&mut Self),
1686 {
1687 let mut cfg = match std::fs::read_to_string(path) {
1688 Ok(raw) if !raw.trim().is_empty() => toml::from_str::<Self>(&raw).map_err(|e| {
1689 super::error::LeanCtxError::Config(format!(
1690 "refusing to modify an unparseable config.toml ({e}); fix it \
1691 manually or run `lean-ctx doctor --fix`, then retry"
1692 ))
1693 })?,
1694 _ => Self::default(),
1695 };
1696 f(&mut cfg);
1697 cfg.save_to(path)?;
1698 Ok(cfg)
1699 }
1700
1701 /// Persists the current config to the global config file.
1702 ///
1703 /// Preserves user comments, formatting, and unknown keys, keeps the file
1704 /// minimal (defaults that were never set on disk stay implicit), and writes
1705 /// atomically with a `.bak` backup so customizations are always recoverable.
1706 pub fn save(&self) -> std::result::Result<(), super::error::LeanCtxError> {
1707 let path = Self::path().ok_or_else(|| {
1708 super::error::LeanCtxError::Config("cannot determine home directory".into())
1709 })?;
1710 self.save_to(&path)
1711 }
1712
1713 /// Path-parameterized core of [`Config::save`] (unit-testable).
1714 fn save_to(&self, path: &Path) -> std::result::Result<(), super::error::LeanCtxError> {
1715 if let Some(parent) = path.parent() {
1716 std::fs::create_dir_all(parent)?;
1717 }
1718 let content = toml::to_string_pretty(self)
1719 .map_err(|e| super::error::LeanCtxError::Config(e.to_string()))?;
1720 // Baseline = what loading an empty config yields. This honors serde's
1721 // field-level `#[serde(default)]` (which can diverge from the struct's
1722 // `Default` impl), so minimal mode skips exactly the keys that a fresh
1723 // load would produce — no spurious lines on save.
1724 let baseline = toml::from_str::<Self>("").unwrap_or_else(|_| Self::default());
1725 let defaults = toml::to_string_pretty(&baseline)
1726 .map_err(|e| super::error::LeanCtxError::Config(e.to_string()))?;
1727 crate::config_io::write_toml_preserving_minimal(path, &content, &defaults)
1728 .map_err(super::error::LeanCtxError::Config)?;
1729 Ok(())
1730 }
1731
1732 /// Formats the current config as a human-readable string with file paths.
1733 pub fn show(&self) -> String {
1734 let global_path = Self::path().map_or_else(
1735 || "~/.lean-ctx/config.toml".to_string(),
1736 |p| p.to_string_lossy().to_string(),
1737 );
1738 let content = toml::to_string_pretty(self).unwrap_or_default();
1739 let mut out = format!("Global config: {global_path}\n\n{content}");
1740
1741 if let Some(root) = Self::find_project_root() {
1742 let local = Self::local_path(&root);
1743 if local.exists() {
1744 out.push_str(&format!("\n\nLocal config (merged): {}\n", local.display()));
1745 } else {
1746 out.push_str(&format!(
1747 "\n\nLocal config: not found (create {} to override per-project)\n",
1748 local.display()
1749 ));
1750 }
1751 }
1752 out
1753 }
1754}