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