lean_ctx/core/config/
logic.rs1use std::path::Path;
2
3#[allow(clippy::wildcard_imports)]
4use super::*;
5impl Config {
6 pub fn crush_verbatim_json_enabled(&self) -> bool {
10 std::env::var("LEAN_CTX_CRUSH_VERBATIM_JSON").is_ok() || self.crush_verbatim_json
11 }
12
13 #[must_use]
19 pub fn resolved_proxy_bind_host(&self) -> std::net::IpAddr {
20 let raw = std::env::var("LEAN_CTX_PROXY_BIND_HOST")
21 .ok()
22 .filter(|v| !v.trim().is_empty())
23 .or_else(|| self.proxy_bind_host.clone());
24 match raw.as_deref().map(str::trim) {
25 Some(v) if !v.is_empty() => v.parse().unwrap_or_else(|_| {
26 tracing::warn!(
27 "proxy_bind_host '{v}' is not a valid IP address — binding 127.0.0.1"
28 );
29 std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST)
30 }),
31 _ => std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST),
32 }
33 }
34
35 pub fn rules_scope_effective(&self) -> RulesScope {
37 let raw = std::env::var("LEAN_CTX_RULES_SCOPE")
38 .ok()
39 .or_else(|| self.rules_scope.clone())
40 .unwrap_or_default();
41 match raw.trim().to_lowercase().as_str() {
42 "global" => RulesScope::Global,
43 "project" => RulesScope::Project,
44 _ => RulesScope::Both,
45 }
46 }
47
48 pub fn rules_injection_effective(&self) -> RulesInjection {
51 let raw = std::env::var("LEAN_CTX_RULES_INJECTION")
52 .ok()
53 .or_else(|| self.rules_injection.clone())
54 .unwrap_or_default();
55 match raw.trim().to_lowercase().as_str() {
56 "dedicated" => RulesInjection::Dedicated,
57 "off" | "none" | "disabled" => RulesInjection::Off,
58 _ => RulesInjection::Shared,
59 }
60 }
61
62 #[must_use]
65 pub fn dashboard_cache_hit_rate(&self) -> Option<f64> {
66 std::env::var("LEAN_CTX_CACHE_HIT_RATE")
67 .ok()
68 .and_then(|v| v.parse().ok())
69 .or(self.dashboard_cache_hit_rate)
70 }
71 #[must_use]
74 pub fn hook_mode_override(&self) -> Option<crate::hooks::HookMode> {
75 let raw = std::env::var("LEAN_CTX_HOOK_MODE")
76 .ok()
77 .or_else(|| self.hook_mode.clone())?;
78 crate::hooks::HookMode::from_str_loose(raw.trim())
79 }
80
81 #[must_use]
85 pub fn permission_inheritance_effective(&self) -> PermissionInheritance {
86 let raw = std::env::var("LEAN_CTX_PERMISSION_INHERITANCE")
87 .ok()
88 .or_else(|| self.permission_inheritance.clone())
89 .unwrap_or_default();
90 match raw.trim().to_lowercase().as_str() {
91 "off" | "false" | "0" | "none" => PermissionInheritance::Off,
92 _ => PermissionInheritance::On,
97 }
98 }
99
100 #[must_use]
107 pub fn dedicated_session_context_active(&self) -> bool {
108 self.rules_injection_effective() == RulesInjection::Dedicated
109 && self.rules_scope_effective() != RulesScope::Project
110 }
111
112 pub(super) fn parse_disabled_tools_env(val: &str) -> Vec<String> {
113 val.split(',')
114 .map(|s| s.trim().to_string())
115 .filter(|s| !s.is_empty())
116 .collect()
117 }
118
119 pub fn disabled_tools_effective(&self) -> Vec<String> {
123 let mut list = if let Ok(val) = std::env::var("LEAN_CTX_DISABLED_TOOLS") {
124 Self::parse_disabled_tools_env(&val)
125 } else {
126 self.disabled_tools.clone()
127 };
128 if self.prefer_native_editor_effective() {
129 for name in EDIT_TOOL_NAMES {
130 if !list.iter().any(|t| t == name) {
131 list.push((*name).to_string());
132 }
133 }
134 }
135 list
136 }
137
138 pub fn prefer_native_editor_effective(&self) -> bool {
141 match std::env::var("LEAN_CTX_PREFER_NATIVE_EDITOR") {
142 Ok(raw) => matches!(
143 raw.trim().to_lowercase().as_str(),
144 "1" | "true" | "yes" | "on"
145 ),
146 Err(_) => self.prefer_native_editor,
147 }
148 }
149
150 pub fn max_index_threads_effective(&self) -> usize {
153 std::env::var("LEANCTX_INDEX_THREADS")
154 .ok()
155 .and_then(|raw| raw.trim().parse::<usize>().ok())
156 .unwrap_or(self.max_index_threads)
157 }
158
159 pub fn edit_tool_blocked(&self, name: &str) -> bool {
163 self.prefer_native_editor_effective() && EDIT_TOOL_NAMES.contains(&name)
164 }
165
166 pub fn minimal_overhead_effective(&self) -> bool {
168 std::env::var("LEAN_CTX_MINIMAL").is_ok() || self.minimal_overhead
169 }
170
171 pub fn minimal_escape_hatch() -> bool {
177 std::env::var("LEAN_CTX_MINIMAL").is_ok()
178 }
179
180 pub fn structure_first_effective(&self) -> bool {
186 match std::env::var("LEAN_CTX_STRUCTURE_FIRST") {
187 Ok(raw) => matches!(
188 raw.trim().to_lowercase().as_str(),
189 "1" | "true" | "yes" | "on"
190 ),
191 Err(_) => self.structure_first,
192 }
193 }
194
195 pub fn session_token_limit_effective(&self) -> usize {
197 std::env::var("LEAN_CTX_SESSION_TOKEN_LIMIT")
198 .ok()
199 .and_then(|v| v.trim().parse().ok())
200 .unwrap_or(self.session_token_limit)
201 }
202
203 pub fn turn_fresh_limit_effective(&self) -> usize {
205 std::env::var("LEAN_CTX_TURN_FRESH_LIMIT")
206 .ok()
207 .and_then(|v| v.trim().parse().ok())
208 .unwrap_or(self.turn_fresh_limit)
209 }
210
211 pub fn progressive_disclosure_effective(&self) -> bool {
214 match std::env::var("LEAN_CTX_PROGRESSIVE_DISCLOSURE") {
215 Ok(raw) => matches!(
216 raw.trim().to_lowercase().as_str(),
217 "1" | "true" | "yes" | "on"
218 ),
219 Err(_) => self.progressive_disclosure,
220 }
221 }
222
223 pub fn auto_mode_learning_effective(&self) -> bool {
228 match std::env::var("LEAN_CTX_AUTO_MODE_LEARNING") {
229 Ok(raw) => matches!(
230 raw.trim().to_lowercase().as_str(),
231 "1" | "true" | "yes" | "on"
232 ),
233 Err(_) => self.auto_mode_learning,
234 }
235 }
236
237 pub fn is_stochastic_enabled(&self) -> bool {
245 match std::env::var("LEAN_CTX_STOCHASTIC") {
246 Ok(raw) => matches!(
247 raw.trim().to_lowercase().as_str(),
248 "1" | "true" | "yes" | "on"
249 ),
250 Err(_) => self.auto_mode_learning_effective(),
251 }
252 }
253
254 pub fn minimal_overhead_effective_for_client(&self, client_name: &str) -> bool {
262 if let Ok(raw) = std::env::var("LEAN_CTX_OVERHEAD_MODE") {
263 match raw.trim().to_lowercase().as_str() {
264 "minimal" => return true,
265 "full" => return self.minimal_overhead_effective(),
266 _ => {}
267 }
268 }
269
270 if self.minimal_overhead_effective() {
271 return true;
272 }
273
274 let client_lower = client_name.trim().to_lowercase();
275 if !client_lower.is_empty() {
276 if let Ok(list) = std::env::var("LEAN_CTX_MINIMAL_CLIENTS") {
277 for needle in list.split(',').map(|s| s.trim().to_lowercase()) {
278 if !needle.is_empty() && client_lower.contains(&needle) {
279 return true;
280 }
281 }
282 } else if client_lower.contains("hermes") || client_lower.contains("minimax") {
283 return true;
284 }
285 }
286
287 let model = std::env::var("LEAN_CTX_MODEL")
288 .or_else(|_| std::env::var("LCTX_MODEL"))
289 .unwrap_or_default();
290 let model = model.trim().to_lowercase();
291 if !model.is_empty() {
292 let m = model.replace(['_', ' '], "-");
293 if m.contains("minimax")
294 || m.contains("mini-max")
295 || m.contains("m2.7")
296 || m.contains("m2-7")
297 {
298 return true;
299 }
300 }
301
302 false
303 }
304
305 pub fn shell_hook_disabled_effective(&self) -> bool {
307 std::env::var("LEAN_CTX_NO_HOOK").is_ok() || self.shell_hook_disabled
308 }
309
310 pub fn shell_activation_effective(&self) -> ShellActivation {
312 ShellActivation::effective(self)
313 }
314
315 pub fn shell_allow_writes_effective(&self) -> bool {
319 match std::env::var("LEAN_CTX_SHELL_ALLOW_WRITES") {
320 Ok(raw) => matches!(
321 raw.trim().to_ascii_lowercase().as_str(),
322 "1" | "true" | "yes" | "on"
323 ),
324 Err(_) => self.shell_allow_writes,
325 }
326 }
327
328 pub fn shell_write_allow_paths_effective(&self) -> Vec<String> {
331 if self.write_allow_paths.is_empty() {
332 default_shell_write_allow_paths()
333 } else {
334 self.write_allow_paths.clone()
335 }
336 }
337
338 pub fn shell_allow_inline_scripts_effective(&self) -> bool {
343 match std::env::var("LEAN_CTX_SHELL_ALLOW_INLINE_SCRIPTS") {
344 Ok(raw) => matches!(
345 raw.trim().to_ascii_lowercase().as_str(),
346 "1" | "true" | "yes" | "on"
347 ),
348 Err(_) => self.shell_allow_inline_scripts,
349 }
350 }
351
352 pub fn update_check_disabled_effective(&self) -> bool {
354 std::env::var("LEAN_CTX_NO_UPDATE_CHECK").is_ok() || self.update_check_disabled
355 }
356
357 pub fn memory_policy_effective(&self) -> Result<MemoryPolicy, String> {
358 let mut policy = self.memory.clone();
359 policy.apply_env_overrides();
360
361 let budget = self.max_disk_mb_effective();
362 if budget > 0 {
363 let scale_factor = (budget as f64 / 500.0).clamp(0.5, 10.0);
364 let default_policy = MemoryPolicy::default();
365 if policy.knowledge.max_facts == default_policy.knowledge.max_facts {
366 policy.knowledge.max_facts = (200.0 * scale_factor) as usize;
367 }
368 if policy.knowledge.max_patterns == default_policy.knowledge.max_patterns {
369 policy.knowledge.max_patterns = (50.0 * scale_factor) as usize;
370 }
371 if policy.episodic.max_episodes == default_policy.episodic.max_episodes {
372 policy.episodic.max_episodes = (500.0 * scale_factor) as usize;
373 }
374 if policy.procedural.max_procedures == default_policy.procedural.max_procedures {
375 policy.procedural.max_procedures = (100.0 * scale_factor) as usize;
376 }
377 }
378
379 policy.validate()?;
380 Ok(policy)
381 }
382
383 pub fn default_tool_categories_effective(&self) -> Vec<String> {
386 if let Ok(val) = std::env::var("LCTX_DEFAULT_CATEGORIES") {
387 return val
388 .split(',')
389 .map(|s| s.trim().to_lowercase())
390 .filter(|s| !s.is_empty())
391 .collect();
392 }
393 if !self.default_tool_categories.is_empty() {
394 return self
395 .default_tool_categories
396 .iter()
397 .map(|s| s.to_lowercase())
398 .collect();
399 }
400 vec!["core".to_string()]
401 }
402
403 pub fn tool_profile_effective(&self) -> super::tool_profiles::ToolProfile {
411 super::persona::Persona::resolve(self).effective_tool_profile(self)
412 }
413
414 #[must_use]
420 pub fn sensitivity_effective(&self) -> crate::core::sensitivity::SensitivityConfig {
421 self.sensitivity
422 .clone()
423 .with_persona_floor(super::persona::Persona::resolve(self).sensitivity_floor)
424 }
425
426 pub fn no_degrade_effective(&self) -> bool {
429 if let Ok(val) = std::env::var("LCTX_NO_DEGRADE") {
430 return val == "1" || val.eq_ignore_ascii_case("true");
431 }
432 self.no_degrade
433 }
434
435 pub fn delta_explicit_effective(&self) -> bool {
444 if let Ok(val) = std::env::var("LCTX_DELTA_EXPLICIT") {
445 return val == "1" || val.eq_ignore_ascii_case("true");
446 }
447 self.delta_explicit
448 }
449
450 pub fn max_disk_mb_effective(&self) -> u64 {
452 std::env::var("LEAN_CTX_MAX_DISK_MB")
453 .ok()
454 .and_then(|v| v.parse().ok())
455 .unwrap_or(self.max_disk_mb)
456 }
457
458 pub fn max_staleness_days_effective(&self) -> u32 {
460 std::env::var("LEAN_CTX_MAX_STALENESS_DAYS")
461 .ok()
462 .and_then(|v| v.parse().ok())
463 .unwrap_or(self.max_staleness_days)
464 }
465
466 pub fn context_budget_tokens_effective(&self) -> usize {
470 std::env::var("LEAN_CTX_CONTEXT_BUDGET_TOKENS")
471 .ok()
472 .and_then(|v| v.parse().ok())
473 .unwrap_or(self.context.budget_tokens)
474 }
475
476 pub fn proactive_expansion_effective(&self) -> bool {
478 self.context.proactive_expansion
479 }
480
481 pub fn proactive_expansion_budget_tokens_effective(&self) -> usize {
483 self.context.proactive_expansion_budget_tokens
484 }
485
486 pub fn proactive_expansion_threshold_effective(&self) -> f64 {
488 self.context.proactive_expansion_threshold
489 }
490
491 pub fn proactive_expansion_max_age_secs_effective(&self) -> u64 {
493 self.context.proactive_expansion_max_age_secs
494 }
495
496 pub fn archive_max_disk_mb_effective(&self) -> u64 {
499 let budget = self.max_disk_mb_effective();
500 if budget > 0 && self.archive.max_disk_mb == ArchiveConfig::default().max_disk_mb {
501 budget * 25 / 100
502 } else {
503 self.archive.max_disk_mb
504 }
505 }
506
507 pub fn archive_max_age_hours_effective(&self) -> u64 {
510 let staleness = self.max_staleness_days_effective();
511 if staleness > 0 && self.archive.max_age_hours == ArchiveConfig::default().max_age_hours {
512 staleness as u64 * 24
513 } else {
514 self.archive.max_age_hours
515 }
516 }
517
518 pub fn bm25_max_cache_mb_effective(&self) -> u64 {
526 if self.bm25_max_cache_mb != serde_defaults::default_bm25_max_cache_mb() {
527 return self.bm25_max_cache_mb;
528 }
529 let budget = self.max_disk_mb_effective();
530 if budget > 0 {
531 return budget * 10 / 100;
532 }
533 DEFAULT_BM25_PERSIST_MB
534 }
535}
536
537impl Config {
538 pub fn update_global<F>(f: F) -> std::result::Result<Self, super::error::LeanCtxError>
547 where
548 F: FnOnce(&mut Self),
549 {
550 let path = Self::path().ok_or_else(|| {
551 super::error::LeanCtxError::Config("cannot determine home directory".into())
552 })?;
553 Self::update_global_at(&path, f)
554 }
555
556 pub(super) fn update_global_at<F>(
558 path: &Path,
559 f: F,
560 ) -> std::result::Result<Self, super::error::LeanCtxError>
561 where
562 F: FnOnce(&mut Self),
563 {
564 let mut cfg = match std::fs::read_to_string(path) {
565 Ok(raw) if !raw.trim().is_empty() => toml::from_str::<Self>(&raw).map_err(|e| {
566 super::error::LeanCtxError::Config(
567 format!(
568 "refusing to modify an unparseable config.toml ({e}); fix it \
569 manually or run `lean-ctx doctor --fix`, then retry"
570 )
571 .into(),
572 )
573 })?,
574 _ => Self::default(),
575 };
576 f(&mut cfg);
577 cfg.save_to(path)?;
578 Ok(cfg)
579 }
580
581 pub fn save(&self) -> std::result::Result<(), super::error::LeanCtxError> {
587 let path = Self::path().ok_or_else(|| {
588 super::error::LeanCtxError::Config("cannot determine home directory".into())
589 })?;
590 self.save_to(&path)
591 }
592
593 pub(super) fn save_to(
595 &self,
596 path: &Path,
597 ) -> std::result::Result<(), super::error::LeanCtxError> {
598 if let Some(parent) = path.parent() {
599 std::fs::create_dir_all(parent)?;
600 }
601 let content = toml::to_string_pretty(self)
602 .map_err(|e| super::error::LeanCtxError::Config(e.to_string().into()))?;
603 let baseline = toml::from_str::<Self>("").unwrap_or_else(|_| Self::default());
608 let defaults = toml::to_string_pretty(&baseline)
609 .map_err(|e| super::error::LeanCtxError::Config(e.to_string().into()))?;
610 crate::config_io::write_toml_preserving_minimal(path, &content, &defaults)
611 .map_err(|e| super::error::LeanCtxError::Config(e.into()))?;
612 Ok(())
613 }
614
615 pub fn show(&self) -> String {
617 let global_path = Self::path().map_or_else(
618 || "~/.lean-ctx/config.toml".to_string(),
619 |p| p.to_string_lossy().to_string(),
620 );
621 let content = toml::to_string_pretty(self).unwrap_or_default();
622 let mut out = format!("Global config: {global_path}\n\n{content}");
623
624 if let Some(root) = Self::find_project_root() {
625 let local = Self::local_path(&root);
626 if local.exists() {
627 out.push_str(&format!("\n\nLocal config (merged): {}\n", local.display()));
628 } else {
629 out.push_str(&format!(
630 "\n\nLocal config: not found (create {} to override per-project)\n",
631 local.display()
632 ));
633 }
634 }
635 out
636 }
637}