lean_ctx/core/config/enums.rs
1//! Configuration enums and their behavior.
2//!
3//! Extracted from `config::mod` to keep the top-level config module focused on
4//! the `Config` struct and loading logic. These types are re-exported from the
5//! `config` module root, so external paths like `config::CompressionLevel`
6//! continue to work unchanged.
7
8use serde::{Deserialize, Serialize};
9use std::sync::atomic::AtomicU8;
10
11use super::Config;
12
13static SESSION_DEGRADE_LEVEL: AtomicU8 = AtomicU8::new(0);
14
15/// Unified reasoning-effort level for the cache-safe, cross-provider effort
16/// control (#834). "Off" is represented by `Option::None`, not a variant — the
17/// feature is strictly opt-in.
18///
19/// This type only carries the operator's *intent*; the wire translation into
20/// each provider's native parameter (OpenAI `reasoning(_).effort`, Anthropic
21/// `output_config.effort`) lives in `proxy::effort`. The value is a
22/// constant once configured, so it is identical on every request of every
23/// conversation — the provider prompt-cache prefix stays byte-stable (#448/#498)
24/// and only the model's reasoning depth changes. Per-turn effort switching is
25/// deliberately *not* supported: it would invalidate the prompt cache.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
27#[serde(rename_all = "lowercase")]
28pub enum Effort {
29 Minimal,
30 Low,
31 Medium,
32 High,
33}
34
35impl Effort {
36 /// Parse a config/env token. `off`, empty, or anything unrecognized yields
37 /// `None` (feature disabled) so a typo can never silently enable it.
38 #[must_use]
39 pub fn parse(s: &str) -> Option<Self> {
40 match s.trim().to_ascii_lowercase().as_str() {
41 "minimal" => Some(Self::Minimal),
42 "low" => Some(Self::Low),
43 "medium" => Some(Self::Medium),
44 "high" => Some(Self::High),
45 _ => None,
46 }
47 }
48
49 /// Stable lowercase label (config display, logs, `/status`).
50 #[must_use]
51 pub fn label(self) -> &'static str {
52 match self {
53 Self::Minimal => "minimal",
54 Self::Low => "low",
55 Self::Medium => "medium",
56 Self::High => "high",
57 }
58 }
59}
60
61/// Controls when shell output is tee'd to disk for later retrieval.
62///
63/// Default is `HighCompression` (not `Failures`): a heavily compressed but
64/// *successful* command is exactly the case where an agent later needs the raw
65/// bytes, and teeing them guarantees the MCP-free recovery path (a real file the
66/// agent can read with any tool) always exists. The archive GC (TTL + size cap)
67/// covers the extra files.
68#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
69#[serde(rename_all = "lowercase")]
70pub enum TeeMode {
71 Never,
72 Failures,
73 #[default]
74 HighCompression,
75 Always,
76}
77
78/// Controls the reactive recovery footer surfaced on compressed tool output
79/// (`ctx_read`, archive/firewall/spill handles, `ctx_shell` tee).
80///
81/// The proactive `RECOVER` rule teaches the vocabulary once in the system
82/// prompt; this knob governs the per-output reminder that names the concrete
83/// file path / handle at point-of-need:
84/// * `Minimal` (default) — a single, non-MCP-first line on the *first* compressed
85/// view of a file/handle per session.
86/// * `Full` — the richer ladder (`mode=full` · `raw=true` · `ctx_retrieve` ·
87/// `ctx_expand`); used by the `exploration`/`review` profiles.
88/// * `Off` — suppresses the footer entirely (the proactive rule still ships, so
89/// reversibility is never undiscoverable).
90#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
91#[serde(rename_all = "lowercase")]
92pub enum RecoveryHints {
93 Off,
94 #[default]
95 Minimal,
96 Full,
97}
98
99impl RecoveryHints {
100 /// Parse a config/env token. Returns `None` for unrecognized input so a typo
101 /// falls back to the default rather than silently disabling the feature.
102 #[must_use]
103 pub fn parse(s: &str) -> Option<Self> {
104 match s.trim().to_ascii_lowercase().as_str() {
105 "off" | "none" | "false" => Some(Self::Off),
106 "minimal" | "min" | "on" | "true" => Some(Self::Minimal),
107 "full" => Some(Self::Full),
108 _ => None,
109 }
110 }
111
112 /// Reads the recovery-hint tier from `LEAN_CTX_RECOVERY_HINTS` (ops/test
113 /// override). Unset or unrecognized yields `None` (use the configured value).
114 #[must_use]
115 pub fn from_env() -> Option<Self> {
116 Self::parse(&std::env::var("LEAN_CTX_RECOVERY_HINTS").ok()?)
117 }
118
119 /// Stable lowercase label (config display, schema, `/status`).
120 #[must_use]
121 pub fn label(self) -> &'static str {
122 match self {
123 Self::Off => "off",
124 Self::Minimal => "minimal",
125 Self::Full => "full",
126 }
127 }
128}
129
130/// Legacy: Controls agent output verbosity level injected into MCP instructions.
131/// Superseded by `CompressionLevel`. Kept for backward compatibility with old config.toml files.
132/// New setups use `compression_level` instead. See `CompressionLevel::effective()`.
133#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
134#[serde(rename_all = "lowercase")]
135pub enum TerseAgent {
136 #[default]
137 Off,
138 Lite,
139 Full,
140 Ultra,
141}
142
143impl TerseAgent {
144 /// Reads the terse-agent level from the `LEAN_CTX_TERSE_AGENT` env var.
145 pub fn from_env() -> Self {
146 match std::env::var("LEAN_CTX_TERSE_AGENT")
147 .unwrap_or_default()
148 .to_lowercase()
149 .as_str()
150 {
151 "lite" => Self::Lite,
152 "full" => Self::Full,
153 "ultra" => Self::Ultra,
154 _ => Self::Off,
155 }
156 }
157}
158
159/// Legacy: Controls how dense/compact MCP tool output is formatted.
160/// Superseded by `CompressionLevel`. Kept for backward compatibility with old config.toml files.
161/// New setups use `compression_level` instead. See `CompressionLevel::effective()`.
162#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
163#[serde(rename_all = "lowercase")]
164pub enum OutputDensity {
165 #[default]
166 Normal,
167 Terse,
168 Ultra,
169}
170
171impl OutputDensity {
172 /// Reads the output density from the `LEAN_CTX_OUTPUT_DENSITY` env var.
173 pub fn from_env() -> Self {
174 match std::env::var("LEAN_CTX_OUTPUT_DENSITY")
175 .unwrap_or_default()
176 .to_lowercase()
177 .as_str()
178 {
179 "terse" => Self::Terse,
180 "ultra" => Self::Ultra,
181 _ => Self::Normal,
182 }
183 }
184}
185
186/// Unified compression level that replaces the 4 separate legacy concepts:
187/// `terse_agent`, `output_density`, `terse_mode`, and `crp_mode`.
188///
189/// Controls how much detail tool responses include.
190///
191/// The config reference of 3.12.9 and earlier documented `normal`, `compact`
192/// and `minimal` (gh-2283). A config written from those docs must still load
193/// instead of failing the whole file: `normal`/`compact` read as `full` (the
194/// output is still compressed as usual), `minimal` as `headers_only` (same
195/// mapping as `LEAN_CTX_RESPONSE_VERBOSITY`).
196#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
197#[serde(rename_all = "snake_case")]
198pub enum ResponseVerbosity {
199 #[default]
200 #[serde(alias = "normal", alias = "compact")]
201 Full,
202 #[serde(alias = "minimal", alias = "headers")]
203 HeadersOnly,
204}
205
206impl ResponseVerbosity {
207 pub fn effective() -> Self {
208 if let Ok(v) = std::env::var("LEAN_CTX_RESPONSE_VERBOSITY") {
209 match v.trim().to_lowercase().as_str() {
210 "headers_only" | "headers" | "minimal" => return Self::HeadersOnly,
211 "full" | "normal" | "compact" | "" => return Self::Full,
212 _ => {}
213 }
214 }
215 Config::load().response_verbosity
216 }
217
218 pub fn is_headers_only(&self) -> bool {
219 matches!(self, Self::HeadersOnly)
220 }
221}
222
223/// Each level maps to specific component settings via `to_components()`.
224#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
225#[serde(rename_all = "lowercase")]
226pub enum CompressionLevel {
227 Off,
228 /// Default: plain-English "concise" guidance (bullets, no filler). Readable
229 /// by humans inspecting their rules files, and still token-saving. The
230 /// denser, symbolic styles (`Standard`/`Max`, which enable CRP and the
231 /// `→ ∵ ∴` vocabulary) are opt-in "power modes" — set `compression_level`
232 /// in config. This only shapes the model's prose; tool-output compression
233 /// is governed separately and is unaffected.
234 #[default]
235 Lite,
236 Standard,
237 Max,
238 /// Ultra-dense bullet-point-only mode — zero prose, diff-style facts,
239 /// strictest token budget (<=50 tokens per non-code response). Maps to
240 /// CrpMode::Tdd with tighter output constraints (#795).
241 Raw,
242}
243
244/// Outcome of [`CompressionLevel::degrade_action`]: what to do with the session
245/// degrade given the current re-fetch pressure. Split from the dispatch so the
246/// threshold logic is a pure, testable function.
247#[derive(Debug, Clone, Copy, PartialEq)]
248pub enum SessionDegrade {
249 /// Set the session degrade to this level.
250 Set(CompressionLevel),
251 /// Clear any session degrade (pressure fully relaxed).
252 Clear,
253 /// Leave the current degrade unchanged (intermediate pressure band).
254 Leave,
255}
256
257impl CompressionLevel {
258 /// Decomposes the unified level into legacy component settings.
259 /// Returns (TerseAgent, OutputDensity, crp_mode_str, terse_mode_bool).
260 pub fn to_components(&self) -> (TerseAgent, OutputDensity, &'static str, bool) {
261 match self {
262 Self::Off => (TerseAgent::Off, OutputDensity::Normal, "off", false),
263 Self::Lite => (TerseAgent::Lite, OutputDensity::Terse, "off", true),
264 Self::Standard => (TerseAgent::Full, OutputDensity::Terse, "compact", true),
265 Self::Max | Self::Raw => (TerseAgent::Ultra, OutputDensity::Ultra, "tdd", true),
266 }
267 }
268
269 /// Infers a `CompressionLevel` from legacy config keys for backward compatibility.
270 /// Priority: terse_agent > output_density (picks the highest implied level).
271 pub fn from_legacy(terse_agent: &TerseAgent, output_density: &OutputDensity) -> Self {
272 match (terse_agent, output_density) {
273 (TerseAgent::Ultra, _) | (_, OutputDensity::Ultra) => Self::Max,
274 (TerseAgent::Full, _) => Self::Standard,
275 (TerseAgent::Lite, _) | (_, OutputDensity::Terse) => Self::Lite,
276 _ => Self::Off,
277 }
278 }
279
280 /// Reads the compression level from the `LEAN_CTX_COMPRESSION` env var.
281 pub fn from_env() -> Option<Self> {
282 std::env::var("LEAN_CTX_COMPRESSION").ok().and_then(|v| {
283 match v.trim().to_lowercase().as_str() {
284 "off" => Some(Self::Off),
285 "lite" => Some(Self::Lite),
286 "standard" => Some(Self::Standard),
287 "max" => Some(Self::Max),
288 "raw" => Some(Self::Raw),
289 _ => None,
290 }
291 })
292 }
293
294 /// Returns the effective compression level with resolution order:
295 /// 0. Session-level degrade override (set by correction-loop feedback)
296 /// 1. `LEAN_CTX_COMPRESSION` env var
297 /// 2. `compression_level` in config
298 /// 3. Legacy `ultra_compact` flag (maps to `Max`)
299 /// 4. Legacy env vars (`LEAN_CTX_TERSE_AGENT`, `LEAN_CTX_OUTPUT_DENSITY`)
300 /// 5. Legacy config fields (`terse_agent`, `output_density`)
301 pub fn effective(config: &Config) -> Self {
302 if let Some(degraded) = Self::session_degrade_level() {
303 return degraded;
304 }
305 if let Some(env_level) = Self::from_env() {
306 return env_level;
307 }
308 if config.compression_level != Self::Off {
309 return config.compression_level;
310 }
311 if config.ultra_compact {
312 return Self::Max;
313 }
314 let ta_env = TerseAgent::from_env();
315 let od_env = OutputDensity::from_env();
316 let ta = if ta_env == TerseAgent::Off {
317 config.terse_agent.clone()
318 } else {
319 ta_env
320 };
321 let od = if od_env == OutputDensity::Normal {
322 config.output_density.clone()
323 } else {
324 od_env
325 };
326 Self::from_legacy(&ta, &od)
327 }
328
329 /// Session-level degrade: correction loop detected, temporarily reduce compression.
330 /// 0 = no override, 1 = Off, 2 = Lite
331 pub fn session_degrade_level() -> Option<Self> {
332 match SESSION_DEGRADE_LEVEL.load(std::sync::atomic::Ordering::Relaxed) {
333 1 => Some(Self::Off),
334 2 => Some(Self::Lite),
335 _ => None,
336 }
337 }
338
339 /// Sets a session-level compression degrade (called by correction loop detection).
340 pub fn set_session_degrade(level: &Self) {
341 let val = match level {
342 Self::Off => 1u8,
343 Self::Lite => 2u8,
344 _ => 0u8,
345 };
346 SESSION_DEGRADE_LEVEL.store(val, std::sync::atomic::Ordering::Relaxed);
347 }
348
349 /// Clears the session-level degrade (recovery after correction rate drops).
350 pub fn clear_session_degrade() {
351 SESSION_DEGRADE_LEVEL.store(0, std::sync::atomic::Ordering::Relaxed);
352 }
353
354 /// Maps re-fetch *pressure* to a session-degrade decision. Pressure is the
355 /// stronger of the correction-loop count (re-reads/re-runs) and the CCR
356 /// retrieve count (`ctx_expand`/`ctx_retrieve`) — two views of the same "too
357 /// aggressive" signal (#941): 5+ degrades to `Off`, 3+ to `Lite`, 0 clears,
358 /// and the 1–2 band leaves the current degrade untouched.
359 ///
360 /// Pure and total so the thresholds are unit-testable without the dispatch
361 /// path — the regression guard for the brittle source-grep test this replaced
362 /// (#957).
363 pub fn degrade_action(correction_count: u32, retrieve_count: u32) -> SessionDegrade {
364 let pressure = correction_count.max(retrieve_count);
365 if pressure >= 5 {
366 SessionDegrade::Set(Self::Off)
367 } else if pressure >= 3 {
368 SessionDegrade::Set(Self::Lite)
369 } else if pressure == 0 {
370 SessionDegrade::Clear
371 } else {
372 SessionDegrade::Leave
373 }
374 }
375
376 /// Applies a [`SessionDegrade`] decision to the process-global session state.
377 pub fn apply_degrade_action(action: SessionDegrade) {
378 match action {
379 SessionDegrade::Set(level) => Self::set_session_degrade(&level),
380 SessionDegrade::Clear => Self::clear_session_degrade(),
381 SessionDegrade::Leave => {}
382 }
383 }
384
385 pub fn from_str_label(s: &str) -> Option<Self> {
386 match s.trim().to_lowercase().as_str() {
387 "off" => Some(Self::Off),
388 "lite" => Some(Self::Lite),
389 "standard" | "std" => Some(Self::Standard),
390 "max" => Some(Self::Max),
391 _ => None,
392 }
393 }
394
395 pub fn is_active(&self) -> bool {
396 !matches!(self, Self::Off)
397 }
398
399 /// Numeric aggression scale for level comparisons (higher = more compression).
400 pub fn aggression_index(self) -> u8 {
401 match self {
402 Self::Off => 0,
403 Self::Lite => 1,
404 Self::Standard => 2,
405 Self::Max => 3,
406 Self::Raw => 4,
407 }
408 }
409
410 /// Returns `true` when `self` compresses more aggressively than `other`.
411 pub fn is_more_aggressive_than(self, other: &Self) -> bool {
412 self.aggression_index() > other.aggression_index()
413 }
414 pub fn label(&self) -> &'static str {
415 match self {
416 Self::Off => "off",
417 Self::Lite => "lite",
418 Self::Standard => "standard",
419 Self::Max => "max",
420 Self::Raw => "raw",
421 }
422 }
423
424 pub fn description(&self) -> &'static str {
425 match self {
426 Self::Off => "No compression — full verbose output",
427 Self::Lite => "Light compression — concise output, basic terse filtering",
428 Self::Standard => {
429 "Standard compression — dense output, compact protocol, pattern-aware"
430 }
431 Self::Max => "Maximum compression — expert mode, TDD protocol, all layers active",
432 Self::Raw => "Raw-dense compression — bullet points only, zero prose, diff-style facts",
433 }
434 }
435}
436
437/// Where agent rule files are installed: global home dir, project-local, or both.
438#[derive(Debug, Clone, Copy, PartialEq, Eq)]
439pub enum RulesScope {
440 Both,
441 Global,
442 Project,
443}
444
445/// How agent rules are injected for AGENTS.md/CLAUDE.md/CODEBUDDY.md/GEMINI.md consumers.
446///
447/// - `Shared` (default): write a marker-delimited block into the user's shared
448/// instruction file (`CLAUDE.md`, `CODEBUDDY.md`, `AGENTS.md`, `GEMINI.md`) — zero-config
449/// discoverability, but touches a file the user also authors.
450/// - `Dedicated`: never write into those shared files. Instead use each agent's
451/// config-driven, fully-removable auto-load path (Claude/Codex `SessionStart`
452/// hook `additionalContext`, OpenCode `instructions[]`, Gemini
453/// `context.fileName`) plus a lean-ctx-owned rules file. See issue #343.
454/// - `Off`: never write any rules file. For hosts that already supply their own
455/// tool-steering workflow (e.g. an embedded extension) or for phase-isolated /
456/// non-caching harnesses where the injected prefix is pure re-billed overhead
457/// with no cached-re-read dividend to amortize it. See GitHub #361.
458#[derive(Debug, Clone, Copy, PartialEq, Eq)]
459pub enum RulesInjection {
460 Shared,
461 Dedicated,
462 Off,
463}
464
465/// Whether lean-ctx mirrors the host IDE's tool-permission rules onto its own
466/// MCP tools ("permission inheritance").
467///
468/// - `Off` (default): lean-ctx tools are governed only by lean-ctx's own layers
469/// (role policy, shell allowlist). lean-ctx's `ctx_shell` therefore runs
470/// independently of the IDE's `bash`/`rm *` permission rules.
471/// - `On`: before dispatching, lean-ctx reads the active IDE's permission config
472/// (v1: OpenCode `opencode.json[c]`) and applies the equivalent decision to
473/// the matching lean-ctx tool — `deny` blocks, `ask` is held back (MCP cannot
474/// prompt for these tools), `allow` proceeds. Read-only; lean-ctx never writes
475/// the IDE's `permission` block.
476#[derive(Debug, Clone, Copy, PartialEq, Eq)]
477pub enum PermissionInheritance {
478 Off,
479 On,
480}
481
482#[cfg(test)]
483mod tests {
484 use super::{CompressionLevel, SessionDegrade};
485
486 #[test]
487 fn degrade_action_thresholds_are_pressure_based() {
488 use CompressionLevel::{Lite, Off};
489 use SessionDegrade::{Clear, Leave, Set};
490 // 5+ pressure → Off, driven by EITHER the correction-loop or the CCR
491 // retrieve count (the stronger of the two), per #941.
492 assert_eq!(CompressionLevel::degrade_action(5, 0), Set(Off));
493 assert_eq!(CompressionLevel::degrade_action(0, 5), Set(Off));
494 assert_eq!(CompressionLevel::degrade_action(9, 1), Set(Off));
495 // 3–4 pressure → Lite.
496 assert_eq!(CompressionLevel::degrade_action(3, 0), Set(Lite));
497 assert_eq!(CompressionLevel::degrade_action(0, 4), Set(Lite));
498 assert_eq!(CompressionLevel::degrade_action(4, 4), Set(Lite));
499 // 0 pressure → clear; the 1–2 band holds the current degrade.
500 assert_eq!(CompressionLevel::degrade_action(0, 0), Clear);
501 assert_eq!(CompressionLevel::degrade_action(2, 1), Leave);
502 assert_eq!(CompressionLevel::degrade_action(1, 2), Leave);
503 }
504}