lean-ctx 3.5.13

Context Runtime for AI Agents with CCP. 57 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing + diaries, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24 AI tools. Reduces LLM token consumption by up to 99%.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
//! # Context Profiles
//!
//! Declarative, version-controlled context strategies ("Context as Code").
//!
//! Profiles configure how lean-ctx processes content for different scenarios:
//! exploration, bugfixing, hotfixes, CI debugging, code review, etc.
//!
//! ## Resolution Order
//!
//! 1. `LEAN_CTX_PROFILE` env var
//! 2. `.lean-ctx/profiles/<name>.toml` (project-local)
//! 3. `~/.lean-ctx/profiles/<name>.toml` (global)
//! 4. Built-in defaults (compiled into the binary)
//!
//! ## Inheritance
//!
//! Profiles can inherit from other profiles via `inherits = "parent"`.
//! Child values override parent values; unset fields fall through.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// A complete context profile definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Profile {
    #[serde(default)]
    pub profile: ProfileMeta,
    #[serde(default)]
    pub read: ReadConfig,
    #[serde(default)]
    pub compression: CompressionConfig,
    #[serde(default)]
    pub translation: TranslationConfig,
    #[serde(default)]
    pub layout: LayoutConfig,
    #[serde(default)]
    pub memory: crate::core::memory_policy::MemoryPolicyOverrides,
    #[serde(default)]
    pub verification: crate::core::output_verification::VerificationConfig,
    #[serde(default)]
    pub budget: BudgetConfig,
    #[serde(default)]
    pub pipeline: PipelineConfig,
    #[serde(default)]
    pub routing: RoutingConfig,
    #[serde(default)]
    pub degradation: DegradationConfig,
    #[serde(default)]
    pub autonomy: ProfileAutonomy,
}

/// Profile identity and inheritance.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ProfileMeta {
    #[serde(default)]
    pub name: String,
    pub inherits: Option<String>,
    #[serde(default)]
    pub description: String,
}

/// Read behavior configuration.
///
/// Fields are `Option<T>` for field-level profile inheritance.
/// Use `_effective()` methods to get the resolved value with defaults.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ReadConfig {
    pub default_mode: Option<String>,
    pub max_tokens_per_file: Option<usize>,
    pub prefer_cache: Option<bool>,
}

impl ReadConfig {
    pub fn default_mode_effective(&self) -> &str {
        self.default_mode.as_deref().unwrap_or("auto")
    }
    pub fn max_tokens_per_file_effective(&self) -> usize {
        self.max_tokens_per_file.unwrap_or(50_000)
    }
    pub fn prefer_cache_effective(&self) -> bool {
        self.prefer_cache.unwrap_or(false)
    }
}

/// Compression strategy configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct CompressionConfig {
    pub crp_mode: Option<String>,
    pub output_density: Option<String>,
    pub entropy_threshold: Option<f64>,
    pub terse_mode: Option<bool>,
}

impl CompressionConfig {
    pub fn crp_mode_effective(&self) -> &str {
        self.crp_mode.as_deref().unwrap_or("tdd")
    }
    pub fn output_density_effective(&self) -> &str {
        self.output_density.as_deref().unwrap_or("normal")
    }
    pub fn entropy_threshold_effective(&self) -> f64 {
        self.entropy_threshold.unwrap_or(0.3)
    }
    pub fn terse_mode_effective(&self) -> bool {
        self.terse_mode.unwrap_or(false)
    }
}

/// Translation (tokenizer-aware) configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct TranslationConfig {
    /// If false, preserve legacy CRP/TDD formats without post-translation.
    pub enabled: Option<bool>,
    /// legacy|ascii|auto
    pub ruleset: Option<String>,
}

impl TranslationConfig {
    pub fn enabled_effective(&self) -> bool {
        self.enabled.unwrap_or(false)
    }
    pub fn ruleset_effective(&self) -> &str {
        self.ruleset.as_deref().unwrap_or("legacy")
    }
}

/// Layout (attention-aware reorder) configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct LayoutConfig {
    /// If false, preserve original order.
    pub enabled: Option<bool>,
    /// Minimum line count for enabling reorder.
    pub min_lines: Option<usize>,
}

impl LayoutConfig {
    pub fn enabled_effective(&self) -> bool {
        self.enabled.unwrap_or(false)
    }
    pub fn min_lines_effective(&self) -> usize {
        self.min_lines.unwrap_or(15)
    }
}

/// Routing policy overrides (intent → model tier → read mode/budgets).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct RoutingConfig {
    /// Hard cap for recommended model tier: fast|standard|premium.
    #[serde(default)]
    pub max_model_tier: Option<String>,
    /// If true, apply deterministic routing degradation under budget/pressure.
    #[serde(default)]
    pub degrade_under_pressure: Option<bool>,
}

impl RoutingConfig {
    pub fn max_model_tier_effective(&self) -> &str {
        self.max_model_tier.as_deref().unwrap_or("premium")
    }

    pub fn degrade_under_pressure_effective(&self) -> bool {
        self.degrade_under_pressure.unwrap_or(true)
    }
}

/// Budget/SLO degradation policy configuration.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct DegradationConfig {
    /// If true, enforce throttling/blocking decisions. Default is warn-only.
    #[serde(default)]
    pub enforce: Option<bool>,
    /// Throttle duration (ms) when policy verdict is Throttle. Default: 250ms.
    #[serde(default)]
    pub throttle_ms: Option<u64>,
}

impl DegradationConfig {
    pub fn enforce_effective(&self) -> bool {
        self.enforce.unwrap_or(false)
    }

    pub fn throttle_ms_effective(&self) -> u64 {
        self.throttle_ms.unwrap_or(250)
    }
}

/// Token and cost budget limits.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct BudgetConfig {
    pub max_context_tokens: Option<usize>,
    pub max_shell_invocations: Option<usize>,
    pub max_cost_usd: Option<f64>,
}

impl BudgetConfig {
    pub fn max_context_tokens_effective(&self) -> usize {
        self.max_context_tokens.unwrap_or(200_000)
    }
    pub fn max_shell_invocations_effective(&self) -> usize {
        self.max_shell_invocations.unwrap_or(100)
    }
    pub fn max_cost_usd_effective(&self) -> f64 {
        self.max_cost_usd.unwrap_or(5.0)
    }
}

/// Pipeline layer activation per profile.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct PipelineConfig {
    pub intent: Option<bool>,
    pub relevance: Option<bool>,
    pub compression: Option<bool>,
    pub translation: Option<bool>,
}

impl PipelineConfig {
    pub fn intent_effective(&self) -> bool {
        self.intent.unwrap_or(true)
    }
    pub fn relevance_effective(&self) -> bool {
        self.relevance.unwrap_or(true)
    }
    pub fn compression_effective(&self) -> bool {
        self.compression.unwrap_or(true)
    }
    pub fn translation_effective(&self) -> bool {
        self.translation.unwrap_or(true)
    }
}

/// Autonomy overrides per profile.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct ProfileAutonomy {
    pub enabled: Option<bool>,
    pub auto_preload: Option<bool>,
    pub auto_dedup: Option<bool>,
    pub auto_related: Option<bool>,
    pub silent_preload: Option<bool>,
    /// Enable bounded prefetch after reads (opt-in by default).
    pub auto_prefetch: Option<bool>,
    /// Enable response shaping for large outputs (opt-in by default).
    pub auto_response: Option<bool>,
    pub dedup_threshold: Option<usize>,
    pub prefetch_max_files: Option<usize>,
    pub prefetch_budget_tokens: Option<usize>,
    pub response_min_tokens: Option<usize>,
    pub checkpoint_interval: Option<u32>,
}

impl ProfileAutonomy {
    pub fn enabled_effective(&self) -> bool {
        self.enabled.unwrap_or(true)
    }
    pub fn auto_preload_effective(&self) -> bool {
        self.auto_preload.unwrap_or(true)
    }
    pub fn auto_dedup_effective(&self) -> bool {
        self.auto_dedup.unwrap_or(true)
    }
    pub fn auto_related_effective(&self) -> bool {
        self.auto_related.unwrap_or(true)
    }
    pub fn silent_preload_effective(&self) -> bool {
        self.silent_preload.unwrap_or(true)
    }
    pub fn auto_prefetch_effective(&self) -> bool {
        self.auto_prefetch.unwrap_or(false)
    }
    pub fn auto_response_effective(&self) -> bool {
        self.auto_response.unwrap_or(false)
    }
    pub fn dedup_threshold_effective(&self) -> usize {
        self.dedup_threshold.unwrap_or(8)
    }
    pub fn prefetch_max_files_effective(&self) -> usize {
        self.prefetch_max_files.unwrap_or(3)
    }
    pub fn prefetch_budget_tokens_effective(&self) -> usize {
        self.prefetch_budget_tokens.unwrap_or(4000)
    }
    pub fn response_min_tokens_effective(&self) -> usize {
        self.response_min_tokens.unwrap_or(600)
    }
    pub fn checkpoint_interval_effective(&self) -> u32 {
        self.checkpoint_interval.unwrap_or(15)
    }
}

// ── Built-in Profiles ──────────────────────────────────────

fn builtin_coder() -> Profile {
    Profile {
        profile: ProfileMeta {
            name: "coder".to_string(),
            inherits: None,
            description: "Default coding workflow with guarded autonomy drivers".to_string(),
        },
        read: ReadConfig {
            default_mode: Some("auto".to_string()),
            max_tokens_per_file: Some(50_000),
            prefer_cache: Some(true),
        },
        compression: CompressionConfig {
            crp_mode: Some("tdd".to_string()),
            output_density: Some("terse".to_string()),
            terse_mode: Some(true),
            ..CompressionConfig::default()
        },
        translation: TranslationConfig {
            enabled: Some(true),
            ruleset: Some("auto".to_string()),
        },
        layout: LayoutConfig::default(),
        memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
        verification: crate::core::output_verification::VerificationConfig::default(),
        budget: BudgetConfig {
            max_context_tokens: Some(150_000),
            max_shell_invocations: Some(100),
            ..BudgetConfig::default()
        },
        pipeline: PipelineConfig::default(),
        routing: RoutingConfig::default(),
        degradation: DegradationConfig::default(),
        autonomy: ProfileAutonomy {
            auto_prefetch: Some(true),
            auto_response: Some(true),
            checkpoint_interval: Some(10),
            ..ProfileAutonomy::default()
        },
    }
}

fn builtin_exploration() -> Profile {
    Profile {
        profile: ProfileMeta {
            name: "exploration".to_string(),
            inherits: None,
            description: "Broad context for understanding codebases".to_string(),
        },
        read: ReadConfig {
            default_mode: Some("map".to_string()),
            max_tokens_per_file: Some(80_000),
            prefer_cache: Some(true),
        },
        compression: CompressionConfig {
            terse_mode: Some(true),
            output_density: Some("terse".to_string()),
            ..CompressionConfig::default()
        },
        translation: TranslationConfig::default(),
        layout: LayoutConfig::default(),
        memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
        verification: crate::core::output_verification::VerificationConfig::default(),
        budget: BudgetConfig {
            max_context_tokens: Some(200_000),
            ..BudgetConfig::default()
        },
        pipeline: PipelineConfig::default(),
        routing: RoutingConfig::default(),
        degradation: DegradationConfig::default(),
        autonomy: ProfileAutonomy::default(),
    }
}

fn builtin_bugfix() -> Profile {
    Profile {
        profile: ProfileMeta {
            name: "bugfix".to_string(),
            inherits: None,
            description: "Focused context for debugging specific issues".to_string(),
        },
        read: ReadConfig {
            default_mode: Some("auto".to_string()),
            max_tokens_per_file: Some(30_000),
            prefer_cache: Some(false),
        },
        compression: CompressionConfig {
            crp_mode: Some("tdd".to_string()),
            output_density: Some("terse".to_string()),
            ..CompressionConfig::default()
        },
        translation: TranslationConfig::default(),
        layout: LayoutConfig::default(),
        memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
        verification: crate::core::output_verification::VerificationConfig::default(),
        budget: BudgetConfig {
            max_context_tokens: Some(100_000),
            max_shell_invocations: Some(50),
            ..BudgetConfig::default()
        },
        pipeline: PipelineConfig::default(),
        routing: RoutingConfig {
            max_model_tier: Some("standard".to_string()),
            ..RoutingConfig::default()
        },
        degradation: DegradationConfig::default(),
        autonomy: ProfileAutonomy {
            checkpoint_interval: Some(10),
            ..ProfileAutonomy::default()
        },
    }
}

fn builtin_hotfix() -> Profile {
    Profile {
        profile: ProfileMeta {
            name: "hotfix".to_string(),
            inherits: None,
            description: "Minimal context, fast iteration for urgent fixes".to_string(),
        },
        read: ReadConfig {
            default_mode: Some("signatures".to_string()),
            max_tokens_per_file: Some(2_000),
            prefer_cache: Some(true),
        },
        compression: CompressionConfig {
            crp_mode: Some("tdd".to_string()),
            output_density: Some("ultra".to_string()),
            ..CompressionConfig::default()
        },
        translation: TranslationConfig::default(),
        layout: LayoutConfig::default(),
        memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
        verification: crate::core::output_verification::VerificationConfig::default(),
        budget: BudgetConfig {
            max_context_tokens: Some(30_000),
            max_shell_invocations: Some(20),
            max_cost_usd: Some(1.0),
        },
        pipeline: PipelineConfig::default(),
        routing: RoutingConfig {
            max_model_tier: Some("fast".to_string()),
            ..RoutingConfig::default()
        },
        degradation: DegradationConfig::default(),
        autonomy: ProfileAutonomy {
            checkpoint_interval: Some(5),
            ..ProfileAutonomy::default()
        },
    }
}

fn builtin_ci_debug() -> Profile {
    Profile {
        profile: ProfileMeta {
            name: "ci-debug".to_string(),
            inherits: None,
            description: "CI/CD debugging with shell-heavy workflows".to_string(),
        },
        read: ReadConfig {
            default_mode: Some("auto".to_string()),
            max_tokens_per_file: Some(50_000),
            prefer_cache: Some(false),
        },
        compression: CompressionConfig {
            output_density: Some("terse".to_string()),
            ..CompressionConfig::default()
        },
        translation: TranslationConfig::default(),
        layout: LayoutConfig::default(),
        memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
        verification: crate::core::output_verification::VerificationConfig::default(),
        budget: BudgetConfig {
            max_context_tokens: Some(150_000),
            max_shell_invocations: Some(200),
            ..BudgetConfig::default()
        },
        pipeline: PipelineConfig::default(),
        routing: RoutingConfig {
            max_model_tier: Some("standard".to_string()),
            ..RoutingConfig::default()
        },
        degradation: DegradationConfig::default(),
        autonomy: ProfileAutonomy::default(),
    }
}

fn builtin_review() -> Profile {
    Profile {
        profile: ProfileMeta {
            name: "review".to_string(),
            inherits: None,
            description: "Code review with broad read-only context".to_string(),
        },
        read: ReadConfig {
            default_mode: Some("map".to_string()),
            max_tokens_per_file: Some(60_000),
            prefer_cache: Some(true),
        },
        compression: CompressionConfig {
            crp_mode: Some("compact".to_string()),
            ..CompressionConfig::default()
        },
        translation: TranslationConfig::default(),
        layout: LayoutConfig {
            enabled: Some(true),
            ..LayoutConfig::default()
        },
        memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
        verification: crate::core::output_verification::VerificationConfig::default(),
        budget: BudgetConfig {
            max_context_tokens: Some(150_000),
            max_shell_invocations: Some(30),
            ..BudgetConfig::default()
        },
        pipeline: PipelineConfig::default(),
        routing: RoutingConfig {
            max_model_tier: Some("standard".to_string()),
            ..RoutingConfig::default()
        },
        degradation: DegradationConfig::default(),
        autonomy: ProfileAutonomy::default(),
    }
}

/// Returns all built-in profile definitions.
pub fn builtin_profiles() -> HashMap<String, Profile> {
    let mut map = HashMap::new();
    for p in [
        builtin_coder(),
        builtin_exploration(),
        builtin_bugfix(),
        builtin_hotfix(),
        builtin_ci_debug(),
        builtin_review(),
    ] {
        map.insert(p.profile.name.clone(), p);
    }
    map
}

// ── Loading ────────────────────────────────────────────────

fn profiles_dir_global() -> Option<PathBuf> {
    crate::core::data_dir::lean_ctx_data_dir()
        .ok()
        .map(|d| d.join("profiles"))
}

fn profiles_dir_project() -> Option<PathBuf> {
    let mut current = std::env::current_dir().ok()?;
    for _ in 0..12 {
        let candidate = current.join(".lean-ctx").join("profiles");
        if candidate.is_dir() {
            return Some(candidate);
        }
        if !current.pop() {
            break;
        }
    }
    None
}

/// Loads a profile by name with full resolution:
/// 1. Project-local `.lean-ctx/profiles/<name>.toml`
/// 2. Global `~/.lean-ctx/profiles/<name>.toml`
/// 3. Built-in defaults
///
/// Applies inheritance chain (max depth 5 to prevent cycles).
pub fn load_profile(name: &str) -> Option<Profile> {
    load_profile_recursive(name, 0)
}

fn load_profile_recursive(name: &str, depth: usize) -> Option<Profile> {
    if depth > 5 {
        return None;
    }

    let mut profile = load_profile_from_disk(name).or_else(|| builtin_profiles().remove(name))?;
    profile.profile.name = name.to_string();

    if let Some(ref parent_name) = profile.profile.inherits.clone() {
        if let Some(parent) = load_profile_recursive(parent_name, depth + 1) {
            profile = merge_profiles(parent, profile);
        }
    }

    Some(profile)
}

fn load_profile_from_disk(name: &str) -> Option<Profile> {
    let filename = format!("{name}.toml");

    if let Some(project_dir) = profiles_dir_project() {
        let path = project_dir.join(&filename);
        if let Some(p) = try_load_toml(&path) {
            return Some(p);
        }
    }

    if let Some(global_dir) = profiles_dir_global() {
        let path = global_dir.join(&filename);
        if let Some(p) = try_load_toml(&path) {
            return Some(p);
        }
    }

    None
}

fn try_load_toml(path: &Path) -> Option<Profile> {
    let content = std::fs::read_to_string(path).ok()?;
    toml::from_str(&content).ok()
}

/// Merges parent into child: child values take precedence,
/// parent provides defaults for unspecified fields.
///
/// ALL sections are merged field-by-field using `Option::or()`.
/// A child profile only needs to set the fields it wants to override.
fn merge_profiles(parent: Profile, child: Profile) -> Profile {
    let read = ReadConfig {
        default_mode: child.read.default_mode.or(parent.read.default_mode),
        max_tokens_per_file: child
            .read
            .max_tokens_per_file
            .or(parent.read.max_tokens_per_file),
        prefer_cache: child.read.prefer_cache.or(parent.read.prefer_cache),
    };
    let compression = CompressionConfig {
        crp_mode: child.compression.crp_mode.or(parent.compression.crp_mode),
        output_density: child
            .compression
            .output_density
            .or(parent.compression.output_density),
        entropy_threshold: child
            .compression
            .entropy_threshold
            .or(parent.compression.entropy_threshold),
        terse_mode: child
            .compression
            .terse_mode
            .or(parent.compression.terse_mode),
    };
    let translation = TranslationConfig {
        enabled: child.translation.enabled.or(parent.translation.enabled),
        ruleset: child.translation.ruleset.or(parent.translation.ruleset),
    };
    let layout = LayoutConfig {
        enabled: child.layout.enabled.or(parent.layout.enabled),
        min_lines: child.layout.min_lines.or(parent.layout.min_lines),
    };
    let memory = crate::core::memory_policy::MemoryPolicyOverrides {
        knowledge: crate::core::memory_policy::KnowledgePolicyOverrides {
            max_facts: child
                .memory
                .knowledge
                .max_facts
                .or(parent.memory.knowledge.max_facts),
            max_patterns: child
                .memory
                .knowledge
                .max_patterns
                .or(parent.memory.knowledge.max_patterns),
            max_history: child
                .memory
                .knowledge
                .max_history
                .or(parent.memory.knowledge.max_history),
            contradiction_threshold: child
                .memory
                .knowledge
                .contradiction_threshold
                .or(parent.memory.knowledge.contradiction_threshold),
            recall_facts_limit: child
                .memory
                .knowledge
                .recall_facts_limit
                .or(parent.memory.knowledge.recall_facts_limit),
            rooms_limit: child
                .memory
                .knowledge
                .rooms_limit
                .or(parent.memory.knowledge.rooms_limit),
            timeline_limit: child
                .memory
                .knowledge
                .timeline_limit
                .or(parent.memory.knowledge.timeline_limit),
            relations_limit: child
                .memory
                .knowledge
                .relations_limit
                .or(parent.memory.knowledge.relations_limit),
        },
        lifecycle: crate::core::memory_policy::LifecyclePolicyOverrides {
            decay_rate: child
                .memory
                .lifecycle
                .decay_rate
                .or(parent.memory.lifecycle.decay_rate),
            low_confidence_threshold: child
                .memory
                .lifecycle
                .low_confidence_threshold
                .or(parent.memory.lifecycle.low_confidence_threshold),
            stale_days: child
                .memory
                .lifecycle
                .stale_days
                .or(parent.memory.lifecycle.stale_days),
            similarity_threshold: child
                .memory
                .lifecycle
                .similarity_threshold
                .or(parent.memory.lifecycle.similarity_threshold),
        },
    };
    let verification = crate::core::output_verification::VerificationConfig {
        enabled: child.verification.enabled.or(parent.verification.enabled),
        mode: child.verification.mode.or(parent.verification.mode),
        strict_mode: child
            .verification
            .strict_mode
            .or(parent.verification.strict_mode),
        check_paths: child
            .verification
            .check_paths
            .or(parent.verification.check_paths),
        check_identifiers: child
            .verification
            .check_identifiers
            .or(parent.verification.check_identifiers),
        check_line_numbers: child
            .verification
            .check_line_numbers
            .or(parent.verification.check_line_numbers),
        check_structure: child
            .verification
            .check_structure
            .or(parent.verification.check_structure),
    };
    let budget = BudgetConfig {
        max_context_tokens: child
            .budget
            .max_context_tokens
            .or(parent.budget.max_context_tokens),
        max_shell_invocations: child
            .budget
            .max_shell_invocations
            .or(parent.budget.max_shell_invocations),
        max_cost_usd: child.budget.max_cost_usd.or(parent.budget.max_cost_usd),
    };
    let pipeline = PipelineConfig {
        intent: child.pipeline.intent.or(parent.pipeline.intent),
        relevance: child.pipeline.relevance.or(parent.pipeline.relevance),
        compression: child.pipeline.compression.or(parent.pipeline.compression),
        translation: child.pipeline.translation.or(parent.pipeline.translation),
    };
    let routing = RoutingConfig {
        max_model_tier: child
            .routing
            .max_model_tier
            .or(parent.routing.max_model_tier),
        degrade_under_pressure: child
            .routing
            .degrade_under_pressure
            .or(parent.routing.degrade_under_pressure),
    };
    let degradation = DegradationConfig {
        enforce: child.degradation.enforce.or(parent.degradation.enforce),
        throttle_ms: child
            .degradation
            .throttle_ms
            .or(parent.degradation.throttle_ms),
    };
    let autonomy = ProfileAutonomy {
        enabled: child.autonomy.enabled.or(parent.autonomy.enabled),
        auto_preload: child.autonomy.auto_preload.or(parent.autonomy.auto_preload),
        auto_dedup: child.autonomy.auto_dedup.or(parent.autonomy.auto_dedup),
        auto_related: child.autonomy.auto_related.or(parent.autonomy.auto_related),
        silent_preload: child
            .autonomy
            .silent_preload
            .or(parent.autonomy.silent_preload),
        auto_prefetch: child
            .autonomy
            .auto_prefetch
            .or(parent.autonomy.auto_prefetch),
        auto_response: child
            .autonomy
            .auto_response
            .or(parent.autonomy.auto_response),
        dedup_threshold: child
            .autonomy
            .dedup_threshold
            .or(parent.autonomy.dedup_threshold),
        prefetch_max_files: child
            .autonomy
            .prefetch_max_files
            .or(parent.autonomy.prefetch_max_files),
        prefetch_budget_tokens: child
            .autonomy
            .prefetch_budget_tokens
            .or(parent.autonomy.prefetch_budget_tokens),
        response_min_tokens: child
            .autonomy
            .response_min_tokens
            .or(parent.autonomy.response_min_tokens),
        checkpoint_interval: child
            .autonomy
            .checkpoint_interval
            .or(parent.autonomy.checkpoint_interval),
    };
    Profile {
        profile: ProfileMeta {
            name: child.profile.name,
            inherits: child.profile.inherits,
            description: if child.profile.description.is_empty() {
                parent.profile.description
            } else {
                child.profile.description
            },
        },
        read,
        compression,
        translation,
        layout,
        memory,
        verification,
        budget,
        pipeline,
        routing,
        degradation,
        autonomy,
    }
}

/// Returns the currently active profile name from env or default.
pub fn active_profile_name() -> String {
    std::env::var("LEAN_CTX_PROFILE")
        .ok()
        .filter(|s| !s.trim().is_empty())
        .unwrap_or_else(|| "exploration".to_string())
}

/// Loads the currently active profile.
pub fn active_profile() -> Profile {
    let name = active_profile_name();
    load_profile(&name).unwrap_or_else(builtin_exploration)
}

/// Sets the active profile for the current process by updating `LEAN_CTX_PROFILE`.
///
/// Returns the resolved profile after applying inheritance.
pub fn set_active_profile(name: &str) -> Result<Profile, String> {
    let name = name.trim();
    if name.is_empty() {
        return Err("profile name is empty".to_string());
    }
    let prev = active_profile_name();
    let profile = load_profile(name).ok_or_else(|| format!("profile '{name}' not found"))?;
    std::env::set_var("LEAN_CTX_PROFILE", name);
    if prev != name {
        crate::core::events::emit_profile_changed(&prev, name);
    }
    Ok(profile)
}

/// Lists all available profile names (built-in + on-disk).
pub fn list_profiles() -> Vec<ProfileInfo> {
    let mut profiles: HashMap<String, ProfileInfo> = HashMap::new();

    for (name, p) in builtin_profiles() {
        profiles.insert(
            name.clone(),
            ProfileInfo {
                name,
                description: p.profile.description,
                source: ProfileSource::Builtin,
            },
        );
    }

    for (source, dir) in [
        (ProfileSource::Global, profiles_dir_global()),
        (ProfileSource::Project, profiles_dir_project()),
    ] {
        if let Some(dir) = dir {
            if let Ok(entries) = std::fs::read_dir(&dir) {
                for entry in entries.flatten() {
                    let path = entry.path();
                    if path.extension().and_then(|e| e.to_str()) == Some("toml") {
                        if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
                            let name = stem.to_string();
                            let desc = try_load_toml(&path)
                                .map(|p| p.profile.description)
                                .unwrap_or_default();
                            profiles.insert(
                                name.clone(),
                                ProfileInfo {
                                    name,
                                    description: desc,
                                    source,
                                },
                            );
                        }
                    }
                }
            }
        }
    }

    let mut result: Vec<ProfileInfo> = profiles.into_values().collect();
    result.sort_by_key(|p| p.name.clone());
    result
}

/// Information about an available profile.
#[derive(Debug, Clone)]
pub struct ProfileInfo {
    pub name: String,
    pub description: String,
    pub source: ProfileSource,
}

/// Where a profile was loaded from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProfileSource {
    Builtin,
    Global,
    Project,
}

impl std::fmt::Display for ProfileSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Builtin => write!(f, "built-in"),
            Self::Global => write!(f, "global"),
            Self::Project => write!(f, "project"),
        }
    }
}

/// Formats a profile as TOML for display or file creation.
pub fn format_as_toml(profile: &Profile) -> String {
    toml::to_string_pretty(profile).unwrap_or_else(|_| "[error serializing profile]".to_string())
}

// ── Tests ──────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn builtin_profiles_has_five() {
        let builtins = builtin_profiles();
        assert_eq!(builtins.len(), 6);
        assert!(builtins.contains_key("coder"));
        assert!(builtins.contains_key("exploration"));
        assert!(builtins.contains_key("bugfix"));
        assert!(builtins.contains_key("hotfix"));
        assert!(builtins.contains_key("ci-debug"));
        assert!(builtins.contains_key("review"));
    }

    #[test]
    fn hotfix_has_minimal_budget() {
        let p = builtin_profiles().remove("hotfix").unwrap();
        assert_eq!(p.budget.max_context_tokens_effective(), 30_000);
        assert_eq!(p.budget.max_shell_invocations_effective(), 20);
        assert_eq!(p.read.default_mode_effective(), "signatures");
        assert_eq!(p.compression.output_density_effective(), "ultra");
    }

    #[test]
    fn exploration_has_broad_context() {
        let p = builtin_profiles().remove("exploration").unwrap();
        assert_eq!(p.budget.max_context_tokens_effective(), 200_000);
        assert_eq!(p.read.default_mode_effective(), "map");
        assert!(p.read.prefer_cache_effective());
    }

    #[test]
    fn profile_roundtrip_toml() {
        let original = builtin_exploration();
        let toml_str = format_as_toml(&original);
        let parsed: Profile = toml::from_str(&toml_str).unwrap();
        assert_eq!(parsed.profile.name, "exploration");
        assert_eq!(parsed.read.default_mode_effective(), "map");
        assert_eq!(parsed.budget.max_context_tokens_effective(), 200_000);
    }

    #[test]
    fn merge_child_overrides_parent() {
        let parent = builtin_exploration();
        let child = Profile {
            profile: ProfileMeta {
                name: "custom".to_string(),
                inherits: Some("exploration".to_string()),
                description: String::new(),
            },
            read: ReadConfig {
                default_mode: Some("signatures".to_string()),
                ..ReadConfig::default()
            },
            compression: CompressionConfig::default(),
            translation: TranslationConfig::default(),
            layout: LayoutConfig::default(),
            memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
            verification: crate::core::output_verification::VerificationConfig::default(),
            budget: BudgetConfig {
                max_context_tokens: Some(10_000),
                ..BudgetConfig::default()
            },
            pipeline: PipelineConfig::default(),
            routing: RoutingConfig::default(),
            degradation: DegradationConfig::default(),
            autonomy: ProfileAutonomy::default(),
        };

        let merged = merge_profiles(parent, child);
        assert_eq!(merged.read.default_mode_effective(), "signatures");
        assert_eq!(merged.budget.max_context_tokens_effective(), 10_000);
        assert_eq!(
            merged.profile.description,
            "Broad context for understanding codebases"
        );
    }

    #[test]
    fn merge_partial_child_inherits_parent_fields() {
        let parent = builtin_exploration();
        let child = Profile {
            profile: ProfileMeta {
                name: "partial".to_string(),
                inherits: Some("exploration".to_string()),
                description: String::new(),
            },
            read: ReadConfig {
                default_mode: Some("map".to_string()),
                ..ReadConfig::default()
            },
            compression: CompressionConfig::default(),
            translation: TranslationConfig::default(),
            layout: LayoutConfig::default(),
            memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
            verification: crate::core::output_verification::VerificationConfig::default(),
            budget: BudgetConfig::default(),
            pipeline: PipelineConfig::default(),
            routing: RoutingConfig::default(),
            degradation: DegradationConfig::default(),
            autonomy: ProfileAutonomy::default(),
        };

        let merged = merge_profiles(parent, child);
        assert_eq!(merged.read.default_mode_effective(), "map");
        assert_eq!(
            merged.read.max_tokens_per_file_effective(),
            80_000,
            "should inherit max_tokens_per_file from parent"
        );
        assert!(
            merged.read.prefer_cache_effective(),
            "should inherit prefer_cache from parent"
        );
        assert_eq!(
            merged.budget.max_context_tokens_effective(),
            200_000,
            "should inherit budget from parent"
        );
    }

    #[test]
    fn load_builtin_by_name() {
        let p = load_profile("hotfix").unwrap();
        assert_eq!(p.profile.name, "hotfix");
        assert_eq!(p.read.default_mode_effective(), "signatures");
    }

    #[test]
    fn load_nonexistent_returns_none() {
        assert!(load_profile("does-not-exist-xyz").is_none());
    }

    #[test]
    fn list_profiles_includes_builtins() {
        let list = list_profiles();
        assert!(list.len() >= 5);
        let names: Vec<&str> = list.iter().map(|p| p.name.as_str()).collect();
        assert!(names.contains(&"exploration"));
        assert!(names.contains(&"hotfix"));
        assert!(names.contains(&"review"));
    }

    #[test]
    fn active_profile_defaults_to_exploration() {
        std::env::remove_var("LEAN_CTX_PROFILE");
        let p = active_profile();
        assert_eq!(p.profile.name, "exploration");
    }

    #[test]
    fn active_profile_from_env() {
        std::env::set_var("LEAN_CTX_PROFILE", "hotfix");
        let name = active_profile_name();
        assert_eq!(name, "hotfix");
        std::env::remove_var("LEAN_CTX_PROFILE");
    }

    #[test]
    fn profile_source_display() {
        assert_eq!(ProfileSource::Builtin.to_string(), "built-in");
        assert_eq!(ProfileSource::Global.to_string(), "global");
        assert_eq!(ProfileSource::Project.to_string(), "project");
    }

    #[test]
    fn default_profile_has_sane_values() {
        let p = Profile {
            profile: ProfileMeta::default(),
            read: ReadConfig::default(),
            compression: CompressionConfig::default(),
            translation: TranslationConfig::default(),
            layout: LayoutConfig::default(),
            memory: crate::core::memory_policy::MemoryPolicyOverrides::default(),
            verification: crate::core::output_verification::VerificationConfig::default(),
            budget: BudgetConfig::default(),
            pipeline: PipelineConfig::default(),
            routing: RoutingConfig::default(),
            degradation: DegradationConfig::default(),
            autonomy: ProfileAutonomy::default(),
        };
        assert_eq!(p.read.default_mode_effective(), "auto");
        assert_eq!(p.compression.crp_mode_effective(), "tdd");
        assert_eq!(p.budget.max_context_tokens_effective(), 200_000);
        assert!(p.pipeline.compression_effective());
        assert!(p.pipeline.intent_effective());
    }

    #[test]
    fn pipeline_layers_configurable() {
        let toml_str = r#"
[profile]
name = "no-intent"

[pipeline]
intent = false
relevance = false
"#;
        let p: Profile = toml::from_str(toml_str).unwrap();
        assert!(!p.pipeline.intent_effective());
        assert!(!p.pipeline.relevance_effective());
        assert!(p.pipeline.compression_effective());
        assert!(p.pipeline.translation_effective());
    }

    #[test]
    fn partial_toml_fills_defaults() {
        let toml_str = r#"
[profile]
name = "minimal"

[read]
default_mode = "entropy"
"#;
        let p: Profile = toml::from_str(toml_str).unwrap();
        assert_eq!(p.read.default_mode_effective(), "entropy");
        assert_eq!(p.read.max_tokens_per_file_effective(), 50_000);
        assert_eq!(p.budget.max_context_tokens_effective(), 200_000);
        assert_eq!(p.compression.crp_mode_effective(), "tdd");
    }

    #[test]
    fn partial_toml_leaves_unset_as_none() {
        let toml_str = r#"
[profile]
name = "sparse"

[read]
default_mode = "map"
"#;
        let p: Profile = toml::from_str(toml_str).unwrap();
        assert_eq!(p.read.default_mode, Some("map".to_string()));
        assert_eq!(p.read.max_tokens_per_file, None);
        assert_eq!(p.read.prefer_cache, None);
        assert_eq!(p.budget.max_context_tokens, None);
        assert_eq!(p.compression.crp_mode, None);
    }
}