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