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
use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct MemoryPolicy {
    pub knowledge: KnowledgePolicy,
    pub episodic: EpisodicPolicy,
    pub procedural: ProceduralPolicy,
    pub lifecycle: LifecyclePolicy,
    pub embeddings: EmbeddingsPolicy,
    pub gotcha: GotchaPolicy,
    pub admission: AdmissionPolicy,
    pub compaction: CompactionPolicy,
}

impl MemoryPolicy {
    pub fn apply_env_overrides(&mut self) {
        self.knowledge.apply_env_overrides();
        self.lifecycle.apply_env_overrides();
        self.embeddings.apply_env_overrides();
        self.gotcha.apply_env_overrides();
        self.admission.apply_env_overrides();
    }

    pub fn apply_overrides(&mut self, o: &MemoryPolicyOverrides) {
        self.knowledge.apply_overrides(&o.knowledge);
        self.lifecycle.apply_overrides(&o.lifecycle);
    }

    pub fn validate(&self) -> Result<(), String> {
        self.knowledge.validate()?;
        self.lifecycle.validate()?;
        self.embeddings.validate()?;
        self.gotcha.validate()?;
        self.admission.validate()?;
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct MemoryPolicyOverrides {
    pub knowledge: KnowledgePolicyOverrides,
    pub lifecycle: LifecyclePolicyOverrides,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct KnowledgePolicyOverrides {
    // A profile's `max_facts` (removed fact cap) is an unknown key here and
    // skipped by serde; see `KnowledgePolicy::max_facts`.
    pub max_patterns: Option<usize>,
    pub max_history: Option<usize>,
    pub contradiction_threshold: Option<f32>,
    pub recall_facts_limit: Option<usize>,
    pub rooms_limit: Option<usize>,
    pub timeline_limit: Option<usize>,
    pub relations_limit: Option<usize>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct LifecyclePolicyOverrides {
    pub decay_rate: Option<f32>,
    pub low_confidence_threshold: Option<f32>,
    pub stale_days: Option<i64>,
    pub similarity_threshold: Option<f32>,
    pub forgetting_model: Option<String>,
    pub base_stability_days: Option<f32>,
    pub archetype_aware_decay: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct KnowledgePolicy {
    /// Deprecated and ignored (3.12.1): knowledge has no fact limit (owner
    /// decision 2026-10-24). Kept only so an existing `max_facts` in a
    /// config.toml still loads and round-trips; nothing reads it. Facts leave
    /// the active store by quality alone (decay, near-duplicate merge,
    /// low-confidence/stale archival), never by count.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_facts: Option<usize>,
    pub max_patterns: usize,
    pub max_history: usize,
    pub contradiction_threshold: f32,
    /// Maximum number of facts returned by recall operations.
    pub recall_facts_limit: usize,
    /// Maximum number of rooms returned by `ctx_knowledge action=rooms`.
    pub rooms_limit: usize,
    /// Maximum number of timeline entries returned by `ctx_knowledge action=timeline`.
    pub timeline_limit: usize,
    /// Maximum number of relations/edges returned by relations queries/diagrams.
    pub relations_limit: usize,
}

impl Default for KnowledgePolicy {
    fn default() -> Self {
        Self {
            max_facts: None,
            max_patterns: 50,
            max_history: 100,
            contradiction_threshold: 0.5,
            recall_facts_limit: crate::core::budgets::KNOWLEDGE_RECALL_FACTS_LIMIT,
            rooms_limit: crate::core::budgets::KNOWLEDGE_ROOMS_LIMIT,
            timeline_limit: crate::core::budgets::KNOWLEDGE_TIMELINE_LIMIT,
            relations_limit: 40,
        }
    }
}

impl KnowledgePolicy {
    fn apply_env_overrides(&mut self) {
        // `LEAN_CTX_KNOWLEDGE_MAX_FACTS` is ignored: knowledge has no fact limit.
        if let Ok(v) = std::env::var("LEAN_CTX_KNOWLEDGE_MAX_PATTERNS")
            && let Ok(n) = v.parse()
        {
            self.max_patterns = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_KNOWLEDGE_MAX_HISTORY")
            && let Ok(n) = v.parse()
        {
            self.max_history = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_KNOWLEDGE_CONTRADICTION_THRESHOLD")
            && let Ok(n) = v.parse()
        {
            self.contradiction_threshold = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_KNOWLEDGE_RECALL_FACTS_LIMIT")
            && let Ok(n) = v.parse()
        {
            self.recall_facts_limit = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_KNOWLEDGE_ROOMS_LIMIT")
            && let Ok(n) = v.parse()
        {
            self.rooms_limit = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_KNOWLEDGE_TIMELINE_LIMIT")
            && let Ok(n) = v.parse()
        {
            self.timeline_limit = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_KNOWLEDGE_RELATIONS_LIMIT")
            && let Ok(n) = v.parse()
        {
            self.relations_limit = n;
        }
    }

    fn validate(&self) -> Result<(), String> {
        // `max_facts` is ignored, so any value (0 included) is accepted.
        if self.max_patterns == 0 {
            return Err("memory.knowledge.max_patterns must be > 0".to_string());
        }
        if self.max_history == 0 {
            return Err("memory.knowledge.max_history must be > 0".to_string());
        }
        if !(0.0..=1.0).contains(&self.contradiction_threshold) {
            return Err(
                "memory.knowledge.contradiction_threshold must be in [0.0, 1.0]".to_string(),
            );
        }
        if self.recall_facts_limit == 0 {
            return Err("memory.knowledge.recall_facts_limit must be > 0".to_string());
        }
        if self.rooms_limit == 0 {
            return Err("memory.knowledge.rooms_limit must be > 0".to_string());
        }
        if self.timeline_limit == 0 {
            return Err("memory.knowledge.timeline_limit must be > 0".to_string());
        }
        if self.relations_limit == 0 {
            return Err("memory.knowledge.relations_limit must be > 0".to_string());
        }
        Ok(())
    }

    fn apply_overrides(&mut self, o: &KnowledgePolicyOverrides) {
        if let Some(v) = o.max_patterns {
            self.max_patterns = v;
        }
        if let Some(v) = o.max_history {
            self.max_history = v;
        }
        if let Some(v) = o.contradiction_threshold {
            self.contradiction_threshold = v;
        }
        if let Some(v) = o.recall_facts_limit {
            self.recall_facts_limit = v;
        }
        if let Some(v) = o.rooms_limit {
            self.rooms_limit = v;
        }
        if let Some(v) = o.timeline_limit {
            self.timeline_limit = v;
        }
        if let Some(v) = o.relations_limit {
            self.relations_limit = v;
        }
    }
}

/// `[memory.episodic]`: no effect. The episode memory is retired
/// (DEPRECATIONS.toml `config-memory-episodic-procedural`); the section stays
/// accepted, unvalidated, so existing configs keep loading. Its
/// `LEAN_CTX_EPISODIC_*` environment variables are ignored.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct EpisodicPolicy {
    pub max_episodes: usize,
    pub max_actions_per_episode: usize,
    pub summary_max_chars: usize,
}

impl Default for EpisodicPolicy {
    fn default() -> Self {
        Self {
            max_episodes: 500,
            max_actions_per_episode: 50,
            summary_max_chars: 200,
        }
    }
}

/// `[memory.procedural]`: no effect. The procedure memory is retired
/// (DEPRECATIONS.toml `config-memory-episodic-procedural`); the section stays
/// accepted, unvalidated, so existing configs keep loading. Its
/// `LEAN_CTX_PROCEDURAL_*` environment variables are ignored.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ProceduralPolicy {
    pub min_repetitions: usize,
    pub min_sequence_len: usize,
    pub max_procedures: usize,
    pub max_window_size: usize,
}

impl Default for ProceduralPolicy {
    fn default() -> Self {
        Self {
            min_repetitions: 3,
            min_sequence_len: 2,
            max_procedures: 100,
            max_window_size: 10,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LifecyclePolicy {
    pub decay_rate: f32,
    pub low_confidence_threshold: f32,
    pub stale_days: i64,
    pub similarity_threshold: f32,
    /// Forgetting curve (#1): `ebbinghaus` (default) or `linear` (legacy).
    pub forgetting_model: String,
    /// Characteristic memory stability in days for the Ebbinghaus curve.
    pub base_stability_days: f32,
    /// Scale Ebbinghaus stability by fact archetype so structural evidence decays
    /// slower than inference. Default false keeps the baseline tuning unchanged.
    pub archetype_aware_decay: bool,
    /// Archive single-confirmation facts untouched for this many days that were
    /// never retrieved — dead weight regardless of confidence (#962). Defaults to
    /// a conservative 90 days (#972): genuinely cold facts are archived (and
    /// rehydrate on recall), so a store self-curates instead of only churning at
    /// its cap. Set `None`/`off` to disable.
    pub prune_unretrieved_after_days: Option<i64>,
    /// Proactive headroom on a capacity reclaim (#995): when a store reaches its
    /// cap, settle it at `1 - reclaim_headroom_pct` (e.g. `0.25` → 75%) instead
    /// of churning right at the cap. Lossless — the reclaimed tail is archived
    /// and restorable.
    pub reclaim_headroom_pct: f32,
    /// Master switch for the proactive reclaim (#995). `false` is the documented
    /// escape hatch: trim only the overflow, no headroom. Eviction stays lossless
    /// either way.
    pub reclaim_enabled: bool,
}

impl Default for LifecyclePolicy {
    fn default() -> Self {
        Self {
            decay_rate: 0.01,
            low_confidence_threshold: 0.3,
            stale_days: 30,
            similarity_threshold: 0.85,
            forgetting_model: "ebbinghaus".to_string(),
            base_stability_days: crate::core::memory_lifecycle::DEFAULT_BASE_STABILITY_DAYS,
            archetype_aware_decay: false,
            prune_unretrieved_after_days: Some(90),
            reclaim_headroom_pct: crate::core::memory_lifecycle::DEFAULT_RECLAIM_HEADROOM_PCT,
            reclaim_enabled: true,
        }
    }
}

impl LifecyclePolicy {
    fn apply_env_overrides(&mut self) {
        if let Ok(v) = std::env::var("LEAN_CTX_LIFECYCLE_DECAY_RATE")
            && let Ok(n) = v.parse()
        {
            self.decay_rate = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_LIFECYCLE_LOW_CONFIDENCE_THRESHOLD")
            && let Ok(n) = v.parse()
        {
            self.low_confidence_threshold = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_LIFECYCLE_STALE_DAYS")
            && let Ok(n) = v.parse()
        {
            self.stale_days = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_LIFECYCLE_SIMILARITY_THRESHOLD")
            && let Ok(n) = v.parse()
        {
            self.similarity_threshold = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_LIFECYCLE_FORGETTING") {
            self.forgetting_model = v;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_LIFECYCLE_BASE_STABILITY_DAYS")
            && let Ok(n) = v.parse()
        {
            self.base_stability_days = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_LIFECYCLE_ARCHETYPE_AWARE") {
            self.archetype_aware_decay = v == "1" || v.eq_ignore_ascii_case("true");
        }
        if let Ok(v) = std::env::var("LEAN_CTX_LIFECYCLE_PRUNE_UNRETRIEVED_DAYS") {
            self.prune_unretrieved_after_days = match v.trim().to_lowercase().as_str() {
                "" | "off" | "none" | "0" => None,
                s => s.parse::<i64>().ok().filter(|&n| n > 0),
            };
        }
        if let Ok(v) = std::env::var("LEAN_CTX_LIFECYCLE_RECLAIM_HEADROOM_PCT")
            && let Ok(n) = v.parse()
        {
            self.reclaim_headroom_pct = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_LIFECYCLE_RECLAIM_ENABLED") {
            self.reclaim_enabled = !(v == "0" || v.eq_ignore_ascii_case("false"));
        }
    }

    fn validate(&self) -> Result<(), String> {
        if !(0.0..=1.0).contains(&self.decay_rate) {
            return Err("memory.lifecycle.decay_rate must be in [0.0, 1.0]".to_string());
        }
        if !(0.0..=1.0).contains(&self.low_confidence_threshold) {
            return Err(
                "memory.lifecycle.low_confidence_threshold must be in [0.0, 1.0]".to_string(),
            );
        }
        if self.stale_days < 0 {
            return Err("memory.lifecycle.stale_days must be >= 0".to_string());
        }
        if !(0.0..=1.0).contains(&self.similarity_threshold) {
            return Err("memory.lifecycle.similarity_threshold must be in [0.0, 1.0]".to_string());
        }
        if self.base_stability_days <= 0.0 {
            return Err("memory.lifecycle.base_stability_days must be > 0".to_string());
        }
        if !(0.0..=0.95).contains(&self.reclaim_headroom_pct) {
            return Err("memory.lifecycle.reclaim_headroom_pct must be in [0.0, 0.95]".to_string());
        }
        Ok(())
    }

    fn apply_overrides(&mut self, o: &LifecyclePolicyOverrides) {
        if let Some(v) = o.decay_rate {
            self.decay_rate = v;
        }
        if let Some(v) = o.low_confidence_threshold {
            self.low_confidence_threshold = v;
        }
        if let Some(v) = o.stale_days {
            self.stale_days = v;
        }
        if let Some(v) = o.similarity_threshold {
            self.similarity_threshold = v;
        }
        if let Some(ref v) = o.forgetting_model {
            self.forgetting_model.clone_from(v);
        }
        if let Some(v) = o.base_stability_days {
            self.base_stability_days = v;
        }
        if let Some(v) = o.archetype_aware_decay {
            self.archetype_aware_decay = v;
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct EmbeddingsPolicy {
    pub max_facts: usize,
}

impl Default for EmbeddingsPolicy {
    fn default() -> Self {
        Self { max_facts: 2000 }
    }
}

impl EmbeddingsPolicy {
    fn apply_env_overrides(&mut self) {
        if let Ok(v) = std::env::var("LEAN_CTX_KNOWLEDGE_EMBEDDINGS_MAX_FACTS")
            && let Ok(n) = v.parse()
        {
            self.max_facts = n;
        }
    }

    fn validate(&self) -> Result<(), String> {
        if self.max_facts == 0 {
            return Err("memory.embeddings.max_facts must be > 0".to_string());
        }
        Ok(())
    }
}

/// Gotcha store bounds (`[memory.gotcha]`).
///
/// Decay follows each gotcha's provenance (promoted, agent-reported,
/// correlated, auto-detected), so the former `default_decay_rate`,
/// `category_decay_overrides`, `retrieval_budget_per_room` and
/// `auto_expire_days` keys were never applied; they are retired
/// (`config::retired`) and ignored when an older config loads.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct GotchaPolicy {
    /// Most gotchas kept per project; the lowest-confidence ones are dropped
    /// first. Env: `LEAN_CTX_GOTCHA_MAX_PER_PROJECT`.
    pub max_gotchas_per_project: usize,
}

impl Default for GotchaPolicy {
    fn default() -> Self {
        Self {
            max_gotchas_per_project: 100,
        }
    }
}

impl GotchaPolicy {
    fn apply_env_overrides(&mut self) {
        if let Ok(v) = std::env::var("LEAN_CTX_GOTCHA_MAX_PER_PROJECT")
            && let Ok(n) = v.parse()
        {
            self.max_gotchas_per_project = n;
        }
    }

    fn validate(&self) -> Result<(), String> {
        if self.max_gotchas_per_project == 0 {
            return Err("memory.gotcha.max_gotchas_per_project must be > 0".to_string());
        }
        Ok(())
    }
}

/// Write-time admission control for the knowledge store (#970). The cap +
/// importance-eviction is a backstop *after* the fact is written; admission is
/// the boundary *before* it, so a capped store fills with signal, not noise.
/// Applied only to direct `ctx_knowledge remember` (the agent-facing path);
/// internal restorers (archive rehydrate, cognition auto-promotion) bypass it.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AdmissionPolicy {
    /// Master switch for write-time admission. When off, every `remember`
    /// inserts as before (legacy behavior).
    pub enabled: bool,
    /// A new fact whose value is at least this similar (word-Jaccard, 0.0–1.0) to
    /// an existing *current* fact in the **same category** under a different key
    /// is merged into it (a confirmation bump) instead of inserted as a new row.
    /// High by default so only genuine near-duplicates collapse; `0.0` disables
    /// auto-merge.
    pub auto_merge_similarity: f32,
    /// Facts whose content salience (`crate::core::memory_salience::text_salience`)
    /// is below this floor are not admitted as normal facts. `0` (default)
    /// disables the floor — the lossless choice; raise it to curate a noisy store.
    pub min_salience: u32,
}

impl Default for AdmissionPolicy {
    fn default() -> Self {
        Self {
            enabled: true,
            auto_merge_similarity: 0.9,
            min_salience: 0,
        }
    }
}

impl AdmissionPolicy {
    fn apply_env_overrides(&mut self) {
        if let Ok(v) = std::env::var("LEAN_CTX_ADMISSION_ENABLED") {
            self.enabled = !(v == "0" || v.eq_ignore_ascii_case("false"));
        }
        if let Ok(v) = std::env::var("LEAN_CTX_ADMISSION_MERGE_SIMILARITY")
            && let Ok(n) = v.parse()
        {
            self.auto_merge_similarity = n;
        }
        if let Ok(v) = std::env::var("LEAN_CTX_ADMISSION_MIN_SALIENCE")
            && let Ok(n) = v.parse()
        {
            self.min_salience = n;
        }
    }

    fn validate(&self) -> Result<(), String> {
        if !(0.0..=1.0).contains(&self.auto_merge_similarity) {
            return Err("memory.admission.auto_merge_similarity must be in [0.0, 1.0]".to_string());
        }
        Ok(())
    }
}

/// `[memory.compaction]`: no effect. Cluster compaction (#971) ran only in the
/// retired cognition loop (DEPRECATIONS.toml `config-memory-compaction`); the
/// section stays accepted, unvalidated, so existing configs keep loading.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CompactionPolicy {
    pub enabled: bool,
    pub min_cluster: usize,
    pub similarity: f32,
    pub max_confidence: f32,
    pub max_confirmations: u32,
}

impl Default for CompactionPolicy {
    fn default() -> Self {
        Self {
            enabled: true,
            min_cluster: 4,
            similarity: 0.5,
            max_confidence: 0.5,
            max_confirmations: 1,
        }
    }
}

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

    fn restore_env(key: &str, prev: Option<String>) {
        match prev {
            Some(v) => crate::test_env::set_var(key, v),
            None => crate::test_env::remove_var(key),
        }
    }

    #[test]
    fn default_policy_is_valid() {
        let p = MemoryPolicy::default();
        p.validate().expect("default policy must be valid");
    }

    #[test]
    fn memory_discipline_defaults_are_premium() {
        // #970/#971/#972: self-curation is on by default, but lossless.
        let p = MemoryPolicy::default();
        assert!(p.admission.enabled, "admission on by default");
        assert_eq!(p.admission.min_salience, 0, "salience floor off (lossless)");
        assert_eq!(
            p.lifecycle.prune_unretrieved_after_days,
            Some(90),
            "conservative recoverable prune default"
        );
    }

    #[test]
    fn admission_env_overrides_apply() {
        let _lock = crate::core::data_dir::test_env_lock();

        let prev = [
            (
                "LEAN_CTX_ADMISSION_ENABLED",
                std::env::var("LEAN_CTX_ADMISSION_ENABLED").ok(),
            ),
            (
                "LEAN_CTX_ADMISSION_MIN_SALIENCE",
                std::env::var("LEAN_CTX_ADMISSION_MIN_SALIENCE").ok(),
            ),
        ];
        crate::test_env::set_var("LEAN_CTX_ADMISSION_ENABLED", "0");
        crate::test_env::set_var("LEAN_CTX_ADMISSION_MIN_SALIENCE", "42");

        let mut p = MemoryPolicy::default();
        p.apply_env_overrides();

        assert!(!p.admission.enabled);
        assert_eq!(p.admission.min_salience, 42);

        for (key, val) in prev {
            restore_env(key, val);
        }
    }

    #[test]
    fn validate_rejects_invalid_admission() {
        let mut p = MemoryPolicy::default();
        p.admission.auto_merge_similarity = 1.5;
        assert!(p.validate().is_err());
    }

    #[test]
    fn retired_compaction_section_still_loads_and_validates() {
        let p: MemoryPolicy =
            toml::from_str("[compaction]\nenabled = true\nmin_cluster = 1\nsimilarity = 2.0\n")
                .expect("a retired [compaction] section must keep loading");
        assert_eq!(p.compaction.min_cluster, 1);
        p.validate()
            .expect("a retired [compaction] section is not validated");
    }

    #[test]
    fn env_overrides_apply() {
        let _lock = crate::core::data_dir::test_env_lock();

        let prev_facts = std::env::var("LEAN_CTX_KNOWLEDGE_MAX_FACTS").ok();
        let prev_stale = std::env::var("LEAN_CTX_LIFECYCLE_STALE_DAYS").ok();
        let prev_rep = std::env::var("LEAN_CTX_PROCEDURAL_MIN_REPETITIONS").ok();
        let prev_eps = std::env::var("LEAN_CTX_EPISODIC_MAX_EPISODES").ok();

        crate::test_env::set_var("LEAN_CTX_KNOWLEDGE_MAX_FACTS", "123");
        crate::test_env::set_var("LEAN_CTX_LIFECYCLE_STALE_DAYS", "7");
        crate::test_env::set_var("LEAN_CTX_PROCEDURAL_MIN_REPETITIONS", "4");
        crate::test_env::set_var("LEAN_CTX_EPISODIC_MAX_EPISODES", "7");

        let mut p = MemoryPolicy::default();
        p.apply_env_overrides();

        // The fact cap is gone: its env var no longer sets anything.
        assert_eq!(p.knowledge.max_facts, None);
        assert_eq!(p.lifecycle.stale_days, 7);
        // The episode and procedure memory is retired: their env vars are ignored.
        assert_eq!(p.procedural.min_repetitions, 3);
        assert_eq!(p.episodic.max_episodes, 500);

        restore_env("LEAN_CTX_KNOWLEDGE_MAX_FACTS", prev_facts);
        restore_env("LEAN_CTX_LIFECYCLE_STALE_DAYS", prev_stale);
        restore_env("LEAN_CTX_PROCEDURAL_MIN_REPETITIONS", prev_rep);
        restore_env("LEAN_CTX_EPISODIC_MAX_EPISODES", prev_eps);
    }

    #[test]
    fn validate_rejects_invalid_values() {
        let mut p = MemoryPolicy::default();
        p.knowledge.max_patterns = 0;
        assert!(p.validate().is_err());

        // The ignored fact cap never fails validation, even at 0.
        let mut p = MemoryPolicy::default();
        p.knowledge.max_facts = Some(0);
        assert!(p.validate().is_ok());

        let mut p = MemoryPolicy::default();
        p.lifecycle.decay_rate = 2.0;
        assert!(p.validate().is_err());
    }

    #[test]
    fn retired_episodic_and_procedural_sections_still_load_and_validate() {
        let p: MemoryPolicy = toml::from_str(
            "[episodic]\nmax_episodes = 0\n[procedural]\nmin_sequence_len = 1\nmax_procedures = 0\n",
        )
        .expect("retired [episodic]/[procedural] sections must keep loading");
        assert_eq!(p.episodic.max_episodes, 0);
        assert_eq!(p.procedural.min_sequence_len, 1);
        p.validate()
            .expect("retired [episodic]/[procedural] sections are not validated");
    }
}