lean-ctx 3.6.2

Context Runtime for AI Agents with CCP. 51 MCP tools, 10 read modes, 60+ 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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! Reversible context overlays — user/policy manipulations that modify
//! context items without changing source files ("synaptic modulation").

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::path::Path;

use super::context_field::{ContextItemId, ContextState, ViewKind};

// ---------------------------------------------------------------------------
// Core types
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct OverlayId(pub String);

impl OverlayId {
    pub fn generate(target: &ContextItemId) -> Self {
        Self(format!(
            "ov_{}_{}",
            target.as_str(),
            Utc::now().timestamp_millis()
        ))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for OverlayId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum OverlayOp {
    Include,
    Exclude { reason: String },
    Pin { verbatim: bool },
    Unpin,
    Rewrite { content: String },
    SetView(ViewKind),
    SetPriority { set_priority: f64 },
    MarkOutdated,
    Expire { after_secs: u64 },
}

impl OverlayOp {
    fn discriminant(&self) -> &'static str {
        match self {
            Self::Include => "include",
            Self::Exclude { .. } => "exclude",
            Self::Pin { .. } => "pin",
            Self::Unpin => "unpin",
            Self::Rewrite { .. } => "rewrite",
            Self::SetView(_) => "set_view",
            Self::SetPriority { .. } => "set_priority",
            Self::MarkOutdated => "mark_outdated",
            Self::Expire { .. } => "expire",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OverlayScope {
    Call,
    Session,
    Project,
    Agent(String),
    Global,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OverlayAuthor {
    User,
    Policy(String),
    Agent(String),
}

// ---------------------------------------------------------------------------
// ContextOverlay
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextOverlay {
    pub id: OverlayId,
    pub target: ContextItemId,
    pub operation: OverlayOp,
    pub scope: OverlayScope,
    pub before_hash: String,
    pub author: OverlayAuthor,
    pub created_at: DateTime<Utc>,
    pub stale: bool,
}

impl ContextOverlay {
    pub fn new(
        target: ContextItemId,
        operation: OverlayOp,
        scope: OverlayScope,
        before_hash: String,
        author: OverlayAuthor,
    ) -> Self {
        Self {
            id: OverlayId::generate(&target),
            target,
            operation,
            scope,
            before_hash,
            author,
            created_at: Utc::now(),
            stale: false,
        }
    }

    fn is_expired(&self) -> bool {
        if let OverlayOp::Expire { after_secs } = &self.operation {
            let elapsed = Utc::now()
                .signed_duration_since(self.created_at)
                .num_seconds();
            elapsed >= *after_secs as i64
        } else {
            false
        }
    }
}

// ---------------------------------------------------------------------------
// OverlayStore
// ---------------------------------------------------------------------------

const OVERLAY_FILE: &str = ".lean-ctx/overlays.json";

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct OverlayStore {
    overlays: Vec<ContextOverlay>,
}

impl OverlayStore {
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds an overlay, replacing any existing overlay with the same
    /// target + operation discriminant.
    pub fn add(&mut self, overlay: ContextOverlay) {
        let disc = overlay.operation.discriminant();
        self.overlays.retain(|existing| {
            !(existing.target == overlay.target && existing.operation.discriminant() == disc)
        });
        self.overlays.push(overlay);
    }

    pub fn remove(&mut self, id: &OverlayId) {
        self.overlays.retain(|o| o.id != *id);
    }

    pub fn for_item(&self, target: &ContextItemId) -> Vec<&ContextOverlay> {
        self.overlays
            .iter()
            .filter(|o| o.target == *target)
            .collect()
    }

    pub fn active_for_scope(&self, scope: &OverlayScope) -> Vec<&ContextOverlay> {
        self.overlays.iter().filter(|o| o.scope == *scope).collect()
    }

    /// Applies all overlays for `target` to `current_state`, returning the
    /// effective state. Later overlays take precedence.
    pub fn apply_to_state(
        &self,
        target: &ContextItemId,
        current_state: ContextState,
    ) -> ContextState {
        let mut state = current_state;
        for overlay in self.overlays.iter().filter(|o| o.target == *target) {
            state = match &overlay.operation {
                OverlayOp::Include => ContextState::Included,
                OverlayOp::Exclude { .. } => ContextState::Excluded,
                OverlayOp::Pin { .. } => ContextState::Pinned,
                OverlayOp::Unpin => ContextState::Candidate,
                OverlayOp::MarkOutdated => ContextState::Stale,
                _ => state,
            };
        }
        state
    }

    /// Marks overlays as stale when the source hash has changed.
    pub fn mark_stale_by_hash(&mut self, target: &ContextItemId, new_hash: &str) {
        for overlay in self.overlays.iter_mut().filter(|o| o.target == *target) {
            if overlay.before_hash != new_hash {
                overlay.stale = true;
            }
        }
    }

    /// Removes overlays whose `Expire` operation has elapsed.
    pub fn prune_expired(&mut self) {
        self.overlays.retain(|o| !o.is_expired());
    }

    /// Returns all overlays for `target`, ordered by creation time.
    pub fn history(&self, target: &ContextItemId) -> Vec<&ContextOverlay> {
        let mut items: Vec<&ContextOverlay> = self.for_item(target);
        items.sort_by_key(|o| o.created_at);
        items
    }

    pub fn remove_for_item(&mut self, target: &ContextItemId) {
        self.overlays.retain(|o| o.target != *target);
    }

    pub fn all(&self) -> &[ContextOverlay] {
        &self.overlays
    }

    pub fn save_project(&self, project_root: &Path) -> Result<(), String> {
        let path = project_root.join(OVERLAY_FILE);
        let json =
            serde_json::to_string_pretty(self).map_err(|e| format!("serialize overlays: {e}"))?;
        crate::config_io::write_atomic(&path, &json)
    }

    pub fn load_project(project_root: &Path) -> Self {
        let path = project_root.join(OVERLAY_FILE);
        let mut store: Self = std::fs::read_to_string(&path)
            .ok()
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or_default();
        let now = chrono::Utc::now();
        let session_ttl = chrono::Duration::hours(24);
        store.overlays.retain(|o| match &o.scope {
            OverlayScope::Session | OverlayScope::Call => {
                now.signed_duration_since(o.created_at) < session_ttl
            }
            _ => true,
        });
        store
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    fn make_target() -> ContextItemId {
        ContextItemId::from_file("src/main.rs")
    }

    fn make_overlay(op: OverlayOp) -> ContextOverlay {
        ContextOverlay::new(
            make_target(),
            op,
            OverlayScope::Session,
            "abc123".into(),
            OverlayAuthor::User,
        )
    }

    // -- State transitions ---------------------------------------------------

    #[test]
    fn exclude_sets_excluded_state() {
        let mut store = OverlayStore::new();
        store.add(make_overlay(OverlayOp::Exclude {
            reason: "too large".into(),
        }));
        let state = store.apply_to_state(&make_target(), ContextState::Candidate);
        assert_eq!(state, ContextState::Excluded);
    }

    #[test]
    fn include_sets_included_state() {
        let mut store = OverlayStore::new();
        store.add(make_overlay(OverlayOp::Include));
        let state = store.apply_to_state(&make_target(), ContextState::Candidate);
        assert_eq!(state, ContextState::Included);
    }

    #[test]
    fn pin_sets_pinned_state() {
        let mut store = OverlayStore::new();
        store.add(make_overlay(OverlayOp::Pin { verbatim: true }));
        let state = store.apply_to_state(&make_target(), ContextState::Candidate);
        assert_eq!(state, ContextState::Pinned);
    }

    #[test]
    fn unpin_resets_to_candidate() {
        let mut store = OverlayStore::new();
        store.add(make_overlay(OverlayOp::Unpin));
        let state = store.apply_to_state(&make_target(), ContextState::Pinned);
        assert_eq!(state, ContextState::Candidate);
    }

    #[test]
    fn mark_outdated_sets_stale_state() {
        let mut store = OverlayStore::new();
        store.add(make_overlay(OverlayOp::MarkOutdated));
        let state = store.apply_to_state(&make_target(), ContextState::Included);
        assert_eq!(state, ContextState::Stale);
    }

    #[test]
    fn non_state_ops_preserve_current_state() {
        let mut store = OverlayStore::new();
        store.add(make_overlay(OverlayOp::SetPriority { set_priority: 0.9 }));
        let state = store.apply_to_state(&make_target(), ContextState::Included);
        assert_eq!(state, ContextState::Included);
    }

    // -- Staleness -----------------------------------------------------------

    #[test]
    fn mark_stale_when_hash_changes() {
        let mut store = OverlayStore::new();
        store.add(make_overlay(OverlayOp::Include));
        assert!(!store.overlays[0].stale);

        store.mark_stale_by_hash(&make_target(), "different_hash");
        assert!(store.overlays[0].stale);
    }

    #[test]
    fn no_stale_when_hash_matches() {
        let mut store = OverlayStore::new();
        store.add(make_overlay(OverlayOp::Include));
        store.mark_stale_by_hash(&make_target(), "abc123");
        assert!(!store.overlays[0].stale);
    }

    // -- Scope filtering -----------------------------------------------------

    #[test]
    fn active_for_scope_filters_correctly() {
        let mut store = OverlayStore::new();
        store.add(make_overlay(OverlayOp::Include));
        store.add(ContextOverlay::new(
            ContextItemId::from_file("other.rs"),
            OverlayOp::Include,
            OverlayScope::Project,
            "xyz".into(),
            OverlayAuthor::User,
        ));

        let session = store.active_for_scope(&OverlayScope::Session);
        assert_eq!(session.len(), 1);

        let project = store.active_for_scope(&OverlayScope::Project);
        assert_eq!(project.len(), 1);

        let global = store.active_for_scope(&OverlayScope::Global);
        assert!(global.is_empty());
    }

    // -- Expiry pruning ------------------------------------------------------

    #[test]
    fn prune_removes_expired_overlays() {
        let mut store = OverlayStore::new();
        let mut expired = make_overlay(OverlayOp::Expire { after_secs: 0 });
        expired.created_at = Utc::now() - chrono::Duration::seconds(10);
        store.add(expired);
        store.add(make_overlay(OverlayOp::Include));

        assert_eq!(store.overlays.len(), 2);
        store.prune_expired();
        assert_eq!(store.overlays.len(), 1);
    }

    #[test]
    fn prune_keeps_unexpired_overlays() {
        let mut store = OverlayStore::new();
        store.add(make_overlay(OverlayOp::Expire { after_secs: 99999 }));
        store.prune_expired();
        assert_eq!(store.overlays.len(), 1);
    }

    // -- Persistence roundtrip -----------------------------------------------

    #[test]
    fn save_and_load_roundtrip() {
        let dir = tempfile::tempdir().expect("tmp dir");
        let root = dir.path();

        let mut store = OverlayStore::new();
        store.add(make_overlay(OverlayOp::Include));
        store.add(make_overlay(OverlayOp::Exclude {
            reason: "noise".into(),
        }));
        store.add(make_overlay(OverlayOp::SetView(ViewKind::Signatures)));

        store.save_project(root).expect("save");
        let loaded = OverlayStore::load_project(root);
        assert_eq!(loaded.overlays.len(), store.overlays.len());
    }

    #[test]
    fn load_missing_file_returns_empty() {
        let dir = tempfile::tempdir().expect("tmp dir");
        let store = OverlayStore::load_project(dir.path());
        assert!(store.overlays.is_empty());
    }

    // -- Override semantics --------------------------------------------------

    #[test]
    fn newer_overlay_replaces_same_target_and_op() {
        let mut store = OverlayStore::new();
        store.add(make_overlay(OverlayOp::Exclude {
            reason: "first".into(),
        }));
        assert_eq!(store.overlays.len(), 1);
        assert_eq!(
            store.overlays[0].operation,
            OverlayOp::Exclude {
                reason: "first".into()
            }
        );

        store.add(make_overlay(OverlayOp::Exclude {
            reason: "second".into(),
        }));
        assert_eq!(store.overlays.len(), 1);
        assert_eq!(
            store.overlays[0].operation,
            OverlayOp::Exclude {
                reason: "second".into()
            }
        );
    }

    #[test]
    fn different_ops_coexist_for_same_target() {
        let mut store = OverlayStore::new();
        store.add(make_overlay(OverlayOp::Include));
        store.add(make_overlay(OverlayOp::SetPriority { set_priority: 0.8 }));
        assert_eq!(store.overlays.len(), 2);
    }

    // -- History order -------------------------------------------------------

    #[test]
    fn history_returns_chronological_order() {
        let mut store = OverlayStore::new();
        let mut older = make_overlay(OverlayOp::Include);
        older.created_at = Utc::now() - chrono::Duration::seconds(60);
        store.overlays.push(older);

        let newer = make_overlay(OverlayOp::SetPriority { set_priority: 0.5 });
        store.overlays.push(newer);

        let hist = store.history(&make_target());
        assert_eq!(hist.len(), 2);
        assert!(hist[0].created_at <= hist[1].created_at);
    }

    // -- Remove --------------------------------------------------------------

    #[test]
    fn remove_deletes_by_id() {
        let mut store = OverlayStore::new();
        let ov = make_overlay(OverlayOp::Include);
        let id = ov.id.clone();
        store.add(ov);
        assert_eq!(store.overlays.len(), 1);

        store.remove(&id);
        assert!(store.overlays.is_empty());
    }
}