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 [`crate::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#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
191#[serde(rename_all = "snake_case")]
192pub enum ResponseVerbosity {
193 #[default]
194 Full,
195 HeadersOnly,
196}
197
198impl ResponseVerbosity {
199 pub fn effective() -> Self {
200 if let Ok(v) = std::env::var("LEAN_CTX_RESPONSE_VERBOSITY") {
201 match v.trim().to_lowercase().as_str() {
202 "headers_only" | "headers" | "minimal" => return Self::HeadersOnly,
203 "full" | "" => return Self::Full,
204 _ => {}
205 }
206 }
207 Config::load().response_verbosity
208 }
209
210 pub fn is_headers_only(&self) -> bool {
211 matches!(self, Self::HeadersOnly)
212 }
213}
214
215/// Each level maps to specific component settings via `to_components()`.
216#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
217#[serde(rename_all = "lowercase")]
218pub enum CompressionLevel {
219 Off,
220 /// Default: plain-English "concise" guidance (bullets, no filler). Readable
221 /// by humans inspecting their rules files, and still token-saving. The
222 /// denser, symbolic styles (`Standard`/`Max`, which enable CRP and the
223 /// `→ ∵ ∴` vocabulary) are opt-in "power modes" — set `compression_level`
224 /// in config. This only shapes the model's prose; tool-output compression
225 /// is governed separately and is unaffected.
226 #[default]
227 Lite,
228 Standard,
229 Max,
230 /// Ultra-dense bullet-point-only mode — zero prose, diff-style facts,
231 /// strictest token budget (<=50 tokens per non-code response). Maps to
232 /// CrpMode::Tdd with tighter output constraints (#795).
233 Raw,
234}
235
236/// Outcome of [`CompressionLevel::degrade_action`]: what to do with the session
237/// degrade given the current re-fetch pressure. Split from the dispatch so the
238/// threshold logic is a pure, testable function.
239#[derive(Debug, Clone, Copy, PartialEq)]
240pub enum SessionDegrade {
241 /// Set the session degrade to this level.
242 Set(CompressionLevel),
243 /// Clear any session degrade (pressure fully relaxed).
244 Clear,
245 /// Leave the current degrade unchanged (intermediate pressure band).
246 Leave,
247}
248
249impl CompressionLevel {
250 /// Decomposes the unified level into legacy component settings.
251 /// Returns (TerseAgent, OutputDensity, crp_mode_str, terse_mode_bool).
252 pub fn to_components(&self) -> (TerseAgent, OutputDensity, &'static str, bool) {
253 match self {
254 Self::Off => (TerseAgent::Off, OutputDensity::Normal, "off", false),
255 Self::Lite => (TerseAgent::Lite, OutputDensity::Terse, "off", true),
256 Self::Standard => (TerseAgent::Full, OutputDensity::Terse, "compact", true),
257 Self::Max | Self::Raw => (TerseAgent::Ultra, OutputDensity::Ultra, "tdd", true),
258 }
259 }
260
261 /// Infers a `CompressionLevel` from legacy config keys for backward compatibility.
262 /// Priority: terse_agent > output_density (picks the highest implied level).
263 pub fn from_legacy(terse_agent: &TerseAgent, output_density: &OutputDensity) -> Self {
264 match (terse_agent, output_density) {
265 (TerseAgent::Ultra, _) | (_, OutputDensity::Ultra) => Self::Max,
266 (TerseAgent::Full, _) => Self::Standard,
267 (TerseAgent::Lite, _) | (_, OutputDensity::Terse) => Self::Lite,
268 _ => Self::Off,
269 }
270 }
271
272 /// Reads the compression level from the `LEAN_CTX_COMPRESSION` env var.
273 pub fn from_env() -> Option<Self> {
274 std::env::var("LEAN_CTX_COMPRESSION").ok().and_then(|v| {
275 match v.trim().to_lowercase().as_str() {
276 "off" => Some(Self::Off),
277 "lite" => Some(Self::Lite),
278 "standard" => Some(Self::Standard),
279 "max" => Some(Self::Max),
280 "raw" => Some(Self::Raw),
281 _ => None,
282 }
283 })
284 }
285
286 /// Returns the effective compression level with resolution order:
287 /// 0. Session-level degrade override (set by correction-loop feedback)
288 /// 1. `LEAN_CTX_COMPRESSION` env var
289 /// 2. `compression_level` in config
290 /// 3. Legacy `ultra_compact` flag (maps to `Max`)
291 /// 4. Legacy env vars (`LEAN_CTX_TERSE_AGENT`, `LEAN_CTX_OUTPUT_DENSITY`)
292 /// 5. Legacy config fields (`terse_agent`, `output_density`)
293 pub fn effective(config: &Config) -> Self {
294 if let Some(degraded) = Self::session_degrade_level() {
295 return degraded;
296 }
297 if let Some(env_level) = Self::from_env() {
298 return env_level;
299 }
300 if config.compression_level != Self::Off {
301 return config.compression_level;
302 }
303 if config.ultra_compact {
304 return Self::Max;
305 }
306 let ta_env = TerseAgent::from_env();
307 let od_env = OutputDensity::from_env();
308 let ta = if ta_env == TerseAgent::Off {
309 config.terse_agent.clone()
310 } else {
311 ta_env
312 };
313 let od = if od_env == OutputDensity::Normal {
314 config.output_density.clone()
315 } else {
316 od_env
317 };
318 Self::from_legacy(&ta, &od)
319 }
320
321 /// Session-level degrade: correction loop detected, temporarily reduce compression.
322 /// 0 = no override, 1 = Off, 2 = Lite
323 pub fn session_degrade_level() -> Option<Self> {
324 match SESSION_DEGRADE_LEVEL.load(std::sync::atomic::Ordering::Relaxed) {
325 1 => Some(Self::Off),
326 2 => Some(Self::Lite),
327 _ => None,
328 }
329 }
330
331 /// Sets a session-level compression degrade (called by correction loop detection).
332 pub fn set_session_degrade(level: &Self) {
333 let val = match level {
334 Self::Off => 1u8,
335 Self::Lite => 2u8,
336 _ => 0u8,
337 };
338 SESSION_DEGRADE_LEVEL.store(val, std::sync::atomic::Ordering::Relaxed);
339 }
340
341 /// Clears the session-level degrade (recovery after correction rate drops).
342 pub fn clear_session_degrade() {
343 SESSION_DEGRADE_LEVEL.store(0, std::sync::atomic::Ordering::Relaxed);
344 }
345
346 /// Maps re-fetch *pressure* to a session-degrade decision. Pressure is the
347 /// stronger of the correction-loop count (re-reads/re-runs) and the CCR
348 /// retrieve count (`ctx_expand`/`ctx_retrieve`) — two views of the same "too
349 /// aggressive" signal (#941): 5+ degrades to `Off`, 3+ to `Lite`, 0 clears,
350 /// and the 1–2 band leaves the current degrade untouched.
351 ///
352 /// Pure and total so the thresholds are unit-testable without the dispatch
353 /// path — the regression guard for the brittle source-grep test this replaced
354 /// (#957).
355 pub fn degrade_action(correction_count: u32, retrieve_count: u32) -> SessionDegrade {
356 let pressure = correction_count.max(retrieve_count);
357 if pressure >= 5 {
358 SessionDegrade::Set(Self::Off)
359 } else if pressure >= 3 {
360 SessionDegrade::Set(Self::Lite)
361 } else if pressure == 0 {
362 SessionDegrade::Clear
363 } else {
364 SessionDegrade::Leave
365 }
366 }
367
368 /// Applies a [`SessionDegrade`] decision to the process-global session state.
369 pub fn apply_degrade_action(action: SessionDegrade) {
370 match action {
371 SessionDegrade::Set(level) => Self::set_session_degrade(&level),
372 SessionDegrade::Clear => Self::clear_session_degrade(),
373 SessionDegrade::Leave => {}
374 }
375 }
376
377 pub fn from_str_label(s: &str) -> Option<Self> {
378 match s.trim().to_lowercase().as_str() {
379 "off" => Some(Self::Off),
380 "lite" => Some(Self::Lite),
381 "standard" | "std" => Some(Self::Standard),
382 "max" => Some(Self::Max),
383 _ => None,
384 }
385 }
386
387 pub fn is_active(&self) -> bool {
388 !matches!(self, Self::Off)
389 }
390
391 pub fn label(&self) -> &'static str {
392 match self {
393 Self::Off => "off",
394 Self::Lite => "lite",
395 Self::Standard => "standard",
396 Self::Max => "max",
397 Self::Raw => "raw",
398 }
399 }
400
401 pub fn description(&self) -> &'static str {
402 match self {
403 Self::Off => "No compression — full verbose output",
404 Self::Lite => "Light compression — concise output, basic terse filtering",
405 Self::Standard => {
406 "Standard compression — dense output, compact protocol, pattern-aware"
407 }
408 Self::Max => "Maximum compression — expert mode, TDD protocol, all layers active",
409 Self::Raw => "Raw-dense compression — bullet points only, zero prose, diff-style facts",
410 }
411 }
412}
413
414/// Where agent rule files are installed: global home dir, project-local, or both.
415#[derive(Debug, Clone, Copy, PartialEq, Eq)]
416pub enum RulesScope {
417 Both,
418 Global,
419 Project,
420}
421
422/// How agent rules are injected for AGENTS.md/CLAUDE.md/CODEBUDDY.md/GEMINI.md consumers.
423///
424/// - `Shared` (default): write a marker-delimited block into the user's shared
425/// instruction file (`CLAUDE.md`, `CODEBUDDY.md`, `AGENTS.md`, `GEMINI.md`) — zero-config
426/// discoverability, but touches a file the user also authors.
427/// - `Dedicated`: never write into those shared files. Instead use each agent's
428/// config-driven, fully-removable auto-load path (Claude/Codex `SessionStart`
429/// hook `additionalContext`, OpenCode `instructions[]`, Gemini
430/// `context.fileName`) plus a lean-ctx-owned rules file. See issue #343.
431/// - `Off`: never write any rules file. For hosts that already supply their own
432/// tool-steering workflow (e.g. an embedded extension) or for phase-isolated /
433/// non-caching harnesses where the injected prefix is pure re-billed overhead
434/// with no cached-re-read dividend to amortize it. See GitHub #361.
435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
436pub enum RulesInjection {
437 Shared,
438 Dedicated,
439 Off,
440}
441
442/// Whether lean-ctx mirrors the host IDE's tool-permission rules onto its own
443/// MCP tools ("permission inheritance").
444///
445/// - `Off` (default): lean-ctx tools are governed only by lean-ctx's own layers
446/// (role policy, shell allowlist). lean-ctx's `ctx_shell` therefore runs
447/// independently of the IDE's `bash`/`rm *` permission rules.
448/// - `On`: before dispatching, lean-ctx reads the active IDE's permission config
449/// (v1: OpenCode `opencode.json[c]`) and applies the equivalent decision to
450/// the matching lean-ctx tool — `deny` blocks, `ask` is held back (MCP cannot
451/// prompt for these tools), `allow` proceeds. Read-only; lean-ctx never writes
452/// the IDE's `permission` block.
453#[derive(Debug, Clone, Copy, PartialEq, Eq)]
454pub enum PermissionInheritance {
455 Off,
456 On,
457}
458
459#[cfg(test)]
460mod tests {
461 use super::{CompressionLevel, SessionDegrade};
462
463 #[test]
464 fn degrade_action_thresholds_are_pressure_based() {
465 use CompressionLevel::{Lite, Off};
466 use SessionDegrade::{Clear, Leave, Set};
467 // 5+ pressure → Off, driven by EITHER the correction-loop or the CCR
468 // retrieve count (the stronger of the two), per #941.
469 assert_eq!(CompressionLevel::degrade_action(5, 0), Set(Off));
470 assert_eq!(CompressionLevel::degrade_action(0, 5), Set(Off));
471 assert_eq!(CompressionLevel::degrade_action(9, 1), Set(Off));
472 // 3–4 pressure → Lite.
473 assert_eq!(CompressionLevel::degrade_action(3, 0), Set(Lite));
474 assert_eq!(CompressionLevel::degrade_action(0, 4), Set(Lite));
475 assert_eq!(CompressionLevel::degrade_action(4, 4), Set(Lite));
476 // 0 pressure → clear; the 1–2 band holds the current degrade.
477 assert_eq!(CompressionLevel::degrade_action(0, 0), Clear);
478 assert_eq!(CompressionLevel::degrade_action(2, 1), Leave);
479 assert_eq!(CompressionLevel::degrade_action(1, 2), Leave);
480 }
481}