Skip to main content

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