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            forgetting_model: child
826                .memory
827                .lifecycle
828                .forgetting_model
829                .clone()
830                .or_else(|| parent.memory.lifecycle.forgetting_model.clone()),
831            base_stability_days: child
832                .memory
833                .lifecycle
834                .base_stability_days
835                .or(parent.memory.lifecycle.base_stability_days),
836            archetype_aware_decay: child
837                .memory
838                .lifecycle
839                .archetype_aware_decay
840                .or(parent.memory.lifecycle.archetype_aware_decay),
841        },
842    };
843    let verification = crate::core::output_verification::VerificationConfig {
844        enabled: child.verification.enabled.or(parent.verification.enabled),
845        mode: child.verification.mode.or(parent.verification.mode),
846        strict_mode: child
847            .verification
848            .strict_mode
849            .or(parent.verification.strict_mode),
850        check_paths: child
851            .verification
852            .check_paths
853            .or(parent.verification.check_paths),
854        check_identifiers: child
855            .verification
856            .check_identifiers
857            .or(parent.verification.check_identifiers),
858        check_line_numbers: child
859            .verification
860            .check_line_numbers
861            .or(parent.verification.check_line_numbers),
862        check_structure: child
863            .verification
864            .check_structure
865            .or(parent.verification.check_structure),
866    };
867    let budget = BudgetConfig {
868        max_context_tokens: child
869            .budget
870            .max_context_tokens
871            .or(parent.budget.max_context_tokens),
872        max_shell_invocations: child
873            .budget
874            .max_shell_invocations
875            .or(parent.budget.max_shell_invocations),
876        max_cost_usd: child.budget.max_cost_usd.or(parent.budget.max_cost_usd),
877    };
878    let pipeline = PipelineConfig {
879        intent: child.pipeline.intent.or(parent.pipeline.intent),
880        relevance: child.pipeline.relevance.or(parent.pipeline.relevance),
881        compression: child.pipeline.compression.or(parent.pipeline.compression),
882        translation: child.pipeline.translation.or(parent.pipeline.translation),
883    };
884    let routing = RoutingConfig {
885        max_model_tier: child
886            .routing
887            .max_model_tier
888            .or(parent.routing.max_model_tier),
889        degrade_under_pressure: child
890            .routing
891            .degrade_under_pressure
892            .or(parent.routing.degrade_under_pressure),
893    };
894    let degradation = DegradationConfig {
895        enforce: child.degradation.enforce.or(parent.degradation.enforce),
896        throttle_ms: child
897            .degradation
898            .throttle_ms
899            .or(parent.degradation.throttle_ms),
900    };
901    let autonomy = ProfileAutonomy {
902        enabled: child.autonomy.enabled.or(parent.autonomy.enabled),
903        auto_preload: child.autonomy.auto_preload.or(parent.autonomy.auto_preload),
904        auto_dedup: child.autonomy.auto_dedup.or(parent.autonomy.auto_dedup),
905        auto_related: child.autonomy.auto_related.or(parent.autonomy.auto_related),
906        silent_preload: child
907            .autonomy
908            .silent_preload
909            .or(parent.autonomy.silent_preload),
910        auto_prefetch: child
911            .autonomy
912            .auto_prefetch
913            .or(parent.autonomy.auto_prefetch),
914        auto_response: child
915            .autonomy
916            .auto_response
917            .or(parent.autonomy.auto_response),
918        dedup_threshold: child
919            .autonomy
920            .dedup_threshold
921            .or(parent.autonomy.dedup_threshold),
922        prefetch_max_files: child
923            .autonomy
924            .prefetch_max_files
925            .or(parent.autonomy.prefetch_max_files),
926        prefetch_budget_tokens: child
927            .autonomy
928            .prefetch_budget_tokens
929            .or(parent.autonomy.prefetch_budget_tokens),
930        response_min_tokens: child
931            .autonomy
932            .response_min_tokens
933            .or(parent.autonomy.response_min_tokens),
934        checkpoint_interval: child
935            .autonomy
936            .checkpoint_interval
937            .or(parent.autonomy.checkpoint_interval),
938    };
939    let output_hints = OutputHints {
940        compressed_hint: child
941            .output_hints
942            .compressed_hint
943            .or(parent.output_hints.compressed_hint),
944        archive_hint: child
945            .output_hints
946            .archive_hint
947            .or(parent.output_hints.archive_hint),
948        verify_footer: child
949            .output_hints
950            .verify_footer
951            .or(parent.output_hints.verify_footer),
952        related_hint: child
953            .output_hints
954            .related_hint
955            .or(parent.output_hints.related_hint),
956        semantic_hint: child
957            .output_hints
958            .semantic_hint
959            .or(parent.output_hints.semantic_hint),
960        elicitation_hint: child
961            .output_hints
962            .elicitation_hint
963            .or(parent.output_hints.elicitation_hint),
964        checkpoint_in_output: child
965            .output_hints
966            .checkpoint_in_output
967            .or(parent.output_hints.checkpoint_in_output),
968        graph_context_block: child
969            .output_hints
970            .graph_context_block
971            .or(parent.output_hints.graph_context_block),
972        efficiency_hint: child
973            .output_hints
974            .efficiency_hint
975            .or(parent.output_hints.efficiency_hint),
976    };
977    Profile {
978        profile: ProfileMeta {
979            name: child.profile.name,
980            inherits: child.profile.inherits,
981            description: if child.profile.description.is_empty() {
982                parent.profile.description
983            } else {
984                child.profile.description
985            },
986        },
987        read,
988        compression,
989        translation,
990        layout,
991        memory,
992        verification,
993        budget,
994        pipeline,
995        routing,
996        degradation,
997        autonomy,
998        output_hints,
999    }
1000}
1001
1002/// Reads the `profile` key directly from `config.toml` without going through
1003/// `Config::load()`. This avoids a reentrancy deadlock: `Config::load()` →
1004/// `find_project_root()` (OnceLock) → `SessionState::load_latest()` →
1005/// `normalize_loaded_session()` → `active_profile()` → here → `Config::load()`.
1006fn profile_name_from_config_file() -> Option<String> {
1007    let path = crate::core::config::Config::path()?;
1008    let content = std::fs::read_to_string(path).ok()?;
1009    let table: toml::Table = toml::from_str(&content).ok()?;
1010    table
1011        .get("profile")?
1012        .as_str()
1013        .map(str::trim)
1014        .filter(|s| !s.is_empty())
1015        .map(String::from)
1016}
1017
1018/// Process-wide active-profile override set by [`set_active_profile`].
1019///
1020/// Takes precedence over `LEAN_CTX_PROFILE`. Storing the runtime selection in an
1021/// in-process cell (rather than mutating the environment) keeps profile
1022/// switching thread-safe inside the multi-threaded MCP server, where
1023/// `set_active_profile` may run on a blocking-pool worker while other workers
1024/// resolve the active profile concurrently.
1025static ACTIVE_PROFILE_OVERRIDE: RwLock<Option<String>> = RwLock::new(None);
1026
1027/// Returns the currently active profile name.
1028///
1029/// Resolution order: in-process override (see [`set_active_profile`]) →
1030/// `LEAN_CTX_PROFILE` env var → config.toml `profile` field → "coder".
1031pub fn active_profile_name() -> String {
1032    if let Some(name) = ACTIVE_PROFILE_OVERRIDE
1033        .read()
1034        .unwrap_or_else(std::sync::PoisonError::into_inner)
1035        .clone()
1036    {
1037        return name;
1038    }
1039    if let Ok(v) = std::env::var("LEAN_CTX_PROFILE") {
1040        let v = v.trim().to_string();
1041        if !v.is_empty() {
1042            return v;
1043        }
1044    }
1045    if let Some(name) = profile_name_from_config_file() {
1046        return name;
1047    }
1048    "coder".to_string()
1049}
1050
1051/// Loads the currently active profile.
1052pub fn active_profile() -> Profile {
1053    let name = active_profile_name();
1054    if let Some(p) = load_profile(&name) {
1055        p
1056    } else {
1057        if name != "coder" {
1058            tracing::warn!(
1059                "Profile '{name}' not found (no built-in or disk file). \
1060                 Falling back to 'coder'. Create it with: lean-ctx profile create {name}"
1061            );
1062        }
1063        builtin_coder()
1064    }
1065}
1066
1067/// Sets the active profile for the current process.
1068///
1069/// Records the selection in a thread-safe in-process override (see
1070/// [`active_profile_name`]) and returns the resolved profile after applying
1071/// inheritance.
1072pub fn set_active_profile(name: &str) -> Result<Profile, String> {
1073    let name = name.trim();
1074    if name.is_empty() {
1075        return Err("profile name is empty".to_string());
1076    }
1077    let prev = active_profile_name();
1078    let profile = load_profile(name).ok_or_else(|| format!("profile '{name}' not found"))?;
1079    *ACTIVE_PROFILE_OVERRIDE
1080        .write()
1081        .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(name.to_string());
1082    if prev != name {
1083        crate::core::events::emit_profile_changed(&prev, name);
1084    }
1085    Ok(profile)
1086}
1087
1088/// Lists all available profile names (built-in + on-disk).
1089pub fn list_profiles() -> Vec<ProfileInfo> {
1090    let mut profiles: HashMap<String, ProfileInfo> = HashMap::new();
1091
1092    for (name, p) in builtin_profiles() {
1093        profiles.insert(
1094            name.clone(),
1095            ProfileInfo {
1096                name,
1097                description: p.profile.description,
1098                source: ProfileSource::Builtin,
1099            },
1100        );
1101    }
1102
1103    for (source, dir) in [
1104        (ProfileSource::Global, profiles_dir_global()),
1105        (ProfileSource::Project, profiles_dir_project()),
1106    ] {
1107        if let Some(dir) = dir
1108            && let Ok(entries) = std::fs::read_dir(&dir)
1109        {
1110            for entry in entries.flatten() {
1111                let path = entry.path();
1112                if path.extension().and_then(|e| e.to_str()) == Some("toml")
1113                    && let Some(stem) = path.file_stem().and_then(|s| s.to_str())
1114                {
1115                    let name = stem.to_string();
1116                    let desc = try_load_toml(&path)
1117                        .map(|p| p.profile.description)
1118                        .unwrap_or_default();
1119                    profiles.insert(
1120                        name.clone(),
1121                        ProfileInfo {
1122                            name,
1123                            description: desc,
1124                            source,
1125                        },
1126                    );
1127                }
1128            }
1129        }
1130    }
1131
1132    let mut result: Vec<ProfileInfo> = profiles.into_values().collect();
1133    result.sort_by_key(|p| p.name.clone());
1134    result
1135}
1136
1137/// Information about an available profile.
1138#[derive(Debug, Clone)]
1139pub struct ProfileInfo {
1140    pub name: String,
1141    pub description: String,
1142    pub source: ProfileSource,
1143}
1144
1145/// Where a profile was loaded from.
1146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1147pub enum ProfileSource {
1148    Builtin,
1149    Global,
1150    Project,
1151}
1152
1153impl std::fmt::Display for ProfileSource {
1154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1155        match self {
1156            Self::Builtin => write!(f, "built-in"),
1157            Self::Global => write!(f, "global"),
1158            Self::Project => write!(f, "project"),
1159        }
1160    }
1161}
1162
1163/// Formats a profile as TOML for display or file creation.
1164pub fn format_as_toml(profile: &Profile) -> String {
1165    toml::to_string_pretty(profile).unwrap_or_else(|_| "[error serializing profile]".to_string())
1166}
1167
1168// ── Tests ──────────────────────────────────────────────────
1169
1170#[cfg(test)]
1171mod tests {
1172    use super::*;
1173
1174    #[test]
1175    fn builtin_profiles_count() {
1176        let builtins = builtin_profiles();
1177        assert_eq!(builtins.len(), 7);
1178        assert!(builtins.contains_key("coder"));
1179        assert!(builtins.contains_key("exploration"));
1180        assert!(builtins.contains_key("bugfix"));
1181        assert!(builtins.contains_key("hotfix"));
1182        assert!(builtins.contains_key("ci-debug"));
1183        assert!(builtins.contains_key("review"));
1184        assert!(builtins.contains_key("passthrough"));
1185    }
1186
1187    #[test]
1188    fn hotfix_has_minimal_budget() {
1189        let p = builtin_profiles().remove("hotfix").unwrap();
1190        assert_eq!(p.budget.max_context_tokens_effective(), 30_000);
1191        assert_eq!(p.budget.max_shell_invocations_effective(), 20);
1192        assert_eq!(p.read.default_mode_effective(), "signatures");
1193        assert_eq!(p.compression.output_density_effective(), "ultra");
1194    }
1195
1196    #[test]
1197    fn exploration_has_broad_context() {
1198        let p = builtin_profiles().remove("exploration").unwrap();
1199        assert_eq!(p.budget.max_context_tokens_effective(), 200_000);
1200        assert_eq!(p.read.default_mode_effective(), "map");
1201        assert!(p.read.prefer_cache_effective());
1202    }
1203
1204    #[test]
1205    fn profile_roundtrip_toml() {
1206        let original = builtin_exploration();
1207        let toml_str = format_as_toml(&original);
1208        let parsed: Profile = toml::from_str(&toml_str).unwrap();
1209        assert_eq!(parsed.profile.name, "exploration");
1210        assert_eq!(parsed.read.default_mode_effective(), "map");
1211        assert_eq!(parsed.budget.max_context_tokens_effective(), 200_000);
1212    }
1213
1214    #[test]
1215    fn merge_child_overrides_parent() {
1216        let parent = builtin_exploration();
1217        let child = Profile {
1218            profile: ProfileMeta {
1219                name: "custom".to_string(),
1220                inherits: Some("exploration".to_string()),
1221                description: String::new(),
1222            },
1223            read: ReadConfig {
1224                default_mode: Some("signatures".to_string()),
1225                ..ReadConfig::default()
1226            },
1227            compression: CompressionConfig::default(),
1228            translation: TranslationConfig::default(),
1229            layout: LayoutConfig::default(),
1230            memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
1231            verification: crate::core::output_verification::VerificationConfig::default(),
1232            budget: BudgetConfig {
1233                max_context_tokens: Some(10_000),
1234                ..BudgetConfig::default()
1235            },
1236            pipeline: PipelineConfig::default(),
1237            routing: RoutingConfig::default(),
1238            degradation: DegradationConfig::default(),
1239            autonomy: ProfileAutonomy::default(),
1240            output_hints: OutputHints::default(),
1241        };
1242
1243        let merged = merge_profiles(parent, child);
1244        assert_eq!(merged.read.default_mode_effective(), "signatures");
1245        assert_eq!(merged.budget.max_context_tokens_effective(), 10_000);
1246        assert_eq!(
1247            merged.profile.description,
1248            "Broad context for understanding codebases"
1249        );
1250    }
1251
1252    #[test]
1253    fn merge_partial_child_inherits_parent_fields() {
1254        let parent = builtin_exploration();
1255        let child = Profile {
1256            profile: ProfileMeta {
1257                name: "partial".to_string(),
1258                inherits: Some("exploration".to_string()),
1259                description: String::new(),
1260            },
1261            read: ReadConfig {
1262                default_mode: Some("map".to_string()),
1263                ..ReadConfig::default()
1264            },
1265            compression: CompressionConfig::default(),
1266            translation: TranslationConfig::default(),
1267            layout: LayoutConfig::default(),
1268            memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
1269            verification: crate::core::output_verification::VerificationConfig::default(),
1270            budget: BudgetConfig::default(),
1271            pipeline: PipelineConfig::default(),
1272            routing: RoutingConfig::default(),
1273            degradation: DegradationConfig::default(),
1274            autonomy: ProfileAutonomy::default(),
1275            output_hints: OutputHints::default(),
1276        };
1277
1278        let merged = merge_profiles(parent, child);
1279        assert_eq!(merged.read.default_mode_effective(), "map");
1280        assert_eq!(
1281            merged.read.max_tokens_per_file_effective(),
1282            80_000,
1283            "should inherit max_tokens_per_file from parent"
1284        );
1285        assert!(
1286            merged.read.prefer_cache_effective(),
1287            "should inherit prefer_cache from parent"
1288        );
1289        assert_eq!(
1290            merged.budget.max_context_tokens_effective(),
1291            200_000,
1292            "should inherit budget from parent"
1293        );
1294    }
1295
1296    #[test]
1297    fn load_builtin_by_name() {
1298        let p = load_profile("hotfix").unwrap();
1299        assert_eq!(p.profile.name, "hotfix");
1300        assert_eq!(p.read.default_mode_effective(), "signatures");
1301    }
1302
1303    #[test]
1304    fn load_nonexistent_returns_none() {
1305        assert!(load_profile("does-not-exist-xyz").is_none());
1306    }
1307
1308    #[test]
1309    fn list_profiles_includes_builtins() {
1310        let list = list_profiles();
1311        assert!(list.len() >= 5);
1312        let names: Vec<&str> = list.iter().map(|p| p.name.as_str()).collect();
1313        assert!(names.contains(&"exploration"));
1314        assert!(names.contains(&"hotfix"));
1315        assert!(names.contains(&"review"));
1316    }
1317
1318    #[test]
1319    fn active_profile_defaults_to_coder() {
1320        let _lock = crate::core::data_dir::test_env_lock();
1321        crate::test_env::remove_var("LEAN_CTX_PROFILE");
1322        let p = active_profile();
1323        assert_eq!(p.profile.name, "coder");
1324    }
1325
1326    #[test]
1327    fn active_profile_from_env() {
1328        let _lock = crate::core::data_dir::test_env_lock();
1329        crate::test_env::set_var("LEAN_CTX_PROFILE", "hotfix");
1330        let name = active_profile_name();
1331        assert_eq!(name, "hotfix");
1332        crate::test_env::remove_var("LEAN_CTX_PROFILE");
1333    }
1334
1335    #[test]
1336    fn profile_source_display() {
1337        assert_eq!(ProfileSource::Builtin.to_string(), "built-in");
1338        assert_eq!(ProfileSource::Global.to_string(), "global");
1339        assert_eq!(ProfileSource::Project.to_string(), "project");
1340    }
1341
1342    #[test]
1343    fn default_profile_has_sane_values() {
1344        let p = Profile {
1345            profile: ProfileMeta::default(),
1346            read: ReadConfig::default(),
1347            compression: CompressionConfig::default(),
1348            translation: TranslationConfig::default(),
1349            layout: LayoutConfig::default(),
1350            memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
1351            verification: crate::core::output_verification::VerificationConfig::default(),
1352            budget: BudgetConfig::default(),
1353            pipeline: PipelineConfig::default(),
1354            routing: RoutingConfig::default(),
1355            degradation: DegradationConfig::default(),
1356            autonomy: ProfileAutonomy::default(),
1357            output_hints: OutputHints::default(),
1358        };
1359        assert_eq!(p.read.default_mode_effective(), "auto");
1360        assert_eq!(p.compression.crp_mode_effective(), "tdd");
1361        assert_eq!(p.budget.max_context_tokens_effective(), 200_000);
1362        assert!(p.pipeline.compression_effective());
1363        assert!(p.pipeline.intent_effective());
1364    }
1365
1366    #[test]
1367    fn pipeline_layers_configurable() {
1368        let toml_str = r#"
1369[profile]
1370name = "no-intent"
1371
1372[pipeline]
1373intent = false
1374relevance = false
1375"#;
1376        let p: Profile = toml::from_str(toml_str).unwrap();
1377        assert!(!p.pipeline.intent_effective());
1378        assert!(!p.pipeline.relevance_effective());
1379        assert!(p.pipeline.compression_effective());
1380        assert!(p.pipeline.translation_effective());
1381    }
1382
1383    #[test]
1384    fn partial_toml_fills_defaults() {
1385        let toml_str = r#"
1386[profile]
1387name = "minimal"
1388
1389[read]
1390default_mode = "entropy"
1391"#;
1392        let p: Profile = toml::from_str(toml_str).unwrap();
1393        assert_eq!(p.read.default_mode_effective(), "entropy");
1394        assert_eq!(p.read.max_tokens_per_file_effective(), 50_000);
1395        assert_eq!(p.budget.max_context_tokens_effective(), 200_000);
1396        assert_eq!(p.compression.crp_mode_effective(), "tdd");
1397    }
1398
1399    #[test]
1400    fn partial_toml_leaves_unset_as_none() {
1401        let toml_str = r#"
1402[profile]
1403name = "sparse"
1404
1405[read]
1406default_mode = "map"
1407"#;
1408        let p: Profile = toml::from_str(toml_str).unwrap();
1409        assert_eq!(p.read.default_mode, Some("map".to_string()));
1410        assert_eq!(p.read.max_tokens_per_file, None);
1411        assert_eq!(p.read.prefer_cache, None);
1412        assert_eq!(p.budget.max_context_tokens, None);
1413        assert_eq!(p.compression.crp_mode, None);
1414    }
1415}