Skip to main content

lean_ctx/core/
memory_lifecycle.rs

1//! Memory Lifecycle Management — consolidation, decay, compaction, archival.
2//!
3//! Runs automatically on knowledge stores to keep memory healthy:
4//! - Confidence decay over time
5//! - Semantic consolidation of similar facts
6//! - Compaction when limits are exceeded
7//! - Archival of old/unused facts
8
9use chrono::{DateTime, Duration, Utc};
10use std::path::PathBuf;
11
12use super::knowledge::KnowledgeFact;
13use super::memory_archive::{ArchiveConfig, MemoryStore};
14
15const DEFAULT_DECAY_RATE: f32 = 0.01;
16const DEFAULT_MAX_FACTS: usize = 1000;
17const LOW_CONFIDENCE_THRESHOLD: f32 = 0.3;
18const STALE_DAYS: i64 = 30;
19/// Default proactive headroom on a capacity reclaim: settle a full store at 75%
20/// so it keeps real working room instead of churning at its cap.
21pub const DEFAULT_RECLAIM_HEADROOM_PCT: f32 = 0.25;
22
23/// Spacing/testing effect: how strongly each prior retrieval lengthens memory
24/// stability. 0.5 ⇒ ~10 retrievals make a fact roughly 6× more durable.
25const SPACING_GAIN: f32 = 0.5;
26/// Floor on derived stability (days) so even a heavily down-voted fact decays
27/// smoothly rather than collapsing in a single pass.
28const MIN_STABILITY_DAYS: f32 = 1.0;
29/// Confidence never decays below this — archival happens elsewhere, decay never
30/// hard-deletes.
31const CONFIDENCE_FLOOR: f32 = 0.05;
32/// Default characteristic memory stability (days) for the Ebbinghaus curve.
33pub const DEFAULT_BASE_STABILITY_DAYS: f32 = 90.0;
34
35/// Which forgetting curve drives confidence decay (#1).
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
37pub enum ForgettingModel {
38    /// Exponential retention `R = exp(-Δt / S)` with spacing-boosted stability
39    /// `S` (Ebbinghaus forgetting curve + SM-2 spacing). Deterministic, the
40    /// default: durable memories fade gracefully, rehearsed ones persist.
41    #[default]
42    Ebbinghaus,
43    /// Legacy linear subtraction, kept for reproducibility / explicit opt-out.
44    Linear,
45}
46
47impl ForgettingModel {
48    pub fn parse(s: &str) -> Self {
49        match s.trim().to_lowercase().as_str() {
50            "linear" => Self::Linear,
51            _ => Self::Ebbinghaus,
52        }
53    }
54
55    pub fn as_str(self) -> &'static str {
56        match self {
57            Self::Ebbinghaus => "ebbinghaus",
58            Self::Linear => "linear",
59        }
60    }
61}
62
63#[derive(Debug, Clone)]
64pub struct LifecycleConfig {
65    pub decay_rate_per_day: f32,
66    pub max_facts: usize,
67    pub low_confidence_threshold: f32,
68    pub stale_days: i64,
69    pub consolidation_similarity: f32,
70    /// Forgetting curve (#1). Defaults to Ebbinghaus.
71    pub forgetting_model: ForgettingModel,
72    /// Characteristic stability (days) for the Ebbinghaus curve before spacing
73    /// and feedback modulation.
74    pub base_stability_days: f32,
75    /// When true, scale stability by the fact's archetype so structural *evidence*
76    /// (architecture/dependency/…) decays slower than *inference* (#802/cognition).
77    /// Default false keeps the baseline tuning byte-for-byte.
78    pub archetype_aware_decay: bool,
79    /// Archive facts untouched for this many days that were **never** retrieved —
80    /// dead weight that costs injection tokens regardless of confidence (#962).
81    /// `None` disables it (the default, so existing tuning is unchanged); the
82    /// production policy can opt in. Reversible: pruned facts go to the archive.
83    pub prune_unretrieved_after_days: Option<i64>,
84    /// Proactive headroom on a capacity reclaim (#995): when a store reaches its
85    /// cap, drop down to `reclaim_target(max_facts, reclaim_headroom_pct)` so it
86    /// settles with working room instead of churning at the cap. `0.25` = 75%.
87    pub reclaim_headroom_pct: f32,
88    /// Master switch for the proactive capacity reclaim (#995). `false` restores
89    /// the legacy "trim only the overflow" behavior — the documented escape
90    /// hatch. Eviction stays lossless either way (excess is archived).
91    pub reclaim_enabled: bool,
92}
93
94impl Default for LifecycleConfig {
95    fn default() -> Self {
96        Self {
97            decay_rate_per_day: DEFAULT_DECAY_RATE,
98            max_facts: DEFAULT_MAX_FACTS,
99            low_confidence_threshold: LOW_CONFIDENCE_THRESHOLD,
100            stale_days: STALE_DAYS,
101            consolidation_similarity: 0.85,
102            forgetting_model: ForgettingModel::default(),
103            base_stability_days: DEFAULT_BASE_STABILITY_DAYS,
104            archetype_aware_decay: false,
105            prune_unretrieved_after_days: None,
106            reclaim_headroom_pct: DEFAULT_RECLAIM_HEADROOM_PCT,
107            reclaim_enabled: true,
108        }
109    }
110}
111
112impl LifecycleConfig {
113    /// Map the persisted [`crate::core::memory_policy::MemoryPolicy`] to the
114    /// runtime lifecycle config. The single mapping site, so adding a knob
115    /// touches exactly one place (previously duplicated across the lifecycle and
116    /// cognition callers).
117    pub fn from_policy(policy: &crate::core::memory_policy::MemoryPolicy) -> Self {
118        Self {
119            max_facts: policy.knowledge.max_facts,
120            decay_rate_per_day: policy.lifecycle.decay_rate,
121            low_confidence_threshold: policy.lifecycle.low_confidence_threshold,
122            stale_days: policy.lifecycle.stale_days,
123            consolidation_similarity: policy.lifecycle.similarity_threshold,
124            forgetting_model: ForgettingModel::parse(&policy.lifecycle.forgetting_model),
125            base_stability_days: policy.lifecycle.base_stability_days,
126            archetype_aware_decay: policy.lifecycle.archetype_aware_decay,
127            prune_unretrieved_after_days: policy.lifecycle.prune_unretrieved_after_days,
128            reclaim_headroom_pct: policy.lifecycle.reclaim_headroom_pct,
129            reclaim_enabled: policy.lifecycle.reclaim_enabled,
130        }
131    }
132}
133
134#[derive(Debug, Default)]
135pub struct LifecycleReport {
136    pub decayed_count: usize,
137    pub consolidated_count: usize,
138    pub archived_count: usize,
139    pub compacted_count: usize,
140    /// Of `archived_count`, how many facts were evicted purely for capacity
141    /// (the proactive reclaim) versus quality (low-confidence/stale/unretrieved).
142    /// Lets callers report per-store capacity reclaim distinctly (#995).
143    pub capacity_archived: usize,
144    pub remaining_facts: usize,
145}
146
147pub fn apply_confidence_decay(facts: &mut [KnowledgeFact], config: &LifecycleConfig) -> usize {
148    let now = Utc::now();
149    let mut count = 0;
150
151    for fact in facts.iter_mut() {
152        if !fact.is_current() {
153            continue;
154        }
155
156        if let Some(valid_until) = fact.valid_until
157            && valid_until < now
158            && fact.confidence > 0.1
159        {
160            fact.confidence = 0.1;
161            count += 1;
162            continue;
163        }
164
165        let days_since_confirmed = now.signed_duration_since(fact.last_confirmed).num_days() as f32;
166        if days_since_confirmed <= 0.0 {
167            continue;
168        }
169        let days_since_retrieved = fact
170            .last_retrieved
171            .map_or(3650.0, |t| now.signed_duration_since(t).num_days() as f32);
172        let retrieval_count = fact.retrieval_count as f32;
173        let net_feedback = i64::from(fact.feedback_up) - i64::from(fact.feedback_down);
174
175        // Archetype-aware stability (opt-in): structural evidence is more durable
176        // than inference. Off by default → identical to the prior baseline.
177        let base_stability = if config.archetype_aware_decay {
178            config.base_stability_days * fact.archetype.stability_multiplier()
179        } else {
180            config.base_stability_days
181        };
182
183        let new_confidence = match config.forgetting_model {
184            ForgettingModel::Ebbinghaus => ebbinghaus_confidence(
185                fact.confidence,
186                days_since_confirmed,
187                days_since_retrieved,
188                retrieval_count,
189                net_feedback,
190                base_stability,
191            ),
192            ForgettingModel::Linear => linear_confidence(
193                fact.confidence,
194                days_since_confirmed,
195                days_since_retrieved,
196                retrieval_count,
197                net_feedback,
198                config.decay_rate_per_day,
199            ),
200        };
201        if (new_confidence - fact.confidence).abs() > 0.001 {
202            fact.confidence = new_confidence;
203            count += 1;
204        }
205    }
206
207    if count > 0 && config.forgetting_model == ForgettingModel::Ebbinghaus {
208        crate::core::introspect::tick("power_law_decay");
209    }
210    count
211}
212
213/// Ebbinghaus retention `R = exp(-Δt / S)` (#1). Stability `S` grows with the
214/// spacing effect (each prior retrieval) and net feedback; `Δt` is time since
215/// the memory was last reinforced (confirmed *or* retrieved). Multiplicative so
216/// confidence approaches the floor smoothly and never overshoots. Deterministic.
217fn ebbinghaus_confidence(
218    confidence: f32,
219    days_since_confirmed: f32,
220    days_since_retrieved: f32,
221    retrieval_count: f32,
222    net_feedback: i64,
223    base_stability_days: f32,
224) -> f32 {
225    let elapsed = days_since_confirmed.min(days_since_retrieved).max(0.0);
226    let spacing = 1.0 + SPACING_GAIN * retrieval_count;
227    let feedback_mult = match net_feedback.cmp(&0) {
228        std::cmp::Ordering::Greater => 1.0 + (net_feedback as f32).ln_1p(),
229        std::cmp::Ordering::Less => 1.0 / (1.0 + (net_feedback.unsigned_abs() as f32).ln_1p()),
230        std::cmp::Ordering::Equal => 1.0,
231    };
232    let stability = (base_stability_days * spacing * feedback_mult).max(MIN_STABILITY_DAYS);
233    let retention = (-(f64::from(elapsed)) / f64::from(stability)).exp() as f32;
234    (confidence * retention).max(CONFIDENCE_FLOOR)
235}
236
237/// Legacy linear subtraction, preserved verbatim for `forgetting_model = linear`.
238/// FadeMem-inspired: protect frequently/recently retrieved facts; feedback
239/// steers retention. Deterministic, local-only.
240fn linear_confidence(
241    confidence: f32,
242    days_since_confirmed: f32,
243    days_since_retrieved: f32,
244    retrieval_count: f32,
245    net_feedback: i64,
246    decay_rate_per_day: f32,
247) -> f32 {
248    let freq_protect = 1.0 / (1.0 + retrieval_count.ln_1p());
249    let recency_protect = (1.0 - (days_since_retrieved / 30.0).min(1.0)).max(0.0);
250    let protect = (freq_protect * (1.0 - 0.5 * recency_protect)).max(0.05);
251    let feedback_factor = match net_feedback.cmp(&0) {
252        std::cmp::Ordering::Greater => 1.0 / (1.0 + (net_feedback as f32).ln_1p()),
253        std::cmp::Ordering::Less => (1.0 + (net_feedback.unsigned_abs() as f32).ln_1p()).min(4.0),
254        std::cmp::Ordering::Equal => 1.0,
255    };
256    let decay = decay_rate_per_day * days_since_confirmed * protect * feedback_factor;
257    (confidence - decay).max(CONFIDENCE_FLOOR)
258}
259
260pub fn consolidate_similar(facts: &mut Vec<KnowledgeFact>, similarity_threshold: f32) -> usize {
261    let mut to_remove: std::collections::HashSet<usize> = std::collections::HashSet::new();
262
263    let mut category_groups: std::collections::HashMap<String, Vec<usize>> =
264        std::collections::HashMap::new();
265    for (i, f) in facts.iter().enumerate() {
266        if f.is_current() {
267            category_groups
268                .entry(f.category.clone())
269                .or_default()
270                .push(i);
271        }
272    }
273
274    for indices in category_groups.values() {
275        for (pos_a, &i) in indices.iter().enumerate() {
276            if to_remove.contains(&i) {
277                continue;
278            }
279            for &j in &indices[pos_a + 1..] {
280                if to_remove.contains(&j) {
281                    continue;
282                }
283                let sim = word_similarity(&facts[i].value, &facts[j].value);
284                if sim >= similarity_threshold {
285                    if facts[i].confidence >= facts[j].confidence {
286                        facts[i].confirmation_count += facts[j].confirmation_count;
287                        if facts[j].last_confirmed > facts[i].last_confirmed {
288                            facts[i].last_confirmed = facts[j].last_confirmed;
289                        }
290                        to_remove.insert(j);
291                    } else {
292                        facts[j].confirmation_count += facts[i].confirmation_count;
293                        if facts[i].last_confirmed > facts[j].last_confirmed {
294                            facts[j].last_confirmed = facts[i].last_confirmed;
295                        }
296                        to_remove.insert(i);
297                        break;
298                    }
299                }
300            }
301        }
302    }
303
304    let count = to_remove.len();
305    let mut sorted: Vec<usize> = to_remove.into_iter().collect();
306    sorted.sort_unstable();
307    for idx in sorted.into_iter().rev() {
308        facts.remove(idx);
309    }
310
311    count
312}
313
314pub fn compact(
315    facts: &mut Vec<KnowledgeFact>,
316    config: &LifecycleConfig,
317) -> (usize, Vec<KnowledgeFact>) {
318    let mut archived: Vec<KnowledgeFact> = Vec::new();
319    let now = Utc::now();
320    let stale_threshold = now - Duration::days(config.stale_days);
321
322    let mut to_archive: Vec<usize> = Vec::new();
323
324    for (i, fact) in facts.iter().enumerate() {
325        let recently_retrieved = fact
326            .last_retrieved
327            .is_some_and(|t| now.signed_duration_since(t).num_days() < 14);
328        let frequently_retrieved = fact.retrieval_count >= 5;
329
330        if fact.confidence < config.low_confidence_threshold {
331            to_archive.push(i);
332            continue;
333        }
334
335        // Real pruning (#962): a single-confirmation fact untouched for the
336        // configured horizon that was *never* retrieved is dead weight even at
337        // high confidence — archive it. Gated on `confirmation_count <= 1` so
338        // repeatedly-confirmed (structurally important) facts are always kept.
339        if let Some(days) = config.prune_unretrieved_after_days {
340            let cutoff = now - Duration::days(days);
341            if fact.last_confirmed < cutoff
342                && fact.retrieval_count == 0
343                && fact.last_retrieved.is_none()
344                && fact.confirmation_count <= 1
345            {
346                to_archive.push(i);
347                continue;
348            }
349        }
350
351        if fact.last_confirmed < stale_threshold
352            && fact.confirmation_count <= 1
353            && fact.confidence < 0.5
354            && !recently_retrieved
355            && !frequently_retrieved
356        {
357            to_archive.push(i);
358        }
359    }
360
361    to_archive.sort_unstable();
362    to_archive.dedup();
363
364    for idx in to_archive.into_iter().rev() {
365        archived.push(facts.remove(idx));
366    }
367
368    // Quality-only archival here. Capacity reclaim moved to `run_lifecycle` so it
369    // flows through the single capacity manager ([`crate::core::memory_capacity`])
370    // like every other store, keeping `compact` a pure quality pass.
371    (archived.len(), archived)
372}
373
374/// Guardrails for cluster compaction (#971). See
375/// [`crate::core::memory_policy::CompactionPolicy`] for field meanings.
376#[derive(Debug, Clone)]
377pub struct ClusterCompactionConfig {
378    pub min_cluster: usize,
379    pub similarity: f32,
380    pub max_confidence: f32,
381    pub max_confirmations: u32,
382}
383
384/// Maximum digest value length (chars). Bounded so a digest never re-bloats the
385/// store it was meant to shrink.
386const COMPACTION_VALUE_MAX: usize = 400;
387
388/// Collapse clusters of low-value, mutually-similar, same-category facts into one
389/// recoverable digest each. Returns `(clusters_collapsed, archived_originals)`;
390/// the caller archives the originals so the operation is lossless. Deterministic:
391/// candidates are scanned in the store's existing order and similarity ties
392/// resolve to the earliest-founded cluster.
393pub fn compact_clusters(
394    facts: &mut Vec<KnowledgeFact>,
395    cfg: &ClusterCompactionConfig,
396) -> (usize, Vec<KnowledgeFact>) {
397    if cfg.min_cluster < 2 {
398        return (0, Vec::new());
399    }
400    let now = Utc::now();
401
402    // Eligible = current, faded, barely-confirmed, cold, and not itself a digest
403    // or a synthesized summary (summaries are never compacted).
404    let eligible = |f: &KnowledgeFact| -> bool {
405        if !f.is_current() {
406            return false;
407        }
408        if f.source_session == crate::core::knowledge::COMPACTION_DIGEST_SOURCE
409            || f.source_session == crate::core::knowledge::COGNITION_SYNTHESIS_SOURCE
410        {
411            return false;
412        }
413        let recently_retrieved = f
414            .last_retrieved
415            .is_some_and(|t| now.signed_duration_since(t).num_days() < 14);
416        let frequently_retrieved = f.retrieval_count >= 5;
417        f.confidence < cfg.max_confidence
418            && f.confirmation_count <= cfg.max_confirmations
419            && !recently_retrieved
420            && !frequently_retrieved
421    };
422
423    // Group eligible indices by category, preserving first-seen order.
424    let mut by_category: Vec<(String, Vec<usize>)> = Vec::new();
425    for (i, f) in facts.iter().enumerate() {
426        if !eligible(f) {
427            continue;
428        }
429        match by_category.iter_mut().find(|(c, _)| *c == f.category) {
430            Some((_, v)) => v.push(i),
431            None => by_category.push((f.category.clone(), vec![i])),
432        }
433    }
434
435    // Greedy agglomerate within each category by average word similarity, then
436    // keep only clusters that reach the minimum size.
437    let mut clusters: Vec<Vec<usize>> = Vec::new();
438    for (_, indices) in &by_category {
439        let mut cat_clusters: Vec<Vec<usize>> = Vec::new();
440        for &i in indices {
441            let mut best: Option<(usize, f32)> = None;
442            for (ci, cl) in cat_clusters.iter().enumerate() {
443                let avg = cl
444                    .iter()
445                    .map(|&j| word_similarity(&facts[i].value, &facts[j].value))
446                    .sum::<f32>()
447                    / cl.len() as f32;
448                if avg >= cfg.similarity && best.is_none_or(|(_, b)| avg > b) {
449                    best = Some((ci, avg));
450                }
451            }
452            if let Some((ci, _)) = best {
453                cat_clusters[ci].push(i);
454            } else {
455                cat_clusters.push(vec![i]);
456            }
457        }
458        clusters.extend(
459            cat_clusters
460                .into_iter()
461                .filter(|c| c.len() >= cfg.min_cluster),
462        );
463    }
464
465    if clusters.is_empty() {
466        return (0, Vec::new());
467    }
468
469    // Build a digest per cluster, then remove the originals (high→low so indices
470    // stay valid) and append the digests.
471    let mut remove: Vec<usize> = Vec::new();
472    let mut digests: Vec<KnowledgeFact> = Vec::with_capacity(clusters.len());
473    for cluster in &clusters {
474        let members: Vec<&KnowledgeFact> = cluster.iter().map(|&i| &facts[i]).collect();
475        digests.push(build_digest(&members, now));
476        remove.extend(cluster.iter().copied());
477    }
478
479    remove.sort_unstable();
480    remove.dedup();
481    let mut archived: Vec<KnowledgeFact> = Vec::with_capacity(remove.len());
482    for idx in remove.into_iter().rev() {
483        archived.push(facts.remove(idx));
484    }
485    facts.extend(digests);
486
487    (clusters.len(), archived)
488}
489
490/// Synthesize one digest fact from a cluster's members. Byte-stable for a given
491/// set of members: members are sorted, the value is built deterministically, and
492/// the key is content-addressed (md5 of category + sorted member keys) so a
493/// re-run over the same inputs is idempotent.
494fn build_digest(members: &[&KnowledgeFact], now: DateTime<Utc>) -> KnowledgeFact {
495    use md5::{Digest, Md5};
496
497    let mut sorted: Vec<&KnowledgeFact> = members.to_vec();
498    sorted.sort_by(|a, b| a.key.cmp(&b.key).then_with(|| a.value.cmp(&b.value)));
499
500    let category = sorted[0].category.clone();
501    let max_conf = sorted.iter().map(|f| f.confidence).fold(0.0_f32, f32::max);
502    let confirmations: u32 = sorted.iter().map(|f| f.confirmation_count).sum();
503
504    let body: Vec<String> = sorted
505        .iter()
506        .map(|f| format!("{}: {}", f.key, f.value))
507        .collect();
508    let value_full = format!(
509        "Compacted {} low-signal {category} facts — {}",
510        sorted.len(),
511        body.join("; ")
512    );
513    let value = truncate_chars(&value_full, COMPACTION_VALUE_MAX);
514
515    let mut hasher = Md5::new();
516    hasher.update(category.as_bytes());
517    for f in &sorted {
518        hasher.update(b"\n");
519        hasher.update(f.key.as_bytes());
520    }
521    let hash = crate::core::agent_identity::hex_encode(&hasher.finalize());
522    let key = format!("digest-{}", &hash[..8]);
523
524    let sensitivity = crate::core::sensitivity::classify_content(&value);
525    KnowledgeFact {
526        anchors: Vec::new(),
527        review: None,
528        capture: Default::default(),
529        origin: if members
530            .iter()
531            .all(|f| f.origin == crate::core::knowledge::FactOrigin::Local)
532        {
533            crate::core::knowledge::FactOrigin::Local
534        } else {
535            crate::core::knowledge::FactOrigin::Derived(
536                members.iter().map(|f| f.origin.clone()).collect(),
537            )
538        },
539        category,
540        key,
541        value,
542        source_session: crate::core::knowledge::COMPACTION_DIGEST_SOURCE.to_string(),
543        confidence: max_conf,
544        created_at: now,
545        last_confirmed: now,
546        retrieval_count: 0,
547        last_retrieved: None,
548        valid_from: Some(now),
549        valid_until: None,
550        supersedes: None,
551        confirmation_count: confirmations.max(1),
552        feedback_up: 0,
553        feedback_down: 0,
554        last_feedback: None,
555        privacy: crate::core::memory_boundary::FactPrivacy::default(),
556        sensitivity,
557        imported_from: None,
558        archetype: crate::core::knowledge::KnowledgeArchetype::Observation,
559        fidelity: None,
560        revision_count: 0,
561        status: None,
562        validity: None,
563    }
564}
565
566/// Truncate to at most `max` characters on a char boundary, appending an ellipsis
567/// when content was dropped.
568fn truncate_chars(s: &str, max: usize) -> String {
569    if s.chars().count() <= max {
570        return s.to_string();
571    }
572    let mut out: String = s.chars().take(max.saturating_sub(1)).collect();
573    out.push('…');
574    out
575}
576
577pub fn run_lifecycle(
578    facts: &mut Vec<KnowledgeFact>,
579    config: &LifecycleConfig,
580) -> Result<LifecycleReport, String> {
581    let decayed = apply_confidence_decay(facts, config);
582    let consolidated = consolidate_similar(facts, config.consolidation_similarity);
583    let (compacted, archived) = compact(facts, config);
584
585    if !archived.is_empty() {
586        archive_facts(&archived)?;
587    }
588
589    // No capacity reclaim for facts: knowledge has no count limit (owner
590    // decision 24.10.); only the quality rules above archive a fact.
591    Ok(LifecycleReport {
592        decayed_count: decayed,
593        consolidated_count: consolidated,
594        archived_count: archived.len(),
595        compacted_count: compacted,
596        capacity_archived: 0,
597        remaining_facts: facts.len(),
598    })
599}
600
601/// Archive evicted facts (lossless) into the request project's facts
602/// partition; the generic multi-store archive lives in
603/// [`crate::core::memory_archive`].
604pub fn archive_facts(facts: &[KnowledgeFact]) -> Result<(), String> {
605    crate::core::memory_archive::archive_items(
606        MemoryStore::Facts,
607        None,
608        facts,
609        &ArchiveConfig::from_env(),
610    )
611    .map(|_| ())
612}
613
614/// Run `f` with `project_root` as the request project, so the facts archive
615/// resolves to that project's partition and never to the process directory.
616fn in_project<T>(project_root: &str, f: impl FnOnce() -> T) -> T {
617    crate::core::policy::runtime::REQUEST_PROJECT.sync_scope(
618        std::cell::RefCell::new(Some(PathBuf::from(project_root))),
619        f,
620    )
621}
622
623/// Restore the facts from a single archive file of `project_root`'s partition
624/// (legacy `facts` key supported).
625pub fn restore_archive(
626    project_root: &str,
627    archive_path: &str,
628) -> Result<Vec<KnowledgeFact>, String> {
629    in_project(project_root, || {
630        crate::core::memory_archive::restore_items(std::path::Path::new(archive_path))
631    })
632}
633
634/// All facts archive files of `project_root`, sorted ascending (chronological).
635pub fn list_archives(project_root: &str) -> Vec<PathBuf> {
636    in_project(project_root, || {
637        crate::core::memory_archive::list_archives(MemoryStore::Facts, None)
638    })
639}
640
641/// The newest reachable facts archives of `project_root` for the recall-miss
642/// rehydrate path — bounded by [`ArchiveConfig::rehydrate_reach`] so every
643/// retained archive is reachable (closes the pre-#995 retained-vs-reachable gap).
644pub fn reachable_archives(project_root: &str, cfg: &ArchiveConfig) -> Vec<PathBuf> {
645    in_project(project_root, || {
646        crate::core::memory_archive::reachable_archives(MemoryStore::Facts, None, cfg)
647    })
648}
649
650fn word_similarity(a: &str, b: &str) -> f32 {
651    let a_lower = a.to_lowercase();
652    let b_lower = b.to_lowercase();
653    let a_words: std::collections::HashSet<&str> = a_lower.split_whitespace().collect();
654    let b_words: std::collections::HashSet<&str> = b_lower.split_whitespace().collect();
655
656    if a_words.is_empty() && b_words.is_empty() {
657        return 1.0;
658    }
659
660    let intersection = a_words.intersection(&b_words).count();
661    let union = a_words.union(&b_words).count();
662
663    if union == 0 {
664        return 0.0;
665    }
666
667    intersection as f32 / union as f32
668}
669
670#[cfg(test)]
671pub mod tests {
672    use super::*;
673    use crate::core::knowledge::KnowledgeArchetype;
674
675    /// Capacity reclaim archives the evicted tail to disk, so any test that drives
676    /// [`run_lifecycle`] over capacity must sandbox the data dir.
677    fn with_temp_data_dir<T>(f: impl FnOnce() -> T) -> T {
678        let _lock = crate::core::data_dir::test_env_lock();
679        let dir = std::env::temp_dir().join(format!(
680            "lctx-lifecycle-{}-{}",
681            std::process::id(),
682            Utc::now().timestamp_nanos_opt().unwrap_or(0)
683        ));
684        let _ = std::fs::create_dir_all(&dir);
685        crate::test_env::set_var("LEAN_CTX_DATA_DIR", dir.to_str().unwrap());
686        let out = f();
687        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
688        let _ = std::fs::remove_dir_all(&dir);
689        out
690    }
691
692    fn make_fact(category: &str, key: &str, value: &str, confidence: f32) -> KnowledgeFact {
693        KnowledgeFact {
694            anchors: Vec::new(),
695            review: None,
696            capture: Default::default(),
697            origin: crate::core::knowledge::FactOrigin::Local,
698            category: category.to_string(),
699            key: key.to_string(),
700            value: value.to_string(),
701            source_session: "s1".to_string(),
702            confidence,
703            created_at: Utc::now(),
704            last_confirmed: Utc::now(),
705            retrieval_count: 0,
706            last_retrieved: None,
707            valid_from: Some(Utc::now()),
708            valid_until: None,
709            supersedes: None,
710            confirmation_count: 1,
711            feedback_up: 0,
712            feedback_down: 0,
713            last_feedback: None,
714            privacy: crate::core::memory_boundary::FactPrivacy::default(),
715            sensitivity: crate::core::sensitivity::SensitivityLevel::default(),
716            imported_from: None,
717            archetype: KnowledgeArchetype::default(),
718            fidelity: None,
719            revision_count: 0,
720            status: None,
721            validity: None,
722        }
723    }
724
725    fn make_old_fact(
726        category: &str,
727        key: &str,
728        value: &str,
729        confidence: f32,
730        days_old: i64,
731    ) -> KnowledgeFact {
732        let past = Utc::now() - Duration::days(days_old);
733        KnowledgeFact {
734            anchors: Vec::new(),
735            review: None,
736            capture: Default::default(),
737            origin: crate::core::knowledge::FactOrigin::Local,
738            category: category.to_string(),
739            key: key.to_string(),
740            value: value.to_string(),
741            source_session: "s1".to_string(),
742            confidence,
743            created_at: past,
744            last_confirmed: past,
745            retrieval_count: 0,
746            last_retrieved: None,
747            valid_from: Some(past),
748            valid_until: None,
749            supersedes: None,
750            confirmation_count: 1,
751            feedback_up: 0,
752            feedback_down: 0,
753            last_feedback: None,
754            privacy: crate::core::memory_boundary::FactPrivacy::default(),
755            sensitivity: crate::core::sensitivity::SensitivityLevel::default(),
756            imported_from: None,
757            archetype: KnowledgeArchetype::default(),
758            fidelity: None,
759            revision_count: 0,
760            status: None,
761            validity: None,
762        }
763    }
764
765    #[test]
766    fn decay_reduces_confidence() {
767        let config = LifecycleConfig::default();
768        let mut facts = vec![make_old_fact("arch", "db", "PostgreSQL", 0.9, 10)];
769
770        let count = apply_confidence_decay(&mut facts, &config);
771        assert_eq!(count, 1);
772        assert!(facts[0].confidence < 0.9);
773        assert!(facts[0].confidence > 0.7);
774    }
775
776    #[test]
777    fn archetype_aware_decay_protects_evidence() {
778        // Opt-in: structural evidence (Architecture) decays slower than inference
779        // (Preference). Off (default), archetype is ignored and both decay alike.
780        let mut evidence = make_old_fact("arch", "db", "PostgreSQL", 0.9, 30);
781        evidence.archetype = KnowledgeArchetype::Architecture;
782        let mut inference = make_old_fact("pref", "style", "tabs", 0.9, 30);
783        inference.archetype = KnowledgeArchetype::Preference;
784
785        let off = LifecycleConfig::default();
786        let mut a = vec![evidence.clone(), inference.clone()];
787        apply_confidence_decay(&mut a, &off);
788        assert!(
789            (a[0].confidence - a[1].confidence).abs() < 1e-6,
790            "flag off → archetype ignored, equal decay"
791        );
792
793        let on = LifecycleConfig {
794            archetype_aware_decay: true,
795            ..Default::default()
796        };
797        let mut b = vec![evidence, inference];
798        apply_confidence_decay(&mut b, &on);
799        assert!(
800            b[0].confidence > b[1].confidence,
801            "evidence {} should outlast inference {}",
802            b[0].confidence,
803            b[1].confidence
804        );
805    }
806
807    #[test]
808    fn decay_skips_recent_facts() {
809        let config = LifecycleConfig::default();
810        let mut facts = vec![make_fact("arch", "db", "PostgreSQL", 0.9)];
811
812        let count = apply_confidence_decay(&mut facts, &config);
813        assert_eq!(count, 0);
814    }
815
816    #[test]
817    fn feedback_steers_decay_keep_vs_forget() {
818        let config = LifecycleConfig::default();
819        let mut praised = make_old_fact("arch", "loved", "keep me", 0.9, 10);
820        praised.feedback_up = 5;
821        let mut panned = make_old_fact("arch", "hated", "forget me", 0.9, 10);
822        panned.feedback_down = 5;
823        let neutral = make_old_fact("arch", "meh", "neutral", 0.9, 10);
824
825        let mut facts = vec![praised, panned, neutral];
826        apply_confidence_decay(&mut facts, &config);
827
828        let (praised_c, panned_c, neutral_c) = (
829            facts[0].confidence,
830            facts[1].confidence,
831            facts[2].confidence,
832        );
833
834        // Reward bridge: up-voted retains more than neutral, neutral more than down-voted.
835        assert!(
836            praised_c > neutral_c,
837            "praised {praised_c} should outlast neutral {neutral_c}"
838        );
839        assert!(
840            neutral_c > panned_c,
841            "neutral {neutral_c} should outlast panned {panned_c}"
842        );
843        // Even a heavily down-voted fact only fades toward the floor — never hard-deleted.
844        assert!(panned_c >= 0.05);
845    }
846
847    #[test]
848    fn spacing_effect_protects_frequently_retrieved() {
849        // #1: under the Ebbinghaus curve, a fact retrieved many times must decay
850        // slower than an identical never-retrieved fact of the same age.
851        let config = LifecycleConfig::default();
852        let rarely = make_old_fact("arch", "rare", "x", 0.9, 20);
853        let mut often = make_old_fact("arch", "often", "y", 0.9, 20);
854        often.retrieval_count = 20;
855        let mut facts = vec![rarely, often];
856        apply_confidence_decay(&mut facts, &config);
857        assert!(
858            facts[1].confidence > facts[0].confidence,
859            "spacing effect: rehearsed {} should outlast un-rehearsed {}",
860            facts[1].confidence,
861            facts[0].confidence
862        );
863    }
864
865    #[test]
866    fn ebbinghaus_decay_is_deterministic() {
867        // Determinism contract (#498): same input → same output, no RNG.
868        let config = LifecycleConfig::default();
869        let mut a = vec![make_old_fact("arch", "k", "v", 0.8, 15)];
870        let mut b = a.clone();
871        apply_confidence_decay(&mut a, &config);
872        apply_confidence_decay(&mut b, &config);
873        assert_eq!(a[0].confidence, b[0].confidence);
874    }
875
876    #[test]
877    fn linear_model_still_available() {
878        // Opt-out path keeps the legacy subtractive behavior.
879        let config = LifecycleConfig {
880            forgetting_model: ForgettingModel::Linear,
881            ..Default::default()
882        };
883        let mut facts = vec![make_old_fact("arch", "db", "PostgreSQL", 0.9, 10)];
884        let count = apply_confidence_decay(&mut facts, &config);
885        assert_eq!(count, 1);
886        assert!(facts[0].confidence < 0.9 && facts[0].confidence > 0.7);
887    }
888
889    #[test]
890    fn forgetting_model_parses() {
891        assert_eq!(ForgettingModel::parse("linear"), ForgettingModel::Linear);
892        assert_eq!(
893            ForgettingModel::parse("ebbinghaus"),
894            ForgettingModel::Ebbinghaus
895        );
896        assert_eq!(
897            ForgettingModel::parse("garbage"),
898            ForgettingModel::Ebbinghaus
899        );
900    }
901
902    #[test]
903    fn consolidate_similar_facts() {
904        let mut facts = vec![
905            make_fact("arch", "db", "uses PostgreSQL database", 0.8),
906            make_fact("arch", "db2", "uses PostgreSQL database system", 0.6),
907            make_fact("ops", "deploy", "docker compose up", 0.9),
908        ];
909
910        let count = consolidate_similar(&mut facts, 0.7);
911        assert!(count > 0, "Should consolidate similar facts");
912        assert!(facts.len() < 3);
913    }
914
915    #[test]
916    fn consolidate_keeps_different_categories() {
917        let mut facts = vec![
918            make_fact("arch", "db", "PostgreSQL", 0.8),
919            make_fact("ops", "db", "PostgreSQL", 0.8),
920        ];
921
922        let count = consolidate_similar(&mut facts, 0.9);
923        assert_eq!(count, 0, "Different categories should not consolidate");
924    }
925
926    #[test]
927    fn compact_removes_low_confidence() {
928        let config = LifecycleConfig::default();
929        let mut facts = vec![
930            make_fact("arch", "db", "PostgreSQL", 0.9),
931            make_fact("arch", "cache", "Redis", 0.1),
932        ];
933
934        let (count, archived) = compact(&mut facts, &config);
935        assert_eq!(count, 1);
936        assert_eq!(facts.len(), 1);
937        assert_eq!(archived.len(), 1);
938        assert_eq!(archived[0].key, "cache");
939    }
940
941    #[test]
942    fn compact_is_quality_only_and_ignores_capacity() {
943        // Post-#995: capacity reclaim moved out of `compact` into the single
944        // capacity manager (driven by `run_lifecycle`). A store full of healthy,
945        // current, high-confidence facts is a *capacity* concern, so `compact`
946        // (quality only) must leave it untouched.
947        let config = LifecycleConfig {
948            max_facts: 8,
949            ..Default::default()
950        };
951        let mut facts: Vec<KnowledgeFact> = (0..8)
952            .map(|i| make_fact("finding", &format!("k{i}"), &format!("value {i}"), 0.8))
953            .collect();
954
955        let (count, archived) = compact(&mut facts, &config);
956
957        assert_eq!(count, 0, "quality compact must not evict for capacity");
958        assert!(archived.is_empty());
959        assert_eq!(facts.len(), 8);
960    }
961
962    #[test]
963    fn run_lifecycle_never_reclaims_capacity() {
964        with_temp_data_dir(|| {
965            // Owner decision 24.10.: knowledge has no count limit. A store over
966            // `max_facts` with only healthy facts keeps all of them, the
967            // expired one included (only quality rules archive).
968            let config = LifecycleConfig {
969                max_facts: 4,
970                ..Default::default()
971            };
972            let mut facts: Vec<KnowledgeFact> = (0..8)
973                .map(|i| make_fact("finding", &format!("k{i}"), &format!("value {i}"), 0.8))
974                .collect();
975            facts[0].valid_until = Some(Utc::now() - Duration::seconds(1));
976
977            let report = run_lifecycle(&mut facts, &config).expect("lifecycle succeeds");
978
979            assert_eq!(report.capacity_archived, 0);
980            assert_eq!(facts.len(), 8);
981            assert_eq!(report.remaining_facts, 8);
982        });
983    }
984
985    #[test]
986    fn prune_unretrieved_archives_old_never_retrieved_facts() {
987        // Opt-in (#962): a 60-day-old, high-confidence, never-retrieved,
988        // single-confirmation fact is dead weight and must be archived even
989        // though its confidence is well above the low-confidence floor.
990        let config = LifecycleConfig {
991            prune_unretrieved_after_days: Some(30),
992            ..Default::default()
993        };
994        let mut facts = vec![make_old_fact("arch", "x", "still confident", 0.9, 60)];
995        let (count, archived) = compact(&mut facts, &config);
996        assert_eq!(count, 1);
997        assert_eq!(archived.len(), 1);
998        assert!(facts.is_empty());
999    }
1000
1001    #[test]
1002    fn prune_unretrieved_is_off_by_default() {
1003        // Default config (None) must not touch a high-confidence stale fact —
1004        // existing tuning stays byte-for-byte.
1005        let config = LifecycleConfig::default();
1006        let mut facts = vec![make_old_fact("arch", "x", "still confident", 0.9, 60)];
1007        let (count, _) = compact(&mut facts, &config);
1008        assert_eq!(count, 0);
1009        assert_eq!(facts.len(), 1);
1010    }
1011
1012    #[test]
1013    fn prune_unretrieved_keeps_retrieved_and_confirmed_facts() {
1014        let config = LifecycleConfig {
1015            prune_unretrieved_after_days: Some(30),
1016            ..Default::default()
1017        };
1018        let mut retrieved = make_old_fact("arch", "used", "v", 0.9, 60);
1019        retrieved.retrieval_count = 3;
1020        let mut confirmed = make_old_fact("arch", "confirmed", "v", 0.9, 60);
1021        confirmed.confirmation_count = 4;
1022        let mut facts = vec![retrieved, confirmed];
1023        let (count, _) = compact(&mut facts, &config);
1024        assert_eq!(count, 0, "retrieved or repeatedly-confirmed facts are kept");
1025        assert_eq!(facts.len(), 2);
1026    }
1027
1028    #[test]
1029    fn compact_archives_stale_facts() {
1030        let config = LifecycleConfig::default();
1031        let mut facts = vec![
1032            make_fact("arch", "db", "PostgreSQL", 0.9),
1033            make_old_fact("arch", "old", "ancient thing", 0.4, 60),
1034        ];
1035
1036        let (count, archived) = compact(&mut facts, &config);
1037        assert_eq!(count, 1);
1038        assert_eq!(archived[0].key, "old");
1039    }
1040
1041    #[test]
1042    fn full_lifecycle_run() {
1043        with_temp_data_dir(|| {
1044            let config = LifecycleConfig {
1045                max_facts: 5,
1046                ..Default::default()
1047            };
1048
1049            let mut facts = vec![
1050                make_fact("arch", "db", "PostgreSQL", 0.9),
1051                make_fact("arch", "cache", "Redis", 0.8),
1052                make_old_fact("arch", "old1", "thing1", 0.2, 50),
1053                make_old_fact("arch", "old2", "thing2", 0.15, 60),
1054                make_fact("ops", "deploy", "docker compose", 0.7),
1055            ];
1056
1057            let report = run_lifecycle(&mut facts, &config).expect("lifecycle succeeds");
1058            assert!(report.remaining_facts < 5, "the stale facts are archived");
1059            assert!(report.decayed_count > 0 || report.compacted_count > 0);
1060        });
1061    }
1062
1063    #[test]
1064    fn word_similarity_identical() {
1065        assert!((word_similarity("hello world", "hello world") - 1.0).abs() < 0.01);
1066    }
1067
1068    #[test]
1069    fn word_similarity_partial() {
1070        let sim = word_similarity("uses PostgreSQL database", "PostgreSQL database system");
1071        assert!(sim >= 0.5, "Expected >= 0.5 but got {sim}");
1072        assert!(sim < 1.0);
1073    }
1074
1075    #[test]
1076    fn word_similarity_different() {
1077        let sim = word_similarity("Redis cache", "Docker compose");
1078        assert!(sim < 0.1);
1079    }
1080
1081    // === Cluster compaction (#971) ===
1082
1083    fn cc_config() -> ClusterCompactionConfig {
1084        ClusterCompactionConfig {
1085            min_cluster: 4,
1086            similarity: 0.5,
1087            max_confidence: 0.5,
1088            max_confirmations: 1,
1089        }
1090    }
1091
1092    fn faded_cluster(n: usize) -> Vec<KnowledgeFact> {
1093        (0..n)
1094            .map(|i| {
1095                make_old_fact(
1096                    "logs",
1097                    &format!("entry{i}"),
1098                    &format!("request handler returned a transient retry case {i}"),
1099                    0.2,
1100                    40,
1101                )
1102            })
1103            .collect()
1104    }
1105
1106    #[test]
1107    fn compact_clusters_collapses_low_value_cluster_into_digest() {
1108        let mut facts = faded_cluster(5);
1109        let (collapsed, archived) = compact_clusters(&mut facts, &cc_config());
1110
1111        assert_eq!(collapsed, 1);
1112        assert_eq!(archived.len(), 5, "all originals archived (recoverable)");
1113        assert_eq!(facts.len(), 1, "five facts became one digest");
1114
1115        let digest = &facts[0];
1116        assert_eq!(
1117            digest.source_session,
1118            crate::core::knowledge::COMPACTION_DIGEST_SOURCE
1119        );
1120        assert!(digest.key.starts_with("digest-"));
1121        assert!(digest.value.contains("Compacted 5 low-signal logs facts"));
1122    }
1123
1124    #[test]
1125    fn compact_clusters_leaves_high_value_facts() {
1126        let cfg = cc_config();
1127
1128        // High confidence → above the importance ceiling.
1129        let mut high_conf: Vec<KnowledgeFact> = (0..5)
1130            .map(|i| {
1131                make_old_fact(
1132                    "logs",
1133                    &format!("k{i}"),
1134                    "request handler returned a transient retry",
1135                    0.9,
1136                    40,
1137                )
1138            })
1139            .collect();
1140        let (c1, _) = compact_clusters(&mut high_conf, &cfg);
1141        assert_eq!(c1, 0);
1142        assert_eq!(high_conf.len(), 5);
1143
1144        // Frequently retrieved → valuable even when faded.
1145        let mut retrieved: Vec<KnowledgeFact> = (0..5)
1146            .map(|i| {
1147                let mut f = make_old_fact(
1148                    "logs",
1149                    &format!("k{i}"),
1150                    "request handler returned a transient retry",
1151                    0.2,
1152                    40,
1153                );
1154                f.retrieval_count = 9;
1155                f
1156            })
1157            .collect();
1158        let (c2, _) = compact_clusters(&mut retrieved, &cfg);
1159        assert_eq!(c2, 0);
1160        assert_eq!(retrieved.len(), 5);
1161    }
1162
1163    #[test]
1164    fn compact_clusters_respects_min_cluster() {
1165        let mut facts = faded_cluster(3); // below min_cluster (4)
1166        let (collapsed, archived) = compact_clusters(&mut facts, &cc_config());
1167        assert_eq!(collapsed, 0);
1168        assert!(archived.is_empty());
1169        assert_eq!(facts.len(), 3);
1170    }
1171
1172    #[test]
1173    fn compact_clusters_is_deterministic() {
1174        let cfg = cc_config();
1175        let mut a = faded_cluster(5);
1176        let mut b = faded_cluster(5);
1177        compact_clusters(&mut a, &cfg);
1178        compact_clusters(&mut b, &cfg);
1179        assert_eq!(a.len(), 1);
1180        assert_eq!(b.len(), 1);
1181        assert_eq!(a[0].key, b[0].key, "content-addressed digest key is stable");
1182        assert_eq!(a[0].value, b[0].value, "digest value is byte-stable");
1183    }
1184
1185    #[test]
1186    fn compact_clusters_skips_digests_and_summaries() {
1187        let mut facts = faded_cluster(5);
1188        for f in &mut facts {
1189            f.source_session = crate::core::knowledge::COMPACTION_DIGEST_SOURCE.to_string();
1190        }
1191        let (collapsed, _) = compact_clusters(&mut facts, &cc_config());
1192        assert_eq!(collapsed, 0, "existing digests are never re-compacted");
1193        assert_eq!(facts.len(), 5);
1194    }
1195
1196    #[test]
1197    fn truncate_chars_is_char_boundary_safe() {
1198        let s = "äöü".repeat(300); // 900 multibyte chars, well over the cap
1199        let t = truncate_chars(&s, 400);
1200        assert!(t.chars().count() <= 400);
1201        assert!(t.ends_with('…'));
1202        // No panic on a non-ASCII boundary is the real assertion here.
1203    }
1204}