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}
77
78impl ConsolidateOptions {
79    /// Explicit CLI / MCP `consolidate`: import everything, full lifecycle and a
80    /// lossless reclaim of every store. Applies a salience floor to keep
81    /// low-signal auto-findings ("Read file.txt") out of knowledge.
82    pub fn manual() -> Self {
83        Self {
84            import_session: true,
85            decision_budget: None,
86            finding_budget: None,
87            finding_salience_floor: Some(45),
88            decision_confidence: 0.85,
89            finding_confidence: 0.7,
90            incremental: false,
91            run_lifecycle: true,
92            reclaim_stores: true,
93            emit_event: false,
94            dry_run: false,
95        }
96    }
97
98    /// Scheduled background pass (post-dispatch / cognition): salience-gated,
99    /// budgeted, runs the fact lifecycle and emits an event.
100    pub fn scheduled(b: ConsolidationBudgets) -> Self {
101        Self {
102            import_session: true,
103            decision_budget: Some(b.max_decisions),
104            finding_budget: Some(b.max_findings),
105            finding_salience_floor: Some(45),
106            decision_confidence: 0.9,
107            finding_confidence: 0.75,
108            incremental: false,
109            run_lifecycle: true,
110            reclaim_stores: false,
111            emit_event: true,
112            dry_run: false,
113        }
114    }
115
116    /// Startup auto-consolidate: incremental (watermark) import only, no lifecycle.
117    pub fn incremental_auto() -> Self {
118        Self {
119            import_session: true,
120            decision_budget: None,
121            finding_budget: None,
122            finding_salience_floor: Some(45),
123            decision_confidence: 0.85,
124            finding_confidence: 0.7,
125            incremental: true,
126            run_lifecycle: false,
127            reclaim_stores: false,
128            emit_event: false,
129            dry_run: false,
130        }
131    }
132
133    /// Same plan, but preview-only: no writes to knowledge, archives or session.
134    #[must_use]
135    pub fn into_dry_run(mut self) -> Self {
136        self.dry_run = true;
137        self
138    }
139}
140
141/// Counts of items promoted by a single `import_session_into` call.
142#[derive(Debug, Default, Clone, Copy)]
143pub struct ImportCounts {
144    pub decisions: usize,
145    pub findings: usize,
146}
147
148impl ImportCounts {
149    pub fn total(self) -> usize {
150        self.decisions + self.findings
151    }
152}
153
154/// The single session→knowledge import. Operates on an already-locked
155/// `knowledge` (no I/O, no lock), so both the locked orchestrator and the
156/// cognition loop — which holds the knowledge lock across all its steps — share
157/// one implementation. `watermark` (incremental mode) imports only newer items.
158pub fn import_session_into(
159    knowledge: &mut ProjectKnowledge,
160    session: &SessionState,
161    opts: &ConsolidateOptions,
162    policy: &MemoryPolicy,
163    watermark: Option<DateTime<Utc>>,
164) -> ImportCounts {
165    let is_new = |ts: DateTime<Utc>| watermark.is_none_or(|w| ts > w);
166
167    let mut decisions: Vec<&crate::core::session::Decision> = session
168        .decisions
169        .iter()
170        .filter(|d| is_new(d.timestamp))
171        .collect();
172    decisions.sort_by_key(|d| std::cmp::Reverse(d.timestamp));
173    if let Some(n) = opts.decision_budget {
174        decisions.truncate(n);
175    }
176    let mut decision_count = 0;
177    for d in &decisions {
178        let key = slug_key(&d.summary, 50);
179        knowledge.remember(
180            "decision",
181            &key,
182            &d.summary,
183            &session.id,
184            opts.decision_confidence,
185            policy,
186        );
187        decision_count += 1;
188    }
189
190    let mut findings: Vec<&Finding> = session
191        .findings
192        .iter()
193        .filter(|f| is_new(f.timestamp))
194        .collect();
195    findings.sort_by_key(|f| std::cmp::Reverse(f.timestamp));
196    let mut finding_count = 0;
197    for f in &findings {
198        if opts.finding_budget.is_some_and(|n| finding_count >= n) {
199            break;
200        }
201        if let Some(floor) = opts.finding_salience_floor
202            && crate::core::memory_salience::text_salience(&f.summary) < floor
203        {
204            continue;
205        }
206        let key = finding_key(f);
207        knowledge.remember(
208            "finding",
209            &key,
210            &f.summary,
211            &session.id,
212            opts.finding_confidence,
213            policy,
214        );
215        finding_count += 1;
216    }
217
218    if opts.import_session {
219        for fact in extract_session_facts(session) {
220            knowledge.add_fact(fact);
221        }
222    }
223
224    ImportCounts {
225        decisions: decision_count,
226        findings: finding_count,
227    }
228}
229
230/// Stable knowledge key for a session finding: `file[:line]` when located, else a
231/// content slug. Content-based (never index-based), so re-imports upsert the same
232/// fact and the output stays deterministic across runs (#498).
233pub fn finding_key(f: &Finding) -> String {
234    match (&f.file, f.line) {
235        (Some(file), Some(line)) => format!("{file}:{line}"),
236        (Some(file), None) => file.clone(),
237        (None, _) => format!("finding-{}", slug_key(&f.summary, 36)),
238    }
239}
240
241/// Scheduled background consolidation. Thin wrapper over the canonical
242/// orchestrator with [`ConsolidateOptions::scheduled`]; kept for the
243/// post-dispatch / tool-lifecycle callers and their `ConsolidationOutcome`.
244pub fn consolidate_latest(
245    project_root: &str,
246    budgets: ConsolidationBudgets,
247) -> Result<ConsolidationOutcome, String> {
248    let opts = ConsolidateOptions::scheduled(budgets);
249    let report =
250        crate::tools::ctx_knowledge::consolidate_project_knowledge_with(project_root, &opts)?;
251
252    Ok(ConsolidationOutcome {
253        promoted: (report.imported_decisions + report.imported_findings) as u32,
254        promoted_decisions: report.imported_decisions as u32,
255        promoted_findings: report.imported_findings as u32,
256        lifecycle_archived: report.lifecycle.archived_count,
257        lifecycle_remaining: report.lifecycle.remaining_facts,
258    })
259}
260
261/// Deterministic, filesystem-safe slug for a fact key: lowercase alphanumerics,
262/// single dashes for separators, trimmed, capped at `max` bytes.
263pub fn slug_key(s: &str, max: usize) -> String {
264    let mut out = String::new();
265    for ch in s.chars() {
266        if out.len() >= max {
267            break;
268        }
269        if ch.is_ascii_alphanumeric() {
270            out.push(ch.to_ascii_lowercase());
271        } else if (ch.is_whitespace() || ch == '-' || ch == '_')
272            && !out.ends_with('-')
273            && !out.is_empty()
274        {
275            out.push('-');
276        }
277    }
278    out.trim_matches('-').to_string()
279}
280
281#[cfg(test)]
282pub mod tests {
283    use super::*;
284
285    #[test]
286    fn consolidate_promotes_decisions_and_salient_findings_only() {
287        let _lock = crate::core::data_dir::test_env_lock();
288        let tmp = tempfile::tempdir().expect("tempdir");
289        crate::test_env::set_var(
290            "LEAN_CTX_DATA_DIR",
291            tmp.path().to_string_lossy().to_string(),
292        );
293
294        let project_root = tmp.path().join("proj");
295        std::fs::create_dir_all(&project_root).expect("mkdir");
296        let project_root_str = project_root.to_string_lossy().to_string();
297
298        let mut session = SessionState::new();
299        session.project_root = Some(project_root_str.clone());
300        session.add_decision("Use archive-only memory lifecycle", None);
301        session.add_finding(None, None, "panic: index out of bounds");
302        session.add_finding(None, None, "just a note");
303        session.save().expect("save session");
304
305        let out = consolidate_latest(
306            &project_root_str,
307            ConsolidationBudgets {
308                max_decisions: 5,
309                max_findings: 5,
310            },
311        )
312        .expect("consolidate");
313        assert!(out.promoted_decisions >= 1);
314        assert!(out.promoted_findings >= 1);
315
316        let k = ProjectKnowledge::load(&project_root_str).expect("knowledge saved");
317        let active = k.facts.iter().filter(|f| f.is_current()).count();
318        assert!(active >= 2, "expected promoted facts");
319
320        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
321    }
322
323    #[test]
324    fn finding_key_is_content_based_and_deterministic() {
325        let f1 = Finding {
326            file: Some("src/main.rs".into()),
327            line: Some(42),
328            summary: "boom".into(),
329            timestamp: Utc::now(),
330        };
331        assert_eq!(finding_key(&f1), "src/main.rs:42");
332
333        let f2 = Finding {
334            file: None,
335            line: None,
336            summary: "Race condition in cache".into(),
337            timestamp: Utc::now(),
338        };
339        // Same content → same key (idempotent re-import, no index drift).
340        assert_eq!(finding_key(&f2), finding_key(&f2));
341        assert_eq!(finding_key(&f2), "finding-race-condition-in-cache");
342    }
343}