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