lean_ctx/core/config/model.rs
1use serde::{Deserialize, Serialize};
2
3#[allow(clippy::wildcard_imports)]
4use super::*;
5fn default_true() -> bool {
6 true
7}
8
9/// Global lean-ctx configuration loaded from `config.toml`, merged with project-local overrides.
10#[derive(Debug, Clone, Serialize, Deserialize)]
11#[serde(default)]
12pub struct Config {
13 pub ultra_compact: bool,
14 #[serde(default, deserialize_with = "serde_defaults::deserialize_tee_mode")]
15 pub tee_mode: TeeMode,
16 /// Verbosity of the reactive recovery footer on compressed output
17 /// (`off|minimal|full`, default `minimal`). See [`RecoveryHints`].
18 #[serde(default)]
19 pub recovery_hints: RecoveryHints,
20 #[serde(default)]
21 pub output_density: OutputDensity,
22 pub checkpoint_interval: u32,
23 pub excluded_commands: Vec<String>,
24 pub passthrough_urls: Vec<String>,
25 pub custom_aliases: Vec<AliasEntry>,
26 /// Output formats that are already compact/token-oriented and must be
27 /// preserved verbatim instead of being recompressed (#342). Matched against
28 /// the *output shape* (not the command name), so any tool emitting the
29 /// format is covered without enumerating commands in `excluded_commands`.
30 /// Default: `["toon"]`. Set to `[]` to disable and always recompress.
31 #[serde(default = "serde_defaults::default_preserve_compact_formats")]
32 pub preserve_compact_formats: Vec<String>,
33 /// Opt-in: apply the lossless JSON crusher to *verbatim* data commands
34 /// (`gh api`, `jq`, `kubectl get -o json`, `curl` JSON). Off by default, so
35 /// those outputs stay byte-for-byte verbatim. When on, an array-heavy JSON
36 /// payload the crusher can at least halve is reshaped into a compact, fully
37 /// reconstructible form; everything else stays verbatim. See
38 /// [`Config::crush_verbatim_json_enabled`] (#936).
39 #[serde(default)]
40 pub crush_verbatim_json: bool,
41 /// Commands taking longer than this threshold (ms) are recorded in the slow log.
42 /// Set to 0 to disable slow logging.
43 pub slow_command_threshold_ms: u64,
44 #[serde(default = "serde_defaults::default_theme")]
45 pub theme: String,
46 /// Anonymous opt-in telemetry heartbeat (version, OS, arch — no code/PII).
47 #[serde(default)]
48 pub telemetry: TelemetryConfig,
49 #[serde(default)]
50 pub cloud: CloudConfig,
51 #[serde(default)]
52 pub gain: GainConfig,
53 /// Model declaration for measured-vs-estimated cost reporting (MCP-only IDEs).
54 #[serde(default)]
55 pub cost: CostConfig,
56 #[serde(default)]
57 pub decision_loop: DecisionLoopConfig,
58 /// Code-health engine: cognitive complexity, naming, coupling, edit-gate.
59 #[serde(default)]
60 pub code_health: CodeHealthConfig,
61 #[serde(default)]
62 pub autonomy: AutonomyConfig,
63 #[serde(default)]
64 pub providers: ProvidersConfig,
65 #[serde(default)]
66 pub knowledge_routing: KnowledgeRoutingConfig,
67 #[serde(default)]
68 pub proxy: ProxyConfig,
69 /// Conversation-history compression (`[conversation]`, opt-in; #1123).
70 #[serde(default)]
71 pub conversation: ConversationConfig,
72 /// Proxy-layer response shaping (`[response_shaping]`, #1125).
73 #[serde(default)]
74 pub response_shaping: ResponseShapingConfig,
75 #[serde(default)]
76 pub ocla: OclaConfig,
77 /// Counterfactual Shadow Mode reporting (`[shadow]`), opt-in.
78 #[serde(default)]
79 pub shadow: ShadowConfig,
80 /// Generalized L1/L2/L3 cache settings (`[cache]`).
81 #[serde(default)]
82 pub cache: CacheConfig,
83 #[serde(default)]
84 pub agents: sections::AgentsConfig,
85 /// Whether the API proxy is enabled. Tri-state:
86 /// - None: undecided (fresh install, will prompt on interactive setup)
87 /// - Some(true): user opted in, proxy managed by lean-ctx
88 /// - Some(false): user opted out, never touch proxy or endpoints
89 #[serde(default)]
90 pub proxy_enabled: Option<bool>,
91 #[serde(default)]
92 pub proxy_port: Option<u16>,
93 /// Proxy reachability timeout in milliseconds. Default: 200.
94 /// Override via LEAN_CTX_PROXY_TIMEOUT_MS env var.
95 #[serde(default)]
96 pub proxy_timeout_ms: Option<u64>,
97 /// Strict proxy auth: when true, authenticate ONLY via the Bearer token
98 /// (`LEAN_CTX_PROXY_TOKEN`) and disable the provider-API-key fallback. Default
99 /// false keeps the loopback-friendly behavior where any local AI tool's own
100 /// provider key authenticates (the proxy never injects upstream credentials —
101 /// it forwards the caller's key verbatim). Enable on shared/multi-user hosts to
102 /// require the token; clients must then send `Authorization: Bearer [REDACTED:Authorization header]
103 #[serde(default)]
104 pub proxy_require_token: bool,
105 /// Skip ALL proxy authentication on loopback-bound listeners (#755).
106 /// When true **and** the proxy binds a loopback address, every request is
107 /// accepted without a Bearer token or provider API key — MCP clients,
108 /// browser dashboards, and CLI tools all work without auth setup.
109 /// Ignored on non-loopback binds (gateway mode always requires auth).
110 /// Env override: `LEAN_CTX_PROXY_LOOPBACK_OPEN`.
111 #[serde(default)]
112 pub proxy_loopback_open: bool,
113 /// Bind address for the proxy listener (gateway mode, enterprise#8).
114 /// Default `None` = `127.0.0.1` — local-safe, nothing changes for existing
115 /// installs. Set `"0.0.0.0"` (or a specific interface IP) to serve a whole
116 /// org from one host; any non-loopback bind hard-disables the provider-key
117 /// auth fallback (Bearer token becomes mandatory) and enables the
118 /// `proxy_allowed_hosts` Host-header allowlist. Env override:
119 /// `LEAN_CTX_PROXY_BIND_HOST`. An unparseable value falls back to loopback,
120 /// never to an open bind.
121 #[serde(default)]
122 pub proxy_bind_host: Option<String>,
123 /// Host-header allowlist for a non-loopback proxy bind (gateway mode):
124 /// DNS-rebinding protection. Entries are hostnames or IPs without port
125 /// (e.g. `"gateway.example.com"`). Loopback names are always allowed.
126 /// Ignored (loopback-only guard, today's behavior) while the bind is
127 /// loopback. Empty + non-loopback bind = only loopback Host headers pass,
128 /// so configure this when exposing the gateway.
129 #[serde(default)]
130 pub proxy_allowed_hosts: Vec<String>,
131 /// Proxy-wide request rate limit in requests/second (token bucket, burst =
132 /// 2x). `None` (default) = unlimited on a loopback bind — today's behavior —
133 /// and 50 rps with burst 100 on a non-loopback bind (gateway mode ships a
134 /// sane floor, enterprise#37). `0` disables the limiter even in gateway
135 /// mode (explicit opt-out).
136 #[serde(default)]
137 pub proxy_max_rps: Option<u32>,
138 /// Require Bearer-token authentication for the dashboard. Default `true`:
139 /// the dashboard generates (or uses the pinned) token and rejects `/api/*`
140 /// and `/metrics` without it. Set to `false` to run the dashboard with **no
141 /// auth token** — useful for a local/Docker setup where managing a token is
142 /// inconvenient. No-auth mode is not unprotected: cross-origin and CSRF
143 /// attacks from a malicious local website are blocked by request-header
144 /// validation instead (`Sec-Fetch-Site`, `Origin`/`Host` same-origin, and a
145 /// `Host` allowlist against DNS rebinding — see `dashboard::no_auth_request_ok`).
146 /// Override per-run via the `--no-auth` / `--auth=<bool>` flag or the
147 /// `LEAN_CTX_DASHBOARD_AUTH` env var.
148 #[serde(default = "serde_defaults::default_true")]
149 pub dashboard_auth: bool,
150 /// Provider prompt-cache hit rate for net-of-injection calculation (#1104).
151 /// Anthropic ~90%, OpenAI ~50%. Default 0.75 (conservative cross-provider).
152 #[serde(default)]
153 pub dashboard_cache_hit_rate: Option<f64>,
154 #[serde(default = "serde_defaults::default_buddy_enabled")]
155 pub buddy_enabled: bool,
156 #[serde(default = "serde_defaults::default_true")]
157 pub enable_wakeup_ctx: bool,
158 #[serde(default)]
159 pub redirect_exclude: Vec<String>,
160 /// Tools to exclude from the MCP tool list returned by list_tools.
161 /// Accepts exact tool names (e.g. `["ctx_graph", "ctx_agent"]`).
162 /// Empty by default — all tools listed, no behaviour change.
163 #[serde(default)]
164 pub disabled_tools: Vec<String>,
165 /// Prefer the host agent's native editor over lean-ctx edit operations (#454).
166 /// When true, the lean-ctx edit tool(s) (see [`EDIT_TOOL_NAMES`]) are neither
167 /// advertised in `list_tools` nor dispatchable (direct or via `ctx_call`), so
168 /// the agent falls back to the host's built-in editing UI. Reads / search /
169 /// shell / memory tools are unaffected. Override via
170 /// `LEAN_CTX_PREFER_NATIVE_EDITOR=1`.
171 #[serde(default)]
172 pub prefer_native_editor: bool,
173 /// Tool categories to activate by default for dynamic-tool-capable clients.
174 /// Values: "core" (always on), "arch", "debug", "memory", "metrics", "session".
175 /// Example: `default_tool_categories = ["core", "arch", "memory"]`
176 /// Override via LCTX_DEFAULT_CATEGORIES env var (comma-separated).
177 /// Empty = lean-ctx default (`core`). Add `session` explicitly to evaluate
178 /// experimental local collaboration tools.
179 #[serde(default)]
180 pub default_tool_categories: Vec<String>,
181 /// Disable all automatic read-mode degradation (auto_degrade + context_gate pressure).
182 /// When true, lean-ctx never downgrades requested read modes regardless of pressure.
183 /// Override via LCTX_NO_DEGRADE=1 env var.
184 #[serde(default)]
185 pub no_degrade: bool,
186 /// Serve explicit `full`/`lines:N-M` re-reads of session-cached files as
187 /// deltas: when the file changed on disk since it was cached, the read
188 /// returns `mode=diff` instead of re-emitting content the model already
189 /// holds. First reads are unaffected; `fresh=true` always bypasses.
190 /// Opt-in. Override via LCTX_DELTA_EXPLICIT=1/0 env var.
191 #[serde(default)]
192 pub delta_explicit: bool,
193 /// Persistent profile name. Checked after LEAN_CTX_PROFILE env var.
194 /// Set via `lean-ctx config set profile passthrough` or editing config.toml.
195 #[serde(default)]
196 pub profile: Option<String>,
197 /// Active task-specific Context Kit. `LEAN_CTX_KIT` takes precedence.
198 /// Set with `lean-ctx kit load <name>`.
199 #[serde(default)]
200 pub active_kit: Option<String>,
201 /// Named configuration overlay selected from `[profiles.<name>]`.
202 /// `LEAN_CTX_CONFIG_PROFILE` takes precedence over this persisted selector.
203 #[serde(default)]
204 pub config_profile: Option<String>,
205 /// Partial configuration overlays keyed by profile name. Each overlay is
206 /// recursively merged over the base configuration at load time.
207 #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
208 pub profiles: std::collections::BTreeMap<String, toml::Table>,
209 /// Tool visibility profile: "minimal" (5), "standard" (15), or "power" (all).
210 /// Override via LEAN_CTX_TOOL_PROFILE env var.
211 /// Existing installs default to "power" (backward compat).
212 #[serde(default)]
213 pub tool_profile: Option<String>,
214 /// 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.
215 /// The universal invoker `ctx_call` stays advertised so unlisted tools remain
216 /// reachable — add `ctx_call` to `disabled_tools` to make this allowlist authoritative.
217 /// Example: `tools_enabled = ["ctx_read", "ctx_shell", "ctx_search"]`
218 #[serde(default)]
219 pub tools_enabled: Vec<String>,
220 /// Active context persona (`persona-spec-v1`). Selects the domain bundle —
221 /// tool surface, read-mode/compressor/chunker defaults, intent taxonomy,
222 /// sensitivity floor. Override via `LEAN_CTX_PERSONA`. Defaults to `coding`.
223 #[serde(default)]
224 pub persona: Option<String>,
225 #[serde(default)]
226 pub loop_detection: LoopDetectionConfig,
227 /// Controls where lean-ctx installs agent rule files.
228 /// Values: "both" (default), "global" (home-dir only), "project" (repo-local only).
229 /// Override via LEAN_CTX_RULES_SCOPE env var.
230 #[serde(default)]
231 pub rules_scope: Option<String>,
232 /// Controls how rules are injected for shared-instruction-file agents.
233 /// Values: "shared" (default, marker block in CLAUDE.md/CODEBUDDY.md/AGENTS.md/GEMINI.md),
234 /// "dedicated" (never touch those files; use each agent's config-driven
235 /// auto-load: SessionStart hook / instructions[] / context.fileName, #343), or
236 /// "off" (write no rules file at all — for hosts that supply their own
237 /// tool-steering workflow or phase-isolated/non-caching harnesses, #361).
238 /// Override via LEAN_CTX_RULES_INJECTION env var.
239 #[serde(default)]
240 pub rules_injection: Option<String>,
241 /// Mirror the host IDE's tool-permission rules onto lean-ctx's own MCP tools.
242 /// Values: "off" (default) or "on". When "on", lean-ctx reads the active
243 /// IDE's permission config (v1: OpenCode) and applies the equivalent
244 /// deny/ask/allow decision to the matching lean-ctx tool — so `ctx_shell`
245 /// honors your `bash`/`rm *` rules instead of bypassing them.
246 /// Override via LEAN_CTX_PERMISSION_INHERITANCE env var.
247 #[serde(default)]
248 pub permission_inheritance: Option<String>,
249 /// Extra glob patterns to ignore in graph/overview/preload (repo-local).
250 /// Example: `["externals/**", "target/**", "temp/**"]`
251 #[serde(default)]
252 pub extra_ignore_patterns: Vec<String>,
253 /// Controls agent output verbosity via instructions injection.
254 /// Values: "off" (default), "lite", "full", "ultra".
255 /// Override via LEAN_CTX_TERSE_AGENT env var.
256 #[serde(default)]
257 pub terse_agent: TerseAgent,
258 /// Unified compression level (replaces separate terse_agent + output_density).
259 /// Values: "off" (default), "lite", "standard", "max".
260 /// Override via LEAN_CTX_COMPRESSION env var.
261 #[serde(default)]
262 pub compression_level: CompressionLevel,
263 /// Science-driven cognitive features mode (#science).
264 #[serde(default)]
265 pub cognitive_mode: CognitiveMode,
266 /// Global compression intensity 0.0 (lossless) – 1.0 (max), mapped onto the
267 /// read modes / entropy / IB stages (see `core::aggressiveness`). `None`
268 /// (default) keeps each mode's built-in default. Override via the
269 /// `LEAN_CTX_AGGRESSIVENESS` env var or the `ctx_read` `aggressiveness` arg.
270 #[serde(default)]
271 pub compression_aggressiveness: Option<f64>,
272 /// Archive configuration for zero-loss compression.
273 #[serde(default)]
274 pub archive: ArchiveConfig,
275 /// Memory policy (knowledge/episodic/procedural/lifecycle budgets & thresholds).
276 #[serde(default)]
277 pub memory: MemoryPolicy,
278 /// Additional paths allowed by PathJail (absolute).
279 /// Useful for multi-project workspaces where the jail root is a parent directory.
280 /// Override via LEAN_CTX_ALLOW_PATH env var (path-list separator).
281 #[serde(default)]
282 pub allow_paths: Vec<String>,
283 /// Allow jailed tool access to home-level IDE config dirs (~/.cursor, VS Code,
284 /// Cline/Roo, JetBrains, …). Tri-state: `None` = not asked yet (setup prompts
285 /// once), `Some(false)` = declined, `Some(true)` = opted in. Those dirs can
286 /// expose other agents' sessions, MCP configs and credentials, so the effective
287 /// default is off. `~/.lean-ctx` (own data dir) is always allowed. The opt-in
288 /// set is registry-derived, covering every supported editor. Override via
289 /// LEAN_CTX_ALLOW_IDE_DIRS=1.
290 #[serde(default)]
291 pub allow_ide_config_dirs: Option<bool>,
292 /// Extra project roots for multi-root workspaces.
293 /// Tools like ctx_tree and ctx_search can scan across all roots in a single call.
294 /// These paths are automatically added to PathJail's allow-list.
295 /// Override via LEAN_CTX_EXTRA_ROOTS env var (path-list separator).
296 #[serde(default)]
297 pub extra_roots: Vec<String>,
298 /// Read-only roots: sibling subtrees the agent may READ but never WRITE.
299 /// Reads resolve as if they were extra_roots; every write tool (edit, refactor,
300 /// handoff/session export, memory compaction) is default-denied inside these
301 /// paths. Useful for reference repos mounted next to the project.
302 /// Override via LEAN_CTX_READ_ONLY_ROOTS env var (path-list separator).
303 #[serde(default)]
304 pub read_only_roots: Vec<String>,
305 /// Extra trusted roots OUTSIDE `$HOME` that lean-ctx may follow when an agent
306 /// config file/dir (`~/.claude.json`, `~/.codex/config.toml`, …) is a symlink
307 /// pointing there (#596). Empty by default → the strict `$HOME`-only boundary
308 /// stays in force (a planted symlink can never redirect a config write out of
309 /// the user's home, preserving the GL#442 symlink-hijack protection). Add a
310 /// parent like `/opt/dotfiles` only for a location you own and trust. Like
311 /// `extra_roots`, security-sensitive: stripped from untrusted project-local
312 /// configs. Override via LEAN_CTX_ALLOW_SYMLINK_ROOTS env var (path-list sep).
313 #[serde(default)]
314 pub allow_symlink_roots: Vec<String>,
315 /// Enable content-defined chunking (Rabin-Karp) for cache-optimal output ordering.
316 /// Stable chunks are emitted first to maximize prompt cache hits.
317 #[serde(default)]
318 pub content_defined_chunking: bool,
319 /// Skip session/knowledge/gotcha blocks in MCP instructions to minimize token overhead.
320 /// Override via LEAN_CTX_MINIMAL env var.
321 ///
322 /// Default `true` (deliberate): initialize-time instructions stay byte-stable
323 /// across sessions, which keeps the provider prompt-cache prefix warm (#498)
324 /// and holds the fixed per-session cost at the `doctor overhead --gate`
325 /// budget. Session continuity is NOT lost — the wakeup briefing (task,
326 /// findings, knowledge) is delivered through the first tool call's
327 /// `--- AUTO CONTEXT ---` block instead, which only bills when the agent
328 /// actually works. Set to `false` to additionally inject the ACTIVE SESSION
329 /// / PROJECT MEMORY blocks directly into the MCP `initialize` instructions.
330 /// #1540: this key never disables the archive/ephemeral firewall — only
331 /// the `LEAN_CTX_MINIMAL` env escape hatch skips that safety net.
332 #[serde(default)]
333 pub minimal_overhead: bool,
334 /// Opt-in: substitute long identifiers with short α-codes (+ a `§MAP` table)
335 /// in `aggressive` reads for projects with >50 source files. Off by default —
336 /// the abbreviated form is confusing for editing/refactoring, where the agent
337 /// needs the real package and symbol names. Enable for max exploration savings.
338 #[serde(default)]
339 pub symbol_map_auto: bool,
340 /// Opt-in: bias `auto` toward structure-first reads (`map`) for medium code
341 /// files on a cold read. Off by default — interactive sessions keep the
342 /// conservative `full` floor that avoids a follow-up body read. Enable for
343 /// phase-isolated harnesses (no warm-session cache payback), where a cold
344 /// `full` read is pure overhead and structure-first reads aid localization.
345 /// Override via the LEAN_CTX_STRUCTURE_FIRST env var.
346 #[serde(default)]
347 pub structure_first: bool,
348 /// Progressive disclosure for first-time reads (LCLM arXiv 2606.09659).
349 /// When true (default), large files default to compact overviews on first read:
350 /// - Below progressive_threshold_lines: full content
351 /// - Below progressive_signatures_max_lines: signatures mode
352 /// - Above: map (manifest) mode
353 /// Models can always bypass with explicit mode= or lines= parameters.
354 /// Override via LEAN_CTX_PROGRESSIVE_DISCLOSURE env var.
355 #[serde(default = "serde_defaults::default_true")]
356 pub progressive_disclosure: bool,
357 /// Files with fewer lines than this threshold are always delivered in full.
358 /// Default: 100 lines.
359 #[serde(default = "serde_defaults::default_progressive_threshold_lines")]
360 pub progressive_threshold_lines: u32,
361 /// Files between threshold and this limit get signatures mode.
362 /// Files above get map (manifest) mode. Default: 500 lines.
363 #[serde(default = "serde_defaults::default_progressive_signatures_max")]
364 pub progressive_signatures_max: u32,
365 /// Opt-in: let the adaptive *learning* signals (predictor, bandit, heatmap,
366 /// adaptive policy, bounce/path memory) participate in `auto` mode
367 /// resolution. Off by default (#683): the default cascade is a deterministic
368 /// function of (file, task) — only capability guards and the size/task
369 /// heuristic decide — which keeps output byte-stable for provider prompt
370 /// caching (#498) and avoids per-read disk I/O from the learning stores.
371 /// Override via the LEAN_CTX_AUTO_MODE_LEARNING env var.
372 #[serde(default)]
373 pub auto_mode_learning: bool,
374 /// Team server URL for opt-in savings roll-up.
375 /// Set via `lean-ctx config set team_url https://...` or `[team] url` in config.toml.
376 /// Override via LEAN_CTX_TEAM_URL env var.
377 #[serde(default)]
378 pub team_url: Option<String>,
379 /// Bearer token for the team server (Authorization header on savings push /
380 /// pull). Set via `lean-ctx config set team_token <tok>` or `team_token` in
381 /// config.toml. Override via the LEAN_CTX_TEAM_TOKEN env var.
382 #[serde(default)]
383 pub team_token: Option<String>,
384 /// Opt-in: when true, the running daemon periodically pushes this machine's
385 /// signed savings batch to `team_url` so the team roll-up fills itself (no
386 /// manual `savings push` per dev). Off by default; requires `team_url` +
387 /// `team_token`. Set via `lean-ctx config set team_auto_push true`.
388 #[serde(default)]
389 pub team_auto_push: bool,
390 /// Enable human-readable activity journal (~/.lean-ctx/journal.md).
391 #[serde(default)]
392 pub journal_enabled: bool,
393 /// Opt-in: auto-persist interesting findings as knowledge facts.
394 #[serde(default)]
395 pub auto_capture: bool,
396 /// Hybrid search weights (BM25/dense/candidates).
397 #[serde(default)]
398 pub search: crate::core::hybrid_search::HybridConfig,
399 /// Code-graph settings, including traversal (co-access) edges (#289).
400 #[serde(default)]
401 pub graph: GraphConfig,
402 /// Index-time file filters (#735): include/exclude globs + gitignore
403 /// handling, applied by every index builder via `core::index_filter`.
404 #[serde(default)]
405 pub index: IndexConfig,
406 /// Skillify miner settings (#290): codify recurring patterns into rules.
407 #[serde(default)]
408 pub skillify: SkillifyConfig,
409 /// AI session-summary settings (#292): periodic, semantically-recallable summaries.
410 #[serde(default)]
411 pub summaries: SummariesConfig,
412 /// Optional LLM enhancement (query expansion, contradiction explanation).
413 #[serde(default)]
414 pub llm: crate::core::llm_enhance::LlmConfig,
415 /// Semantic-embedding engine settings (which local ONNX model to use).
416 #[serde(default)]
417 pub embedding: EmbeddingConfig,
418 /// Disable shell hook injection (the _lc() function that wraps CLI commands).
419 /// Override via LEAN_CTX_NO_HOOK env var.
420 #[serde(default)]
421 pub shell_hook_disabled: bool,
422 /// Shadow mode (default: true): denies native Read/Grep/Glob at the
423 /// permission level, forcing agents to use ctx_* MCP tools for maximum
424 /// compression. Without this, many harnesses silently prefer native tools,
425 /// negating lean-ctx's token savings. Disable with `shadow_mode = false`.
426 /// Native Shell/Bash coverage is governed separately by `shell_hook_mode`.
427 #[serde(default = "serde_defaults::default_true")]
428 pub shadow_mode: bool,
429 /// Shell hook mode (#1278): how the PreToolUse shell hook treats native
430 /// Bash/Shell calls.
431 /// - `rewrite` (default): rewrite known read/search/list commands to
432 /// lean-ctx equivalents; anything unrecognized passes through raw.
433 /// - `deny`: block native shell calls outright so every command goes
434 /// through `ctx_shell` (same fail-opens as the deny hook: lean-ctx
435 /// disabled, MCP daemon dead, explicit shadow-only tool surface).
436 /// - `auto`: currently equals `rewrite`; reserved for a future default flip.
437 ///
438 /// Env override: `LEAN_CTX_SHELL_HOOK_MODE`. Lives in config.toml, so the
439 /// choice survives reinstalls and updates.
440 #[serde(default)]
441 pub shell_hook_mode: Option<String>,
442 /// Per-turn tool-precedence reinjection (#1288): the UserPromptSubmit hook
443 /// emits a one-line `additionalContext` reminder that ctx_* tools are the
444 /// mandated path, so it always post-dates any session-level harness
445 /// instruction preferring native Bash. `on` | `off` | `auto` (default:
446 /// auto = active only while `shadow_mode` is on). Env override:
447 /// `LEAN_CTX_PROMPT_REINJECT`. Costs ~45 tokens per turn when active.
448 #[serde(default)]
449 pub prompt_reinject: Option<String>,
450 /// Global hook mode override. When set, overrides the per-agent auto-detection.
451 /// - `replace`: Native Read/Grep/Glob/Shell denied, lean-ctx MCP is the only path
452 /// - `hybrid`: MCP + shell hooks for compression (legacy)
453 /// - `mcp`: MCP server only, no hooks
454 ///
455 /// Default: unset (auto-detect per agent via `recommend_hook_mode`)
456 #[serde(default)]
457 pub hook_mode: Option<String>,
458 /// MCP tool surface mode. Controls how many tools `tools/list` advertises.
459 /// - `auto` (default): shadow-only (`ctx_call` only) for hook-covered
460 /// clients, full lazy-core surface for all others.
461 /// - `mcp`: always advertise the full lazy-core/profile surface.
462 /// - `shadow`: always advertise only `ctx_call` (requires installed hooks).
463 #[serde(default)]
464 pub tool_surface: Option<String>,
465 /// Opt-in (#520): write a human-readable debug log of intercepted MCP tool
466 /// calls and hook routing decisions (lean-ctx vs native, with reasons) to
467 /// `<state_dir>/logs/debug.log`. Override via the LEAN_CTX_DEBUG_LOG env var.
468 #[serde(default)]
469 pub debug_log: bool,
470 /// Controls when the shell hook auto-activates aliases.
471 /// - `agents-only`: (Default since #699) Aliases only active when an AI
472 /// agent env var is detected — transparent in plain human terminals.
473 /// - `always`: Aliases active in every interactive shell (pre-#699 default).
474 /// - `off`: Aliases never auto-activate (user must call `lean-ctx-on` manually).
475 ///
476 /// Override via `LEAN_CTX_SHELL_ACTIVATION` env var.
477 #[serde(default)]
478 pub shell_activation: ShellActivation,
479 /// Do not install agent CLI aliases (`claude`, `codex`, `gemini`,
480 /// `codebuddy`) into `~/.zshrc` / `~/.bashrc` during `onboard` / `setup`.
481 /// Existing alias blocks are removed when this is toggled on (#754).
482 /// Does NOT affect the shell compression hook (`_lc()`) — use
483 /// `shell_hook_disabled` for that. Orthogonal to `shell_activation` which
484 /// controls *when* aliases activate, not *whether* they are installed.
485 #[serde(default)]
486 pub skip_agent_aliases: bool,
487 /// Controls the native-Read → `ctx_read` redirect hook (#637).
488 /// - `auto`: (Default) redirect everywhere except hosts with a native
489 /// read-before-write guard (Claude Code / CodeBuddy), where the path-swap
490 /// would break native Write/Edit.
491 /// - `on`: always redirect (legacy behavior).
492 /// - `off`: never redirect native Read.
493 ///
494 /// Override via the `LEAN_CTX_READ_REDIRECT` env var.
495 #[serde(default)]
496 pub read_redirect: ReadRedirect,
497 /// Controls the PostToolUse native-Read re-read dedup (GL #1140).
498 /// - `auto`: (Default) replace only re-reads of unchanged files, and only on
499 /// guard hosts (Claude Code / CodeBuddy) where the PreToolUse redirect is
500 /// disabled — the guard-safe way to win the dedup savings back.
501 /// - `on`: dedup wherever the PostToolUse hook fires.
502 /// - `off`: never replace a Read result.
503 ///
504 /// Override via the `LEAN_CTX_READ_DEDUP` env var.
505 #[serde(default)]
506 pub read_dedup: ReadDedup,
507 /// Disable the daily version check against leanctx.com/version.txt.
508 /// Override via LEAN_CTX_NO_UPDATE_CHECK env var.
509 #[serde(default)]
510 pub update_check_disabled: bool,
511 #[serde(default)]
512 pub updates: UpdatesConfig,
513 /// Fixed-context budget accounting for `doctor overhead` / `gain` (#964).
514 #[serde(default)]
515 pub context: ContextConfig,
516 /// Maximum BM25 cache file size in MB. Indexes exceeding this are quarantined on load
517 /// and refused on save. Override via LEAN_CTX_BM25_MAX_CACHE_MB env var.
518 #[serde(default = "serde_defaults::default_bm25_max_cache_mb")]
519 pub bm25_max_cache_mb: u64,
520 /// Maximum number of files scanned by the lightweight JSON graph index.
521 /// 0 = unlimited (default). Set >0 to cap for constrained systems.
522 #[serde(default = "serde_defaults::default_graph_index_max_files")]
523 pub graph_index_max_files: u64,
524 /// Controls RAM vs feature trade-off. Values: "low", "balanced" (default), "performance".
525 /// Override via LEAN_CTX_MEMORY_PROFILE env var.
526 #[serde(default)]
527 pub memory_profile: MemoryProfile,
528 /// Controls how aggressively memory is freed when idle.
529 /// Values: "shared" (default, 1h TTL), "aggressive" (5 min TTL for low-memory devices).
530 /// Override via LEAN_CTX_MEMORY_CLEANUP env var.
531 #[serde(default)]
532 pub memory_cleanup: MemoryCleanup,
533 /// Soft process-RSS target as a percentage of system RAM (default: 5).
534 /// The guardian throttles and evicts above it, but this is not an OS hard cap.
535 /// Use a cgroup/container MemoryMax when strict isolation is required.
536 /// Override via LEAN_CTX_MAX_RAM_PERCENT env var.
537 #[serde(default = "serde_defaults::default_max_ram_percent")]
538 pub max_ram_percent: u8,
539 /// Simplified disk budget (MB). When set and detail values are at defaults,
540 /// distributes proportionally: archive=25%, bm25=10%, remainder for stores.
541 /// 0 = disabled (use individual settings). Override via LEAN_CTX_MAX_DISK_MB.
542 #[serde(default)]
543 pub max_disk_mb: u64,
544 /// Auto-purge data older than this many days. 0 = disabled.
545 /// Flows into archive.max_age_hours and lifecycle idle TTL.
546 #[serde(default)]
547 pub max_staleness_days: u32,
548 /// Retention window for explicit session cleanup. This is independent from
549 /// archive retention and always preserves the newest session per project.
550 /// Override via LEAN_CTX_SESSION_RETENTION_DAYS.
551 #[serde(default = "serde_defaults::default_session_retention_days")]
552 pub session_retention_days: u32,
553 /// Cap on the rayon worker threads used by the CPU-heavy index build
554 /// (call graph etc.). 0 = rayon default (all cores). Set >0 to bound
555 /// per-instance CPU so a fleet of concurrent sessions can't saturate the
556 /// host on startup. Override via LEANCTX_INDEX_THREADS env var.
557 #[serde(default)]
558 pub max_index_threads: usize,
559 /// Controls visibility of token savings footers in tool output.
560 /// Values: "always" (default, show on every response), "never", "auto" (legacy compatibility).
561 /// Override via LEAN_CTX_SAVINGS_FOOTER or LEAN_CTX_SHOW_SAVINGS=1|0 env var.
562 #[serde(default)]
563 pub savings_footer: SavingsFooter,
564 /// Controls compression annotation style in savings footers.
565 /// Values: "quantized" (default, round to 10% buckets), "full" (exact %), "none" (suppress all).
566 /// Override via LEAN_CTX_COMPRESSION_ANNOTATION env var.
567 #[serde(default)]
568 pub compression_annotation: CompressionAnnotation,
569 /// Minimum savings percentage to emit a footer annotation. Below this threshold,
570 /// annotations are suppressed (the savings are too small to be worth the token cost).
571 /// Default: 5 (suppress annotations for savings below 5%).
572 #[serde(default = "serde_defaults::default_annotation_threshold_pct")]
573 pub annotation_threshold_pct: u8,
574 /// In-band behavior hints (heavy full/raw reads, search→read→search
575 /// chains): "auto" (default, one hint per pattern per session) or "off".
576 /// Detections are always counted for `tools health`, hints or not.
577 #[serde(default = "serde_defaults::default_behavior_nudges")]
578 pub behavior_nudges: String,
579 /// Maximum fresh tokens per single tool response (turn budget).
580 /// 0 = unlimited. Default: 4096. Prevents context bloat from oversized responses.
581 /// Override via LEAN_CTX_TURN_FRESH_LIMIT env var.
582 #[serde(default = "serde_defaults::default_turn_fresh_limit")]
583 pub turn_fresh_limit: usize,
584 /// Turn budget for a response the caller explicitly asked to be verbatim
585 /// (`ctx_read` with `raw=true` or `mode="raw"`). 0 = unlimited.
586 /// Default: 32768. Override via LEAN_CTX_TURN_FRESH_LIMIT_VERBATIM.
587 ///
588 /// The ordinary `turn_fresh_limit` is a compression backstop for output the
589 /// agent did not size itself. A verbatim read is the documented recovery
590 /// path out of compression (#1582); capping it at the same 4096 tokens made
591 /// that path unreachable for any file above ~16 KB.
592 #[serde(default = "serde_defaults::default_turn_fresh_limit_verbatim")]
593 pub turn_fresh_limit_verbatim: usize,
594 /// Maximum cumulative fresh tokens per session. 0 = unlimited.
595 /// Default: 200000. Progressive compression kicks in at 50/75/90%.
596 /// Override via LEAN_CTX_SESSION_TOKEN_LIMIT env var.
597 #[serde(default = "serde_defaults::default_session_token_limit")]
598 pub session_token_limit: usize,
599 /// Explicit project root override. When set, lean-ctx uses this instead of auto-detection.
600 /// This prevents accidental home-directory scans when running from $HOME.
601 /// Override via LEAN_CTX_PROJECT_ROOT env var.
602 #[serde(default)]
603 pub project_root: Option<String>,
604 /// LSP server overrides. Map language name to custom binary path.
605 /// Example: `[lsp]\nrust = "/opt/rust-analyzer"\npython = "~/.venvs/main/bin/pylsp"`
606 #[serde(default)]
607 pub lsp: std::collections::HashMap<String, String>,
608 /// Per-IDE allowed paths. Restricts which directories lean-ctx will scan/index for each IDE.
609 /// Example: `[ide_paths]\ncursor = ["/home/user/projects/app1"]\ncodex = ["/home/user/codex"]`
610 /// When set, only these paths are indexed for the matching agent. Global `allow_paths` still applies.
611 #[serde(default)]
612 pub ide_paths: HashMap<String, Vec<String>>,
613 /// Custom model context window overrides.
614 /// Example: `[model_context_windows]\n"my-custom-model" = 500000`
615 #[serde(default)]
616 pub model_context_windows: HashMap<String, usize>,
617 /// Controls how much detail tool responses include.
618 ///
619 /// - `full` (default): complete compressed output
620 /// - `headers_only`: metadata line only (path, mode, token count)
621 ///
622 /// Override via `LEAN_CTX_RESPONSE_VERBOSITY` env var.
623 #[serde(default)]
624 pub response_verbosity: ResponseVerbosity,
625 /// Bypass hint mode. When agents use native Read/Grep instead of lean-ctx tools,
626 /// a hint is appended to the next tool response.
627 /// Values: "on" (default), "off", "aggressive" (hint on every call, no cooldown).
628 /// Override via LEAN_CTX_BYPASS_HINTS env var.
629 #[serde(default)]
630 pub bypass_hints: Option<String>,
631 /// Cache policy for ctx_read. Controls behavior on cache hits.
632 /// Values: "aggressive" (default, 13-tok stubs + compaction-aware reset),
633 /// "safe" (delivers map instead of stub), "off" (no caching, always disk read).
634 /// Override via LEAN_CTX_CACHE_POLICY env var.
635 #[serde(default)]
636 pub cache_policy: Option<String>,
637 /// Token budget for the in-memory `ctx_read` cache. When the cached total
638 /// plus an incoming read would exceed this, lean-ctx evicts the least-valuable
639 /// entries *immediately* (RRF: recency × frequency × size) so the read always
640 /// proceeds — eviction is never deferred to the staleness TTL. `0` uses the
641 /// built-in default (2M). `LEAN_CTX_CACHE_MAX_TOKENS` env var overrides this.
642 #[serde(default)]
643 pub cache_max_tokens: usize,
644 /// Cross-project boundary policy.
645 /// Controls whether cross-project search/import is allowed and whether access is audited.
646 #[serde(default)]
647 pub boundary_policy: crate::core::memory_boundary::BoundaryPolicy,
648 #[serde(default)]
649 pub secret_detection: SecretDetectionConfig,
650 /// Per-item sensitivity model with a uniform policy floor (#212).
651 /// Disabled by default → fully no-op until `sensitivity.enabled = true`.
652 #[serde(default)]
653 pub sensitivity: crate::core::sensitivity::SensitivityConfig,
654 /// MCP Tool-Catalog Gateway (#210): aggregate + query-route downstream MCP
655 /// servers. Global-only (never merged from project-local config) and a full
656 /// no-op until `gateway.enabled = true`.
657 #[serde(default)]
658 pub gateway: crate::core::mcp_catalog::GatewayConfig,
659 /// Self-hosted org gateway server (`[gateway_server]`, enterprise#20):
660 /// deployment parameters for the usage cockpit — seat count for the
661 /// org-wide projection, display label, and the central admin API the local
662 /// cockpit may read from. All optional; absent = local-only behavior.
663 #[serde(default)]
664 pub gateway_server: GatewayServerConfig,
665 /// Enterprise Suite connection (`[enterprise]`): connects this Runtime to
666 /// a LeanCTX Enterprise Gateway for economics tracking and model routing.
667 #[serde(default)]
668 pub enterprise: EnterpriseConfig,
669 /// Deprecated: auto-reroot is now always active when the jail root is
670 /// suspicious, None, or has no project marker. Kept for config-file
671 /// backward compatibility but no longer controls behavior.
672 #[serde(default = "default_true")]
673 pub allow_auto_reroot: bool,
674 /// Verbatim binary path/expression for generated agent-hook commands
675 /// (#708). Users who sync agent settings (`~/.claude/settings.json`, …)
676 /// across machines with different usernames need an env-based form like
677 /// `$HOME/.local/bin/lean-ctx` — agent hosts run hook commands through a
678 /// shell, which expands it. When set (env `LEAN_CTX_HOOK_BINARY` wins,
679 /// then this key), every hook writer emits the value verbatim instead of
680 /// the machine-absolute exe path, so `init`/`doctor --fix`/`update` stop
681 /// rewriting synced files into sync ping-pong. Autostart plists/services
682 /// and daemon spawns are NOT affected — launchd/systemd do not expand
683 /// shell variables, so those keep the real absolute path. Empty (default)
684 /// = automatic absolute-path resolution (#367).
685 #[serde(default)]
686 pub hook_binary: Option<String>,
687 /// Disable PathJail entirely by setting `path_jail = false` in config.toml.
688 /// Useful in container/Docker environments where the sandbox is the boundary.
689 /// (The former `LEAN_CTX_NO_JAIL=1` env override was removed in v3.7.3.)
690 #[serde(default)]
691 pub path_jail: Option<bool>,
692 /// Sandbox level for code execution (ctx_exec).
693 /// 0 = subprocess only (current), 1 = OS-level restriction (Seatbelt/Landlock).
694 /// Override via LEAN_CTX_SANDBOX_LEVEL env var.
695 #[serde(default)]
696 pub sandbox_level: u8,
697 /// When true, large tool outputs (>4000 chars) are stored as references
698 /// and a short URI is returned instead of the full content.
699 /// Override via LEAN_CTX_REFERENCE_RESULTS env var.
700 #[serde(default)]
701 pub reference_results: bool,
702 /// Default per-agent token budget. 0 means unlimited.
703 /// Override per-agent via ctx_session or programmatically.
704 #[serde(default)]
705 pub agent_token_budget: usize,
706 /// Optional shell command allowlist. When non-empty, only commands whose base binary
707 /// is in this list are permitted by ctx_shell. Empty = disable allowlist (allow all).
708 /// Default includes common dev tools. Set to `[]` to disable.
709 /// Override via LEAN_CTX_SHELL_ALLOWLIST env var (comma-separated).
710 #[serde(default = "default_shell_allowlist")]
711 pub shell_allowlist: Vec<String>,
712
713 /// Extra commands MERGED on top of the effective `shell_allowlist` without replacing
714 /// the defaults. Setting `shell_allowlist` replaces the whole built-in list (a common
715 /// footgun); entries here are purely additive, which is what `lean-ctx allow <cmd>`
716 /// writes. Only applied in restricted mode (when the base allowlist is non-empty).
717 #[serde(default)]
718 pub shell_allowlist_extra: Vec<String>,
719
720 /// When true, block command substitution ($(), backticks) and process substitution
721 /// (<(), >()) in shell arguments. When false (default), only warn via tracing.
722 /// Default false preserves backward compatibility — set true for maximum security.
723 #[serde(default)]
724 pub shell_strict_mode: bool,
725
726 /// Shell-security mode for ctx_shell / `lean-ctx -c` command gating (GL #788):
727 /// `enforce` (default, secure), `warn` (run checks, log violations, never
728 /// block) or `off` (skip the allowlist + dangerous-pattern blocks entirely —
729 /// a deliberate opt-out; compression stays active). Override via
730 /// LEAN_CTX_SHELL_SECURITY. `None` resolves to `enforce`.
731 #[serde(default)]
732 pub shell_security: Option<String>,
733
734 /// Default shell-command timeout in seconds for *normal* commands. `None`
735 /// resolves to the built-in 2-minute default; heavy builds/tests use
736 /// [`Config::shell_heavy_timeout_secs`]. Override via
737 /// `LEAN_CTX_SHELL_TIMEOUT_SECS` (`LEAN_CTX_SHELL_TIMEOUT_MS` still wins over
738 /// both, in milliseconds).
739 #[serde(default)]
740 pub shell_timeout_secs: Option<u64>,
741
742 /// Shell-command timeout in seconds for *heavy* commands (cargo build/test,
743 /// make, docker build, git commit/push, …). `None` resolves to the built-in
744 /// 10-minute ceiling. Override via `LEAN_CTX_SHELL_HEAVY_TIMEOUT_SECS`.
745 #[serde(default)]
746 pub shell_heavy_timeout_secs: Option<u64>,
747
748 /// Extra command prefixes that get the heavy timeout ceiling. Merged with
749 /// the built-in list. Useful for project-specific long-running scripts.
750 /// Example: `shell_heavy_prefixes = ["python3 ", "./scripts/"]`
751 #[serde(default)]
752 pub shell_heavy_prefixes: Vec<String>,
753 /// When true, `ctx_shell` accepts shell file-write redirects (`>`, `>>`,
754 /// `tee`, heredoc-to-file, `curl -o`, `wget` default mode). Default false —
755 /// the native Write/Edit tool is preferred. Opt-in for power users who want
756 /// classic shell syntax; the real command gating (allowlist,
757 /// dangerous-pattern and interpreter-eval blocks) still applies. Override
758 /// via `LEAN_CTX_SHELL_ALLOW_WRITES=1`.
759 #[serde(default)]
760 pub shell_allow_writes: bool,
761 /// Absolute paths where shell redirects and `tee` may capture output.
762 /// Empty uses the operating system's temporary directories. Project files
763 /// remain denied even when a configured path overlaps the project root.
764 #[serde(default)]
765 pub write_allow_paths: Vec<String>,
766
767 /// #814: opt-in to allow `python3 -c`, `node -e`, etc. in ctx_shell.
768 /// Default `false` — inline code is blocked because it leaves no auditable
769 /// artifact. Override via `LEAN_CTX_SHELL_ALLOW_INLINE_SCRIPTS=1`.
770 #[serde(default)]
771 pub shell_allow_inline_scripts: bool,
772
773 /// Setup behavior: controls what gets injected during setup and updates.
774 #[serde(default)]
775 pub setup: SetupConfig,
776 #[serde(default)]
777 pub solution: super::solution::SolutionConfig,
778 #[serde(default)]
779 pub provenance: super::provenance::ProvenanceConfig,
780 pub cross_agent: super::provenance::CrossAgentConfig,
781}