lean-ctx 3.6.4

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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::path::Path;

use crate::core::handoff_ledger::HandoffLedgerV1;

const MAX_BUNDLE_BYTES: usize = 350_000;
const MAX_PROOF_FILES: usize = 50;
const MAX_ARTIFACT_ITEMS: usize = 80;
const MAX_LEDGER_SNAPSHOT_CHARS: usize = 80_000;
const MAX_CURATED_REF_CHARS: usize = 20_000;
const MAX_DECISION_CHARS: usize = 2_000;
const MAX_FINDING_CHARS: usize = 2_000;
const MAX_NEXT_STEP_CHARS: usize = 1_000;
const MAX_TASK_CHARS: usize = 4_000;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BundlePrivacyV1 {
    Redacted,
    Full,
}

impl BundlePrivacyV1 {
    pub fn parse(s: Option<&str>) -> Self {
        match s.unwrap_or("redacted").trim().to_lowercase().as_str() {
            "full" => Self::Full,
            _ => Self::Redacted,
        }
    }

    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Redacted => "redacted",
            Self::Full => "full",
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HandoffTransferBundleV1 {
    pub schema_version: u32,
    pub exported_at: DateTime<Utc>,
    pub privacy: String,
    pub project: ProjectIdentityV1,
    pub ledger: HandoffLedgerV1,
    pub artifacts: ArtifactsExcerptV1,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signature: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signer_public_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub signer_agent_id: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectIdentityV1 {
    pub project_root_hash: Option<String>,
    pub project_identity_hash: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ArtifactsExcerptV1 {
    pub resolved: Vec<crate::core::artifacts::ResolvedArtifact>,
    pub proof_files: Vec<ProofFileV1>,
    pub warnings: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProofFileV1 {
    pub name: String,
    pub md5: String,
    pub bytes: u64,
}

pub fn build_bundle_v1(
    mut ledger: HandoffLedgerV1,
    project_root: Option<&str>,
    privacy: BundlePrivacyV1,
) -> HandoffTransferBundleV1 {
    let role_name = crate::core::roles::active_role_name();
    let effective_privacy = match privacy {
        BundlePrivacyV1::Full
            if role_name == "admin"
                && !crate::core::redaction::redaction_enabled_for_active_role() =>
        {
            BundlePrivacyV1::Full
        }
        _ => BundlePrivacyV1::Redacted,
    };

    let (project_root_hash, project_identity_hash) = project_root.map_or((None, None), |root| {
        let root_hash = crate::core::project_hash::hash_project_root(root);
        let identity = crate::core::project_hash::project_identity(root);
        let identity_hash = identity.as_deref().map(crate::core::hasher::hash_str);
        (Some(root_hash), identity_hash)
    });

    cap_ledger_in_place(&mut ledger);

    match effective_privacy {
        BundlePrivacyV1::Full => {}
        BundlePrivacyV1::Redacted => {
            redact_ledger_in_place(&mut ledger);
        }
    }

    // Keep embedded ledger internally consistent.
    ledger.content_md5 = crate::core::handoff_ledger::compute_content_md5_for_ledger(&ledger);

    let artifacts = project_root
        .map(Path::new)
        .map(build_artifacts_excerpt_v1)
        .unwrap_or_default();

    let mut bundle = HandoffTransferBundleV1 {
        schema_version: crate::core::contracts::HANDOFF_TRANSFER_BUNDLE_V1_SCHEMA_VERSION,
        exported_at: Utc::now(),
        privacy: effective_privacy.as_str().to_string(),
        project: ProjectIdentityV1 {
            project_root_hash,
            project_identity_hash,
        },
        ledger,
        artifacts,
        signature: None,
        signer_public_key: None,
        signer_agent_id: None,
    };

    let agent_id = role_name;
    sign_bundle(&mut bundle, &agent_id).ok();

    bundle
}

pub fn sign_bundle(bundle: &mut HandoffTransferBundleV1, agent_id: &str) -> Result<(), String> {
    bundle.signature = None;
    bundle.signer_public_key = None;
    bundle.signer_agent_id = None;

    let canonical =
        serde_json::to_string(bundle).map_err(|e| format!("serialize for signing: {e}"))?;

    let sig_bytes = crate::core::agent_identity::sign_bytes(agent_id, canonical.as_bytes())?;
    let pub_key = crate::core::agent_identity::get_public_key(agent_id)?;

    bundle.signature = Some(crate::core::agent_identity::hex_encode(&sig_bytes));
    bundle.signer_public_key = Some(crate::core::agent_identity::hex_encode(&pub_key.to_bytes()));
    bundle.signer_agent_id = Some(agent_id.to_string());
    Ok(())
}

pub fn verify_bundle_signature(bundle: &HandoffTransferBundleV1) -> Result<String, String> {
    let sig_hex = bundle
        .signature
        .as_deref()
        .ok_or_else(|| "bundle has no signature".to_string())?;
    let pk_hex = bundle
        .signer_public_key
        .as_deref()
        .ok_or_else(|| "bundle has no signer_public_key".to_string())?;
    let agent_id = bundle
        .signer_agent_id
        .as_deref()
        .ok_or_else(|| "bundle has no signer_agent_id".to_string())?;

    let sig_bytes = crate::core::agent_identity::hex_decode(sig_hex)?;
    let pk_bytes = crate::core::agent_identity::hex_decode(pk_hex)?;

    let mut verify_bundle = bundle.clone();
    verify_bundle.signature = None;
    verify_bundle.signer_public_key = None;
    verify_bundle.signer_agent_id = None;

    let canonical =
        serde_json::to_string(&verify_bundle).map_err(|e| format!("serialize for verify: {e}"))?;

    if crate::core::agent_identity::verify_signature(&pk_bytes, canonical.as_bytes(), &sig_bytes) {
        Ok(agent_id.to_string())
    } else {
        Err("signature verification failed".to_string())
    }
}

pub fn serialize_bundle_v1_pretty(bundle: &HandoffTransferBundleV1) -> Result<String, String> {
    let json = serde_json::to_string_pretty(bundle).map_err(|e| e.to_string())?;
    if json.len() > MAX_BUNDLE_BYTES {
        return Err(format!(
            "ERROR: bundle too large ({} bytes > max {}). Use privacy=redacted and/or reduce curated refs.",
            json.len(),
            MAX_BUNDLE_BYTES
        ));
    }
    Ok(json)
}

pub fn parse_bundle_v1(json: &str) -> Result<HandoffTransferBundleV1, String> {
    let b: HandoffTransferBundleV1 = serde_json::from_str(json).map_err(|e| e.to_string())?;
    if b.schema_version != crate::core::contracts::HANDOFF_TRANSFER_BUNDLE_V1_SCHEMA_VERSION {
        return Err(format!(
            "ERROR: unsupported schema_version {} (expected {})",
            b.schema_version,
            crate::core::contracts::HANDOFF_TRANSFER_BUNDLE_V1_SCHEMA_VERSION
        ));
    }
    Ok(b)
}

pub fn write_bundle_v1(path: &Path, json: &str) -> Result<(), String> {
    let parent = path
        .parent()
        .ok_or_else(|| "ERROR: invalid path".to_string())?;
    if !parent.exists() {
        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
    }
    let tmp = parent.join(format!(
        ".{}.tmp",
        path.file_name()
            .and_then(|s| s.to_str())
            .unwrap_or("bundle")
    ));
    std::fs::write(&tmp, json).map_err(|e| e.to_string())?;
    std::fs::rename(&tmp, path).map_err(|e| e.to_string())?;
    Ok(())
}

pub fn read_bundle_v1(path: &Path) -> Result<HandoffTransferBundleV1, String> {
    let json = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
    if json.len() > MAX_BUNDLE_BYTES {
        return Err(format!(
            "ERROR: bundle file too large ({} bytes > max {})",
            json.len(),
            MAX_BUNDLE_BYTES
        ));
    }
    parse_bundle_v1(&json)
}

pub fn project_identity_warning(
    bundle: &HandoffTransferBundleV1,
    project_root: &str,
) -> Option<String> {
    let current_root_hash = crate::core::project_hash::hash_project_root(project_root);
    let current_identity_hash = crate::core::project_hash::project_identity(project_root)
        .as_deref()
        .map(crate::core::hasher::hash_str);

    if let Some(ref exported) = bundle.project.project_root_hash {
        if exported != &current_root_hash {
            return Some(
                "WARNING: project_root_hash mismatch (importing into different project root)."
                    .to_string(),
            );
        }
    }

    if let (Some(exported), Some(current)) = (
        bundle.project.project_identity_hash.as_ref(),
        current_identity_hash.as_ref(),
    ) {
        if exported != current {
            return Some(
                "WARNING: project_identity_hash mismatch (importing into different project identity)."
                    .to_string(),
            );
        }
    }

    None
}

fn build_artifacts_excerpt_v1(project_root: &Path) -> ArtifactsExcerptV1 {
    let mut out = ArtifactsExcerptV1::default();

    let resolved = crate::core::artifacts::load_resolved(project_root);
    out.warnings.extend(resolved.warnings);
    out.resolved = resolved
        .artifacts
        .into_iter()
        .take(MAX_ARTIFACT_ITEMS)
        .collect();

    let proofs_dir = project_root.join(".lean-ctx").join("proofs");
    if let Ok(rd) = std::fs::read_dir(&proofs_dir) {
        let mut files = Vec::new();
        for e in rd.flatten() {
            let p = e.path();
            if !p.is_file() {
                continue;
            }
            let name = p
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_default();
            if name.is_empty() {
                continue;
            }
            let bytes = p.metadata().map_or(0, |m| m.len());
            let md5 = match std::fs::read(&p) {
                Ok(b) => crate::core::hasher::hash_hex(&b),
                Err(e) => {
                    out.warnings
                        .push(format!("proof read failed: {} ({e})", p.display()));
                    continue;
                }
            };
            files.push(ProofFileV1 { name, md5, bytes });
        }
        files.sort_by(|a, b| a.name.cmp(&b.name));
        out.proof_files = files.into_iter().take(MAX_PROOF_FILES).collect();
    }

    out
}

fn cap_ledger_in_place(ledger: &mut HandoffLedgerV1) {
    if ledger.session_snapshot.len() > MAX_LEDGER_SNAPSHOT_CHARS {
        ledger.session_snapshot =
            truncate_chars(&ledger.session_snapshot, MAX_LEDGER_SNAPSHOT_CHARS);
    }

    if let Some(ref mut task) = ledger.session.task {
        *task = truncate_chars(task, MAX_TASK_CHARS);
    }

    for d in &mut ledger.session.decisions {
        *d = truncate_chars(d, MAX_DECISION_CHARS);
    }
    for f in &mut ledger.session.findings {
        *f = truncate_chars(f, MAX_FINDING_CHARS);
    }
    for s in &mut ledger.session.next_steps {
        *s = truncate_chars(s, MAX_NEXT_STEP_CHARS);
    }

    for r in &mut ledger.curated_refs {
        if r.content.len() > MAX_CURATED_REF_CHARS {
            r.content = truncate_chars(&r.content, MAX_CURATED_REF_CHARS);
        }
    }
}

fn redact_ledger_in_place(ledger: &mut HandoffLedgerV1) {
    ledger.project_root = None;
    ledger.session_snapshot.clear();

    if let Some(ref mut task) = ledger.session.task {
        *task = crate::core::redaction::redact_text(task);
    }
    for d in &mut ledger.session.decisions {
        *d = crate::core::redaction::redact_text(d);
    }
    for f in &mut ledger.session.findings {
        *f = crate::core::redaction::redact_text(f);
    }
    for s in &mut ledger.session.next_steps {
        *s = crate::core::redaction::redact_text(s);
    }

    for fact in &mut ledger.knowledge.facts {
        fact.value = crate::core::redaction::redact_text(&fact.value);
    }

    for r in &mut ledger.curated_refs {
        r.content = crate::core::redaction::redact_text(&r.content);
    }
}

fn truncate_chars(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        return s.to_string();
    }
    s.chars().take(max).collect::<String>()
}

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

    fn sample_ledger() -> HandoffLedgerV1 {
        HandoffLedgerV1 {
            schema_version: crate::core::contracts::HANDOFF_LEDGER_V1_SCHEMA_VERSION,
            created_at: "20260503T000000Z".to_string(),
            content_md5: "old".to_string(),
            manifest_md5: "m".to_string(),
            project_root: Some("/abs/project".to_string()),
            agent_id: Some("a".to_string()),
            client_name: Some("cursor".to_string()),
            workflow: None,
            session_snapshot: "snapshot".to_string(),
            session: crate::core::handoff_ledger::SessionExcerpt {
                id: "s".to_string(),
                task: Some("task".to_string()),
                decisions: vec!["d1".to_string()],
                findings: vec!["f1".to_string()],
                next_steps: vec!["n1".to_string()],
            },
            tool_calls: crate::core::handoff_ledger::ToolCallsSummary::default(),
            evidence_keys: vec!["tool:ctx_read".to_string()],
            knowledge: crate::core::handoff_ledger::KnowledgeExcerpt {
                project_hash: None,
                facts: vec![crate::core::handoff_ledger::KnowledgeFactMini {
                    category: "c".to_string(),
                    key: "k".to_string(),
                    value: "secret=abcdef0123456789abcdef0123456789".to_string(),
                    confidence: 0.9,
                }],
            },
            curated_refs: vec![crate::core::handoff_ledger::CuratedRef {
                path: "src/lib.rs".to_string(),
                mode: "signatures".to_string(),
                content_md5: "x".to_string(),
                content: "fn a() {}".to_string(),
            }],
            active_overlays: Vec::new(),
        }
    }

    #[test]
    fn redacted_bundle_removes_sensitive_fields() {
        let ledger = sample_ledger();
        let b = build_bundle_v1(ledger, None, BundlePrivacyV1::Redacted);
        assert_eq!(b.privacy, "redacted");
        assert!(b.ledger.project_root.is_none());
        assert!(b.ledger.session_snapshot.is_empty());
    }

    #[test]
    fn serialize_parse_roundtrip() {
        let ledger = sample_ledger();
        let b = build_bundle_v1(ledger, None, BundlePrivacyV1::Redacted);
        let json = serialize_bundle_v1_pretty(&b).expect("json");
        assert!(json.len() < MAX_BUNDLE_BYTES);
        let parsed = parse_bundle_v1(&json).expect("parse");
        assert_eq!(parsed.schema_version, b.schema_version);
        assert_eq!(parsed.privacy, "redacted");
    }
}