Skip to main content

lean_ctx/core/
profiles.rs

1//! # Context Profiles
2//!
3//! Declarative, version-controlled context strategies ("Context as Code").
4//!
5//! Profiles configure how lean-ctx processes content for different scenarios:
6//! exploration, bugfixing, hotfixes, CI debugging, code review, etc.
7//!
8//! ## Resolution Order
9//!
10//! 1. `LEAN_CTX_PROFILE` env var
11//! 2. `.lean-ctx/profiles/<name>.toml` (project-local)
12//! 3. `~/.lean-ctx/profiles/<name>.toml` (global)
13//! 4. Built-in defaults (compiled into the binary)
14//!
15//! ## Inheritance
16//!
17//! Profiles can inherit from other profiles via `inherits = "parent"`.
18//! Child values override parent values; unset fields fall through.
19
20use serde::{Deserialize, Serialize};
21use std::collections::HashMap;
22use std::path::{Path, PathBuf};
23use std::sync::RwLock;
24
25/// A complete context profile definition.
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct Profile {
28    #[serde(default)]
29    pub profile: ProfileMeta,
30    #[serde(default)]
31    pub read: ReadConfig,
32    #[serde(default)]
33    pub compression: CompressionConfig,
34    #[serde(default)]
35    pub translation: TranslationConfig,
36    #[serde(default)]
37    pub layout: LayoutConfig,
38    #[serde(default)]
39    pub memory: crate::core::memory_policy::MemoryPolicyOverrides,
40    #[serde(default)]
41    pub verification: crate::core::output_verification::VerificationConfig,
42    #[serde(default)]
43    pub budget: BudgetConfig,
44    #[serde(default)]
45    pub pipeline: PipelineConfig,
46    #[serde(default)]
47    pub routing: RoutingConfig,
48    #[serde(default)]
49    pub degradation: DegradationConfig,
50    #[serde(default)]
51    pub autonomy: ProfileAutonomy,
52    #[serde(default)]
53    pub output_hints: OutputHints,
54}
55
56/// Profile identity and inheritance.
57#[derive(Debug, Clone, Serialize, Deserialize, Default)]
58pub struct ProfileMeta {
59    #[serde(default)]
60    pub name: String,
61    pub inherits: Option<String>,
62    #[serde(default)]
63    pub description: String,
64}
65
66/// Read behavior configuration.
67///
68/// Fields are `Option<T>` for field-level profile inheritance.
69/// Use `_effective()` methods to get the resolved value with defaults.
70#[derive(Debug, Clone, Serialize, Deserialize, Default)]
71#[serde(default)]
72pub struct ReadConfig {
73    pub default_mode: Option<String>,
74    pub max_tokens_per_file: Option<usize>,
75    pub prefer_cache: Option<bool>,
76}
77
78impl ReadConfig {
79    pub fn default_mode_effective(&self) -> &str {
80        self.default_mode.as_deref().unwrap_or("auto")
81    }
82    pub fn max_tokens_per_file_effective(&self) -> usize {
83        self.max_tokens_per_file.unwrap_or(50_000)
84    }
85    pub fn prefer_cache_effective(&self) -> bool {
86        self.prefer_cache.unwrap_or(false)
87    }
88}
89
90/// Compression strategy configuration.
91#[derive(Debug, Clone, Serialize, Deserialize, Default)]
92#[serde(default)]
93pub struct CompressionConfig {
94    pub crp_mode: Option<String>,
95    pub output_density: Option<String>,
96    pub entropy_threshold: Option<f64>,
97    pub terse_mode: Option<bool>,
98}
99
100impl CompressionConfig {
101    pub fn crp_mode_effective(&self) -> &str {
102        self.crp_mode.as_deref().unwrap_or("tdd")
103    }
104    pub fn output_density_effective(&self) -> &str {
105        self.output_density.as_deref().unwrap_or("normal")
106    }
107    pub fn entropy_threshold_effective(&self) -> f64 {
108        self.entropy_threshold.unwrap_or(0.3)
109    }
110    pub fn terse_mode_effective(&self) -> bool {
111        self.terse_mode.unwrap_or(false)
112    }
113}
114
115/// Translation (tokenizer-aware) configuration.
116#[derive(Debug, Clone, Serialize, Deserialize, Default)]
117#[serde(default)]
118pub struct TranslationConfig {
119    /// If false, preserve legacy CRP/TDD formats without post-translation.
120    pub enabled: Option<bool>,
121    /// legacy|ascii|auto
122    pub ruleset: Option<String>,
123}
124
125impl TranslationConfig {
126    pub fn enabled_effective(&self) -> bool {
127        self.enabled.unwrap_or(false)
128    }
129    pub fn ruleset_effective(&self) -> &str {
130        self.ruleset.as_deref().unwrap_or("legacy")
131    }
132}
133
134/// Layout (attention-aware reorder) configuration.
135#[derive(Debug, Clone, Serialize, Deserialize, Default)]
136#[serde(default)]
137pub struct LayoutConfig {
138    /// If false, preserve original order.
139    pub enabled: Option<bool>,
140    /// Minimum line count for enabling reorder.
141    pub min_lines: Option<usize>,
142}
143
144impl LayoutConfig {
145    pub fn enabled_effective(&self) -> bool {
146        self.enabled.unwrap_or(false)
147    }
148    pub fn min_lines_effective(&self) -> usize {
149        self.min_lines.unwrap_or(15)
150    }
151}
152
153/// Routing policy overrides (intent → model tier → read mode/budgets).
154#[derive(Debug, Clone, Serialize, Deserialize, Default)]
155pub struct RoutingConfig {
156    /// Hard cap for recommended model tier: fast|standard|premium.
157    #[serde(default)]
158    pub max_model_tier: Option<String>,
159    /// If true, apply deterministic routing degradation under budget/pressure.
160    #[serde(default)]
161    pub degrade_under_pressure: Option<bool>,
162}
163
164impl RoutingConfig {
165    pub fn max_model_tier_effective(&self) -> &str {
166        self.max_model_tier.as_deref().unwrap_or("premium")
167    }
168
169    pub fn degrade_under_pressure_effective(&self) -> bool {
170        self.degrade_under_pressure.unwrap_or(true)
171    }
172}
173
174/// Budget/SLO degradation policy configuration.
175#[derive(Debug, Clone, Serialize, Deserialize, Default)]
176pub struct DegradationConfig {
177    /// If true, enforce throttling/blocking decisions. Default is warn-only.
178    #[serde(default)]
179    pub enforce: Option<bool>,
180    /// Throttle duration (ms) when policy verdict is Throttle. Default: 250ms.
181    #[serde(default)]
182    pub throttle_ms: Option<u64>,
183}
184
185impl DegradationConfig {
186    pub fn enforce_effective(&self) -> bool {
187        self.enforce.unwrap_or(false)
188    }
189
190    pub fn throttle_ms_effective(&self) -> u64 {
191        self.throttle_ms.unwrap_or(250)
192    }
193}
194
195/// Controls which optional hints/footers are appended to tool output.
196/// All default to `false` for minimal output overhead.
197#[derive(Debug, Clone, Default, Serialize, Deserialize)]
198#[serde(default)]
199pub struct OutputHints {
200    pub compressed_hint: Option<bool>,
201    pub archive_hint: Option<bool>,
202    pub verify_footer: Option<bool>,
203    pub related_hint: Option<bool>,
204    pub semantic_hint: Option<bool>,
205    pub elicitation_hint: Option<bool>,
206    pub checkpoint_in_output: Option<bool>,
207    pub graph_context_block: Option<bool>,
208    pub efficiency_hint: Option<bool>,
209}
210
211impl OutputHints {
212    pub fn compressed_hint(&self) -> bool {
213        self.compressed_hint.unwrap_or(false)
214    }
215    pub fn archive_hint(&self) -> bool {
216        self.archive_hint.unwrap_or(false)
217    }
218    pub fn verify_footer(&self) -> bool {
219        self.verify_footer.unwrap_or(false)
220    }
221    pub fn related_hint(&self) -> bool {
222        self.related_hint.unwrap_or(false)
223    }
224    pub fn semantic_hint(&self) -> bool {
225        self.semantic_hint.unwrap_or(false)
226    }
227    pub fn elicitation_hint(&self) -> bool {
228        self.elicitation_hint.unwrap_or(false)
229    }
230    pub fn checkpoint_in_output(&self) -> bool {
231        self.checkpoint_in_output.unwrap_or(false)
232    }
233    pub fn graph_context_block(&self) -> bool {
234        self.graph_context_block.unwrap_or(false)
235    }
236    pub fn efficiency_hint(&self) -> bool {
237        self.efficiency_hint.unwrap_or(false)
238    }
239}
240
241/// Token and cost budget limits.
242#[derive(Debug, Clone, Serialize, Deserialize, Default)]
243#[serde(default)]
244pub struct BudgetConfig {
245    pub max_context_tokens: Option<usize>,
246    pub max_shell_invocations: Option<usize>,
247    pub max_cost_usd: Option<f64>,
248}
249
250impl BudgetConfig {
251    pub fn max_context_tokens_effective(&self) -> usize {
252        self.max_context_tokens.unwrap_or(200_000)
253    }
254    pub fn max_shell_invocations_effective(&self) -> usize {
255        self.max_shell_invocations.unwrap_or(100)
256    }
257    pub fn max_cost_usd_effective(&self) -> f64 {
258        self.max_cost_usd.unwrap_or(5.0)
259    }
260}
261
262/// Pipeline layer activation per profile.
263#[derive(Debug, Clone, Serialize, Deserialize, Default)]
264#[serde(default)]
265pub struct PipelineConfig {
266    pub intent: Option<bool>,
267    pub relevance: Option<bool>,
268    pub compression: Option<bool>,
269    pub translation: Option<bool>,
270}
271
272impl PipelineConfig {
273    pub fn intent_effective(&self) -> bool {
274        self.intent.unwrap_or(true)
275    }
276    pub fn relevance_effective(&self) -> bool {
277        self.relevance.unwrap_or(true)
278    }
279    pub fn compression_effective(&self) -> bool {
280        self.compression.unwrap_or(true)
281    }
282    pub fn translation_effective(&self) -> bool {
283        self.translation.unwrap_or(true)
284    }
285}
286
287/// Autonomy overrides per profile.
288#[derive(Debug, Clone, Serialize, Deserialize, Default)]
289#[serde(default)]
290pub struct ProfileAutonomy {
291    pub enabled: Option<bool>,
292    pub auto_preload: Option<bool>,
293    pub auto_dedup: Option<bool>,
294    pub auto_related: Option<bool>,
295    pub silent_preload: Option<bool>,
296    /// Enable bounded prefetch after reads (opt-in by default).
297    pub auto_prefetch: Option<bool>,
298    /// Enable response shaping for large outputs (opt-in by default).
299    pub auto_response: Option<bool>,
300    pub dedup_threshold: Option<usize>,
301    pub prefetch_max_files: Option<usize>,
302    pub prefetch_budget_tokens: Option<usize>,
303    pub response_min_tokens: Option<usize>,
304    pub checkpoint_interval: Option<u32>,
305}
306
307impl ProfileAutonomy {
308    pub fn enabled_effective(&self) -> bool {
309        self.enabled.unwrap_or(true)
310    }
311    pub fn auto_preload_effective(&self) -> bool {
312        self.auto_preload.unwrap_or(true)
313    }
314    pub fn auto_dedup_effective(&self) -> bool {
315        self.auto_dedup.unwrap_or(true)
316    }
317    pub fn auto_related_effective(&self) -> bool {
318        self.auto_related.unwrap_or(true)
319    }
320    pub fn silent_preload_effective(&self) -> bool {
321        self.silent_preload.unwrap_or(true)
322    }
323    pub fn auto_prefetch_effective(&self) -> bool {
324        self.auto_prefetch.unwrap_or(false)
325    }
326    pub fn auto_response_effective(&self) -> bool {
327        self.auto_response.unwrap_or(false)
328    }
329    pub fn dedup_threshold_effective(&self) -> usize {
330        self.dedup_threshold.unwrap_or(8)
331    }
332    pub fn prefetch_max_files_effective(&self) -> usize {
333        self.prefetch_max_files.unwrap_or(3)
334    }
335    pub fn prefetch_budget_tokens_effective(&self) -> usize {
336        self.prefetch_budget_tokens.unwrap_or(4000)
337    }
338    pub fn response_min_tokens_effective(&self) -> usize {
339        self.response_min_tokens.unwrap_or(600)
340    }
341    pub fn checkpoint_interval_effective(&self) -> u32 {
342        self.checkpoint_interval.unwrap_or(15)
343    }
344}
345
346// ── Built-in Profiles ──────────────────────────────────────
347
348fn builtin_coder() -> Profile {
349    Profile {
350        profile: ProfileMeta {
351            name: "coder".to_string(),
352            inherits: None,
353            description: "Default coding workflow with guarded autonomy drivers".to_string(),
354        },
355        read: ReadConfig {
356            default_mode: Some("auto".to_string()),
357            max_tokens_per_file: Some(50_000),
358            prefer_cache: Some(true),
359        },
360        compression: CompressionConfig {
361            crp_mode: Some("tdd".to_string()),
362            output_density: Some("terse".to_string()),
363            terse_mode: Some(true),
364            ..CompressionConfig::default()
365        },
366        translation: TranslationConfig {
367            enabled: Some(true),
368            ruleset: Some("auto".to_string()),
369        },
370        layout: LayoutConfig::default(),
371        memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
372        verification: crate::core::output_verification::VerificationConfig::default(),
373        budget: BudgetConfig {
374            max_context_tokens: Some(150_000),
375            max_shell_invocations: Some(100),
376            ..BudgetConfig::default()
377        },
378        pipeline: PipelineConfig::default(),
379        routing: RoutingConfig::default(),
380        degradation: DegradationConfig::default(),
381        autonomy: ProfileAutonomy {
382            auto_prefetch: Some(true),
383            auto_response: Some(true),
384            checkpoint_interval: Some(10),
385            ..ProfileAutonomy::default()
386        },
387        output_hints: OutputHints::default(),
388    }
389}
390
391fn builtin_exploration() -> Profile {
392    Profile {
393        profile: ProfileMeta {
394            name: "exploration".to_string(),
395            inherits: None,
396            description: "Broad context for understanding codebases".to_string(),
397        },
398        read: ReadConfig {
399            default_mode: Some("map".to_string()),
400            max_tokens_per_file: Some(80_000),
401            prefer_cache: Some(true),
402        },
403        compression: CompressionConfig {
404            terse_mode: Some(true),
405            output_density: Some("terse".to_string()),
406            ..CompressionConfig::default()
407        },
408        translation: TranslationConfig::default(),
409        layout: LayoutConfig::default(),
410        memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
411        verification: crate::core::output_verification::VerificationConfig::default(),
412        budget: BudgetConfig {
413            max_context_tokens: Some(200_000),
414            ..BudgetConfig::default()
415        },
416        pipeline: PipelineConfig::default(),
417        routing: RoutingConfig::default(),
418        degradation: DegradationConfig::default(),
419        autonomy: ProfileAutonomy::default(),
420        output_hints: OutputHints {
421            related_hint: Some(true),
422            compressed_hint: Some(true),
423            ..OutputHints::default()
424        },
425    }
426}
427
428fn builtin_bugfix() -> Profile {
429    Profile {
430        profile: ProfileMeta {
431            name: "bugfix".to_string(),
432            inherits: None,
433            description: "Focused context for debugging specific issues".to_string(),
434        },
435        read: ReadConfig {
436            default_mode: Some("auto".to_string()),
437            max_tokens_per_file: Some(30_000),
438            prefer_cache: Some(false),
439        },
440        compression: CompressionConfig {
441            crp_mode: Some("tdd".to_string()),
442            output_density: Some("terse".to_string()),
443            ..CompressionConfig::default()
444        },
445        translation: TranslationConfig::default(),
446        layout: LayoutConfig::default(),
447        memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
448        verification: crate::core::output_verification::VerificationConfig::default(),
449        budget: BudgetConfig {
450            max_context_tokens: Some(100_000),
451            max_shell_invocations: Some(50),
452            ..BudgetConfig::default()
453        },
454        pipeline: PipelineConfig::default(),
455        routing: RoutingConfig {
456            max_model_tier: Some("standard".to_string()),
457            ..RoutingConfig::default()
458        },
459        degradation: DegradationConfig::default(),
460        autonomy: ProfileAutonomy {
461            checkpoint_interval: Some(10),
462            ..ProfileAutonomy::default()
463        },
464        output_hints: OutputHints::default(),
465    }
466}
467
468fn builtin_hotfix() -> Profile {
469    Profile {
470        profile: ProfileMeta {
471            name: "hotfix".to_string(),
472            inherits: None,
473            description: "Minimal context, fast iteration for urgent fixes".to_string(),
474        },
475        read: ReadConfig {
476            default_mode: Some("signatures".to_string()),
477            max_tokens_per_file: Some(2_000),
478            prefer_cache: Some(true),
479        },
480        compression: CompressionConfig {
481            crp_mode: Some("tdd".to_string()),
482            output_density: Some("ultra".to_string()),
483            ..CompressionConfig::default()
484        },
485        translation: TranslationConfig::default(),
486        layout: LayoutConfig::default(),
487        memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
488        verification: crate::core::output_verification::VerificationConfig::default(),
489        budget: BudgetConfig {
490            max_context_tokens: Some(30_000),
491            max_shell_invocations: Some(20),
492            max_cost_usd: Some(1.0),
493        },
494        pipeline: PipelineConfig::default(),
495        routing: RoutingConfig {
496            max_model_tier: Some("fast".to_string()),
497            ..RoutingConfig::default()
498        },
499        degradation: DegradationConfig::default(),
500        autonomy: ProfileAutonomy {
501            checkpoint_interval: Some(5),
502            ..ProfileAutonomy::default()
503        },
504        output_hints: OutputHints::default(),
505    }
506}
507
508fn builtin_ci_debug() -> Profile {
509    Profile {
510        profile: ProfileMeta {
511            name: "ci-debug".to_string(),
512            inherits: None,
513            description: "CI/CD debugging with shell-heavy workflows".to_string(),
514        },
515        read: ReadConfig {
516            default_mode: Some("auto".to_string()),
517            max_tokens_per_file: Some(50_000),
518            prefer_cache: Some(false),
519        },
520        compression: CompressionConfig {
521            output_density: Some("terse".to_string()),
522            ..CompressionConfig::default()
523        },
524        translation: TranslationConfig::default(),
525        layout: LayoutConfig::default(),
526        memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
527        verification: crate::core::output_verification::VerificationConfig::default(),
528        budget: BudgetConfig {
529            max_context_tokens: Some(150_000),
530            max_shell_invocations: Some(200),
531            ..BudgetConfig::default()
532        },
533        pipeline: PipelineConfig::default(),
534        routing: RoutingConfig {
535            max_model_tier: Some("standard".to_string()),
536            ..RoutingConfig::default()
537        },
538        degradation: DegradationConfig::default(),
539        autonomy: ProfileAutonomy::default(),
540        output_hints: OutputHints::default(),
541    }
542}
543
544fn builtin_review() -> Profile {
545    Profile {
546        profile: ProfileMeta {
547            name: "review".to_string(),
548            inherits: None,
549            description: "Code review with broad read-only context".to_string(),
550        },
551        read: ReadConfig {
552            default_mode: Some("map".to_string()),
553            max_tokens_per_file: Some(60_000),
554            prefer_cache: Some(true),
555        },
556        compression: CompressionConfig {
557            crp_mode: Some("compact".to_string()),
558            ..CompressionConfig::default()
559        },
560        translation: TranslationConfig::default(),
561        layout: LayoutConfig {
562            enabled: Some(true),
563            ..LayoutConfig::default()
564        },
565        memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
566        verification: crate::core::output_verification::VerificationConfig::default(),
567        budget: BudgetConfig {
568            max_context_tokens: Some(150_000),
569            max_shell_invocations: Some(30),
570            ..BudgetConfig::default()
571        },
572        pipeline: PipelineConfig::default(),
573        routing: RoutingConfig {
574            max_model_tier: Some("standard".to_string()),
575            ..RoutingConfig::default()
576        },
577        degradation: DegradationConfig::default(),
578        autonomy: ProfileAutonomy::default(),
579        output_hints: OutputHints {
580            verify_footer: Some(true),
581            related_hint: Some(true),
582            compressed_hint: Some(true),
583            ..OutputHints::default()
584        },
585    }
586}
587
588fn builtin_passthrough() -> Profile {
589    Profile {
590        profile: ProfileMeta {
591            name: "passthrough".to_string(),
592            inherits: None,
593            description: "No output modification — always full content, no compression".to_string(),
594        },
595        read: ReadConfig {
596            default_mode: Some("full".to_string()),
597            max_tokens_per_file: Some(10_000_000),
598            prefer_cache: Some(false),
599        },
600        compression: CompressionConfig {
601            crp_mode: Some("off".to_string()),
602            output_density: Some("normal".to_string()),
603            entropy_threshold: None,
604            terse_mode: Some(false),
605        },
606        translation: TranslationConfig {
607            enabled: Some(false),
608            ..TranslationConfig::default()
609        },
610        layout: LayoutConfig::default(),
611        memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
612        verification: crate::core::output_verification::VerificationConfig::default(),
613        budget: BudgetConfig {
614            max_context_tokens: Some(1_000_000),
615            ..BudgetConfig::default()
616        },
617        pipeline: PipelineConfig {
618            intent: Some(false),
619            relevance: Some(false),
620            compression: Some(false),
621            translation: Some(false),
622        },
623        routing: RoutingConfig::default(),
624        degradation: DegradationConfig {
625            enforce: Some(false),
626            ..DegradationConfig::default()
627        },
628        autonomy: ProfileAutonomy::default(),
629        output_hints: OutputHints::default(),
630    }
631}
632
633/// Returns all built-in profile definitions.
634pub fn builtin_profiles() -> HashMap<String, Profile> {
635    let mut map = HashMap::new();
636    for p in [
637        builtin_coder(),
638        builtin_exploration(),
639        builtin_bugfix(),
640        builtin_hotfix(),
641        builtin_ci_debug(),
642        builtin_review(),
643        builtin_passthrough(),
644    ] {
645        map.insert(p.profile.name.clone(), p);
646    }
647    map
648}
649
650// ── Loading ────────────────────────────────────────────────
651
652fn profiles_dir_global() -> Option<PathBuf> {
653    crate::core::data_dir::lean_ctx_data_dir()
654        .ok()
655        .map(|d| d.join("profiles"))
656}
657
658fn profiles_dir_project() -> Option<PathBuf> {
659    let mut current = std::env::current_dir().ok()?;
660    for _ in 0..12 {
661        let candidate = current.join(".lean-ctx").join("profiles");
662        if candidate.is_dir() {
663            return Some(candidate);
664        }
665        if !current.pop() {
666            break;
667        }
668    }
669    None
670}
671
672/// Loads a profile by name with full resolution:
673/// 1. Project-local `.lean-ctx/profiles/<name>.toml`
674/// 2. Global `~/.lean-ctx/profiles/<name>.toml`
675/// 3. Built-in defaults
676///
677/// Applies inheritance chain (max depth 5 to prevent cycles).
678pub fn load_profile(name: &str) -> Option<Profile> {
679    load_profile_recursive(name, 0)
680}
681
682fn load_profile_recursive(name: &str, depth: usize) -> Option<Profile> {
683    if depth > 5 {
684        return None;
685    }
686
687    let mut profile = load_profile_from_disk(name).or_else(|| builtin_profiles().remove(name))?;
688    profile.profile.name = name.to_string();
689
690    if let Some(ref parent_name) = profile.profile.inherits.clone()
691        && let Some(parent) = load_profile_recursive(parent_name, depth + 1)
692    {
693        profile = merge_profiles(parent, profile);
694    }
695
696    Some(profile)
697}
698
699fn load_profile_from_disk(name: &str) -> Option<Profile> {
700    let filename = format!("{name}.toml");
701
702    if let Some(project_dir) = profiles_dir_project() {
703        let path = project_dir.join(&filename);
704        if let Some(p) = try_load_toml(&path) {
705            return Some(p);
706        }
707    }
708
709    if let Some(global_dir) = profiles_dir_global() {
710        let path = global_dir.join(&filename);
711        if let Some(p) = try_load_toml(&path) {
712            return Some(p);
713        }
714    }
715
716    None
717}
718
719fn try_load_toml(path: &Path) -> Option<Profile> {
720    let content = std::fs::read_to_string(path).ok()?;
721    toml::from_str(&content).ok()
722}
723
724/// Merges parent into child: child values take precedence,
725/// parent provides defaults for unspecified fields.
726///
727/// ALL sections are merged field-by-field using `Option::or()`.
728/// A child profile only needs to set the fields it wants to override.
729fn merge_profiles(parent: Profile, child: Profile) -> Profile {
730    let read = ReadConfig {
731        default_mode: child.read.default_mode.or(parent.read.default_mode),
732        max_tokens_per_file: child
733            .read
734            .max_tokens_per_file
735            .or(parent.read.max_tokens_per_file),
736        prefer_cache: child.read.prefer_cache.or(parent.read.prefer_cache),
737    };
738    let compression = CompressionConfig {
739        crp_mode: child.compression.crp_mode.or(parent.compression.crp_mode),
740        output_density: child
741            .compression
742            .output_density
743            .or(parent.compression.output_density),
744        entropy_threshold: child
745            .compression
746            .entropy_threshold
747            .or(parent.compression.entropy_threshold),
748        terse_mode: child
749            .compression
750            .terse_mode
751            .or(parent.compression.terse_mode),
752    };
753    let translation = TranslationConfig {
754        enabled: child.translation.enabled.or(parent.translation.enabled),
755        ruleset: child.translation.ruleset.or(parent.translation.ruleset),
756    };
757    let layout = LayoutConfig {
758        enabled: child.layout.enabled.or(parent.layout.enabled),
759        min_lines: child.layout.min_lines.or(parent.layout.min_lines),
760    };
761    let memory = crate::core::memory_policy::MemoryPolicyOverrides {
762        knowledge: crate::core::memory_policy::KnowledgePolicyOverrides {
763            max_facts: child
764                .memory
765                .knowledge
766                .max_facts
767                .or(parent.memory.knowledge.max_facts),
768            max_patterns: child
769                .memory
770                .knowledge
771                .max_patterns
772                .or(parent.memory.knowledge.max_patterns),
773            max_history: child
774                .memory
775                .knowledge
776                .max_history
777                .or(parent.memory.knowledge.max_history),
778            contradiction_threshold: child
779                .memory
780                .knowledge
781                .contradiction_threshold
782                .or(parent.memory.knowledge.contradiction_threshold),
783            recall_facts_limit: child
784                .memory
785                .knowledge
786                .recall_facts_limit
787                .or(parent.memory.knowledge.recall_facts_limit),
788            rooms_limit: child
789                .memory
790                .knowledge
791                .rooms_limit
792                .or(parent.memory.knowledge.rooms_limit),
793            timeline_limit: child
794                .memory
795                .knowledge
796                .timeline_limit
797                .or(parent.memory.knowledge.timeline_limit),
798            relations_limit: child
799                .memory
800                .knowledge
801                .relations_limit
802                .or(parent.memory.knowledge.relations_limit),
803        },
804        lifecycle: crate::core::memory_policy::LifecyclePolicyOverrides {
805            decay_rate: child
806                .memory
807                .lifecycle
808                .decay_rate
809                .or(parent.memory.lifecycle.decay_rate),
810            low_confidence_threshold: child
811                .memory
812                .lifecycle
813                .low_confidence_threshold
814                .or(parent.memory.lifecycle.low_confidence_threshold),
815            stale_days: child
816                .memory
817                .lifecycle
818                .stale_days
819                .or(parent.memory.lifecycle.stale_days),
820            similarity_threshold: child
821                .memory
822                .lifecycle
823                .similarity_threshold
824                .or(parent.memory.lifecycle.similarity_threshold),
825        },
826    };
827    let verification = crate::core::output_verification::VerificationConfig {
828        enabled: child.verification.enabled.or(parent.verification.enabled),
829        mode: child.verification.mode.or(parent.verification.mode),
830        strict_mode: child
831            .verification
832            .strict_mode
833            .or(parent.verification.strict_mode),
834        check_paths: child
835            .verification
836            .check_paths
837            .or(parent.verification.check_paths),
838        check_identifiers: child
839            .verification
840            .check_identifiers
841            .or(parent.verification.check_identifiers),
842        check_line_numbers: child
843            .verification
844            .check_line_numbers
845            .or(parent.verification.check_line_numbers),
846        check_structure: child
847            .verification
848            .check_structure
849            .or(parent.verification.check_structure),
850    };
851    let budget = BudgetConfig {
852        max_context_tokens: child
853            .budget
854            .max_context_tokens
855            .or(parent.budget.max_context_tokens),
856        max_shell_invocations: child
857            .budget
858            .max_shell_invocations
859            .or(parent.budget.max_shell_invocations),
860        max_cost_usd: child.budget.max_cost_usd.or(parent.budget.max_cost_usd),
861    };
862    let pipeline = PipelineConfig {
863        intent: child.pipeline.intent.or(parent.pipeline.intent),
864        relevance: child.pipeline.relevance.or(parent.pipeline.relevance),
865        compression: child.pipeline.compression.or(parent.pipeline.compression),
866        translation: child.pipeline.translation.or(parent.pipeline.translation),
867    };
868    let routing = RoutingConfig {
869        max_model_tier: child
870            .routing
871            .max_model_tier
872            .or(parent.routing.max_model_tier),
873        degrade_under_pressure: child
874            .routing
875            .degrade_under_pressure
876            .or(parent.routing.degrade_under_pressure),
877    };
878    let degradation = DegradationConfig {
879        enforce: child.degradation.enforce.or(parent.degradation.enforce),
880        throttle_ms: child
881            .degradation
882            .throttle_ms
883            .or(parent.degradation.throttle_ms),
884    };
885    let autonomy = ProfileAutonomy {
886        enabled: child.autonomy.enabled.or(parent.autonomy.enabled),
887        auto_preload: child.autonomy.auto_preload.or(parent.autonomy.auto_preload),
888        auto_dedup: child.autonomy.auto_dedup.or(parent.autonomy.auto_dedup),
889        auto_related: child.autonomy.auto_related.or(parent.autonomy.auto_related),
890        silent_preload: child
891            .autonomy
892            .silent_preload
893            .or(parent.autonomy.silent_preload),
894        auto_prefetch: child
895            .autonomy
896            .auto_prefetch
897            .or(parent.autonomy.auto_prefetch),
898        auto_response: child
899            .autonomy
900            .auto_response
901            .or(parent.autonomy.auto_response),
902        dedup_threshold: child
903            .autonomy
904            .dedup_threshold
905            .or(parent.autonomy.dedup_threshold),
906        prefetch_max_files: child
907            .autonomy
908            .prefetch_max_files
909            .or(parent.autonomy.prefetch_max_files),
910        prefetch_budget_tokens: child
911            .autonomy
912            .prefetch_budget_tokens
913            .or(parent.autonomy.prefetch_budget_tokens),
914        response_min_tokens: child
915            .autonomy
916            .response_min_tokens
917            .or(parent.autonomy.response_min_tokens),
918        checkpoint_interval: child
919            .autonomy
920            .checkpoint_interval
921            .or(parent.autonomy.checkpoint_interval),
922    };
923    let output_hints = OutputHints {
924        compressed_hint: child
925            .output_hints
926            .compressed_hint
927            .or(parent.output_hints.compressed_hint),
928        archive_hint: child
929            .output_hints
930            .archive_hint
931            .or(parent.output_hints.archive_hint),
932        verify_footer: child
933            .output_hints
934            .verify_footer
935            .or(parent.output_hints.verify_footer),
936        related_hint: child
937            .output_hints
938            .related_hint
939            .or(parent.output_hints.related_hint),
940        semantic_hint: child
941            .output_hints
942            .semantic_hint
943            .or(parent.output_hints.semantic_hint),
944        elicitation_hint: child
945            .output_hints
946            .elicitation_hint
947            .or(parent.output_hints.elicitation_hint),
948        checkpoint_in_output: child
949            .output_hints
950            .checkpoint_in_output
951            .or(parent.output_hints.checkpoint_in_output),
952        graph_context_block: child
953            .output_hints
954            .graph_context_block
955            .or(parent.output_hints.graph_context_block),
956        efficiency_hint: child
957            .output_hints
958            .efficiency_hint
959            .or(parent.output_hints.efficiency_hint),
960    };
961    Profile {
962        profile: ProfileMeta {
963            name: child.profile.name,
964            inherits: child.profile.inherits,
965            description: if child.profile.description.is_empty() {
966                parent.profile.description
967            } else {
968                child.profile.description
969            },
970        },
971        read,
972        compression,
973        translation,
974        layout,
975        memory,
976        verification,
977        budget,
978        pipeline,
979        routing,
980        degradation,
981        autonomy,
982        output_hints,
983    }
984}
985
986/// Reads the `profile` key directly from `config.toml` without going through
987/// `Config::load()`. This avoids a reentrancy deadlock: `Config::load()` →
988/// `find_project_root()` (OnceLock) → `SessionState::load_latest()` →
989/// `normalize_loaded_session()` → `active_profile()` → here → `Config::load()`.
990fn profile_name_from_config_file() -> Option<String> {
991    let path = crate::core::config::Config::path()?;
992    let content = std::fs::read_to_string(path).ok()?;
993    let table: toml::Table = toml::from_str(&content).ok()?;
994    table
995        .get("profile")?
996        .as_str()
997        .map(str::trim)
998        .filter(|s| !s.is_empty())
999        .map(String::from)
1000}
1001
1002/// Process-wide active-profile override set by [`set_active_profile`].
1003///
1004/// Takes precedence over `LEAN_CTX_PROFILE`. Storing the runtime selection in an
1005/// in-process cell (rather than mutating the environment) keeps profile
1006/// switching thread-safe inside the multi-threaded MCP server, where
1007/// `set_active_profile` may run on a blocking-pool worker while other workers
1008/// resolve the active profile concurrently.
1009static ACTIVE_PROFILE_OVERRIDE: RwLock<Option<String>> = RwLock::new(None);
1010
1011/// Returns the currently active profile name.
1012///
1013/// Resolution order: in-process override (see [`set_active_profile`]) →
1014/// `LEAN_CTX_PROFILE` env var → config.toml `profile` field → "coder".
1015pub fn active_profile_name() -> String {
1016    if let Some(name) = ACTIVE_PROFILE_OVERRIDE
1017        .read()
1018        .unwrap_or_else(std::sync::PoisonError::into_inner)
1019        .clone()
1020    {
1021        return name;
1022    }
1023    if let Ok(v) = std::env::var("LEAN_CTX_PROFILE") {
1024        let v = v.trim().to_string();
1025        if !v.is_empty() {
1026            return v;
1027        }
1028    }
1029    if let Some(name) = profile_name_from_config_file() {
1030        return name;
1031    }
1032    "coder".to_string()
1033}
1034
1035/// Loads the currently active profile.
1036pub fn active_profile() -> Profile {
1037    let name = active_profile_name();
1038    if let Some(p) = load_profile(&name) {
1039        p
1040    } else {
1041        if name != "coder" {
1042            tracing::warn!(
1043                "Profile '{name}' not found (no built-in or disk file). \
1044                 Falling back to 'coder'. Create it with: lean-ctx profile create {name}"
1045            );
1046        }
1047        builtin_coder()
1048    }
1049}
1050
1051/// Sets the active profile for the current process.
1052///
1053/// Records the selection in a thread-safe in-process override (see
1054/// [`active_profile_name`]) and returns the resolved profile after applying
1055/// inheritance.
1056pub fn set_active_profile(name: &str) -> Result<Profile, String> {
1057    let name = name.trim();
1058    if name.is_empty() {
1059        return Err("profile name is empty".to_string());
1060    }
1061    let prev = active_profile_name();
1062    let profile = load_profile(name).ok_or_else(|| format!("profile '{name}' not found"))?;
1063    *ACTIVE_PROFILE_OVERRIDE
1064        .write()
1065        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(name.to_string());
1066    if prev != name {
1067        crate::core::events::emit_profile_changed(&prev, name);
1068    }
1069    Ok(profile)
1070}
1071
1072/// Lists all available profile names (built-in + on-disk).
1073pub fn list_profiles() -> Vec<ProfileInfo> {
1074    let mut profiles: HashMap<String, ProfileInfo> = HashMap::new();
1075
1076    for (name, p) in builtin_profiles() {
1077        profiles.insert(
1078            name.clone(),
1079            ProfileInfo {
1080                name,
1081                description: p.profile.description,
1082                source: ProfileSource::Builtin,
1083            },
1084        );
1085    }
1086
1087    for (source, dir) in [
1088        (ProfileSource::Global, profiles_dir_global()),
1089        (ProfileSource::Project, profiles_dir_project()),
1090    ] {
1091        if let Some(dir) = dir
1092            && let Ok(entries) = std::fs::read_dir(&dir)
1093        {
1094            for entry in entries.flatten() {
1095                let path = entry.path();
1096                if path.extension().and_then(|e| e.to_str()) == Some("toml")
1097                    && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
1098                {
1099                    let name = stem.to_string();
1100                    let desc = try_load_toml(&path)
1101                        .map(|p| p.profile.description)
1102                        .unwrap_or_default();
1103                    profiles.insert(
1104                        name.clone(),
1105                        ProfileInfo {
1106                            name,
1107                            description: desc,
1108                            source,
1109                        },
1110                    );
1111                }
1112            }
1113        }
1114    }
1115
1116    let mut result: Vec<ProfileInfo> = profiles.into_values().collect();
1117    result.sort_by_key(|p| p.name.clone());
1118    result
1119}
1120
1121/// Information about an available profile.
1122#[derive(Debug, Clone)]
1123pub struct ProfileInfo {
1124    pub name: String,
1125    pub description: String,
1126    pub source: ProfileSource,
1127}
1128
1129/// Where a profile was loaded from.
1130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1131pub enum ProfileSource {
1132    Builtin,
1133    Global,
1134    Project,
1135}
1136
1137impl std::fmt::Display for ProfileSource {
1138    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1139        match self {
1140            Self::Builtin => write!(f, "built-in"),
1141            Self::Global => write!(f, "global"),
1142            Self::Project => write!(f, "project"),
1143        }
1144    }
1145}
1146
1147/// Formats a profile as TOML for display or file creation.
1148pub fn format_as_toml(profile: &Profile) -> String {
1149    toml::to_string_pretty(profile).unwrap_or_else(|_| "[error serializing profile]".to_string())
1150}
1151
1152// ── Tests ──────────────────────────────────────────────────
1153
1154#[cfg(test)]
1155mod tests {
1156    use super::*;
1157
1158    #[test]
1159    fn builtin_profiles_count() {
1160        let builtins = builtin_profiles();
1161        assert_eq!(builtins.len(), 7);
1162        assert!(builtins.contains_key("coder"));
1163        assert!(builtins.contains_key("exploration"));
1164        assert!(builtins.contains_key("bugfix"));
1165        assert!(builtins.contains_key("hotfix"));
1166        assert!(builtins.contains_key("ci-debug"));
1167        assert!(builtins.contains_key("review"));
1168        assert!(builtins.contains_key("passthrough"));
1169    }
1170
1171    #[test]
1172    fn hotfix_has_minimal_budget() {
1173        let p = builtin_profiles().remove("hotfix").unwrap();
1174        assert_eq!(p.budget.max_context_tokens_effective(), 30_000);
1175        assert_eq!(p.budget.max_shell_invocations_effective(), 20);
1176        assert_eq!(p.read.default_mode_effective(), "signatures");
1177        assert_eq!(p.compression.output_density_effective(), "ultra");
1178    }
1179
1180    #[test]
1181    fn exploration_has_broad_context() {
1182        let p = builtin_profiles().remove("exploration").unwrap();
1183        assert_eq!(p.budget.max_context_tokens_effective(), 200_000);
1184        assert_eq!(p.read.default_mode_effective(), "map");
1185        assert!(p.read.prefer_cache_effective());
1186    }
1187
1188    #[test]
1189    fn profile_roundtrip_toml() {
1190        let original = builtin_exploration();
1191        let toml_str = format_as_toml(&original);
1192        let parsed: Profile = toml::from_str(&toml_str).unwrap();
1193        assert_eq!(parsed.profile.name, "exploration");
1194        assert_eq!(parsed.read.default_mode_effective(), "map");
1195        assert_eq!(parsed.budget.max_context_tokens_effective(), 200_000);
1196    }
1197
1198    #[test]
1199    fn merge_child_overrides_parent() {
1200        let parent = builtin_exploration();
1201        let child = Profile {
1202            profile: ProfileMeta {
1203                name: "custom".to_string(),
1204                inherits: Some("exploration".to_string()),
1205                description: String::new(),
1206            },
1207            read: ReadConfig {
1208                default_mode: Some("signatures".to_string()),
1209                ..ReadConfig::default()
1210            },
1211            compression: CompressionConfig::default(),
1212            translation: TranslationConfig::default(),
1213            layout: LayoutConfig::default(),
1214            memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
1215            verification: crate::core::output_verification::VerificationConfig::default(),
1216            budget: BudgetConfig {
1217                max_context_tokens: Some(10_000),
1218                ..BudgetConfig::default()
1219            },
1220            pipeline: PipelineConfig::default(),
1221            routing: RoutingConfig::default(),
1222            degradation: DegradationConfig::default(),
1223            autonomy: ProfileAutonomy::default(),
1224            output_hints: OutputHints::default(),
1225        };
1226
1227        let merged = merge_profiles(parent, child);
1228        assert_eq!(merged.read.default_mode_effective(), "signatures");
1229        assert_eq!(merged.budget.max_context_tokens_effective(), 10_000);
1230        assert_eq!(
1231            merged.profile.description,
1232            "Broad context for understanding codebases"
1233        );
1234    }
1235
1236    #[test]
1237    fn merge_partial_child_inherits_parent_fields() {
1238        let parent = builtin_exploration();
1239        let child = Profile {
1240            profile: ProfileMeta {
1241                name: "partial".to_string(),
1242                inherits: Some("exploration".to_string()),
1243                description: String::new(),
1244            },
1245            read: ReadConfig {
1246                default_mode: Some("map".to_string()),
1247                ..ReadConfig::default()
1248            },
1249            compression: CompressionConfig::default(),
1250            translation: TranslationConfig::default(),
1251            layout: LayoutConfig::default(),
1252            memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
1253            verification: crate::core::output_verification::VerificationConfig::default(),
1254            budget: BudgetConfig::default(),
1255            pipeline: PipelineConfig::default(),
1256            routing: RoutingConfig::default(),
1257            degradation: DegradationConfig::default(),
1258            autonomy: ProfileAutonomy::default(),
1259            output_hints: OutputHints::default(),
1260        };
1261
1262        let merged = merge_profiles(parent, child);
1263        assert_eq!(merged.read.default_mode_effective(), "map");
1264        assert_eq!(
1265            merged.read.max_tokens_per_file_effective(),
1266            80_000,
1267            "should inherit max_tokens_per_file from parent"
1268        );
1269        assert!(
1270            merged.read.prefer_cache_effective(),
1271            "should inherit prefer_cache from parent"
1272        );
1273        assert_eq!(
1274            merged.budget.max_context_tokens_effective(),
1275            200_000,
1276            "should inherit budget from parent"
1277        );
1278    }
1279
1280    #[test]
1281    fn load_builtin_by_name() {
1282        let p = load_profile("hotfix").unwrap();
1283        assert_eq!(p.profile.name, "hotfix");
1284        assert_eq!(p.read.default_mode_effective(), "signatures");
1285    }
1286
1287    #[test]
1288    fn load_nonexistent_returns_none() {
1289        assert!(load_profile("does-not-exist-xyz").is_none());
1290    }
1291
1292    #[test]
1293    fn list_profiles_includes_builtins() {
1294        let list = list_profiles();
1295        assert!(list.len() >= 5);
1296        let names: Vec<&str> = list.iter().map(|p| p.name.as_str()).collect();
1297        assert!(names.contains(&"exploration"));
1298        assert!(names.contains(&"hotfix"));
1299        assert!(names.contains(&"review"));
1300    }
1301
1302    #[test]
1303    fn active_profile_defaults_to_coder() {
1304        let _lock = crate::core::data_dir::test_env_lock();
1305        crate::test_env::remove_var("LEAN_CTX_PROFILE");
1306        let p = active_profile();
1307        assert_eq!(p.profile.name, "coder");
1308    }
1309
1310    #[test]
1311    fn active_profile_from_env() {
1312        let _lock = crate::core::data_dir::test_env_lock();
1313        crate::test_env::set_var("LEAN_CTX_PROFILE", "hotfix");
1314        let name = active_profile_name();
1315        assert_eq!(name, "hotfix");
1316        crate::test_env::remove_var("LEAN_CTX_PROFILE");
1317    }
1318
1319    #[test]
1320    fn profile_source_display() {
1321        assert_eq!(ProfileSource::Builtin.to_string(), "built-in");
1322        assert_eq!(ProfileSource::Global.to_string(), "global");
1323        assert_eq!(ProfileSource::Project.to_string(), "project");
1324    }
1325
1326    #[test]
1327    fn default_profile_has_sane_values() {
1328        let p = Profile {
1329            profile: ProfileMeta::default(),
1330            read: ReadConfig::default(),
1331            compression: CompressionConfig::default(),
1332            translation: TranslationConfig::default(),
1333            layout: LayoutConfig::default(),
1334            memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
1335            verification: crate::core::output_verification::VerificationConfig::default(),
1336            budget: BudgetConfig::default(),
1337            pipeline: PipelineConfig::default(),
1338            routing: RoutingConfig::default(),
1339            degradation: DegradationConfig::default(),
1340            autonomy: ProfileAutonomy::default(),
1341            output_hints: OutputHints::default(),
1342        };
1343        assert_eq!(p.read.default_mode_effective(), "auto");
1344        assert_eq!(p.compression.crp_mode_effective(), "tdd");
1345        assert_eq!(p.budget.max_context_tokens_effective(), 200_000);
1346        assert!(p.pipeline.compression_effective());
1347        assert!(p.pipeline.intent_effective());
1348    }
1349
1350    #[test]
1351    fn pipeline_layers_configurable() {
1352        let toml_str = r#"
1353[profile]
1354name = "no-intent"
1355
1356[pipeline]
1357intent = false
1358relevance = false
1359"#;
1360        let p: Profile = toml::from_str(toml_str).unwrap();
1361        assert!(!p.pipeline.intent_effective());
1362        assert!(!p.pipeline.relevance_effective());
1363        assert!(p.pipeline.compression_effective());
1364        assert!(p.pipeline.translation_effective());
1365    }
1366
1367    #[test]
1368    fn partial_toml_fills_defaults() {
1369        let toml_str = r#"
1370[profile]
1371name = "minimal"
1372
1373[read]
1374default_mode = "entropy"
1375"#;
1376        let p: Profile = toml::from_str(toml_str).unwrap();
1377        assert_eq!(p.read.default_mode_effective(), "entropy");
1378        assert_eq!(p.read.max_tokens_per_file_effective(), 50_000);
1379        assert_eq!(p.budget.max_context_tokens_effective(), 200_000);
1380        assert_eq!(p.compression.crp_mode_effective(), "tdd");
1381    }
1382
1383    #[test]
1384    fn partial_toml_leaves_unset_as_none() {
1385        let toml_str = r#"
1386[profile]
1387name = "sparse"
1388
1389[read]
1390default_mode = "map"
1391"#;
1392        let p: Profile = toml::from_str(toml_str).unwrap();
1393        assert_eq!(p.read.default_mode, Some("map".to_string()));
1394        assert_eq!(p.read.max_tokens_per_file, None);
1395        assert_eq!(p.read.prefer_cache, None);
1396        assert_eq!(p.budget.max_context_tokens, None);
1397        assert_eq!(p.compression.crp_mode, None);
1398    }
1399}