lean-ctx-engine 3.12.2

LeanCTX | OSS library: the open-source runtime for the Context Gateway for AI agents behind the lean-ctx CLI, MCP server and proxy integrations.
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// SPDX-License-Identifier: Apache-2.0

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

use crate::core::session::{
    Decision, EvidenceRecord, FileTouched, Finding, ProgressEntry, SessionState, SessionStats,
    TaskInfo, TestSnapshot,
};

const MAX_BUNDLE_BYTES: usize = 250_000;
const MAX_NEXT_STEPS: usize = 25;

#[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,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CcpSessionBundleV1 {
    pub schema_version: u32,
    pub exported_at: DateTime<Utc>,
    pub project: ProjectIdentityV1,
    pub role: PolicyIdentityV1,
    pub profile: PolicyIdentityV1,
    pub session: SessionExcerptV1,
}

#[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)]
pub struct PolicyIdentityV1 {
    pub name: String,
    /// BLAKE3 hex; the serialized name keeps its historical `_md5` suffix.
    #[serde(rename = "policy_md5")]
    pub policy_blake3: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionExcerptV1 {
    pub id: String,
    pub version: u32,
    pub started_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    pub project_root: Option<String>,
    pub shell_cwd: Option<String>,
    pub task: Option<TaskInfo>,
    pub findings: Vec<Finding>,
    pub decisions: Vec<Decision>,
    pub files_touched: Vec<FileTouched>,
    pub test_results: Option<TestSnapshot>,
    pub progress: Vec<ProgressEntry>,
    pub next_steps: Vec<String>,
    pub evidence: Vec<EvidenceRecord>,
    pub stats: SessionStats,
    #[serde(default)]
    pub terse_mode: bool,
    #[serde(default)]
    pub compression_level: String,
}

pub fn build_bundle_v1(session: &SessionState, privacy: BundlePrivacyV1) -> CcpSessionBundleV1 {
    let role_name = crate::core::roles::active_role_name();
    let role = crate::core::roles::active_role();
    let profile_name = crate::core::profiles::active_profile_name();
    let profile = crate::core::profiles::active_profile();

    let role_policy_blake3 =
        crate::core::hasher::hash_str(&serde_json::to_string(&role).unwrap_or_default());
    let profile_policy_blake3 =
        crate::core::hasher::hash_str(&serde_json::to_string(&profile).unwrap_or_default());

    let (project_root_hash, project_identity_hash) =
        session
            .project_root
            .as_deref()
            .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)
            });

    let mut excerpt = SessionExcerptV1 {
        id: session.id.clone(),
        version: session.version,
        started_at: session.started_at,
        updated_at: session.updated_at,
        project_root: session.project_root.clone(),
        shell_cwd: session.shell_cwd.clone(),
        task: session.task.clone(),
        // Only findings that may be delivered now leave in a bundle
        // (`SessionState::finding_served`): a finding bound to a source that
        // no longer admits is left out.
        findings: session
            .findings
            .iter()
            .filter(|finding| session.finding_served(finding))
            .cloned()
            .collect(),
        decisions: session.decisions.clone(),
        files_touched: session.files_touched.clone(),
        test_results: session.test_results.clone(),
        progress: session.progress.clone(),
        next_steps: session
            .next_steps
            .iter()
            .take(MAX_NEXT_STEPS)
            .cloned()
            .collect(),
        evidence: session.evidence.clone(),
        stats: session.stats.clone(),
        terse_mode: session.terse_mode,
        compression_level: session.compression_level.clone(),
    };

    // Path minimization: prefer relative paths when project_root is known.
    let root = excerpt.project_root.clone().unwrap_or_default();
    if !root.is_empty() {
        for f in &mut excerpt.files_touched {
            if let Some(rel) = strip_root_prefix(&root, &f.path) {
                f.path = rel;
            }
        }
        for finding in &mut excerpt.findings {
            if let Some(ref file) = finding.file.clone()
                && let Some(rel) = strip_root_prefix(&root, file)
            {
                finding.file = Some(rel);
            }
        }
    }

    match privacy {
        BundlePrivacyV1::Full => {
            // Full export is allowed only for admin role; otherwise force redaction.
            if role_name != "admin" {
                redact_excerpt_in_place(&mut excerpt);
            } else if crate::core::redaction::redaction_enabled_for_active_role() {
                // Admin opted into redaction — keep it consistent.
                redact_excerpt_in_place(&mut excerpt);
            }
        }
        BundlePrivacyV1::Redacted => {
            redact_excerpt_in_place(&mut excerpt);
        }
    }

    CcpSessionBundleV1 {
        schema_version: crate::core::contracts::CCP_SESSION_BUNDLE_V1_SCHEMA_VERSION,
        exported_at: Utc::now(),
        project: ProjectIdentityV1 {
            project_root_hash,
            project_identity_hash,
        },
        role: PolicyIdentityV1 {
            name: role_name,
            policy_blake3: role_policy_blake3,
        },
        profile: PolicyIdentityV1 {
            name: profile_name,
            policy_blake3: profile_policy_blake3,
        },
        session: excerpt,
    }
}

pub fn serialize_bundle_v1_pretty(bundle: &CcpSessionBundleV1) -> 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 session evidence.",
            json.len(),
            MAX_BUNDLE_BYTES
        ));
    }
    Ok(json)
}

pub(crate) fn parse_bundle_v1(json: &str) -> Result<CcpSessionBundleV1, String> {
    let b: CcpSessionBundleV1 = serde_json::from_str(json).map_err(|e| e.to_string())?;
    if b.schema_version != crate::core::contracts::CCP_SESSION_BUNDLE_V1_SCHEMA_VERSION {
        return Err(format!(
            "ERROR: unsupported schema_version {} (expected {})",
            b.schema_version,
            crate::core::contracts::CCP_SESSION_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<CcpSessionBundleV1, String> {
    use std::io::Read as _;
    let mut options = std::fs::OpenOptions::new();
    options.read(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt as _;
        options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
    }
    #[cfg(windows)]
    {
        use std::os::windows::fs::OpenOptionsExt as _;
        options.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT
    }
    let file = options.open(path).map_err(|_| "bundle cannot be opened")?;
    let metadata = file.metadata().map_err(|_| "bundle metadata unavailable")?;
    #[cfg(windows)]
    {
        use std::os::windows::fs::MetadataExt as _;
        if metadata.file_attributes() & 0x0400 != 0 {
            return Err("bundle reparse point rejected".into());
        }
    }
    if !metadata.is_file() || metadata.len() > MAX_BUNDLE_BYTES as u64 {
        return Err("bundle must be a bounded regular file".into());
    }
    let mut json = String::new();
    file.take(MAX_BUNDLE_BYTES as u64 + 1)
        .read_to_string(&mut json)
        .map_err(|_| "bundle cannot be read")?;
    if json.len() > MAX_BUNDLE_BYTES {
        return Err("bundle exceeds byte limit".into());
    }
    parse_bundle_v1(&json)
}

pub fn import_bundle_v1_into_session(
    session: &mut SessionState,
    bundle: &CcpSessionBundleV1,
    current_project_root: Option<&str>,
) -> ImportReportV1 {
    let mut imported = bundle.session.clone();

    // Prefer current project root when provided (replay safety).
    if let Some(root) = current_project_root {
        imported.project_root = Some(root.to_string());
    }

    // Mark stale file paths if missing or outside jail.
    let jail_root = imported.project_root.clone().unwrap_or_else(|| {
        std::env::current_dir()
            .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string())
    });
    let jail_root_path = PathBuf::from(&jail_root);

    let mut stale = 0u32;
    for f in &mut imported.files_touched {
        let candidate = candidate_path(&jail_root_path, &f.path);
        if let Ok((jailed, _warning)) = crate::core::io_boundary::jail_and_check_path(
            "ctx_session.import",
            candidate.as_path(),
            jail_root_path.as_path(),
        ) {
            if jailed.exists() {
                f.stale = false;
            } else {
                f.stale = true;
                stale += 1;
            }
        } else {
            f.stale = true;
            stale += 1;
        }
    }

    *session = SessionState {
        canonical_checkpoint: None,
        handoff_context: Vec::new(),
        id: SessionState::new().id,
        version: imported.version,
        started_at: imported.started_at,
        updated_at: imported.updated_at,
        project_root: imported.project_root.clone(),
        // A machine-local cwd from the source never changes the target's scope.
        shell_cwd: None,
        task: imported.task.clone(),
        findings: imported.findings.clone(),
        decisions: imported.decisions.clone(),
        files_touched: imported.files_touched.clone(),
        test_results: imported.test_results.clone(),
        progress: imported.progress.clone(),
        next_steps: imported.next_steps.clone(),
        evidence: imported.evidence.clone(),
        intents: Vec::new(),
        active_structured_intent: None,
        stats: imported.stats.clone(),
        terse_mode: imported.terse_mode,
        compression_level: imported.compression_level.clone(),
        last_consolidate_ts: None,
        last_aaak_hash: None,
        extra_roots: Vec::new(),
        playbook: crate::core::session::Playbook::default(),
        last_semantic_query: None,
        last_flush: None,
        save_gate: Default::default(),
        last_save_failed: false,
        live_zone: Default::default(),
    };

    use sha2::{Digest as _, Sha256};
    let source_digest = crate::core::agent_identity::hex_encode(&Sha256::digest(
        crate::core::canonical::canonical_serialize(bundle),
    ));
    // Append directly: record_manual_evidence may auto-save, whereas this
    // candidate must remain unpublished until the caller's guarded commit.
    session.evidence.push(EvidenceRecord {
        kind: crate::core::session::EvidenceKind::Manual,
        key: "session_import_source".into(),
        value: Some(
            serde_json::json!({"schema_version":1,
            "source_session_id":imported.id,
            "source_digest":format!("sha256:{source_digest}")})
            .to_string(),
        ),
        tool: None,
        input_md5: None,
        output_md5: None,
        agent_id: None,
        client_name: None,
        task_id: None,
        timestamp: Utc::now(),
    });
    ImportReportV1 {
        session_id: session.id.clone(),
        source_session_id: imported.id,
        version: session.version,
        files_touched: session.files_touched.len() as u32,
        stale_files: stale,
    }
}

#[derive(Debug, Clone)]
pub struct ImportReportV1 {
    pub session_id: String,
    pub source_session_id: String,
    pub version: u32,
    pub files_touched: u32,
    pub stale_files: u32,
}

fn redact_excerpt_in_place(ex: &mut SessionExcerptV1) {
    ex.shell_cwd = None;
    // project_root is represented as hashes at bundle level; avoid exporting raw paths.
    ex.project_root = None;

    if let Some(ref mut t) = ex.task {
        t.description = crate::core::redaction::redact_text(&t.description);
        if let Some(ref mut intent) = t.intent {
            *intent = crate::core::redaction::redact_text(intent);
        }
    }
    for f in &mut ex.findings {
        f.summary = crate::core::redaction::redact_text(&f.summary);
        if let Some(ref mut file) = f.file {
            *file = crate::core::redaction::redact_text(file);
        }
    }
    for d in &mut ex.decisions {
        d.summary = crate::core::redaction::redact_text(&d.summary);
        if let Some(ref mut r) = d.rationale {
            *r = crate::core::redaction::redact_text(r);
        }
    }
    for p in &mut ex.progress {
        p.action = crate::core::redaction::redact_text(&p.action);
        if let Some(ref mut detail) = p.detail {
            *detail = crate::core::redaction::redact_text(detail);
        }
    }
    for s in &mut ex.next_steps {
        *s = crate::core::redaction::redact_text(s);
    }
    for ev in &mut ex.evidence {
        ev.value = None;
    }
}

fn strip_root_prefix(root: &str, path: &str) -> Option<String> {
    let root = root.trim_end_matches(std::path::MAIN_SEPARATOR);
    let root_prefix = format!("{root}{}", std::path::MAIN_SEPARATOR);
    if path.starts_with(&root_prefix) {
        Some(path.trim_start_matches(&root_prefix).to_string())
    } else {
        None
    }
}

fn candidate_path(jail_root: &Path, stored_path: &str) -> PathBuf {
    let p = PathBuf::from(stored_path);
    if p.is_absolute() {
        p
    } else {
        jail_root.join(p)
    }
}

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

    #[test]
    fn redacted_export_drops_evidence_values() {
        let mut s = SessionState::new();
        s.record_manual_evidence("k", Some("secret=abcdef0123456789abcdef0123456789"));
        let b = build_bundle_v1(&s, BundlePrivacyV1::Redacted);
        assert!(b.session.evidence.iter().all(|e| e.value.is_none()));
    }

    #[test]
    fn serialize_respects_size_cap() {
        let s = SessionState::new();
        let b = build_bundle_v1(&s, 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);
    }

    #[test]
    fn import_marks_missing_files_stale() {
        let mut s = SessionState::new();
        s.project_root = Some(
            std::env::current_dir()
                .unwrap()
                .to_string_lossy()
                .to_string(),
        );
        s.touch_file("does-not-exist-xyz.txt", None, "full", 10);
        let b = build_bundle_v1(&s, BundlePrivacyV1::Redacted);

        let root = std::env::current_dir()
            .unwrap()
            .to_string_lossy()
            .to_string();
        let mut target = SessionState::new();
        let report = import_bundle_v1_into_session(&mut target, &b, Some(&root));
        assert_eq!(report.files_touched, 1);
        assert_eq!(report.stale_files, 1);
        assert!(target.files_touched[0].stale);
    }

    fn with_two_findings(root: &str) -> SessionState {
        std::fs::write(format!("{root}/pool.rs"), "pub fn lease() {}\n").expect("source");
        let mut session = SessionState::new();
        session.project_root = Some(root.to_owned());
        session.add_finding_for_file(Some("pool.rs"), Some(1), "the pool leaks one lease");
        session.add_finding_for_file(None, None, "noted without a file");
        session
    }

    fn exported(session: &SessionState) -> Vec<String> {
        build_bundle_v1(session, BundlePrivacyV1::Redacted)
            .session
            .findings
            .into_iter()
            .map(|finding| finding.summary)
            .collect()
    }

    /// A bundle carries a finding bound to a source while the source admits
    /// and leaves it out once the source is deleted; the finding without a
    /// file is exported either way.
    #[test]
    fn a_finding_whose_source_is_gone_is_not_exported() {
        use crate::core::context_admission::stored::lineage_support::{governed, project, scoped};
        let _data = governed();
        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
        let (_directory, root) = project();
        let session = with_two_findings(&root);

        assert_eq!(
            scoped(&root, || exported(&session)),
            ["the pool leaks one lease", "noted without a file"]
        );
        std::fs::remove_file(format!("{root}/pool.rs")).expect("delete");
        assert_eq!(
            scoped(&root, || exported(&session)),
            ["noted without a file"]
        );
        assert_eq!(session.findings.len(), 2, "the session keeps both");
    }

    /// Developer mode: every finding is exported as before.
    #[test]
    fn findings_are_exported_as_before_in_developer_mode() {
        use crate::core::context_admission::stored::lineage_support::project;
        let _data = crate::core::data_dir::isolated_data_dir();
        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
        let (_directory, root) = project();
        let session = with_two_findings(&root);
        std::fs::remove_file(format!("{root}/pool.rs")).expect("delete");
        assert_eq!(
            exported(&session),
            ["the pool leaks one lease", "noted without a file"]
        );
    }
}