Skip to main content

lean_ctx/core/
consolidation_engine.rs

1//! Canonical session→knowledge consolidation (#995 Phase 4).
2//!
3//! One session-import core (`import_session_into`) and one option set
4//! ([`ConsolidateOptions`]) back every consolidation driver — the CLI/MCP
5//! `consolidate`, the post-dispatch scheduled pass, startup auto-consolidate and
6//! the cognition loop — so promotion budgets, fact keys, confidences and the
7//! lossless capacity reclaim stay identical regardless of who triggers a run.
8//!
9//! The full, locked orchestrator (import + history + lifecycle + per-store
10//! reclaim + report) lives in
11//! `ctx_knowledge::consolidate_project_knowledge_with`; this module owns the
12//! shared import primitive plus the thin `scheduled` wrapper the background
13//! drivers call.
14
15use chrono::{DateTime, Utc};
16
17use crate::core::knowledge::ProjectKnowledge;
18use crate::core::memory_policy::MemoryPolicy;
19use crate::core::session::{Finding, SessionState, extract_session_facts};
20
21/// Promotion budgets for the scheduled (post-dispatch / cognition) pass.
22#[derive(Debug, Clone, Copy)]
23pub struct ConsolidationBudgets {
24    pub max_decisions: usize,
25    pub max_findings: usize,
26}
27
28impl Default for ConsolidationBudgets {
29    fn default() -> Self {
30        Self {
31            max_decisions: 5,
32            max_findings: 8,
33        }
34    }
35}
36
37/// Leaner outcome kept for the scheduled callers (post_dispatch / tool_lifecycle)
38/// that only need the promotion + lifecycle headline, not the full report.
39#[derive(Debug, Clone)]
40pub struct ConsolidationOutcome {
41    pub promoted: u32,
42    pub promoted_decisions: u32,
43    pub promoted_findings: u32,
44    pub lifecycle_archived: usize,
45    pub lifecycle_remaining: usize,
46}
47
48/// How a consolidation run imports the session and reclaims capacity. One option
49/// set per driver — see the constructors. Replaces the four divergent, copy-pasted
50/// import loops (each with subtly different keys, caps and confidences).
51#[derive(Debug, Clone)]
52pub struct ConsolidateOptions {
53    /// Promote the latest session's findings/decisions into knowledge.
54    pub import_session: bool,
55    /// Cap promoted decisions (`None` = all).
56    pub decision_budget: Option<usize>,
57    /// Cap promoted findings (`None` = all).
58    pub finding_budget: Option<usize>,
59    /// Skip findings below this salience score (`None` = import all).
60    pub finding_salience_floor: Option<u32>,
61    /// Confidence assigned to imported decisions.
62    pub decision_confidence: f32,
63    /// Confidence assigned to imported findings.
64    pub finding_confidence: f32,
65    /// Import only items newer than the session watermark and advance it after
66    /// (incremental auto-consolidate).
67    pub incremental: bool,
68    /// Run the fact lifecycle (decay / dedup / quality + capacity) after import.
69    pub run_lifecycle: bool,
70    /// Run the lossless capacity reclaim for history / procedures / patterns.
71    pub reclaim_stores: bool,
72    /// Emit a `KnowledgeUpdate` event after a successful (non-dry) run.
73    pub emit_event: bool,
74    /// Compute the report without mutating knowledge, archives or the session.
75    pub dry_run: bool,
76    /// Optional private selection for bounded scheduled imports; never used with
77    /// a watermark, which would otherwise skip unselected session entries.
78    pub private_curation: bool,
79}
80
81impl ConsolidateOptions {
82    /// Explicit CLI / MCP `consolidate`: import everything, full lifecycle and a
83    /// lossless reclaim of every store. Applies a salience floor to keep
84    /// low-signal auto-findings ("Read file.txt") out of knowledge.
85    pub fn manual() -> Self {
86        Self {
87            import_session: true,
88            decision_budget: None,
89            finding_budget: None,
90            finding_salience_floor: Some(45),
91            decision_confidence: 0.85,
92            finding_confidence: 0.7,
93            incremental: false,
94            run_lifecycle: true,
95            reclaim_stores: true,
96            emit_event: false,
97            dry_run: false,
98            private_curation: false,
99        }
100    }
101
102    /// Scheduled background pass (post-dispatch / cognition): salience-gated,
103    /// budgeted, runs the fact lifecycle and emits an event.
104    pub fn scheduled(b: ConsolidationBudgets) -> Self {
105        Self {
106            import_session: true,
107            decision_budget: Some(b.max_decisions),
108            finding_budget: Some(b.max_findings),
109            finding_salience_floor: Some(45),
110            decision_confidence: 0.9,
111            finding_confidence: 0.75,
112            incremental: false,
113            run_lifecycle: true,
114            reclaim_stores: false,
115            emit_event: true,
116            dry_run: false,
117            private_curation: true,
118        }
119    }
120
121    /// Startup auto-consolidate: incremental (watermark) import only, no lifecycle.
122    pub fn incremental_auto() -> Self {
123        Self {
124            import_session: true,
125            decision_budget: None,
126            finding_budget: None,
127            finding_salience_floor: Some(45),
128            decision_confidence: 0.85,
129            finding_confidence: 0.7,
130            incremental: true,
131            run_lifecycle: false,
132            reclaim_stores: false,
133            emit_event: false,
134            dry_run: false,
135            private_curation: false,
136        }
137    }
138
139    /// Same plan, but preview-only: no writes to knowledge, archives or session.
140    #[must_use]
141    pub fn into_dry_run(mut self) -> Self {
142        self.dry_run = true;
143        self
144    }
145}
146
147/// Counts of items promoted by a single `import_session_into` call.
148#[derive(Debug, Default, Clone, Copy)]
149pub struct ImportCounts {
150    pub decisions: usize,
151    pub findings: usize,
152    pub curation: Option<&'static str>,
153}
154
155impl ImportCounts {
156    pub fn total(self) -> usize {
157        self.decisions + self.findings
158    }
159}
160
161/// The single session→knowledge import. Operates on an already-locked
162/// `knowledge` (no nested knowledge lock), so both the locked orchestrator and the
163/// cognition loop — which holds the knowledge lock across all its steps — share
164/// one implementation. `watermark` (incremental mode) imports only newer items.
165pub fn import_session_into(
166    knowledge: &mut ProjectKnowledge,
167    session: &SessionState,
168    opts: &ConsolidateOptions,
169    policy: &MemoryPolicy,
170    watermark: Option<DateTime<Utc>>,
171) -> ImportCounts {
172    let is_new = |ts: DateTime<Utc>| watermark.is_none_or(|w| ts > w);
173
174    let mut decisions: Vec<&crate::core::session::Decision> = session
175        .decisions
176        .iter()
177        .filter(|d| is_new(d.timestamp))
178        .collect();
179    decisions.sort_by_key(|d| std::cmp::Reverse(d.timestamp));
180    let mut findings: Vec<&Finding> = session
181        .findings
182        .iter()
183        .filter(|f| is_new(f.timestamp))
184        .collect();
185    findings.sort_by_key(|f| std::cmp::Reverse(f.timestamp));
186    let curation = if opts.private_curation && !opts.incremental && watermark.is_none() {
187        curate(knowledge, &mut decisions, &mut findings, opts)
188    } else {
189        None
190    };
191    if let Some(n) = opts.decision_budget {
192        decisions.truncate(n);
193    }
194    let mut decision_count = 0;
195    for d in &decisions {
196        let key = slug_key(&d.summary, 50);
197        knowledge.remember(
198            "decision",
199            &key,
200            &d.summary,
201            &session.id,
202            opts.decision_confidence,
203            policy,
204        );
205        decision_count += 1;
206    }
207
208    let mut finding_count = 0;
209    for f in &findings {
210        if opts.finding_budget.is_some_and(|n| finding_count >= n) {
211            break;
212        }
213        if let Some(floor) = opts.finding_salience_floor
214            && crate::core::memory_salience::text_salience(&f.summary) < floor
215        {
216            continue;
217        }
218        let key = finding_key(f);
219        knowledge.remember(
220            "finding",
221            &key,
222            &f.summary,
223            &session.id,
224            opts.finding_confidence,
225            policy,
226        );
227        finding_count += 1;
228    }
229
230    if opts.import_session {
231        for fact in extract_session_facts(session) {
232            knowledge.add_fact(fact);
233        }
234    }
235
236    ImportCounts {
237        decisions: decision_count,
238        findings: finding_count,
239        curation,
240    }
241}
242
243/// Build a bounded metadata projection before any import mutates knowledge.
244/// Failure keeps the original OSS input lists; selected views never replace or
245/// advance the original session, and structured session facts keep their path.
246fn curate(
247    knowledge: &ProjectKnowledge,
248    decisions: &mut Vec<&crate::core::session::Decision>,
249    findings: &mut Vec<&Finding>,
250    opts: &ConsolidateOptions,
251) -> Option<&'static str> {
252    use crate::core::intelligence_runtime::memory_curation::{Candidate, select};
253    let known = |category: &str, key: &str, value: &str| {
254        knowledge.facts.iter().any(|fact| {
255            fact.is_current() && fact.category == category && fact.key == key && fact.value == value
256        })
257    };
258    let now = Utc::now();
259    let age = |timestamp: DateTime<Utc>| (now - timestamp).num_days().clamp(0, 36500) as u16;
260    let mut candidates = Vec::with_capacity(128);
261    for d in decisions.iter().take(64) {
262        candidates.push(Candidate {
263            candidate_id: candidates.len(),
264            decision: true,
265            salience: crate::core::memory_salience::text_salience(&d.summary).min(100) as u8,
266            known: known("decision", &slug_key(&d.summary, 50), &d.summary),
267            age_days: age(d.timestamp),
268        });
269    }
270    let decision_count = candidates.len();
271    for f in findings.iter().take(64) {
272        candidates.push(Candidate {
273            candidate_id: candidates.len(),
274            decision: false,
275            salience: crate::core::memory_salience::text_salience(&f.summary).min(100) as u8,
276            known: known("finding", &finding_key(f), &f.summary),
277            age_days: age(f.timestamp),
278        });
279    }
280    let Ok(selected) = select(
281        &candidates,
282        opts.decision_budget.unwrap_or(32),
283        opts.finding_budget.unwrap_or(32),
284    )?
285    else {
286        return Some("unavailable; standard local consolidation used");
287    };
288    *decisions = decisions
289        .iter()
290        .take(64)
291        .enumerate()
292        .filter(|(index, _)| selected.binary_search(index).is_ok())
293        .map(|(_, item)| *item)
294        .collect();
295    *findings = findings
296        .iter()
297        .take(64)
298        .enumerate()
299        .filter(|(index, _)| selected.binary_search(&(decision_count + index)).is_ok())
300        .map(|(_, item)| *item)
301        .collect();
302    Some("novel_salience_v1; original session retained")
303}
304
305/// Stable knowledge key for a session finding: `file[:line]` when located, else a
306/// content slug. Content-based (never index-based), so re-imports upsert the same
307/// fact and the output stays deterministic across runs (#498).
308pub fn finding_key(f: &Finding) -> String {
309    match (&f.file, f.line) {
310        (Some(file), Some(line)) => format!("{file}:{line}"),
311        (Some(file), None) => file.clone(),
312        (None, _) => format!("finding-{}", slug_key(&f.summary, 36)),
313    }
314}
315
316/// Scheduled background consolidation. Thin wrapper over the canonical
317/// orchestrator with [`ConsolidateOptions::scheduled`]; kept for the
318/// post-dispatch / tool-lifecycle callers and their `ConsolidationOutcome`.
319pub fn consolidate_latest(
320    project_root: &str,
321    budgets: ConsolidationBudgets,
322) -> Result<ConsolidationOutcome, String> {
323    let opts = ConsolidateOptions::scheduled(budgets);
324    let report =
325        crate::tools::ctx_knowledge::consolidate_project_knowledge_with(project_root, &opts)?;
326
327    Ok(ConsolidationOutcome {
328        promoted: (report.imported_decisions + report.imported_findings) as u32,
329        promoted_decisions: report.imported_decisions as u32,
330        promoted_findings: report.imported_findings as u32,
331        lifecycle_archived: report.lifecycle.archived_count,
332        lifecycle_remaining: report.lifecycle.remaining_facts,
333    })
334}
335
336/// Deterministic, filesystem-safe slug for a fact key: lowercase alphanumerics,
337/// single dashes for separators, trimmed, capped at `max` bytes.
338pub fn slug_key(s: &str, max: usize) -> String {
339    let mut out = String::new();
340    for ch in s.chars() {
341        if out.len() >= max {
342            break;
343        }
344        if ch.is_ascii_alphanumeric() {
345            out.push(ch.to_ascii_lowercase());
346        } else if (ch.is_whitespace() || ch == '-' || ch == '_')
347            && !out.ends_with('-')
348            && !out.is_empty()
349        {
350            out.push('-');
351        }
352    }
353    out.trim_matches('-').to_string()
354}
355
356#[cfg(test)]
357pub mod tests {
358    use super::*;
359
360    #[test]
361    fn consolidate_promotes_decisions_and_salient_findings_only() {
362        let _lock = crate::core::data_dir::test_env_lock();
363        let tmp = tempfile::tempdir().expect("tempdir");
364        crate::test_env::set_var(
365            "LEAN_CTX_DATA_DIR",
366            tmp.path().to_string_lossy().to_string(),
367        );
368
369        let project_root = tmp.path().join("proj");
370        std::fs::create_dir_all(&project_root).expect("mkdir");
371        let project_root_str = project_root.to_string_lossy().to_string();
372
373        let mut session = SessionState::new();
374        session.project_root = Some(project_root_str.clone());
375        session.add_decision("Use archive-only memory lifecycle", None);
376        session.add_finding(None, None, "panic: index out of bounds");
377        session.add_finding(None, None, "just a note");
378        session.save().expect("save session");
379
380        let out = consolidate_latest(
381            &project_root_str,
382            ConsolidationBudgets {
383                max_decisions: 5,
384                max_findings: 5,
385            },
386        )
387        .expect("consolidate");
388        assert!(out.promoted_decisions >= 1);
389        assert!(out.promoted_findings >= 1);
390
391        let k = ProjectKnowledge::load(&project_root_str).expect("knowledge saved");
392        let active = k.facts.iter().filter(|f| f.is_current()).count();
393        assert!(active >= 2, "expected promoted facts");
394
395        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
396    }
397
398    #[test]
399    fn finding_key_is_content_based_and_deterministic() {
400        let f1 = Finding {
401            file: Some("src/main.rs".into()),
402            line: Some(42),
403            summary: "boom".into(),
404            timestamp: Utc::now(),
405        };
406        assert_eq!(finding_key(&f1), "src/main.rs:42");
407
408        let f2 = Finding {
409            file: None,
410            line: None,
411            summary: "Race condition in cache".into(),
412            timestamp: Utc::now(),
413        };
414        // Same content → same key (idempotent re-import, no index drift).
415        assert_eq!(finding_key(&f2), finding_key(&f2));
416        assert_eq!(finding_key(&f2), "finding-race-condition-in-cache");
417    }
418}