lean-ctx 3.8.13

Context Runtime for AI Agents with CCP. 71 MCP tools, 10 read modes, 95+ compression patterns, cross-session memory (CCP), persistent AI knowledge with temporal facts + contradiction detection, multi-agent context sharing, LITM-aware positioning, AAAK compact format, adaptive compression with Thompson Sampling bandits. Supports 24+ AI tools. Reduces LLM token consumption by up to 99%.
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
//! Semantic knowledge search + fact formatting/salience helpers.
//! Split out of `ctx_knowledge/mod.rs`; `use super::*` re-imports parent items.

#[allow(clippy::wildcard_imports)]
use super::*;
pub(crate) fn handle_search(query: Option<&str>) -> String {
    let Some(q) = query else {
        return "Error: query is required for search".to_string();
    };

    let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() else {
        return "Cannot determine data directory.".to_string();
    };

    let sessions_dir = data_dir.join("sessions");

    if !sessions_dir.exists() {
        return "No sessions found.".to_string();
    }

    let knowledge_dir = data_dir.join("knowledge");

    let allow_cross_project = {
        let role = crate::core::roles::active_role();
        role.io.allow_cross_project_search
    };

    let current_project_hash = std::env::current_dir()
        .ok()
        .map(|p| crate::core::project_hash::hash_project_root(&p.to_string_lossy()));

    let q_lower = q.to_lowercase();
    let terms: Vec<&str> = q_lower.split_whitespace().collect();
    let mut results = Vec::new();

    if knowledge_dir.exists()
        && let Ok(entries) = std::fs::read_dir(&knowledge_dir)
    {
        for entry in entries.flatten() {
            let dir_name = entry.file_name().to_string_lossy().to_string();

            if !allow_cross_project
                && let Some(ref current_hash) = current_project_hash
                && &dir_name != current_hash
            {
                continue;
            }

            if let Some(ref current_hash) = current_project_hash
                && dir_name != *current_hash
            {
                let policy = crate::core::config::Config::load().boundary_policy;
                let allowed = crate::core::memory_boundary::check_boundary(
                    current_hash,
                    &dir_name,
                    &policy,
                    &crate::core::memory_boundary::CrossProjectEventType::Search,
                );
                crate::core::memory_boundary::record_audit_event(
                    &crate::core::memory_boundary::CrossProjectAuditEvent {
                        timestamp: Utc::now().to_rfc3339(),
                        event_type: crate::core::memory_boundary::CrossProjectEventType::Search,
                        source_project_hash: current_hash.clone(),
                        target_project_hash: dir_name.clone(),
                        tool: "ctx_knowledge".to_string(),
                        action: "search".to_string(),
                        facts_accessed: 0,
                        allowed,
                        policy_reason: if allowed {
                            "boundary_policy_allowed".to_string()
                        } else {
                            "boundary_policy_denied".to_string()
                        },
                    },
                );
                if !allowed {
                    continue;
                }
            }

            let knowledge_file = entry.path().join("knowledge.json");
            if let Ok(content) = std::fs::read_to_string(&knowledge_file)
                && let Ok(knowledge) = serde_json::from_str::<ProjectKnowledge>(&content)
            {
                let is_foreign = current_project_hash
                    .as_ref()
                    .is_some_and(|h| h != &knowledge.project_hash);

                for fact in &knowledge.facts {
                    if is_foreign
                        && fact.privacy == crate::core::memory_boundary::FactPrivacy::ProjectOnly
                    {
                        continue;
                    }

                    let searchable = format!(
                        "{} {} {}",
                        fact.category.to_lowercase(),
                        fact.key.to_lowercase(),
                        fact.value.to_lowercase()
                    );
                    let match_count = terms.iter().filter(|t| searchable.contains(**t)).count();
                    if match_count > 0 {
                        results.push((
                            knowledge.project_root.clone(),
                            fact.category.clone(),
                            fact.key.clone(),
                            fact.value.clone(),
                            fact.confidence,
                            match_count as f32 / terms.len() as f32,
                        ));
                    }
                }
            }
        }
    }

    if let Ok(entries) = std::fs::read_dir(&sessions_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.extension().and_then(|e| e.to_str()) != Some("json") {
                continue;
            }
            if path.file_name().and_then(|n| n.to_str()) == Some("latest.json") {
                continue;
            }
            if let Ok(json) = std::fs::read_to_string(&path)
                && let Ok(session) = serde_json::from_str::<SessionState>(&json)
            {
                for finding in &session.findings {
                    let searchable = finding.summary.to_lowercase();
                    let match_count = terms.iter().filter(|t| searchable.contains(**t)).count();
                    if match_count > 0 {
                        let project = session
                            .project_root
                            .clone()
                            .unwrap_or_else(|| "unknown".to_string());
                        results.push((
                            project,
                            "session-finding".to_string(),
                            session.id.clone(),
                            finding.summary.clone(),
                            0.6,
                            match_count as f32 / terms.len() as f32,
                        ));
                    }
                }
                for decision in &session.decisions {
                    let searchable = decision.summary.to_lowercase();
                    let match_count = terms.iter().filter(|t| searchable.contains(**t)).count();
                    if match_count > 0 {
                        let project = session
                            .project_root
                            .clone()
                            .unwrap_or_else(|| "unknown".to_string());
                        results.push((
                            project,
                            "session-decision".to_string(),
                            session.id.clone(),
                            decision.summary.clone(),
                            0.7,
                            match_count as f32 / terms.len() as f32,
                        ));
                    }
                }
            }
        }
    }

    if results.is_empty() {
        return format!("No results found for '{q}' across all sessions and projects.");
    }

    results.sort_by(|a, b| {
        b.5.partial_cmp(&a.5)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| b.4.partial_cmp(&a.4).unwrap_or(std::cmp::Ordering::Equal))
            .then_with(|| a.0.cmp(&b.0))
            .then_with(|| a.1.cmp(&b.1))
            .then_with(|| a.2.cmp(&b.2))
            .then_with(|| a.3.cmp(&b.3))
    });
    results.truncate(crate::core::budgets::KNOWLEDGE_CROSS_PROJECT_SEARCH_LIMIT);

    let mut out = format!("Cross-session search '{q}' ({} results):\n", results.len());
    for (project, cat, key, value, conf, _relevance) in &results {
        let project_short = short_path(project);
        out.push_str(&format!(
            "  [{cat}/{key}] {value} (project: {project_short}, conf: {:.0}%)\n",
            conf * 100.0
        ));
    }
    out
}

#[cfg(feature = "embeddings")]
pub(crate) struct SemanticHit {
    pub(crate) category: String,
    pub(crate) key: String,
    pub(crate) value: String,
    pub(crate) score: f32,
    pub(crate) semantic_score: f32,
    pub(crate) confidence_score: f32,
}

#[cfg(feature = "embeddings")]
pub(crate) fn apply_retrieval_signals_from_hits(
    knowledge: &mut ProjectKnowledge,
    hits: &[SemanticHit],
) {
    let now = Utc::now();
    for s in hits {
        for f in &mut knowledge.facts {
            if !f.is_current() {
                continue;
            }
            if f.category == s.category && f.key == s.key {
                f.retrieval_count = f.retrieval_count.saturating_add(1);
                f.last_retrieved = Some(now);
                break;
            }
        }
    }
}

#[cfg(feature = "embeddings")]
pub(crate) fn format_semantic_facts(query: &str, hits: &[SemanticHit]) -> String {
    if hits.is_empty() {
        return format!("No facts matching '{query}'.");
    }
    let mut out = format!("Semantic recall '{query}' (showing {}):\n", hits.len());
    for s in hits {
        out.push_str(&format!(
            "  [{}/{}]: {} (score: {:.0}%, sem: {:.0}%, conf: {:.0}%)\n",
            s.category,
            s.key,
            s.value,
            s.score * 100.0,
            s.semantic_score * 100.0,
            s.confidence_score * 100.0
        ));
    }
    out
}

pub(crate) fn format_facts_with_annotations(
    facts: &[crate::core::knowledge::KnowledgeFact],
    total: usize,
    category: Option<&str>,
    judged_pairs: &[crate::core::knowledge::JudgedPair],
) -> String {
    // Preserve the caller's order: recall_for_output / recall_by_category_for_output
    // already rank facts (balanced observation tier #802, exact-match precedence,
    // relevance). Re-sorting here by salience would discard that ranking and bury a
    // synthesized summary under a high-salience raw fact. The formatter renders; it
    // does not re-rank.
    let facts: Vec<&crate::core::knowledge::KnowledgeFact> = facts.iter().collect();

    let mut out = String::new();
    if let Some(cat) = category {
        out.push_str(&format!(
            "Facts [{cat}] (showing {}/{}):\n",
            facts.len(),
            total
        ));
    } else {
        out.push_str(&format!(
            "Matching facts (showing {}/{}):\n",
            facts.len(),
            total
        ));
    }
    for f in facts {
        let temporal = if f.is_current() { "" } else { " [archived]" };
        let rev = if f.revision_count > 1 {
            format!(" rev {}", f.revision_count)
        } else {
            String::new()
        };
        out.push_str(&format!(
            "  [{}/{}]: {} (quality: {:.0}%, confidence: {:.0}%, confirmed: {} x{}){rev}{temporal}\n",
            f.category,
            f.key,
            f.value,
            f.quality_score() * 100.0,
            f.confidence * 100.0,
            f.last_confirmed.format("%Y-%m-%d"),
            f.confirmation_count
        ));

        if !judged_pairs.is_empty() {
            let composite = format!("{}/{}", f.category, f.key);
            for jp in judged_pairs {
                if jp.key_a == composite {
                    out.push_str(&format!("{} {}\n", jp.verdict, jp.key_b));
                } else if jp.key_b == composite && jp.verdict == "supersedes" {
                    out.push_str(&format!("    ↳ superseded by {}\n", jp.key_a));
                }
            }
        }
    }
    out
}

pub(crate) fn short_path(path: &str) -> String {
    let parts: Vec<&str> = path.split('/').collect();
    if parts.len() <= 2 {
        return path.to_string();
    }
    parts[parts.len() - 2..].join("/")
}

pub(crate) fn short_hash(hash: &str) -> &str {
    if hash.len() > 8 { &hash[..8] } else { hash }
}

pub(crate) fn sort_fact_for_output(
    a: &crate::core::knowledge::KnowledgeFact,
    b: &crate::core::knowledge::KnowledgeFact,
) -> std::cmp::Ordering {
    // Pure salience ordering. The observation tier (#802) is applied at the selection
    // layer (recall_*), not here; this comparator is the as-of recall tiebreak and the
    // display only preserves the order the recall functions already produced.
    salience_score(b)
        .cmp(&salience_score(a))
        .then_with(|| {
            b.quality_score()
                .partial_cmp(&a.quality_score())
                .unwrap_or(std::cmp::Ordering::Equal)
        })
        .then_with(|| {
            b.confidence
                .partial_cmp(&a.confidence)
                .unwrap_or(std::cmp::Ordering::Equal)
        })
        .then_with(|| b.confirmation_count.cmp(&a.confirmation_count))
        .then_with(|| b.retrieval_count.cmp(&a.retrieval_count))
        .then_with(|| b.last_retrieved.cmp(&a.last_retrieved))
        .then_with(|| b.last_confirmed.cmp(&a.last_confirmed))
        .then_with(|| a.category.cmp(&b.category))
        .then_with(|| a.key.cmp(&b.key))
        .then_with(|| a.value.cmp(&b.value))
}

pub(crate) fn salience_score(f: &crate::core::knowledge::KnowledgeFact) -> u32 {
    let cat = f.category.to_lowercase();
    let base: u32 = match cat.as_str() {
        "decision" => 70,
        "gotcha" => 75,
        "architecture" | "arch" => 60,
        "security" => 65,
        "testing" | "tests" | "deployment" | "deploy" => 55,
        "conventions" | "convention" => 45,
        "finding" => 40,
        _ => 30,
    };

    let quality_bonus = (f.quality_score() * 60.0) as u32;
    let recency_bonus = f.last_retrieved.map_or(0u32, |t| {
        let days = chrono::Utc::now().signed_duration_since(t).num_days();
        if days <= 7 {
            10u32
        } else if days <= 30 {
            5u32
        } else {
            0u32
        }
    });

    base + quality_bonus + recency_bonus
}

#[cfg(test)]
mod tests {
    use crate::core::knowledge::{COGNITION_SYNTHESIS_SOURCE, ProjectKnowledge};
    use crate::core::memory_policy::MemoryPolicy;

    // #802: the formatter renders in the caller's order and must never re-rank.
    // `recall_for_output` ranks a synthesized observation ahead via the balanced tier;
    // the display must preserve that, not re-sort by salience (which would bury the
    // summary under a high-salience gotcha). Feeding both orders proves no re-sort.
    #[test]
    fn format_preserves_caller_order_not_salience() {
        let policy = MemoryPolicy::default();
        let mut k = ProjectKnowledge::new("/tmp/test-fmt-preserve");
        k.remember(
            "gotcha",
            "src/a.rs:1",
            "race condition",
            "s1",
            0.95,
            &policy,
        );
        k.remember(
            "observation",
            "src/a.rs",
            "src/a.rs — gotcha: race condition",
            COGNITION_SYNTHESIS_SOURCE,
            0.60,
            &policy,
        );
        let obs = k
            .facts
            .iter()
            .find(|f| f.is_synthesized_observation())
            .cloned()
            .expect("observation present");
        let gotcha = k
            .facts
            .iter()
            .find(|f| !f.is_synthesized_observation())
            .cloned()
            .expect("gotcha present");

        let out =
            super::format_facts_with_annotations(&[obs.clone(), gotcha.clone()], 2, None, &[]);
        assert!(
            out.find("[observation/").unwrap() < out.find("[gotcha/").unwrap(),
            "observation ranked first by recall must stay first in the rendered output"
        );

        let out_rev = super::format_facts_with_annotations(&[gotcha, obs], 2, None, &[]);
        assert!(
            out_rev.find("[gotcha/").unwrap() < out_rev.find("[observation/").unwrap(),
            "formatter must preserve caller order, never impose its own salience sort"
        );
    }
}