lean-ctx-engine 3.12.1

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
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
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
//! Auxiliary configuration section structs.
//!
//! Nested config structs (secret-detection, setup, archive, providers,
//! autonomy, updates, cloud, gain, loop-detection, embedding, …) split out of
//! `config/mod.rs` to keep the top-level module focused on `Config` itself.
//! Re-exported via `pub use sections::*`, so external paths stay stable.

use super::serde_defaults;
#[allow(clippy::wildcard_imports)]
use super::*;
use serde::{Deserialize, Serialize};

/// Opt-in configuration for counterfactual Shadow Mode reports.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ShadowConfig {
    pub enabled: bool,
    pub report_interval: usize,
    pub report_dir: String,
}

impl Default for ShadowConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            report_interval: 10,
            report_dir: String::new(),
        }
    }
}

/// OCLA settings (`[ocla.delivery]`). The former `[ocla.sidecar]` and
/// `[ocla.grpc]` sections started no server and are ignored when present.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct OclaConfig {
    pub delivery: DeliveryConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DeliveryConfig {
    pub enabled: bool,
    /// Allow subagents to receive a cross-agent delivery stub instead of
    /// forcing a fresh disk read.
    pub delivery_for_subagents: bool,
    pub max_entries: usize,
    pub ttl_minutes: u64,
}

impl Default for DeliveryConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            delivery_for_subagents: true,
            max_entries: 4096,
            ttl_minutes: 30,
        }
    }
}

impl OclaConfig {
    pub fn delivery_enabled(&self) -> bool {
        self.delivery.enabled
    }
}

/// Bounds and switches for the cross-agent delivery cache (`[cache]`).
///
/// The one source for these values: the former copy under
/// `[ocla.delivery.cache]` is moved here by the automatic config migration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CacheConfig {
    /// Process-local tier lifetime (seconds).
    pub l1_ttl_secs: u64,
    /// Daemon tier size (entries).
    pub l2_max_entries: usize,
    /// Daemon tier lifetime (seconds).
    pub l2_ttl_secs: u64,
    /// Disk tier budget (bytes), enforced when the cache opens.
    pub l3_max_bytes: u64,
    /// Reuse a `ctx_compose` result for the same task and path.
    pub compose_cache_enabled: bool,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            l1_ttl_secs: 300,
            l2_max_entries: 10_000,
            l2_ttl_secs: 3_600,
            l3_max_bytes: 500_000_000,
            compose_cache_enabled: true,
        }
    }
}

#[cfg(test)]
mod cache_config_tests {
    use super::CacheConfig;

    #[test]
    fn cache_defaults_match_delivery_budget() {
        assert_eq!(CacheConfig::default().l3_max_bytes, 500_000_000);
        assert!(CacheConfig::default().compose_cache_enabled);
    }

    #[test]
    fn cache_config_deserializes_partial_overrides() {
        // `shell_cache_enabled` was removed (#1980); configs that still set it
        // must keep loading.
        // `l1_max_entries` and `l3_gc_threshold` were retired (never applied).
        let parsed: CacheConfig = serde_json::from_str(
            r#"{"l1_max_entries": 12, "l3_gc_threshold": 0.5, "shell_cache_enabled": true, "l2_ttl_secs": 60}"#,
        )
        .unwrap();
        assert_eq!(parsed.l2_ttl_secs, 60);
        assert_eq!(parsed.l2_max_entries, 10_000);
    }
}

/// Agent lifecycle configuration: TTLs, GC intervals, scratchpad limits.
///
/// Maps to `[agents]` in config.toml. All fields have sane defaults so existing
/// configs without this section continue to work.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AgentsConfig {
    /// How often the background reaper runs (minutes). 0 = disabled.
    pub gc_interval_minutes: u64,
    /// Presence registry: remove finished agents older than this (hours).
    pub presence_ttl_hours: u64,
    /// Default TTL for scratchpad messages without explicit expiry (hours).
    pub scratchpad_default_ttl_hours: u64,
    /// Logical session timeout (seconds).
    pub logical_session_ttl_seconds: u64,
    /// Active worker lease. Missing heartbeats release capacity automatically.
    pub active_worker_lease_seconds: u64,
    /// Opt-in: let only one cargo/npm build or test run at a time across all
    /// lean-ctx sessions on this machine (ctx_shell waits for the slot).
    /// Off by default — it queued every user's builds behind other sessions.
    pub serialize_build_commands: bool,
    /// Opt-in: `CARGO_BUILD_JOBS` for builds run through ctx_shell. `0`
    /// (default) leaves cargo's own setting alone.
    pub cargo_build_jobs: usize,
    /// Opt-in: point builds run through ctx_shell at one machine-wide
    /// `CARGO_TARGET_DIR` (`<data dir>/build-cache/cargo-target`). Off by
    /// default: when on, `./target` stops receiving the output, so a binary
    /// run from there is stale.
    pub shared_cargo_target: bool,
    /// Max scratchpad entries before oldest are evicted.
    pub max_scratchpad_entries: usize,
}

impl Default for AgentsConfig {
    fn default() -> Self {
        Self {
            gc_interval_minutes: 10,
            presence_ttl_hours: 24,
            scratchpad_default_ttl_hours: 12,
            logical_session_ttl_seconds: 180,
            active_worker_lease_seconds: 120,
            serialize_build_commands: false,
            cargo_build_jobs: 0,
            shared_cargo_target: false,
            max_scratchpad_entries: 200,
        }
    }
}

#[cfg(test)]
mod agents_config_tests {
    use super::AgentsConfig;

    #[test]
    fn default_values_are_sane() {
        let cfg = AgentsConfig::default();
        assert_eq!(cfg.gc_interval_minutes, 10);
        assert_eq!(cfg.presence_ttl_hours, 24);
        assert_eq!(cfg.scratchpad_default_ttl_hours, 12);
        assert_eq!(cfg.logical_session_ttl_seconds, 180);
        assert_eq!(cfg.active_worker_lease_seconds, 120);
        // Builds are the user's own: lean-ctx neither queues, throttles nor
        // relocates them unless asked (a shared target made `./target` stale).
        assert!(!cfg.serialize_build_commands);
        assert_eq!(cfg.cargo_build_jobs, 0);
        assert!(!cfg.shared_cargo_target);
        assert_eq!(cfg.max_scratchpad_entries, 200);
    }

    #[test]
    fn deserializes_with_missing_fields() {
        let json = r"{}";
        let cfg: AgentsConfig = serde_json::from_str(json).expect("empty object → defaults");
        assert_eq!(cfg.gc_interval_minutes, 10);
    }

    #[test]
    fn partial_override() {
        let json = r#"{"gc_interval_minutes": 5, "presence_ttl_hours": 12}"#;
        let cfg: AgentsConfig = serde_json::from_str(json).expect("partial");
        assert_eq!(cfg.gc_interval_minutes, 5);
        assert_eq!(cfg.presence_ttl_hours, 12);
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SecretDetectionConfig {
    pub enabled: bool,
    pub redact: bool,
    pub custom_patterns: Vec<String>,
    /// #718: subtractive counterpart to `custom_patterns` — a detected secret
    /// whose matched text is covered by any of these regexes is neither
    /// reported nor redacted. Lets users carve out known-safe identifiers or
    /// repo naming conventions without disabling secret detection wholesale.
    pub exclude_patterns: Vec<String>,
}

/// Controls what lean-ctx injects during `setup` and `update --rewire`.
/// Fresh installs default to non-invasive (rules/skills off, MCP on).
/// Users who ran setup interactively get explicit true/false.
/// `None` = undecided (legacy: check if rules already exist and preserve behavior).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SetupConfig {
    /// Inject agent rule files (CLAUDE.md, .cursor/rules/, etc.).
    /// None = undecided (legacy compat: inject if rules already present).
    /// Some(true) = always inject. Some(false) = never inject.
    pub auto_inject_rules: Option<bool>,
    /// Install SKILL.md files for supported agents.
    /// None = undecided. Some(true) = install. Some(false) = skip.
    pub auto_inject_skills: Option<bool>,
    /// Register lean-ctx as an MCP server in editor configs.
    #[serde(default = "serde_defaults::default_true")]
    pub auto_update_mcp: bool,
    /// Keep already-installed agent hooks current on MCP server start (#1879).
    /// `false` leaves hook entries, `permissions.deny` and the status line in
    /// agent settings exactly as the user wrote them; only an explicit
    /// `lean-ctx setup` / `init --agent` / `doctor --fix` writes them.
    #[serde(default = "serde_defaults::default_true")]
    pub manage_hooks: bool,
    /// AI tools (agent keys, e.g. `claude`, `cursor`) that `setup`, `onboard`
    /// and the post-update refresh may configure. Written by the setup
    /// selection or `--agents`. None = no choice recorded yet: setup offers
    /// every detected tool, an update refreshes only already-connected ones.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub agents: Option<Vec<String>>,
}

impl Default for SetupConfig {
    fn default() -> Self {
        Self {
            auto_inject_rules: None,
            auto_inject_skills: None,
            auto_update_mcp: true,
            manage_hooks: true,
            agents: None,
        }
    }
}

impl SetupConfig {
    /// Returns whether rules should be injected, considering legacy installs.
    /// If undecided (None), checks if lean-ctx rules markers already exist
    /// in any agent config — if so, keeps injecting for backward compat.
    pub fn should_inject_rules(&self) -> bool {
        match self.auto_inject_rules {
            Some(v) => v,
            None => Self::rules_already_present(),
        }
    }

    /// Returns whether skills should be installed.
    pub fn should_inject_skills(&self) -> bool {
        match self.auto_inject_skills {
            Some(v) => v,
            None => Self::rules_already_present(),
        }
    }

    /// Returns whether `setup`/`onboard`/`init` may (re)register the lean-ctx
    /// MCP server in editor configs. Honors `auto_update_mcp` (#281) so locked-
    /// down environments can keep MCP out of agent settings while still getting
    /// hooks, rules and skills.
    pub fn should_update_mcp(&self) -> bool {
        self.auto_update_mcp
    }

    /// Check if lean-ctx rules markers exist in any known agent config location.
    ///
    /// Delegates the per-agent path catalog to `rules_inject::any_rules_marker_present`
    /// (derived from the injector's own target list) so this never drifts behind
    /// newly supported agents again (#442). Claude Code and CodeBuddy have no
    /// rules *target* (they auto-load an inline block instead), so their legacy
    /// rule files are checked separately to keep honoring older installs.
    fn rules_already_present() -> bool {
        let Some(home) = dirs::home_dir() else {
            return false;
        };
        if crate::rules_inject::any_rules_marker_present(&home) {
            return true;
        }
        let legacy_paths = [
            crate::core::editor_registry::claude_rules_dir(&home).join("lean-ctx.md"),
            crate::core::editor_registry::codebuddy_rules_dir(&home).join("lean-ctx.md"),
        ];
        legacy_paths.iter().any(|p| {
            std::fs::read_to_string(p)
                .is_ok_and(|c| c.contains(crate::core::rules_canonical::START_MARK))
        })
    }
}

impl Default for SecretDetectionConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            redact: true,
            custom_patterns: Vec::new(),
            exclude_patterns: Vec::new(),
        }
    }
}

/// Settings for the zero-loss compression archive (large tool outputs saved to disk).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ArchiveConfig {
    pub enabled: bool,
    pub threshold_chars: usize,
    pub max_age_hours: u64,
    pub max_disk_mb: u64,
    pub ephemeral: bool,
    /// Minimum output tokens before the ephemeral firewall replaces an inline tool
    /// result with a summary + retrieval ref. Outputs below this stay fully inline.
    pub ephemeral_min_tokens: usize,
    /// Maximum output size that `ctx_shell(inline=true)` returns verbatim before
    /// the archive/firewall path takes over.
    pub inline_max_bytes: usize,
    /// Programs whose stdout *is* a dataset (#1260). Head+tail elision does not
    /// compress those — it drops the interior rows that hold the answer — so a
    /// `ctx_shell` command running one of these passes through verbatim at any
    /// size. Set to `[]` to disable the passthrough.
    pub raw_commands: Vec<String>,
    /// Context-window guard for *implicitly* verbatim `ctx_shell` deliveries
    /// (dataset passthrough #1260, `inline=true`): above this many output
    /// tokens the content is archived losslessly and delivered as a head+tail
    /// digest with `ctx_expand` drilldown instead of flooding the calling
    /// agent's context window. Explicit `raw=true`/`bypass=true` and the
    /// `LEAN_CTX_MINIMAL` escape hatch are never capped. `0` disables the
    /// cap. Env: LEAN_CTX_VERBATIM_MAX_TOKENS (#1541).
    pub verbatim_max_tokens: usize,
}

/// Opt-in conversation-history compression settings (#1123).
///
/// The proxy leaves conversation history byte-for-byte unchanged unless
/// `compression_enabled` is true and the configured token threshold is met.
/// Each older message is scored; it is kept verbatim at or above
/// `min_score_to_preserve`, replaced by a stub below `drop_score_below`, and
/// summarized to one line in between. Neither a summary nor a stub keeps a
/// recoverable copy, so the proxy leaves history untouched under protection.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct ConversationConfig {
    /// Enable message-level compression in the proxy. Default: false.
    pub compression_enabled: bool,
    /// Number of most recent messages always kept verbatim.
    pub preserve_last_n_turns: usize,
    /// Minimum estimated message-array size before compression starts.
    pub compression_threshold_tokens: usize,
    /// Minimum score for verbatim preservation.
    pub min_score_to_preserve: f64,
    /// Messages scoring below this value are replaced by a one-line stub.
    pub drop_score_below: f64,
}

impl Default for ConversationConfig {
    fn default() -> Self {
        Self {
            compression_enabled: false,
            preserve_last_n_turns: 10,
            compression_threshold_tokens: 50_000,
            min_score_to_preserve: 0.5,
            drop_score_below: 0.2,
        }
    }
}

impl Default for ArchiveConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            threshold_chars: 800,
            max_age_hours: 48,
            max_disk_mb: 500,
            ephemeral: true,
            ephemeral_min_tokens: 2000,
            inline_max_bytes: 32 * 1024,
            raw_commands: crate::core::firewall::DEFAULT_RAW_COMMANDS
                .iter()
                .map(|s| (*s).to_string())
                .collect(),
            verbatim_max_tokens: 100_000,
        }
    }
}

impl ArchiveConfig {
    pub fn ephemeral_effective(&self) -> bool {
        if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL") {
            return !matches!(v.trim(), "0" | "false" | "off");
        }
        self.ephemeral && self.enabled
    }

    pub fn ephemeral_min_tokens_effective(&self) -> usize {
        if let Ok(v) = std::env::var("LEAN_CTX_EPHEMERAL_MIN_TOKENS")
            && let Ok(n) = v.trim().parse::<usize>()
        {
            return n;
        }
        self.ephemeral_min_tokens
    }

    /// Effective context-window cap for implicitly verbatim deliveries (#1541).
    pub fn verbatim_max_tokens_effective(&self) -> usize {
        if let Ok(v) = std::env::var("LEAN_CTX_VERBATIM_MAX_TOKENS")
            && let Ok(n) = v.trim().parse::<usize>()
        {
            return n;
        }
        self.verbatim_max_tokens
    }

    pub fn inline_max_bytes_effective(&self) -> usize {
        if let Ok(v) = std::env::var("LEAN_CTX_INLINE_MAX_BYTES")
            && let Ok(n) = v.trim().parse::<usize>()
        {
            return n;
        }
        self.inline_max_bytes
    }
}

/// Configuration for external context providers (GitHub, GitLab, Jira, etc.).
/// Each provider can be enabled/disabled and configured with auth tokens.
/// Override individual tokens via env vars (GITHUB_TOKEN, GITLAB_TOKEN, etc.).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ProvidersConfig {
    /// Master switch for the provider subsystem.
    pub enabled: bool,
    /// GitHub provider configuration.
    pub github: ProviderEntryConfig,
    /// GitLab provider configuration.
    pub gitlab: ProviderEntryConfig,
    /// Auto-ingest provider results into BM25/embedding indexes.
    pub auto_index: bool,
    /// Default cache TTL for provider results (seconds).
    pub cache_ttl_secs: u64,
    /// MCP Bridge providers: `{ "name" = { url = "...", description = "..." } }`.
    #[serde(default)]
    pub mcp_bridges: std::collections::HashMap<String, McpBridgeEntry>,
}

impl Default for ProvidersConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            github: ProviderEntryConfig::default(),
            gitlab: ProviderEntryConfig::default(),
            auto_index: true,
            cache_ttl_secs: 120,
            mcp_bridges: std::collections::HashMap::new(),
        }
    }
}

/// Controls additive KnowledgeRouter hints in Context Gate output.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct KnowledgeRoutingConfig {
    pub enabled: bool,
    pub max_references: usize,
    pub hint_prefix: String,
}

impl Default for KnowledgeRoutingConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_references: 5,
            hint_prefix: "--- Knowledge Context ---".to_string(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpBridgeEntry {
    /// HTTP/SSE URL for remote MCP servers.
    #[serde(default)]
    pub url: Option<String>,
    /// Command to spawn a local MCP server (stdio transport).
    #[serde(default)]
    pub command: Option<String>,
    /// Arguments for the command.
    #[serde(default)]
    pub args: Vec<String>,
    /// Human-readable description.
    #[serde(default)]
    pub description: Option<String>,
    /// Environment variable name containing an auth token.
    #[serde(default)]
    pub auth_env: Option<String>,
}

/// Per-provider configuration entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ProviderEntryConfig {
    /// Whether this specific provider is enabled.
    pub enabled: bool,
    /// Auth token (prefer env var; only use this for project-local overrides).
    pub token: Option<String>,
    /// API base URL override (for GitHub Enterprise, self-hosted GitLab, etc.).
    pub api_url: Option<String>,
    /// Default project/repo for this provider (auto-detected from git remote if empty).
    pub project: Option<String>,
}

impl Default for ProviderEntryConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            token: None,
            api_url: None,
            project: None,
        }
    }
}

/// Controls autonomous background behaviors (preload, dedup, consolidation).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AutonomyConfig {
    pub enabled: bool,
    pub auto_consolidate: bool,
    pub consolidate_every_calls: u32,
    pub consolidate_cooldown_secs: u64,
    /// No effect: the background cognition loop is retired (DEPRECATIONS.toml
    /// `config-autonomy-cognition-loop`). The four `cognition_*` keys stay
    /// accepted so existing configs keep loading.
    pub cognition_loop_enabled: bool,
    #[serde(default = "serde_defaults::default_cognition_loop_interval")]
    pub cognition_loop_interval_secs: u64,
    #[serde(default = "serde_defaults::default_cognition_loop_max_steps")]
    pub cognition_loop_max_steps: u8,
    #[serde(default = "serde_defaults::default_cognition_synthesis_min_cluster")]
    pub cognition_synthesis_min_cluster: usize,
}

impl Default for AutonomyConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            auto_consolidate: true,
            consolidate_every_calls: 25,
            consolidate_cooldown_secs: 120,
            cognition_loop_enabled: false,
            cognition_loop_interval_secs: 3600,
            cognition_loop_max_steps: 9,
            cognition_synthesis_min_cluster: 3,
        }
    }
}

/// Controls automatic update behavior. All defaults are OFF — auto-updates
/// require explicit opt-in via `lean-ctx setup` or `lean-ctx update --schedule`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct UpdatesConfig {
    pub auto_update: bool,
    pub check_interval_hours: u64,
    pub notify_only: bool,
    /// Persistent release pin used by manual and scheduled update checks.
    /// `None` follows the latest release; values are normalized without `v`.
    #[serde(default)]
    pub pinned_version: Option<String>,
}

impl Default for UpdatesConfig {
    fn default() -> Self {
        Self {
            auto_update: false,
            check_interval_hours: 6,
            notify_only: false,
            pinned_version: None,
        }
    }
}

/// Fixed-context budget accounting (#964). The per-session footprint lean-ctx
/// adds — tool schemas + MCP instructions + auto-loaded rules files + the wakeup
/// briefing — is warned about once it crosses `budget_tokens`. The
/// `LEAN_CTX_CONTEXT_BUDGET_TOKENS` env var overrides it; `lean-ctx doctor
/// overhead --gate` turns a breach into a non-zero exit for CI.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ContextConfig {
    pub budget_tokens: usize,
    /// Inject matching CCR archives into later tool responses.
    pub proactive_expansion: bool,
    /// Maximum proactive archive content per tool response.
    pub proactive_expansion_budget_tokens: usize,
    /// Minimum normalized BM25 score required for an injection.
    pub proactive_expansion_threshold: f64,
    /// Ignore archived content older than this many seconds; 0 disables age expiry.
    pub proactive_expansion_max_age_secs: u64,
}

impl Default for ContextConfig {
    fn default() -> Self {
        Self {
            budget_tokens: 8000,
            proactive_expansion: true,
            proactive_expansion_budget_tokens: 2000,
            proactive_expansion_threshold: 0.6,
            proactive_expansion_max_age_secs: 3600,
        }
    }
}

impl UpdatesConfig {
    pub fn from_env() -> Self {
        let mut cfg = Self::default();
        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_UPDATE") {
            cfg.auto_update = v == "1" || v.eq_ignore_ascii_case("true");
        }
        if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_INTERVAL_HOURS")
            && let Ok(h) = v.parse::<u64>()
        {
            cfg.check_interval_hours = h.clamp(1, 168);
        }
        if let Ok(v) = std::env::var("LEAN_CTX_UPDATE_NOTIFY_ONLY") {
            cfg.notify_only = v == "1" || v.eq_ignore_ascii_case("true");
        }
        cfg
    }
}

impl AutonomyConfig {
    /// Creates an autonomy config from env vars, falling back to defaults.
    pub fn from_env() -> Self {
        let mut cfg = Self::default();
        if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
            && (v == "false" || v == "0")
        {
            cfg.enabled = false;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_AUTO_CONSOLIDATE") {
            cfg.auto_consolidate = v != "false" && v != "0";
        }
        if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_EVERY_CALLS")
            && let Ok(n) = v.parse()
        {
            cfg.consolidate_every_calls = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_CONSOLIDATE_COOLDOWN_SECS")
            && let Ok(n) = v.parse()
        {
            cfg.consolidate_cooldown_secs = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
            cfg.cognition_loop_enabled = v != "false" && v != "0";
        }
        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
            && let Ok(n) = v.parse()
        {
            cfg.cognition_loop_interval_secs = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
            && let Ok(n) = v.parse()
        {
            cfg.cognition_loop_max_steps = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_SYNTHESIS_MIN_CLUSTER")
            && let Ok(n) = v.parse()
        {
            cfg.cognition_synthesis_min_cluster = n;
        }
        cfg
    }

    /// Loads autonomy config from disk, with env var overrides applied.
    pub fn load() -> Self {
        let file_cfg = Config::load().autonomy;
        let mut cfg = file_cfg;
        if let Ok(v) = std::env::var("LEAN_CTX_AUTONOMY")
            && (v == "false" || v == "0")
        {
            cfg.enabled = false;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_ENABLED") {
            cfg.cognition_loop_enabled = v != "false" && v != "0";
        }
        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_INTERVAL_SECS")
            && let Ok(n) = v.parse()
        {
            cfg.cognition_loop_interval_secs = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_LOOP_MAX_STEPS")
            && let Ok(n) = v.parse()
        {
            cfg.cognition_loop_max_steps = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_COGNITION_SYNTHESIS_MIN_CLUSTER")
            && let Ok(n) = v.parse()
        {
            cfg.cognition_synthesis_min_cluster = n;
        }
        cfg
    }
}

/// Persisted telemetry choice. This distinguishes the v4 default from a user
/// choice so upgrades never erase an earlier opt-out.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum TelemetryPreference {
    #[default]
    DefaultOn,
    ExplicitlyEnabled,
    ExplicitlyDisabled,
}

/// Privacy-safe product telemetry settings.
///
/// When enabled, lean-ctx sends cumulative daily aggregates to `api.leanctx.com`
/// several times per day: a random installation ID (UUID v4), version, OS,
/// setup profile and counters. No code, filenames, prompts, or personal data.
/// Enabled by default (accepted at install); `lean-ctx telemetry off`,
/// `DO_NOT_TRACK=1` and `LEAN_CTX_TELEMETRY=off` opt out.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TelemetryConfig {
    /// Master switch for privacy-safe product telemetry.
    pub enabled: bool,
    /// Whether the state came from the v4 default or an explicit user choice.
    pub preference: TelemetryPreference,
    /// YYYY-MM-DD of the last successful telemetry send.
    pub last_heartbeat: Option<String>,
}

impl Default for TelemetryConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            preference: TelemetryPreference::DefaultOn,
            last_heartbeat: None,
        }
    }
}

impl TelemetryConfig {
    #[must_use]
    pub fn environment_disables(do_not_track: Option<&str>, env_override: Option<&str>) -> bool {
        do_not_track.is_some_and(|value| value.trim() == "1")
            || env_override.is_some_and(|value| {
                matches!(
                    value.trim().to_ascii_lowercase().as_str(),
                    "off" | "false" | "0" | "no"
                )
            })
    }

    #[must_use]
    pub fn explicitly_disabled(&self) -> bool {
        !self.enabled || self.preference == TelemetryPreference::ExplicitlyDisabled
    }

    #[must_use]
    pub fn send_eligible(&self, do_not_track: Option<&str>, env_override: Option<&str>) -> bool {
        self.enabled
            && self.preference != TelemetryPreference::ExplicitlyDisabled
            && !Self::environment_disables(do_not_track, env_override)
    }
}

/// What remains of the retired `[cloud]` section: the legacy opt-in the
/// loader turns into `telemetry.enabled`. Read, never written.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct LegacyCloudConfig {
    pub contribute_enabled: bool,
}

/// Model declaration for **measured-vs-estimated** cost reporting.
///
/// Proxy-routed clients (Claude Code, Codex, Pi, Gemini CLI, OpenCode) report
/// their real model and billed tokens, so lean-ctx prices them *measured* with
/// no configuration. MCP-only IDEs (Cursor, Copilot, Windsurf, VS Code, Zed)
/// send their LLM traffic straight to the provider, bypassing lean-ctx — their
/// real model is invisible. Declaring it here lets those *estimated* turns be
/// priced with the correct model instead of a blended fallback.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct CostConfig {
    /// Fallback pricing model for any client without a per-client entry.
    /// Unset/empty → lean-ctx keeps its blended heuristic.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_model: Option<String>,
    /// Per-client pricing model, keyed by client id (`cursor`, `copilot`,
    /// `windsurf`, `claude`, `codex`, …). Used for MCP-only IDEs whose real
    /// model lean-ctx cannot observe. Example:
    /// `[cost.models]` then `cursor = "claude-opus-4.5"`.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub models: HashMap<String, String>,
    /// Operator price overrides (#1189), keyed by model name — for negotiated
    /// enterprise rates (committed-use discounts, Azure PTU, zero-rated
    /// internal models) that no public catalog can know. Merged into the
    /// pricing table as **exact** entries, overriding embedded and live rows;
    /// only a provider-measured bill beats them. Example:
    /// `[cost.prices."internal-llm"]` then `input_per_m = 0.10`,
    /// `output_per_m = 0.40`.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub prices: HashMap<String, PriceOverride>,
}

/// User-controlled never-lossy zones (`[protection]`, #1570 P4).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ProtectionConfig {
    /// Glob patterns matched against a call's path-like arguments (`path`,
    /// `file_path`, `filePath`). A hit exempts the call's output from every
    /// lossy filter (triage), same standard as `raw=true`. Lossless paths
    /// (archive + ctx_expand) are unaffected — protection means "never
    /// lossy", not "never compressed".
    pub file_patterns: Vec<String>,
    /// Honor inline `<protect>` spans: any tool output containing the tag
    /// bypasses lossy line filtering, and history pruning leaves the
    /// matching tool result verbatim.
    pub tags: bool,
}

impl Default for ProtectionConfig {
    fn default() -> Self {
        Self {
            file_patterns: Vec::new(),
            tags: true,
        }
    }
}

impl ProtectionConfig {
    /// Whether `path` matches a protected glob. Invalid patterns are ignored.
    pub fn path_is_protected(&self, path: &str) -> bool {
        !path.is_empty()
            && self
                .file_patterns
                .iter()
                .filter_map(|p| glob::Pattern::new(p).ok())
                .any(|pattern| pattern.matches(path))
    }
}

#[cfg(test)]
mod protection_tests {
    use super::ProtectionConfig;

    #[test]
    fn protected_globs_match_paths_and_ignore_invalid_patterns() {
        let cfg = ProtectionConfig {
            file_patterns: vec![
                "docs/audits/**".into(),
                "*.secret.md".into(),
                "[invalid".into(),
            ],
            tags: true,
        };
        assert!(cfg.path_is_protected("docs/audits/q3/blockers.md"));
        assert!(cfg.path_is_protected("notes.secret.md"));
        assert!(!cfg.path_is_protected("src/main.rs"));
        assert!(!cfg.path_is_protected(""));

        let empty = ProtectionConfig::default();
        assert!(!empty.path_is_protected("docs/audits/q3/blockers.md"));
        assert!(empty.tags, "protect tags are honored by default");
    }
}
/// MCP decision-loop runtime settings (`[decision_loop]`).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DecisionLoopConfig {
    pub enabled: bool,
    /// Maximum lossy post-dispatch triage level (`0` disables output filtering).
    /// Classification and decision-loop accounting remain active at level 0.
    #[serde(default)]
    pub max_filter_level: u8,
}

impl Default for DecisionLoopConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_filter_level: 0,
        }
    }
}

/// One `[cost.prices.<model>]` row: USD per million tokens. Omitted cache
/// rates default to the input rate (the same convention the catalogs use).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct PriceOverride {
    pub input_per_m: Option<f64>,
    pub output_per_m: Option<f64>,
    pub cache_write_per_m: Option<f64>,
    pub cache_read_per_m: Option<f64>,
}

impl CostConfig {
    /// Configured pricing model for a client id: the per-client entry first, then
    /// the global default. `None` when neither is set (the caller then falls back
    /// to the env override / heuristic). Blank entries are ignored.
    pub fn model_for_client(&self, client: &str) -> Option<String> {
        self.models
            .get(client)
            .or(self.default_model.as_ref())
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
    }
}

/// Code-health engine (`[code_health]`): clean code as a token-cost lever.
///
/// Cognitive complexity, naming quality, and coupling are computed once during
/// indexing and surfaced at read- and edit-time. These switches tune the
/// thresholds and how assertively findings are surfaced.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CodeHealthConfig {
    /// Cognitive-complexity threshold above which a function is a hotspot.
    /// Mirrors `core::code_health::DEFAULT_COGNITIVE_THRESHOLD` (15).
    pub cognitive_threshold: u32,
    /// Edit-gate behavior on complexity drift: `"warn"` (annotate, default),
    /// `"block"` (refuse clean→over-threshold edits), or `"off"`.
    pub gate: String,
    /// Annotate over-threshold functions inline in `ctx_read` output.
    pub annotate_reads: bool,
    /// Run the naming-quality heuristic.
    pub naming: bool,
    /// Inject `[CODE HEALTH]` notices as `additionalContext` in PostToolUse stdout.
    /// Default: **false** — prevents prompt-cache invalidation on Anthropic models
    /// (#778: each injection causes 440-520k tokens of cache re-bills when Claude
    /// Code strips stale system-reminders retroactively).
    /// When false, notices route to `ctx_knowledge` + dashboard instead.
    #[serde(default)]
    pub inject_context: bool,
}

impl Default for CodeHealthConfig {
    fn default() -> Self {
        Self {
            cognitive_threshold: 15,
            gate: "warn".to_string(),
            annotate_reads: true,
            naming: true,
            inject_context: false,
        }
    }
}

/// Index-time file filters (#735): declare the retrieval corpus explicitly
/// instead of abusing `.gitignore` for retrieval policy.
///
/// Applies to every index builder through one shared filter layer
/// (`core::index_filter`): BM25, graph, and the watch/incremental path; the
/// semantic index chunks the BM25 corpus and inherits the same universe.
/// Excluded files never produce chunks, graph nodes, or embeddings. Globs are
/// matched against the root-relative path (forward slashes); exclude wins
/// over include. The empty default preserves today's behavior byte-for-byte.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct IndexConfig {
    /// Honor `.gitignore` / global gitignore / `.git/info/exclude` during
    /// index walks. `false` indexes ignored files too (rarely wanted; the
    /// vendor-directory guard still applies).
    pub respect_gitignore: bool,
    /// Files to drop from the index corpus, e.g. `["**/*.csv", "fixtures/**"]`.
    /// Evaluated after `include`; a file matching both is excluded.
    pub exclude: Vec<String>,
    /// When non-empty, ONLY matching files enter the index corpus, e.g.
    /// `["**/*.rs", "**/*.ts"]`. Empty = no restriction.
    pub include: Vec<String>,
}

impl Default for IndexConfig {
    fn default() -> Self {
        Self {
            respect_gitignore: true,
            exclude: Vec::new(),
            include: Vec::new(),
        }
    }
}

/// Skillify (#290): mine the project's session diary + knowledge facts into
/// versioned, git-committable `.cursor/rules/skillify-*.mdc` rule files.
///
/// The miner is precision-biased — it only codifies recurring or high-confidence
/// patterns and never invents content. Runs on demand (`ctx_skillify` /
/// `lean-ctx skillify`); re-running merges (bumps version) only when the distilled
/// content actually changes.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SkillifyConfig {
    /// Master switch for the skillify miner. On by default; the miner only ever
    /// acts when explicitly invoked, so this never writes files unprompted.
    pub enabled: bool,
    /// Where generated rules are written: `project` (`<repo>/.cursor/rules`,
    /// git-committable, default) or `global` (`~/.cursor/rules`).
    pub scope: String,
    /// Minimum confidence for a single curated knowledge fact to be codified even
    /// without repetition. 0.0..=1.0.
    pub min_confidence: f32,
    /// Minimum number of reinforcements (confirmations / repeated mentions) before
    /// a pattern is codified when its confidence is below `min_confidence`.
    pub min_recurrence: u32,
}

impl Default for SkillifyConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            scope: "project".to_string(),
            min_confidence: 0.7,
            min_recurrence: 2,
        }
    }
}

/// AI session summaries (#292): periodically distil the working session into a
/// compact, *semantically recallable* summary so a future session can answer
/// "what did I do last time on X?". Deterministic and local-first — recall uses
/// embeddings when the `embeddings` feature is on, else a lexical fallback.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SummariesConfig {
    /// Record periodic session summaries. On by default; recording is cheap and
    /// happens at most once per `every_n_turns` tool calls.
    pub enabled: bool,
    /// Tool calls between automatic summaries. The auto-checkpoint cadence still
    /// gates the check, so the effective minimum is the checkpoint interval.
    pub every_n_turns: u32,
    /// Maximum summaries kept per project (oldest pruned first).
    pub max_kept: u32,
}

impl Default for SummariesConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            every_n_turns: 25,
            max_kept: 100,
        }
    }
}

/// A user-defined command alias mapping for shell compression patterns.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AliasEntry {
    pub command: String,
    pub alias: String,
}

/// Thresholds for detecting and throttling repetitive agent tool call loops.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LoopDetectionConfig {
    pub normal_threshold: u32,
    pub reduced_threshold: u32,
    pub blocked_threshold: u32,
    pub window_secs: u64,
    pub search_group_limit: u32,
    pub tool_total_limits: HashMap<String, u32>,
}

impl Default for LoopDetectionConfig {
    fn default() -> Self {
        let mut tool_total_limits = HashMap::new();
        tool_total_limits.insert("ctx_read".to_string(), 100);
        tool_total_limits.insert("ctx_search".to_string(), 80);
        tool_total_limits.insert("ctx_shell".to_string(), 50);
        Self {
            normal_threshold: 2,
            reduced_threshold: 4,
            blocked_threshold: 0,
            window_secs: 300,
            search_group_limit: 10,
            tool_total_limits,
        }
    }
}

/// Semantic-embedding engine settings.
///
/// `model` selects which local embedding model lean-ctx downloads and uses for
/// `ctx_semantic_search`. Unset, it is `minilm` where ONNX Runtime is installed and
/// `potion-code` otherwise (see `model_registry::default_model`). Accepts the same
/// aliases as the `LEAN_CTX_EMBEDDING_MODEL` env var: `minilm` (all-MiniLM-L6-v2,
/// 384d), `potion-code` (potion-code-16M, 256d static, pure Rust), `nomic` (768d) — or any
/// HuggingFace repo with an ONNX export via `hf:org/repo[@revision]` (GL #397), e.g.
/// `hf:jinaai/jina-embeddings-v2-base-code` for code-specialized embeddings. When the
/// env var is set it takes precedence; an
/// unset/`None` value uses the default model. Switching models triggers a one-time
/// re-index on the next semantic search (vector dimensions follow from the model).
///
/// `dimensions` is only consulted for `hf:` custom models as the declared fallback
/// width; the real width is probed from the ONNX graph at load time. Built-ins ignore it.
/// `[gateway_server]` — deployment parameters of the self-hosted org gateway
/// (enterprise#20). Distinct from `[gateway]` (the MCP tool-catalog gateway):
/// this section describes the LLM-proxy *server* deployment and its cockpit.
///
/// All fields optional; an empty section keeps every local behavior unchanged.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct GatewayServerConfig {
    /// Seats the org-wide projection extrapolates to (e.g. `800`). `None`
    /// disables the projection — the cockpit never invents a seat count.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub seats: Option<u32>,
    /// Display label for the cockpit header (e.g. `"Zühlke AI Gateway"`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub org_label: Option<String>,
    /// Central admin API base URL (e.g. `https://ai-gateway.example.com`).
    /// When set, the local cockpit's usage breakdown reads the org-wide
    /// `GET /api/admin/usage` instead of the machine-local snapshot. The
    /// bearer token comes from `LEAN_CTX_GATEWAY_ADMIN_TOKEN` (never config).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub admin_url: Option<String>,
    /// Replace `person` with a stable keyed pseudonym (`p:<hash>`) before it
    /// reaches metering, budgets, dashboards and logs (enterprise#39, GDPR).
    /// The salt lives in `<data_dir>/gateway_pii_salt`; `gateway gdpr`
    /// re-derives pseudonyms from e-mail input, so DSGVO delete/export keep
    /// working. Default `false` (cleartext person tags).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pseudonymize_persons: Option<bool>,
    /// MCP upstream registry (GL#91/#99, Doc 15 §7 — the observe stage of MCP
    /// context governance). Each entry publishes a governed reverse-proxy
    /// route `/mcp/{id}` on the enterprise gateway server's port (the local
    /// proxy mounts no `/mcp/{id}` routes): same per-person key auth as the
    /// LLM channel, tool calls metered into `mcp_events`, tool definitions
    /// inventoried + hash-tracked (rug-pull detection). Observe-only: the
    /// gateway never blocks or rewrites MCP traffic in this stage.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub mcp_servers: Vec<McpServerEntry>,
}

/// One `[[gateway_server.mcp_servers]]` registry entry — an MCP server the org
/// gateway fronts. Distinct from `[[gateway.servers]]` (the *local* tool-
/// catalog aggregator, #210): this registry is the org-facing reverse proxy.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct McpServerEntry {
    /// Registry id, used in the `/mcp/{id}` route. Lowercase alphanumeric
    /// plus `-`/`_` (it becomes a URL path segment).
    pub id: String,
    /// Upstream Streamable-HTTP endpoint (the server's single MCP endpoint,
    /// e.g. `https://mcp.example.com/mcp`). HTTPS for any non-loopback host;
    /// plaintext HTTP needs the same explicit opt-in as LLM upstreams
    /// (`[proxy] allow_insecure_http_upstream`).
    pub url: String,
    /// Name of the environment variable holding the upstream credential. When
    /// set, the gateway sends `Authorization: Bearer <value>` upstream — the
    /// credential lives in the gateway's environment, never on laptops. The
    /// caller's own `Authorization` header (their gateway key) is **always**
    /// stripped before forwarding, with or without this field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth_env: Option<String>,
    /// Set `false` to keep the entry in config but take it out of service.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
}

/// A validated, ready-to-serve MCP registry entry (runtime view of
/// [`McpServerEntry`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedMcpServer {
    pub id: String,
    pub url: String,
    pub auth_env: Option<String>,
}

impl GatewayServerConfig {
    /// Validate + resolve the `[[gateway_server.mcp_servers]]` registry.
    /// Same resilience contract as `[[proxy.providers]]`: invalid entries are
    /// logged and skipped (one typo never takes the gateway down), duplicates
    /// keep the first occurrence. `allow_insecure_http` mirrors the proxy's
    /// plaintext-HTTP opt-in so the two registries share one security posture.
    #[must_use]
    pub fn resolve_mcp_servers(&self, allow_insecure_http: bool) -> Vec<ResolvedMcpServer> {
        let mut seen: std::collections::BTreeSet<&str> = std::collections::BTreeSet::new();
        let mut out = Vec::new();
        for entry in &self.mcp_servers {
            if !entry.enabled.unwrap_or(true) {
                continue;
            }
            let id = entry.id.trim();
            if !is_valid_mcp_server_id(id) {
                tracing::warn!(
                    "[gateway_server.mcp_servers] invalid id '{id}' \
                     (lowercase alnum/-/_ only) — entry skipped"
                );
                continue;
            }
            if !seen.insert(id) {
                tracing::warn!(
                    "[gateway_server.mcp_servers] duplicate id '{id}' — keeping first entry"
                );
                continue;
            }
            match validate_mcp_upstream_url(&entry.url, allow_insecure_http) {
                Ok(url) => out.push(ResolvedMcpServer {
                    id: id.to_string(),
                    url,
                    auth_env: entry
                        .auth_env
                        .as_deref()
                        .map(str::trim)
                        .filter(|v| !v.is_empty())
                        .map(str::to_string),
                }),
                Err(e) => {
                    tracing::warn!(
                        "[gateway_server.mcp_servers] '{id}' has invalid url — skipped: {e}"
                    );
                }
            }
        }
        out
    }
}

/// True when `id` is usable as an MCP registry id: non-empty, lowercase alnum
/// plus `-`/`_` (it becomes a URL path segment). Same shape rule as
/// `[[proxy.providers]]` ids; no built-in namespace exists to shadow here.
fn is_valid_mcp_server_id(id: &str) -> bool {
    !id.is_empty()
        && id
            .chars()
            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
}

/// Validates an MCP upstream URL. A declared registry entry is itself the
/// deliberate custom-host opt-in (same rationale as `[[proxy.providers]]`):
/// any HTTPS host is accepted; loopback HTTP is always fine; non-loopback
/// plaintext HTTP requires the explicit insecure-HTTP opt-in. This is the
/// SSRF boundary — the proxy only ever connects to URLs that passed here.
fn validate_mcp_upstream_url(url: &str, allow_insecure_http: bool) -> Result<String, String> {
    let trimmed = url.trim().trim_end_matches('/');
    if trimmed.is_empty() {
        return Err("empty url".into());
    }
    if crate::core::config::is_local_proxy_url(trimmed) {
        return Ok(trimmed.to_string());
    }
    if trimmed.starts_with("http://") {
        if allow_insecure_http {
            return Ok(trimmed.to_string());
        }
        return Err(format!(
            "MCP upstream must use HTTPS: {trimmed} (for a trusted local-network HTTP \
             upstream opt in with `[proxy] allow_insecure_http_upstream = true`)"
        ));
    }
    if trimmed.starts_with("https://") {
        return Ok(trimmed.to_string());
    }
    Err(format!(
        "MCP upstream must start with http:// or https://: {trimmed}"
    ))
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct EmbeddingConfig {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub dimensions: Option<usize>,
    /// Allow downloading the embedding model on first semantic need (#551).
    /// `None` (unset) means **allowed** — the soft default that activates the
    /// semantic features without manual setup. Set `false` for air-gapped
    /// machines. The `LEAN_CTX_EMBEDDINGS_AUTO_DOWNLOAD` env var, when set,
    /// overrides this in either direction.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auto_download: Option<bool>,
    /// Pin embedding inference to a single CPU thread (no GPU EP) so vectors are
    /// bit-identical across machines, not just run-to-run on one host (#895).
    /// `None`/`false` keeps the multi-threaded GPU-capable path. Extractive prose
    /// ranking is already deterministic via score quantization + stable tiebreak;
    /// this flag is the extra hardening for cross-machine reproducibility. The
    /// `LEAN_CTX_EMBEDDING_DETERMINISTIC` env var overrides this either way.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deterministic: Option<bool>,
}

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

    fn mcp_entry(id: &str, url: &str) -> McpServerEntry {
        McpServerEntry {
            id: id.into(),
            url: url.into(),
            auth_env: None,
            enabled: None,
        }
    }

    #[test]
    fn mcp_registry_validates_ids_urls_and_duplicates() {
        let cfg = GatewayServerConfig {
            mcp_servers: vec![
                mcp_entry("github", "https://mcp.example.com/mcp/"),
                // invalid id (uppercase) — skipped, never panics
                mcp_entry("GitHub", "https://mcp.example.com/mcp"),
                // duplicate — first occurrence wins
                mcp_entry("github", "https://other.example.com/mcp"),
                // plaintext HTTP on a non-loopback host without the opt-in — skipped
                mcp_entry("plain", "http://mcp.example.com/mcp"),
                // loopback HTTP is always fine (local/dev)
                mcp_entry("local", "http://127.0.0.1:9200/mcp"),
                McpServerEntry {
                    enabled: Some(false),
                    ..mcp_entry("disabled", "https://mcp.example.com/mcp")
                },
                McpServerEntry {
                    auth_env: Some("  GITHUB_MCP_PAT  ".into()),
                    ..mcp_entry("authed", "https://api.githubcopilot.com/mcp")
                },
            ],
            ..Default::default()
        };
        let resolved = cfg.resolve_mcp_servers(false);
        let ids: Vec<&str> = resolved.iter().map(|s| s.id.as_str()).collect();
        assert_eq!(ids, ["github", "local", "authed"]);
        // Trailing slash normalized; the duplicate kept the first URL.
        assert_eq!(resolved[0].url, "https://mcp.example.com/mcp");
        assert_eq!(resolved[2].auth_env.as_deref(), Some("GITHUB_MCP_PAT"));

        // The insecure-HTTP opt-in admits the plaintext entry (trusted LAN).
        let with_optin = cfg.resolve_mcp_servers(true);
        assert!(with_optin.iter().any(|s| s.id == "plain"));
    }

    #[test]
    fn mcp_upstream_url_rules_match_the_proxy_posture() {
        assert!(validate_mcp_upstream_url("https://mcp.example.com/mcp", false).is_ok());
        assert!(validate_mcp_upstream_url("http://localhost:9200/mcp", false).is_ok());
        assert!(validate_mcp_upstream_url("http://mcp.example.com/mcp", false).is_err());
        assert!(validate_mcp_upstream_url("http://mcp.example.com/mcp", true).is_ok());
        assert!(validate_mcp_upstream_url("ftp://mcp.example.com", false).is_err());
        assert!(validate_mcp_upstream_url("   ", false).is_err());
    }
}

#[cfg(test)]
mod ocla_tests {
    use super::OclaConfig;
    use serde::Deserialize;

    #[derive(Deserialize)]
    struct ConfigFile {
        ocla: OclaConfig,
    }

    /// Configs written for the removed sidecar/gRPC listeners keep loading.
    #[test]
    fn removed_listener_sections_are_ignored() {
        let config: ConfigFile = toml::from_str(
            r#"
                [ocla.sidecar]
                bind_addr = "127.0.0.1:9000"
                enabled = true
                [ocla.grpc]
                enabled = true
                listen = "127.0.0.1:60051"
                [ocla.delivery]
                max_entries = 7
            "#,
        )
        .expect("legacy OCLA config");
        assert_eq!(config.ocla.delivery.max_entries, 7);
        assert!(config.ocla.delivery.enabled);
    }
}

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

    #[test]
    fn telemetry_config_defaults_on_and_send_eligible() {
        let cfg = TelemetryConfig::default();
        assert!(cfg.enabled);
        assert_eq!(cfg.preference, TelemetryPreference::DefaultOn);
        assert!(cfg.send_eligible(None, None));
        assert!(cfg.last_heartbeat.is_none());
    }

    #[test]
    fn telemetry_config_serde_roundtrip() {
        let toml_str = r#"
[telemetry]
enabled = true
last_heartbeat = "2026-07-30"
"#;
        #[derive(serde::Deserialize)]
        struct Wrap {
            telemetry: TelemetryConfig,
        }
        let wrap: Wrap = toml::from_str(toml_str).expect("parse telemetry config");
        assert!(wrap.telemetry.enabled);
        assert_eq!(wrap.telemetry.preference, TelemetryPreference::DefaultOn);
        assert_eq!(wrap.telemetry.last_heartbeat.as_deref(), Some("2026-07-30"));
    }

    #[test]
    fn a_retired_notice_key_in_an_existing_config_still_parses() {
        let cfg: TelemetryConfig =
            toml::from_str("enabled = true\nnotice_shown = false").expect("pre-removal config");
        assert!(cfg.send_eligible(None, None));
    }

    #[test]
    fn telemetry_config_missing_section_uses_defaults() {
        let toml_str = "";
        #[derive(serde::Deserialize, Default)]
        #[serde(default)]
        struct Wrap {
            telemetry: TelemetryConfig,
        }
        let wrap: Wrap = toml::from_str(toml_str).expect("parse empty config");
        assert!(wrap.telemetry.enabled);
        assert_eq!(wrap.telemetry.preference, TelemetryPreference::DefaultOn);
        assert!(wrap.telemetry.last_heartbeat.is_none());
    }

    #[test]
    fn legacy_false_remains_an_explicit_opt_out() {
        let cfg: TelemetryConfig = toml::from_str("enabled = false").expect("legacy config");
        assert!(cfg.explicitly_disabled());
    }

    #[test]
    fn send_honors_the_explicit_and_both_environment_opt_outs() {
        let mut cfg = TelemetryConfig::default();
        assert!(cfg.send_eligible(None, None));
        assert!(!cfg.send_eligible(Some("1"), None));
        assert!(!cfg.send_eligible(None, Some("OFF")));
        cfg.preference = TelemetryPreference::ExplicitlyDisabled;
        assert!(!cfg.send_eligible(None, None));
    }
}