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;
20pub(crate) mod 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    /// Global hook mode override. When set, overrides the per-agent auto-detection.
438    /// - `replace`: Native Read/Grep/Glob/Shell denied, lean-ctx MCP is the only path
439    /// - `hybrid`: MCP + shell hooks for compression (legacy)
440    /// - `mcp`: MCP server only, no hooks
441    ///
442    /// Default: unset (auto-detect per agent via `recommend_hook_mode`)
443    #[serde(default)]
444    pub hook_mode: Option<String>,
445    /// Opt-in (#520): write a human-readable debug log of intercepted MCP tool
446    /// calls and hook routing decisions (lean-ctx vs native, with reasons) to
447    /// `<state_dir>/logs/debug.log`. Override via the LEAN_CTX_DEBUG_LOG env var.
448    #[serde(default)]
449    pub debug_log: bool,
450    /// Controls when the shell hook auto-activates aliases.
451    /// - `agents-only`: (Default since #699) Aliases only active when an AI
452    ///   agent env var is detected — transparent in plain human terminals.
453    /// - `always`: Aliases active in every interactive shell (pre-#699 default).
454    /// - `off`: Aliases never auto-activate (user must call `lean-ctx-on` manually).
455    ///
456    /// Override via `LEAN_CTX_SHELL_ACTIVATION` env var.
457    #[serde(default)]
458    pub shell_activation: ShellActivation,
459    /// Do not install agent CLI aliases (`claude`, `codex`, `gemini`,
460    /// `codebuddy`) into `~/.zshrc` / `~/.bashrc` during `onboard` / `setup`.
461    /// Existing alias blocks are removed when this is toggled on (#754).
462    /// Does NOT affect the shell compression hook (`_lc()`) — use
463    /// `shell_hook_disabled` for that. Orthogonal to `shell_activation` which
464    /// controls *when* aliases activate, not *whether* they are installed.
465    #[serde(default)]
466    pub skip_agent_aliases: bool,
467    /// Controls the native-Read → `ctx_read` redirect hook (#637).
468    /// - `auto`: (Default) redirect everywhere except hosts with a native
469    ///   read-before-write guard (Claude Code / CodeBuddy), where the path-swap
470    ///   would break native Write/Edit.
471    /// - `on`: always redirect (legacy behavior).
472    /// - `off`: never redirect native Read.
473    ///
474    /// Override via the `LEAN_CTX_READ_REDIRECT` env var.
475    #[serde(default)]
476    pub read_redirect: ReadRedirect,
477    /// Controls the PostToolUse native-Read re-read dedup (GL #1140).
478    /// - `auto`: (Default) replace only re-reads of unchanged files, and only on
479    ///   guard hosts (Claude Code / CodeBuddy) where the PreToolUse redirect is
480    ///   disabled — the guard-safe way to win the dedup savings back.
481    /// - `on`: dedup wherever the PostToolUse hook fires.
482    /// - `off`: never replace a Read result.
483    ///
484    /// Override via the `LEAN_CTX_READ_DEDUP` env var.
485    #[serde(default)]
486    pub read_dedup: ReadDedup,
487    /// Disable the daily version check against leanctx.com/version.txt.
488    /// Override via LEAN_CTX_NO_UPDATE_CHECK env var.
489    #[serde(default)]
490    pub update_check_disabled: bool,
491    #[serde(default)]
492    pub updates: UpdatesConfig,
493    /// Fixed-context budget accounting for `doctor overhead` / `gain` (#964).
494    #[serde(default)]
495    pub context: ContextConfig,
496    /// Maximum BM25 cache file size in MB. Indexes exceeding this are quarantined on load
497    /// and refused on save. Override via LEAN_CTX_BM25_MAX_CACHE_MB env var.
498    #[serde(default = "serde_defaults::default_bm25_max_cache_mb")]
499    pub bm25_max_cache_mb: u64,
500    /// Maximum number of files scanned by the lightweight JSON graph index.
501    /// 0 = unlimited (default). Set >0 to cap for constrained systems.
502    #[serde(default = "serde_defaults::default_graph_index_max_files")]
503    pub graph_index_max_files: u64,
504    /// Controls RAM vs feature trade-off. Values: "low", "balanced" (default), "performance".
505    /// Override via LEAN_CTX_MEMORY_PROFILE env var.
506    #[serde(default)]
507    pub memory_profile: MemoryProfile,
508    /// Controls how aggressively memory is freed when idle.
509    /// Values: "shared" (default, 1h TTL), "aggressive" (5 min TTL for low-memory devices).
510    /// Override via LEAN_CTX_MEMORY_CLEANUP env var.
511    #[serde(default)]
512    pub memory_cleanup: MemoryCleanup,
513    /// Maximum percentage of system RAM that lean-ctx may use (default: 5).
514    /// Override via LEAN_CTX_MAX_RAM_PERCENT env var.
515    #[serde(default = "serde_defaults::default_max_ram_percent")]
516    pub max_ram_percent: u8,
517    /// Simplified disk budget (MB). When set and detail values are at defaults,
518    /// distributes proportionally: archive=25%, bm25=10%, remainder for stores.
519    /// 0 = disabled (use individual settings). Override via LEAN_CTX_MAX_DISK_MB.
520    #[serde(default)]
521    pub max_disk_mb: u64,
522    /// Auto-purge data older than this many days. 0 = disabled.
523    /// Flows into archive.max_age_hours and lifecycle idle TTL.
524    #[serde(default)]
525    pub max_staleness_days: u32,
526    /// Cap on the rayon worker threads used by the CPU-heavy index build
527    /// (call graph etc.). 0 = rayon default (all cores). Set >0 to bound
528    /// per-instance CPU so a fleet of concurrent sessions can't saturate the
529    /// host on startup. Override via LEANCTX_INDEX_THREADS env var.
530    #[serde(default)]
531    pub max_index_threads: usize,
532    /// Controls visibility of token savings footers in tool output.
533    /// Values: "always" (default, show on every response), "never", "auto" (legacy compatibility).
534    /// Override via LEAN_CTX_SAVINGS_FOOTER or LEAN_CTX_SHOW_SAVINGS=1|0 env var.
535    #[serde(default)]
536    pub savings_footer: SavingsFooter,
537    /// Explicit project root override. When set, lean-ctx uses this instead of auto-detection.
538    /// This prevents accidental home-directory scans when running from $HOME.
539    /// Override via LEAN_CTX_PROJECT_ROOT env var.
540    #[serde(default)]
541    pub project_root: Option<String>,
542    /// LSP server overrides. Map language name to custom binary path.
543    /// Example: `[lsp]\nrust = "/opt/rust-analyzer"\npython = "~/.venvs/main/bin/pylsp"`
544    #[serde(default)]
545    pub lsp: std::collections::HashMap<String, String>,
546    /// Per-IDE allowed paths. Restricts which directories lean-ctx will scan/index for each IDE.
547    /// Example: `[ide_paths]\ncursor = ["/home/user/projects/app1"]\ncodex = ["/home/user/codex"]`
548    /// When set, only these paths are indexed for the matching agent. Global `allow_paths` still applies.
549    #[serde(default)]
550    pub ide_paths: HashMap<String, Vec<String>>,
551    /// Custom model context window overrides.
552    /// Example: `[model_context_windows]\n"my-custom-model" = 500000`
553    #[serde(default)]
554    pub model_context_windows: HashMap<String, usize>,
555    /// Controls how much detail tool responses include.
556    ///
557    /// - `full` (default): complete compressed output
558    /// - `headers_only`: metadata line only (path, mode, token count)
559    ///
560    /// Override via `LEAN_CTX_RESPONSE_VERBOSITY` env var.
561    #[serde(default)]
562    pub response_verbosity: ResponseVerbosity,
563    /// Bypass hint mode. When agents use native Read/Grep instead of lean-ctx tools,
564    /// a hint is appended to the next tool response.
565    /// Values: "on" (default), "off", "aggressive" (hint on every call, no cooldown).
566    /// Override via LEAN_CTX_BYPASS_HINTS env var.
567    #[serde(default)]
568    pub bypass_hints: Option<String>,
569    /// Cache policy for ctx_read. Controls behavior on cache hits.
570    /// Values: "aggressive" (default, 13-tok stubs + compaction-aware reset),
571    /// "safe" (delivers map instead of stub), "off" (no caching, always disk read).
572    /// Override via LEAN_CTX_CACHE_POLICY env var.
573    #[serde(default)]
574    pub cache_policy: Option<String>,
575    /// Token budget for the in-memory `ctx_read` cache. When the cached total
576    /// plus an incoming read would exceed this, lean-ctx evicts the least-valuable
577    /// entries *immediately* (RRF: recency × frequency × size) so the read always
578    /// proceeds — eviction is never deferred to the staleness TTL. `0` uses the
579    /// built-in default (2M). `LEAN_CTX_CACHE_MAX_TOKENS` env var overrides this.
580    #[serde(default)]
581    pub cache_max_tokens: usize,
582    /// Cross-project boundary policy.
583    /// Controls whether cross-project search/import is allowed and whether access is audited.
584    #[serde(default)]
585    pub boundary_policy: crate::core::memory_boundary::BoundaryPolicy,
586    #[serde(default)]
587    pub secret_detection: SecretDetectionConfig,
588    /// Per-item sensitivity model with a uniform policy floor (#212).
589    /// Disabled by default → fully no-op until `sensitivity.enabled = true`.
590    #[serde(default)]
591    pub sensitivity: crate::core::sensitivity::SensitivityConfig,
592    /// MCP Tool-Catalog Gateway (#210): aggregate + query-route downstream MCP
593    /// servers. Global-only (never merged from project-local config) and a full
594    /// no-op until `gateway.enabled = true`.
595    #[serde(default)]
596    pub gateway: crate::core::mcp_catalog::GatewayConfig,
597    /// Self-hosted org gateway server (`[gateway_server]`, enterprise#20):
598    /// deployment parameters for the usage cockpit — seat count for the
599    /// org-wide projection, display label, and the central admin API the local
600    /// cockpit may read from. All optional; absent = local-only behavior.
601    #[serde(default)]
602    pub gateway_server: GatewayServerConfig,
603    /// Addon ecosystem security floor (#863): install policy, registry-signature
604    /// requirement and sandboxing for spawned addon servers. Global-only (never
605    /// merged from project-local config) and fully permissive by default.
606    #[serde(default)]
607    pub addons: crate::core::addons::AddonsConfig,
608    /// Allow automatic project-root re-rooting when absolute paths outside the jail are seen.
609    /// When false (default), absolute paths outside the jail are rejected without re-rooting.
610    /// Override via LEAN_CTX_ALLOW_REROOT env var.
611    #[serde(default)]
612    pub allow_auto_reroot: bool,
613    /// Verbatim binary path/expression for generated agent-hook commands
614    /// (#708). Users who sync agent settings (`~/.claude/settings.json`, …)
615    /// across machines with different usernames need an env-based form like
616    /// `$HOME/.local/bin/lean-ctx` — agent hosts run hook commands through a
617    /// shell, which expands it. When set (env `LEAN_CTX_HOOK_BINARY` wins,
618    /// then this key), every hook writer emits the value verbatim instead of
619    /// the machine-absolute exe path, so `init`/`doctor --fix`/`update` stop
620    /// rewriting synced files into sync ping-pong. Autostart plists/services
621    /// and daemon spawns are NOT affected — launchd/systemd do not expand
622    /// shell variables, so those keep the real absolute path. Empty (default)
623    /// = automatic absolute-path resolution (#367).
624    #[serde(default)]
625    pub hook_binary: Option<String>,
626    /// Disable PathJail entirely by setting `path_jail = false` in config.toml.
627    /// Useful in container/Docker environments where the sandbox is the boundary.
628    /// (The former `LEAN_CTX_NO_JAIL=1` env override was removed in v3.7.3.)
629    #[serde(default)]
630    pub path_jail: Option<bool>,
631    /// Sandbox level for code execution (ctx_exec).
632    /// 0 = subprocess only (current), 1 = OS-level restriction (Seatbelt/Landlock).
633    /// Override via LEAN_CTX_SANDBOX_LEVEL env var.
634    #[serde(default)]
635    pub sandbox_level: u8,
636    /// When true, large tool outputs (>4000 chars) are stored as references
637    /// and a short URI is returned instead of the full content.
638    /// Override via LEAN_CTX_REFERENCE_RESULTS env var.
639    #[serde(default)]
640    pub reference_results: bool,
641    /// Default per-agent token budget. 0 means unlimited.
642    /// Override per-agent via ctx_session or programmatically.
643    #[serde(default)]
644    pub agent_token_budget: usize,
645    /// Optional shell command allowlist. When non-empty, only commands whose base binary
646    /// is in this list are permitted by ctx_shell. Empty = disable allowlist (allow all).
647    /// Default includes common dev tools. Set to `[]` to disable.
648    /// Override via LEAN_CTX_SHELL_ALLOWLIST env var (comma-separated).
649    #[serde(default = "default_shell_allowlist")]
650    pub shell_allowlist: Vec<String>,
651
652    /// Extra commands MERGED on top of the effective `shell_allowlist` without replacing
653    /// the defaults. Setting `shell_allowlist` replaces the whole built-in list (a common
654    /// footgun); entries here are purely additive, which is what `lean-ctx allow <cmd>`
655    /// writes. Only applied in restricted mode (when the base allowlist is non-empty).
656    #[serde(default)]
657    pub shell_allowlist_extra: Vec<String>,
658
659    /// When true, block command substitution ($(), backticks) and process substitution
660    /// (<(), >()) in shell arguments. When false (default), only warn via tracing.
661    /// Default false preserves backward compatibility — set true for maximum security.
662    #[serde(default)]
663    pub shell_strict_mode: bool,
664
665    /// Shell-security mode for ctx_shell / `lean-ctx -c` command gating (GL #788):
666    /// `enforce` (default, secure), `warn` (run checks, log violations, never
667    /// block) or `off` (skip the allowlist + dangerous-pattern blocks entirely —
668    /// a deliberate opt-out; compression stays active). Override via
669    /// LEAN_CTX_SHELL_SECURITY. `None` resolves to `enforce`.
670    #[serde(default)]
671    pub shell_security: Option<String>,
672
673    /// Default shell-command timeout in seconds for *normal* commands. `None`
674    /// resolves to the built-in 2-minute default; heavy builds/tests use
675    /// [`Config::shell_heavy_timeout_secs`]. Override via
676    /// `LEAN_CTX_SHELL_TIMEOUT_SECS` (`LEAN_CTX_SHELL_TIMEOUT_MS` still wins over
677    /// both, in milliseconds).
678    #[serde(default)]
679    pub shell_timeout_secs: Option<u64>,
680
681    /// Shell-command timeout in seconds for *heavy* commands (cargo build/test,
682    /// make, docker build, git commit/push, …). `None` resolves to the built-in
683    /// 10-minute ceiling. Override via `LEAN_CTX_SHELL_HEAVY_TIMEOUT_SECS`.
684    #[serde(default)]
685    pub shell_heavy_timeout_secs: Option<u64>,
686
687    /// When true, `ctx_shell` accepts shell file-write redirects (`>`, `>>`,
688    /// `tee`, heredoc-to-file, `curl -o`, `wget` default mode). Default false —
689    /// the native Write/Edit tool is preferred. Opt-in for power users who want
690    /// classic shell syntax; the real command gating (allowlist,
691    /// dangerous-pattern and interpreter-eval blocks) still applies. Override
692    /// via `LEAN_CTX_SHELL_ALLOW_WRITES=1`.
693    #[serde(default)]
694    pub shell_allow_writes: bool,
695
696    /// Setup behavior: controls what gets injected during setup and updates.
697    #[serde(default)]
698    pub setup: SetupConfig,
699}
700
701impl Default for Config {
702    fn default() -> Self {
703        Self {
704            ultra_compact: false,
705            tee_mode: TeeMode::default(),
706            recovery_hints: RecoveryHints::default(),
707            output_density: OutputDensity::default(),
708            checkpoint_interval: 15,
709            excluded_commands: Vec::new(),
710            passthrough_urls: Vec::new(),
711            custom_aliases: Vec::new(),
712            preserve_compact_formats: serde_defaults::default_preserve_compact_formats(),
713            crush_verbatim_json: false,
714            slow_command_threshold_ms: 5000,
715            theme: serde_defaults::default_theme(),
716            cloud: CloudConfig::default(),
717            gain: GainConfig::default(),
718            cost: CostConfig::default(),
719            code_health: CodeHealthConfig::default(),
720            autonomy: AutonomyConfig::default(),
721            providers: ProvidersConfig::default(),
722            proxy: ProxyConfig::default(),
723            proxy_enabled: None,
724            proxy_port: None,
725            proxy_timeout_ms: None,
726            proxy_require_token: false,
727            proxy_loopback_open: false,
728            proxy_bind_host: None,
729            proxy_allowed_hosts: Vec::new(),
730            proxy_max_rps: None,
731            dashboard_auth: true,
732            buddy_enabled: serde_defaults::default_buddy_enabled(),
733            enable_wakeup_ctx: true,
734            redirect_exclude: Vec::new(),
735            disabled_tools: Vec::new(),
736            prefer_native_editor: false,
737            default_tool_categories: Vec::new(),
738            no_degrade: false,
739            delta_explicit: false,
740            profile: None,
741            tool_profile: None,
742            tools_enabled: Vec::new(),
743            persona: None,
744            loop_detection: LoopDetectionConfig::default(),
745            rules_scope: None,
746            rules_injection: None,
747            permission_inheritance: None,
748            extra_ignore_patterns: Vec::new(),
749            terse_agent: TerseAgent::default(),
750            compression_level: CompressionLevel::default(),
751            compression_aggressiveness: None,
752            archive: ArchiveConfig::default(),
753            memory: MemoryPolicy::default(),
754            allow_paths: Vec::new(),
755            allow_ide_config_dirs: None,
756            extra_roots: Vec::new(),
757            read_only_roots: Vec::new(),
758            allow_symlink_roots: Vec::new(),
759            content_defined_chunking: false,
760            minimal_overhead: true,
761            symbol_map_auto: false,
762            structure_first: false,
763            auto_mode_learning: false,
764            team_url: None,
765            team_token: None,
766            team_auto_push: false,
767            journal_enabled: true,
768            auto_capture: true,
769            search: crate::core::hybrid_search::HybridConfig::default(),
770            graph: GraphConfig::default(),
771            index: IndexConfig::default(),
772            skillify: SkillifyConfig::default(),
773            summaries: SummariesConfig::default(),
774            llm: crate::core::llm_enhance::LlmConfig::default(),
775            embedding: EmbeddingConfig::default(),
776            shell_hook_disabled: false,
777            shadow_mode: false,
778            hook_mode: None,
779            debug_log: false,
780            shell_activation: ShellActivation::default(),
781            skip_agent_aliases: false,
782            read_redirect: ReadRedirect::default(),
783            read_dedup: ReadDedup::default(),
784            update_check_disabled: false,
785            updates: UpdatesConfig::default(),
786            context: ContextConfig::default(),
787            graph_index_max_files: serde_defaults::default_graph_index_max_files(),
788            bm25_max_cache_mb: serde_defaults::default_bm25_max_cache_mb(),
789            memory_profile: MemoryProfile::default(),
790            memory_cleanup: MemoryCleanup::default(),
791            max_ram_percent: serde_defaults::default_max_ram_percent(),
792            max_disk_mb: 0,
793            max_staleness_days: 0,
794            max_index_threads: 0,
795            savings_footer: SavingsFooter::default(),
796            project_root: None,
797            lsp: std::collections::HashMap::new(),
798            ide_paths: HashMap::new(),
799            model_context_windows: HashMap::new(),
800            response_verbosity: ResponseVerbosity::default(),
801            bypass_hints: None,
802            cache_policy: None,
803            cache_max_tokens: 0,
804            boundary_policy: crate::core::memory_boundary::BoundaryPolicy::default(),
805            secret_detection: SecretDetectionConfig::default(),
806            sensitivity: crate::core::sensitivity::SensitivityConfig::default(),
807            gateway: crate::core::mcp_catalog::GatewayConfig::default(),
808            gateway_server: GatewayServerConfig::default(),
809            addons: crate::core::addons::AddonsConfig::default(),
810            allow_auto_reroot: false,
811            hook_binary: None,
812            path_jail: None,
813            sandbox_level: 0,
814            reference_results: false,
815            agent_token_budget: 0,
816            shell_allowlist: default_shell_allowlist(),
817            shell_allowlist_extra: Vec::new(),
818            shell_strict_mode: false,
819            shell_security: None,
820            shell_timeout_secs: None,
821            shell_heavy_timeout_secs: None,
822            shell_allow_writes: false,
823            setup: SetupConfig::default(),
824        }
825    }
826}
827
828/// Holds the most recent global `config.toml` parse error, if the file currently
829/// fails to parse. When that happens `Config::load()` silently falls back to the
830/// built-in defaults and only logs to stderr — which is invisible over an MCP/stdio
831/// transport. Recording it here lets callers (e.g. the shell-allowlist diagnostic
832/// and `lean-ctx doctor`) surface "you're on defaults because your config is broken".
833static LAST_PARSE_ERROR: Mutex<Option<String>> = Mutex::new(None);
834
835/// Returns the most recent global config parse error, or `None` if the current
836/// `config.toml` parsed successfully (or no config file exists).
837#[must_use]
838pub fn last_config_parse_error() -> Option<String> {
839    LAST_PARSE_ERROR.lock().ok().and_then(|g| g.clone())
840}
841
842fn record_parse_error(err: Option<String>) {
843    if let Ok(mut guard) = LAST_PARSE_ERROR.lock() {
844        *guard = err;
845    }
846}
847
848/// Reset every SECURITY-sensitive field of a parsed project-local `Config` back
849/// to its default, returning the names of the ones that actually carried an
850/// override. Used by [`Config::merge_local`] for untrusted workspaces: clearing a
851/// field to its default makes the downstream "== default ⇒ no override" merge
852/// guards skip it automatically, so a single list here gates every sensitive key
853/// without touching the per-field merge arms (security audit #4).
854///
855/// Sensitive = anything that can widen lean-ctx's own boundaries or steer the
856/// agent: the shell allowlist, path-jail roots, proxy upstreams, command
857/// aliases, network passthrough, rules scope/injection, tool surface control
858/// (profile/enabled-list/categories, disabling) and permission inheritance.
859/// Comfort/perf knobs are intentionally NOT listed.
860fn strip_sensitive_overrides(local: &mut Config) -> Vec<&'static str> {
861    let mut withheld: Vec<&'static str> = Vec::new();
862
863    if local.shell_allowlist != default_shell_allowlist() {
864        local.shell_allowlist = default_shell_allowlist();
865        withheld.push("shell_allowlist");
866    }
867    if !local.shell_allowlist_extra.is_empty() {
868        local.shell_allowlist_extra.clear();
869        withheld.push("shell_allowlist_extra");
870    }
871    if !local.allow_paths.is_empty() {
872        local.allow_paths.clear();
873        withheld.push("allow_paths");
874    }
875    if !local.extra_roots.is_empty() {
876        local.extra_roots.clear();
877        withheld.push("extra_roots");
878    }
879    if !local.allow_symlink_roots.is_empty() {
880        local.allow_symlink_roots.clear();
881        withheld.push("allow_symlink_roots");
882    }
883    if !local.custom_aliases.is_empty() {
884        local.custom_aliases.clear();
885        withheld.push("custom_aliases");
886    }
887    if !local.passthrough_urls.is_empty() {
888        local.passthrough_urls.clear();
889        withheld.push("passthrough_urls");
890    }
891    if local.proxy.anthropic_upstream.is_some()
892        || local.proxy.openai_upstream.is_some()
893        || local.proxy.chatgpt_upstream.is_some()
894        || local.proxy.gemini_upstream.is_some()
895    {
896        local.proxy.anthropic_upstream = None;
897        local.proxy.openai_upstream = None;
898        local.proxy.chatgpt_upstream = None;
899        local.proxy.gemini_upstream = None;
900        withheld.push("proxy.*_upstream");
901    }
902    if local.rules_scope.is_some() {
903        local.rules_scope = None;
904        withheld.push("rules_scope");
905    }
906    if local.rules_injection.is_some() {
907        local.rules_injection = None;
908        withheld.push("rules_injection");
909    }
910    if local.permission_inheritance.is_some() {
911        local.permission_inheritance = None;
912        withheld.push("permission_inheritance");
913    }
914    if !local.disabled_tools.is_empty() {
915        local.disabled_tools.clear();
916        withheld.push("disabled_tools");
917    }
918    if local.tool_profile.is_some() {
919        local.tool_profile = None;
920        withheld.push("tool_profile");
921    }
922    if !local.tools_enabled.is_empty() {
923        local.tools_enabled.clear();
924        withheld.push("tools_enabled");
925    }
926    if !local.default_tool_categories.is_empty() {
927        local.default_tool_categories.clear();
928        withheld.push("default_tool_categories");
929    }
930
931    withheld
932}
933
934/// Names of the SECURITY-sensitive overrides a project-local `.lean-ctx.toml`
935/// carries — the keys `strip_sensitive_overrides` would withhold for an
936/// untrusted workspace. Read-only (parses a throwaway `Config`); used by
937/// `lean-ctx trust` to tell the user exactly what trusting will enable.
938#[must_use]
939pub fn local_sensitive_overrides(local_toml: &str) -> Vec<&'static str> {
940    match toml::from_str::<Config>(local_toml) {
941        Ok(mut parsed) => strip_sensitive_overrides(&mut parsed),
942        Err(_) => Vec::new(),
943    }
944}
945
946impl Config {
947    /// Whether opt-in lossless JSON crushing of verbatim data commands (#936) is
948    /// active. `LEAN_CTX_CRUSH_VERBATIM_JSON` (any value) wins, then the
949    /// `crush_verbatim_json` config flag, else `false`.
950    pub fn crush_verbatim_json_enabled(&self) -> bool {
951        std::env::var("LEAN_CTX_CRUSH_VERBATIM_JSON").is_ok() || self.crush_verbatim_json
952    }
953
954    /// Effective proxy bind address (gateway mode, enterprise#8). Precedence:
955    /// `LEAN_CTX_PROXY_BIND_HOST` env > `proxy_bind_host` config > loopback.
956    /// The value must parse as an IP address; anything else (including a blank)
957    /// resolves to `127.0.0.1` — a typo can only ever *narrow* exposure, never
958    /// silently open the listener.
959    #[must_use]
960    pub fn resolved_proxy_bind_host(&self) -> std::net::IpAddr {
961        let raw = std::env::var("LEAN_CTX_PROXY_BIND_HOST")
962            .ok()
963            .filter(|v| !v.trim().is_empty())
964            .or_else(|| self.proxy_bind_host.clone());
965        match raw.as_deref().map(str::trim) {
966            Some(v) if !v.is_empty() => v.parse().unwrap_or_else(|_| {
967                tracing::warn!(
968                    "proxy_bind_host '{v}' is not a valid IP address — binding 127.0.0.1"
969                );
970                std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
971            }),
972            _ => std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
973        }
974    }
975
976    /// Returns the effective rules scope, preferring env var over config file.
977    pub fn rules_scope_effective(&self) -> RulesScope {
978        let raw = std::env::var("LEAN_CTX_RULES_SCOPE")
979            .ok()
980            .or_else(|| self.rules_scope.clone())
981            .unwrap_or_default();
982        match raw.trim().to_lowercase().as_str() {
983            "global" => RulesScope::Global,
984            "project" => RulesScope::Project,
985            _ => RulesScope::Both,
986        }
987    }
988
989    /// Returns the effective rules injection mode, preferring env var over config.
990    /// Default is `Shared` (zero-config discovery via a CLAUDE.md/CODEBUDDY.md/AGENTS.md block).
991    pub fn rules_injection_effective(&self) -> RulesInjection {
992        let raw = std::env::var("LEAN_CTX_RULES_INJECTION")
993            .ok()
994            .or_else(|| self.rules_injection.clone())
995            .unwrap_or_default();
996        match raw.trim().to_lowercase().as_str() {
997            "dedicated" => RulesInjection::Dedicated,
998            "off" | "none" | "disabled" => RulesInjection::Off,
999            _ => RulesInjection::Shared,
1000        }
1001    }
1002
1003    /// Returns the user-configured hook mode override, or `None` for auto-detect.
1004    /// Env var `LEAN_CTX_HOOK_MODE` takes priority over config.
1005    #[must_use]
1006    pub fn hook_mode_override(&self) -> Option<crate::hooks::HookMode> {
1007        let raw = std::env::var("LEAN_CTX_HOOK_MODE")
1008            .ok()
1009            .or_else(|| self.hook_mode.clone())?;
1010        crate::hooks::HookMode::from_str_loose(raw.trim())
1011    }
1012
1013    /// Returns the effective permission-inheritance mode, preferring the
1014    /// `LEAN_CTX_PERMISSION_INHERITANCE` env var over config. Default is `Off`.
1015    /// Accepts `on`/`true`/`1` as enabled.
1016    #[must_use]
1017    pub fn permission_inheritance_effective(&self) -> PermissionInheritance {
1018        let raw = std::env::var("LEAN_CTX_PERMISSION_INHERITANCE")
1019            .ok()
1020            .or_else(|| self.permission_inheritance.clone())
1021            .unwrap_or_default();
1022        match raw.trim().to_lowercase().as_str() {
1023            "on" | "true" | "1" | "inherit" => PermissionInheritance::On,
1024            _ => PermissionInheritance::Off,
1025        }
1026    }
1027
1028    /// True when lean-ctx should inject its rules via each agent's dedicated,
1029    /// non-polluting auto-load path *and* global rules are in scope.
1030    ///
1031    /// Gates the Claude/Codex `SessionStart` `additionalContext` summary: it
1032    /// stands in for the (now-skipped) shared CLAUDE.md/CODEBUDDY.md/AGENTS.md block, so it
1033    /// only fires when injection is `Dedicated` and the scope isn't project-only.
1034    #[must_use]
1035    pub fn dedicated_session_context_active(&self) -> bool {
1036        self.rules_injection_effective() == RulesInjection::Dedicated
1037            && self.rules_scope_effective() != RulesScope::Project
1038    }
1039
1040    fn parse_disabled_tools_env(val: &str) -> Vec<String> {
1041        val.split(',')
1042            .map(|s| s.trim().to_string())
1043            .filter(|s| !s.is_empty())
1044            .collect()
1045    }
1046
1047    /// Returns the effective disabled tools list, preferring env var over config
1048    /// file. When `prefer_native_editor` is active, the lean-ctx edit tools are
1049    /// folded in so they are hidden from `list_tools` (#454).
1050    pub fn disabled_tools_effective(&self) -> Vec<String> {
1051        let mut list = if let Ok(val) = std::env::var("LEAN_CTX_DISABLED_TOOLS") {
1052            Self::parse_disabled_tools_env(&val)
1053        } else {
1054            self.disabled_tools.clone()
1055        };
1056        if self.prefer_native_editor_effective() {
1057            for name in EDIT_TOOL_NAMES {
1058                if !list.iter().any(|t| t == name) {
1059                    list.push((*name).to_string());
1060                }
1061            }
1062        }
1063        list
1064    }
1065
1066    /// Whether lean-ctx edit operations are disabled in favour of the host's
1067    /// native editor (#454). `LEAN_CTX_PREFER_NATIVE_EDITOR` wins over config.
1068    pub fn prefer_native_editor_effective(&self) -> bool {
1069        match std::env::var("LEAN_CTX_PREFER_NATIVE_EDITOR") {
1070            Ok(raw) => matches!(
1071                raw.trim().to_lowercase().as_str(),
1072                "1" | "true" | "yes" | "on"
1073            ),
1074            Err(_) => self.prefer_native_editor,
1075        }
1076    }
1077
1078    /// Cap on the rayon index-build worker threads. `LEANCTX_INDEX_THREADS` wins
1079    /// over config; `0` means "no cap" — rayon's all-cores default is kept.
1080    pub fn max_index_threads_effective(&self) -> usize {
1081        std::env::var("LEANCTX_INDEX_THREADS")
1082            .ok()
1083            .and_then(|raw| raw.trim().parse::<usize>().ok())
1084            .unwrap_or(self.max_index_threads)
1085    }
1086
1087    /// Whether `name` is a lean-ctx edit operation that must be blocked from
1088    /// dispatch (direct and via `ctx_call`) when [`Self::prefer_native_editor_effective`]
1089    /// is set (#454). Read/search/shell/memory tools are never blocked.
1090    pub fn edit_tool_blocked(&self, name: &str) -> bool {
1091        self.prefer_native_editor_effective() && EDIT_TOOL_NAMES.contains(&name)
1092    }
1093
1094    /// Returns `true` if minimal overhead is enabled via env var or config.
1095    pub fn minimal_overhead_effective(&self) -> bool {
1096        std::env::var("LEAN_CTX_MINIMAL").is_ok() || self.minimal_overhead
1097    }
1098
1099    /// Returns `true` if structure-first auto reads are enabled.
1100    ///
1101    /// The `LEAN_CTX_STRUCTURE_FIRST` env var wins over the config field, and
1102    /// accepts the usual truthy/falsy spellings so a harness can flip it per run
1103    /// (`LEAN_CTX_STRUCTURE_FIRST=0` forces it off even if config enables it).
1104    pub fn structure_first_effective(&self) -> bool {
1105        match std::env::var("LEAN_CTX_STRUCTURE_FIRST") {
1106            Ok(raw) => matches!(
1107                raw.trim().to_lowercase().as_str(),
1108                "1" | "true" | "yes" | "on"
1109            ),
1110            Err(_) => self.structure_first,
1111        }
1112    }
1113
1114    /// Returns `true` when the adaptive learning signals may participate in
1115    /// `auto` mode resolution (#683). Off by default for a deterministic,
1116    /// I/O-light cascade; the `LEAN_CTX_AUTO_MODE_LEARNING` env var wins over the
1117    /// config field and accepts the usual truthy/falsy spellings.
1118    pub fn auto_mode_learning_effective(&self) -> bool {
1119        match std::env::var("LEAN_CTX_AUTO_MODE_LEARNING") {
1120            Ok(raw) => matches!(
1121                raw.trim().to_lowercase().as_str(),
1122                "1" | "true" | "yes" | "on"
1123            ),
1124            Err(_) => self.auto_mode_learning,
1125        }
1126    }
1127
1128    /// Returns `true` when probabilistic exploration (Thompson sampling,
1129    /// Boltzmann-temperature eviction, simulated annealing) may influence
1130    /// decisions. Off by default so tool output stays a deterministic, byte-
1131    /// stable function of (content, mode, task) — the determinism contract
1132    /// (#498) that lets provider prompt caching apply. The `LEAN_CTX_STOCHASTIC`
1133    /// env var wins (the usual truthy/falsy spellings); otherwise it follows
1134    /// [`Self::auto_mode_learning_effective`], which is itself off by default.
1135    pub fn is_stochastic_enabled(&self) -> bool {
1136        match std::env::var("LEAN_CTX_STOCHASTIC") {
1137            Ok(raw) => matches!(
1138                raw.trim().to_lowercase().as_str(),
1139                "1" | "true" | "yes" | "on"
1140            ),
1141            Err(_) => self.auto_mode_learning_effective(),
1142        }
1143    }
1144
1145    /// Returns `true` if minimal overhead should be enabled for this MCP client.
1146    ///
1147    /// This is a superset of `minimal_overhead_effective()`:
1148    /// - `LEAN_CTX_OVERHEAD_MODE=minimal` forces minimal overhead
1149    /// - `LEAN_CTX_OVERHEAD_MODE=full` disables client/model heuristics (still honors LEAN_CTX_MINIMAL / config)
1150    /// - In auto mode (default), certain low-context clients/models are treated as minimal to prevent
1151    ///   large metadata blocks from destabilizing smaller context windows (e.g. Hermes + MiniMax).
1152    pub fn minimal_overhead_effective_for_client(&self, client_name: &str) -> bool {
1153        if let Ok(raw) = std::env::var("LEAN_CTX_OVERHEAD_MODE") {
1154            match raw.trim().to_lowercase().as_str() {
1155                "minimal" => return true,
1156                "full" => return self.minimal_overhead_effective(),
1157                _ => {}
1158            }
1159        }
1160
1161        if self.minimal_overhead_effective() {
1162            return true;
1163        }
1164
1165        let client_lower = client_name.trim().to_lowercase();
1166        if !client_lower.is_empty() {
1167            if let Ok(list) = std::env::var("LEAN_CTX_MINIMAL_CLIENTS") {
1168                for needle in list.split(',').map(|s| s.trim().to_lowercase()) {
1169                    if !needle.is_empty() && client_lower.contains(&needle) {
1170                        return true;
1171                    }
1172                }
1173            } else if client_lower.contains("hermes") || client_lower.contains("minimax") {
1174                return true;
1175            }
1176        }
1177
1178        let model = std::env::var("LEAN_CTX_MODEL")
1179            .or_else(|_| std::env::var("LCTX_MODEL"))
1180            .unwrap_or_default();
1181        let model = model.trim().to_lowercase();
1182        if !model.is_empty() {
1183            let m = model.replace(['_', ' '], "-");
1184            if m.contains("minimax")
1185                || m.contains("mini-max")
1186                || m.contains("m2.7")
1187                || m.contains("m2-7")
1188            {
1189                return true;
1190            }
1191        }
1192
1193        false
1194    }
1195
1196    /// Returns `true` if shell hook injection is disabled via env var or config.
1197    pub fn shell_hook_disabled_effective(&self) -> bool {
1198        std::env::var("LEAN_CTX_NO_HOOK").is_ok() || self.shell_hook_disabled
1199    }
1200
1201    /// Returns the effective shell activation mode (env var > config > default).
1202    pub fn shell_activation_effective(&self) -> ShellActivation {
1203        ShellActivation::effective(self)
1204    }
1205
1206    /// Returns `true` if `ctx_shell` may accept shell file-write redirects.
1207    /// `LEAN_CTX_SHELL_ALLOW_WRITES` (`1`/`true`/`yes`/`on`) overrides
1208    /// `config.toml`. The real command gating still applies either way.
1209    pub fn shell_allow_writes_effective(&self) -> bool {
1210        match std::env::var("LEAN_CTX_SHELL_ALLOW_WRITES") {
1211            Ok(raw) => matches!(
1212                raw.trim().to_ascii_lowercase().as_str(),
1213                "1" | "true" | "yes" | "on"
1214            ),
1215            Err(_) => self.shell_allow_writes,
1216        }
1217    }
1218
1219    /// Returns `true` if the daily update check is disabled via env var or config.
1220    pub fn update_check_disabled_effective(&self) -> bool {
1221        std::env::var("LEAN_CTX_NO_UPDATE_CHECK").is_ok() || self.update_check_disabled
1222    }
1223
1224    pub fn memory_policy_effective(&self) -> Result<MemoryPolicy, String> {
1225        let mut policy = self.memory.clone();
1226        policy.apply_env_overrides();
1227
1228        let budget = self.max_disk_mb_effective();
1229        if budget > 0 {
1230            let scale_factor = (budget as f64 / 500.0).clamp(0.5, 10.0);
1231            let default_policy = MemoryPolicy::default();
1232            if policy.knowledge.max_facts == default_policy.knowledge.max_facts {
1233                policy.knowledge.max_facts = (200.0 * scale_factor) as usize;
1234            }
1235            if policy.knowledge.max_patterns == default_policy.knowledge.max_patterns {
1236                policy.knowledge.max_patterns = (50.0 * scale_factor) as usize;
1237            }
1238            if policy.episodic.max_episodes == default_policy.episodic.max_episodes {
1239                policy.episodic.max_episodes = (500.0 * scale_factor) as usize;
1240            }
1241            if policy.procedural.max_procedures == default_policy.procedural.max_procedures {
1242                policy.procedural.max_procedures = (100.0 * scale_factor) as usize;
1243            }
1244        }
1245
1246        policy.validate()?;
1247        Ok(policy)
1248    }
1249
1250    /// Returns the effective set of default tool categories.
1251    /// Priority: LCTX_DEFAULT_CATEGORIES env var > config.toml > hardcoded default.
1252    pub fn default_tool_categories_effective(&self) -> Vec<String> {
1253        if let Ok(val) = std::env::var("LCTX_DEFAULT_CATEGORIES") {
1254            return val
1255                .split(',')
1256                .map(|s| s.trim().to_lowercase())
1257                .filter(|s| !s.is_empty())
1258                .collect();
1259        }
1260        if !self.default_tool_categories.is_empty() {
1261            return self
1262                .default_tool_categories
1263                .iter()
1264                .map(|s| s.to_lowercase())
1265                .collect();
1266        }
1267        vec!["core".to_string(), "session".to_string()]
1268    }
1269
1270    /// Returns the effective tool profile.
1271    /// Priority: LEAN_CTX_TOOL_PROFILE env > config tool_profile > config
1272    /// tools_enabled > active persona's tool surface > power.
1273    ///
1274    /// Explicit settings win (backward compatible); when none are set, the
1275    /// active persona supplies the tool surface (the `coding` default resolves
1276    /// to `power`, so existing installs are unaffected).
1277    pub fn tool_profile_effective(&self) -> super::tool_profiles::ToolProfile {
1278        super::persona::Persona::resolve(self).effective_tool_profile(self)
1279    }
1280
1281    /// The `[sensitivity]` config with the active persona's floor folded in
1282    /// (persona-spec-v1). Enforcement chokepoints use this instead of the raw
1283    /// field so a persona like `lead-gen` (`sensitivity_floor = "confidential"`)
1284    /// protects PII out of the box. The `coding` default (`public`) passes the
1285    /// config through unchanged.
1286    #[must_use]
1287    pub fn sensitivity_effective(&self) -> crate::core::sensitivity::SensitivityConfig {
1288        self.sensitivity
1289            .clone()
1290            .with_persona_floor(super::persona::Persona::resolve(self).sensitivity_floor)
1291    }
1292
1293    /// Returns `true` if all automatic read-mode degradation is disabled.
1294    /// Checks LCTX_NO_DEGRADE env var first, then config.toml field.
1295    pub fn no_degrade_effective(&self) -> bool {
1296        if let Ok(val) = std::env::var("LCTX_NO_DEGRADE") {
1297            return val == "1" || val.eq_ignore_ascii_case("true");
1298        }
1299        self.no_degrade
1300    }
1301
1302    /// Returns `true` if explicit `full`/`lines:N-M` re-reads of
1303    /// cached-but-changed files should be served as deltas (`mode=diff`)
1304    /// instead of re-emitting full content.
1305    ///
1306    /// Checks the `LCTX_DELTA_EXPLICIT` env var first, then the config.toml
1307    /// field. Unlike a presence-only knob, an explicit `0`/`false` in the env
1308    /// forces the feature OFF even when the config field is `true`, so the env
1309    /// can fully override config in both directions.
1310    pub fn delta_explicit_effective(&self) -> bool {
1311        if let Ok(val) = std::env::var("LCTX_DELTA_EXPLICIT") {
1312            return val == "1" || val.eq_ignore_ascii_case("true");
1313        }
1314        self.delta_explicit
1315    }
1316
1317    /// Effective max_disk_mb from env or config.
1318    pub fn max_disk_mb_effective(&self) -> u64 {
1319        std::env::var("LEAN_CTX_MAX_DISK_MB")
1320            .ok()
1321            .and_then(|v| v.parse().ok())
1322            .unwrap_or(self.max_disk_mb)
1323    }
1324
1325    /// Effective max_staleness_days from env or config.
1326    pub fn max_staleness_days_effective(&self) -> u32 {
1327        std::env::var("LEAN_CTX_MAX_STALENESS_DAYS")
1328            .ok()
1329            .and_then(|v| v.parse().ok())
1330            .unwrap_or(self.max_staleness_days)
1331    }
1332
1333    /// Effective fixed-context budget (tokens) from env or config (#964). `0`
1334    /// (env or config) disables the warning; otherwise the per-session footprint
1335    /// is checked against this in `doctor overhead` and `gain`.
1336    pub fn context_budget_tokens_effective(&self) -> usize {
1337        std::env::var("LEAN_CTX_CONTEXT_BUDGET_TOKENS")
1338            .ok()
1339            .and_then(|v| v.parse().ok())
1340            .unwrap_or(self.context.budget_tokens)
1341    }
1342
1343    /// Archive max_disk_mb derived from simplified max_disk_mb if the detail
1344    /// value is still at its default. Explicit overrides take priority.
1345    pub fn archive_max_disk_mb_effective(&self) -> u64 {
1346        let budget = self.max_disk_mb_effective();
1347        if budget > 0 && self.archive.max_disk_mb == ArchiveConfig::default().max_disk_mb {
1348            budget * 25 / 100
1349        } else {
1350            self.archive.max_disk_mb
1351        }
1352    }
1353
1354    /// Archive max_age_hours derived from max_staleness_days if the detail
1355    /// value is still at its default. Explicit overrides take priority.
1356    pub fn archive_max_age_hours_effective(&self) -> u64 {
1357        let staleness = self.max_staleness_days_effective();
1358        if staleness > 0 && self.archive.max_age_hours == ArchiveConfig::default().max_age_hours {
1359            staleness as u64 * 24
1360        } else {
1361            self.archive.max_age_hours
1362        }
1363    }
1364
1365    /// Effective on-disk ceiling (MB) for the persisted BM25 index. Single source
1366    /// of truth for `save`/`load`, `cache prune`, and the doctor health check.
1367    ///
1368    /// Priority: explicit `bm25_max_cache_mb` › `max_disk_mb` budget (10%) ›
1369    /// generous default ([`DEFAULT_BM25_PERSIST_MB`]). The default is decoupled
1370    /// from the RAM profile so large repos persist instead of rebuilding forever
1371    /// (issue #249).
1372    pub fn bm25_max_cache_mb_effective(&self) -> u64 {
1373        if self.bm25_max_cache_mb != serde_defaults::default_bm25_max_cache_mb() {
1374            return self.bm25_max_cache_mb;
1375        }
1376        let budget = self.max_disk_mb_effective();
1377        if budget > 0 {
1378            return budget * 10 / 100;
1379        }
1380        DEFAULT_BM25_PERSIST_MB
1381    }
1382}
1383
1384impl Config {
1385    /// Returns the path to the global config file (`$XDG_CONFIG_HOME/lean-ctx/config.toml`).
1386    ///
1387    /// Resolves via [`crate::core::paths::config_dir`] so config lives in the
1388    /// RO-safe config category. Behavior-neutral today: `config_dir()` equals the
1389    /// legacy data dir for existing/single-dir installs (GH #408 / GL #602).
1390    pub fn path() -> Option<PathBuf> {
1391        crate::core::paths::config_dir()
1392            .ok()
1393            .map(|d| d.join("config.toml"))
1394    }
1395
1396    /// `Some(path)` when the global config the runtime *resolves* does not exist,
1397    /// so lean-ctx is silently on built-in defaults. `None` when a config file is
1398    /// present (or HOME is unresolvable).
1399    ///
1400    /// The directory is layout-dependent (XDG `~/.config/lean-ctx` vs legacy
1401    /// `~/.lean-ctx` vs `$LEAN_CTX_DATA_DIR`) and an MCP client may launch the
1402    /// server in a sandbox/container with a different `$HOME`. An edit made to a
1403    /// *different* `config.toml` than this one is silently ignored; the block
1404    /// messages use this to say so out loud over MCP, where the stderr path is
1405    /// invisible (#540).
1406    #[must_use]
1407    pub fn missing_config_path() -> Option<PathBuf> {
1408        match Self::path() {
1409            Some(p) if !p.exists() => Some(p),
1410            _ => None,
1411        }
1412    }
1413
1414    /// Returns the path to the project-local config override file.
1415    pub fn local_path(project_root: &str) -> PathBuf {
1416        PathBuf::from(project_root).join(".lean-ctx.toml")
1417    }
1418
1419    /// Resolves the active project root (env override → session → git toplevel →
1420    /// cwd), cached for the process. Exposed crate-wide so workspace-trust and the
1421    /// CLI agree with config loading on *which* directory a `.lean-ctx.toml`
1422    /// belongs to (GH security audit, finding 4).
1423    pub(crate) fn find_project_root() -> Option<String> {
1424        static ROOT_CACHE: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
1425        ROOT_CACHE
1426            .get_or_init(Self::find_project_root_inner)
1427            .clone()
1428    }
1429
1430    fn find_project_root_inner() -> Option<String> {
1431        if let Ok(env_root) = std::env::var("LEAN_CTX_PROJECT_ROOT")
1432            && !env_root.is_empty()
1433        {
1434            return Some(env_root);
1435        }
1436
1437        let cwd = std::env::current_dir().ok();
1438
1439        if let Some(root) =
1440            crate::core::session::SessionState::load_latest().and_then(|s| s.project_root)
1441        {
1442            let root_path = std::path::Path::new(&root);
1443            let cwd_is_under_root = cwd.as_ref().is_some_and(|c| c.starts_with(root_path));
1444            // Route the marker probe through the TCC-guarded helper and never
1445            // adopt a ~/Documents project root from a launchd-standalone process
1446            // (#356): doing so would later stat its `.lean-ctx.toml`/markers and
1447            // pop the macOS privacy prompt in lean-ctx's own name.
1448            let has_marker = crate::core::pathutil::has_project_marker(root_path);
1449
1450            if (cwd_is_under_root || has_marker) && crate::core::pathutil::may_probe_path(root_path)
1451            {
1452                return Some(root);
1453            }
1454        }
1455
1456        if let Some(ref cwd) = cwd {
1457            // A launchd-standalone process must not shell out to `git` (which
1458            // stats the working tree) or adopt cwd as the project root when cwd
1459            // is under a TCC-protected dir (#356).
1460            let may_probe_cwd = crate::core::pathutil::may_probe_path(cwd);
1461            let git_root = if may_probe_cwd {
1462                std::process::Command::new("git")
1463                    .args(["rev-parse", "--show-toplevel"])
1464                    .current_dir(cwd)
1465                    .stdout(std::process::Stdio::piped())
1466                    .stderr(std::process::Stdio::null())
1467                    .output()
1468                    .ok()
1469                    .and_then(|o| {
1470                        if o.status.success() {
1471                            String::from_utf8(o.stdout)
1472                                .ok()
1473                                .map(|s| s.trim().to_string())
1474                        } else {
1475                            None
1476                        }
1477                    })
1478            } else {
1479                None
1480            };
1481            if let Some(root) = git_root {
1482                return Some(root);
1483            }
1484            if may_probe_cwd && !crate::core::pathutil::is_broad_or_unsafe_root(cwd) {
1485                return Some(cwd.to_string_lossy().to_string());
1486            }
1487        }
1488        None
1489    }
1490
1491    /// Loads config from disk with caching, merging global + project-local overrides.
1492    ///
1493    /// The cache is keyed on a **content hash** of the global + project-local
1494    /// files, not their mtime. mtime-only invalidation silently served a stale
1495    /// `Config` whenever a content edit preserved the mtime (coarse filesystem
1496    /// mtime resolution, `cp -p`, atomic save-then-rename, two edits within the
1497    /// same second). A long-lived MCP server then kept the old value (e.g.
1498    /// `path_jail`) while a fresh `lean-ctx doctor` process — with an empty
1499    /// cache — saw the new one (#406). Config files are tiny, so reading +
1500    /// hashing them on every load is negligible and guarantees liveness.
1501    pub fn load() -> Self {
1502        (*Self::load_arc()).clone()
1503    }
1504
1505    /// Shared-ownership variant of [`load`](Self::load): returns the cached
1506    /// `Arc<Config>` so the per-dispatch hot path bumps a refcount instead of
1507    /// deep-cloning the whole struct. Liveness is identical to `load` — the
1508    /// global and project-local files are still read and content-hashed on
1509    /// every call (#406); only the cache payload became an `Arc`, so a cache
1510    /// hit is a cheap `Arc::clone`.
1511    pub fn load_arc() -> Arc<Self> {
1512        static CACHE: Mutex<ConfigCacheSlot> = Mutex::new(None);
1513
1514        let Some(path) = Self::path() else {
1515            return Arc::new(Self::default());
1516        };
1517
1518        let project_root = Self::find_project_root();
1519        let local_path = project_root.as_deref().map(Self::local_path);
1520
1521        // Read raw content up front so the cache key is a content hash.
1522        let global_content = std::fs::read_to_string(&path).ok();
1523        // TCC (#356): never read a project-local `.lean-ctx.toml` under
1524        // ~/Documents from a launchd-standalone process — the read pops the
1525        // macOS privacy prompt. `find_project_root` already avoids returning
1526        // such roots; this also guards the explicit `LEAN_CTX_PROJECT_ROOT` path.
1527        let local_content = local_path
1528            .as_ref()
1529            .filter(|p| crate::core::pathutil::may_probe_path(p.as_path()))
1530            .and_then(|p| std::fs::read_to_string(p).ok());
1531
1532        let global_hash = global_content.as_deref().map(crate::core::hasher::hash_str);
1533        let local_hash = local_content.as_deref().map(crate::core::hasher::hash_str);
1534
1535        if let Ok(guard) = CACHE.lock()
1536            && let Some((ref cfg, ref cached_global, ref cached_local)) = *guard
1537            && *cached_global == global_hash
1538            && *cached_local == local_hash
1539        {
1540            return Arc::clone(cfg);
1541        }
1542
1543        let mut cfg: Config = if let Some(ref content) = global_content {
1544            match toml::from_str(content) {
1545                Ok(c) => {
1546                    record_parse_error(None);
1547                    c
1548                }
1549                Err(e) => {
1550                    record_parse_error(Some(format!("{e}")));
1551                    tracing::warn!("config parse error in {}: {e}", path.display());
1552                    eprintln!(
1553                        "\x1b[33m[lean-ctx] WARNING: config parse error in {}: {e}\n  \
1554                         Using defaults. Run `lean-ctx doctor --fix` to repair.\x1b[0m",
1555                        path.display()
1556                    );
1557                    Self::default()
1558                }
1559            }
1560        } else {
1561            record_parse_error(None);
1562            Self::default()
1563        };
1564
1565        if let Some(ref local) = local_content {
1566            // Finding 4: a project-local `.lean-ctx.toml`'s SECURITY-sensitive
1567            // overrides (shell allowlist, path-jail widening, proxy upstream, …)
1568            // are honoured only for a workspace the user has explicitly trusted.
1569            // `local_hash` is exactly the content hash workspace-trust pins, so
1570            // editing the file after trust re-gates it (see `workspace_trust`).
1571            let trusted = project_root.as_deref().is_some_and(|r| {
1572                crate::core::workspace_trust::is_trusted_for(
1573                    std::path::Path::new(r),
1574                    local_hash.as_deref().unwrap_or_default(),
1575                )
1576            });
1577            cfg.merge_local(local, trusted);
1578        }
1579
1580        let cfg = Arc::new(cfg);
1581        if let Ok(mut guard) = CACHE.lock() {
1582            *guard = Some((Arc::clone(&cfg), global_hash, local_hash));
1583        }
1584
1585        cfg
1586    }
1587
1588    // `merge_local` is in `merge.rs` (extracted for #660 LOC gate).
1589
1590    /// Loads ONLY the global config file — never merging project-local
1591    /// `.lean-ctx.toml` overrides, and bypassing the in-memory cache. Every
1592    /// PERSIST path must use this (or [`Config::update_global`]): [`Config::load`]
1593    /// folds per-project overrides into the struct, and [`Config::save`] writes
1594    /// the whole struct back to the GLOBAL file — so a `load → mutate → save`
1595    /// round-trip silently leaks per-project values (and, historically, reset
1596    /// customized keys) into the global config (#443). Reading global-only makes
1597    /// the save leak-free by construction.
1598    pub fn load_global() -> Self {
1599        Self::path().map_or_else(Self::default, |p| Self::load_global_from(&p))
1600    }
1601
1602    /// Path-parameterized core of [`Config::load_global`] (unit-testable without
1603    /// the real config dir). Missing, empty, or unparseable files yield
1604    /// defaults; persisting callers that must not clobber a corrupt file use
1605    /// [`Config::update_global`], which refuses instead.
1606    fn load_global_from(path: &Path) -> Self {
1607        match std::fs::read_to_string(path) {
1608            Ok(raw) if !raw.trim().is_empty() => toml::from_str(&raw).unwrap_or_default(),
1609            _ => Self::default(),
1610        }
1611    }
1612
1613    /// Safely mutate and persist the GLOBAL config. Reads the global file only
1614    /// (no project-local merge), applies `f`, then writes minimally. Refuses
1615    /// (returns `Err`) when the file exists but is unparseable, so a typo can
1616    /// never clobber a customized config (#443). Returns the saved `Config`.
1617    ///
1618    /// This is the canonical persistence entry point: prefer it over
1619    /// `Config::load()` followed by `save()`, which leaks project-local
1620    /// overrides into the global file.
1621    pub fn update_global<F>(f: F) -> std::result::Result<Self, super::error::LeanCtxError>
1622    where
1623        F: FnOnce(&mut Self),
1624    {
1625        let path = Self::path().ok_or_else(|| {
1626            super::error::LeanCtxError::Config("cannot determine home directory".into())
1627        })?;
1628        Self::update_global_at(&path, f)
1629    }
1630
1631    /// Path-parameterized core of [`Config::update_global`] (unit-testable).
1632    fn update_global_at<F>(
1633        path: &Path,
1634        f: F,
1635    ) -> std::result::Result<Self, super::error::LeanCtxError>
1636    where
1637        F: FnOnce(&mut Self),
1638    {
1639        let mut cfg = match std::fs::read_to_string(path) {
1640            Ok(raw) if !raw.trim().is_empty() => toml::from_str::<Self>(&raw).map_err(|e| {
1641                super::error::LeanCtxError::Config(
1642                    format!(
1643                        "refusing to modify an unparseable config.toml ({e}); fix it \
1644                     manually or run `lean-ctx doctor --fix`, then retry"
1645                    )
1646                    .into(),
1647                )
1648            })?,
1649            _ => Self::default(),
1650        };
1651        f(&mut cfg);
1652        cfg.save_to(path)?;
1653        Ok(cfg)
1654    }
1655
1656    /// Persists the current config to the global config file.
1657    ///
1658    /// Preserves user comments, formatting, and unknown keys, keeps the file
1659    /// minimal (defaults that were never set on disk stay implicit), and writes
1660    /// atomically with a `.bak` backup so customizations are always recoverable.
1661    pub fn save(&self) -> std::result::Result<(), super::error::LeanCtxError> {
1662        let path = Self::path().ok_or_else(|| {
1663            super::error::LeanCtxError::Config("cannot determine home directory".into())
1664        })?;
1665        self.save_to(&path)
1666    }
1667
1668    /// Path-parameterized core of [`Config::save`] (unit-testable).
1669    fn save_to(&self, path: &Path) -> std::result::Result<(), super::error::LeanCtxError> {
1670        if let Some(parent) = path.parent() {
1671            std::fs::create_dir_all(parent)?;
1672        }
1673        let content = toml::to_string_pretty(self)
1674            .map_err(|e| super::error::LeanCtxError::Config(e.to_string().into()))?;
1675        // Baseline = what loading an empty config yields. This honors serde's
1676        // field-level `#[serde(default)]` (which can diverge from the struct's
1677        // `Default` impl), so minimal mode skips exactly the keys that a fresh
1678        // load would produce — no spurious lines on save.
1679        let baseline = toml::from_str::<Self>("").unwrap_or_else(|_| Self::default());
1680        let defaults = toml::to_string_pretty(&baseline)
1681            .map_err(|e| super::error::LeanCtxError::Config(e.to_string().into()))?;
1682        crate::config_io::write_toml_preserving_minimal(path, &content, &defaults)
1683            .map_err(|e| super::error::LeanCtxError::Config(e.into()))?;
1684        Ok(())
1685    }
1686
1687    /// Formats the current config as a human-readable string with file paths.
1688    pub fn show(&self) -> String {
1689        let global_path = Self::path().map_or_else(
1690            || "~/.lean-ctx/config.toml".to_string(),
1691            |p| p.to_string_lossy().to_string(),
1692        );
1693        let content = toml::to_string_pretty(self).unwrap_or_default();
1694        let mut out = format!("Global config: {global_path}\n\n{content}");
1695
1696        if let Some(root) = Self::find_project_root() {
1697            let local = Self::local_path(&root);
1698            if local.exists() {
1699                out.push_str(&format!("\n\nLocal config (merged): {}\n", local.display()));
1700            } else {
1701                out.push_str(&format!(
1702                    "\n\nLocal config: not found (create {} to override per-project)\n",
1703                    local.display()
1704                ));
1705            }
1706        }
1707        out
1708    }
1709}