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