lean-ctx 3.12.7

LeanCTX | OSS: the open-source runtime for the Context Gateway for AI agents. CLI, MCP server, and supported 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
// SPDX-License-Identifier: Apache-2.0
//! `lean-ctx snapshot` — create / list / show / verify Context Snapshots (#1024).
//!
//! Headless surface of the Context Time Machine: capture the current context
//! state as a git-anchored, signed snapshot and browse the append-only timeline.

use lean_ctx::core::context_snapshot::{
    self, ContextSnapshotV1, GitRestore, ImportOutcome, PublishOptions, PublishOutcome,
    RestoreOptions, RestoreOutcome, SnapshotOptions,
};

pub(crate) fn cmd_snapshot(args: &[String]) {
    let subcommand = args
        .iter()
        .find(|a| !a.starts_with("--"))
        .map_or("list", String::as_str);

    match subcommand {
        "create" => cmd_create(args),
        "list" | "ls" => cmd_list(args),
        "show" => cmd_show(args),
        "verify" => cmd_verify(args),
        "restore" => cmd_restore(args),
        "publish" => cmd_publish(args),
        "import" => cmd_import(args),
        other => {
            eprintln!("unknown snapshot subcommand: {other}");
            usage();
            std::process::exit(2);
        }
    }
}

fn usage() {
    eprintln!(
        "Usage: lean-ctx snapshot <create|list|show|verify|restore|publish|import> [options]\n\
         \n  create [--sign]      build + store a snapshot of the current context state\
         \n  list [--json]        list this project's snapshot timeline\
         \n  show <id> [--json]   print a stored snapshot\
         \n  verify <id>          check a snapshot's signature + integrity\
         \n  restore <id> [--git] resume the snapshot's session (and, with --git, check out its commit)\
         \n  publish <id> [--out <path>]  write a signed, shareable snapshot file\
         \n  import <file>        verify + add a shared snapshot to this project's timeline\
         \n\nCommon: [--root <path>] selects the project (default: cwd)."
    );
}

fn has_flag(args: &[String], flag: &str) -> bool {
    args.iter().any(|a| a == flag)
}

/// Value following `flag` (e.g. `--out <path>`), if present.
fn flag_value(args: &[String], flag: &str) -> Option<String> {
    args.iter()
        .position(|a| a == flag)
        .and_then(|i| args.get(i + 1))
        .cloned()
}

/// First non-flag argument after the subcommand (the id for show / verify).
fn id_arg(args: &[String]) -> Option<String> {
    args.iter().filter(|a| !a.starts_with("--")).nth(1).cloned()
}

/// The run of a `snapshot` output. A snapshot is stored session context
/// (task, findings, touched files); what this command prints about it is a
/// summary for the person at the terminal or a `--json` document for a
/// script. Both pass the release point; neither is recorded as a delivery of
/// project sources.
fn snapshot_run(project_root: &str) -> super::common::CliToolRun<'_> {
    super::common::CliToolRun::new("ctx_session", project_root, None).human_facing()
}

/// Print a rendered report (it ends with its own newline) through the run.
/// It is released without that final `\n`, which the one observed writer
/// adds back: the bytes on stdout are unchanged and the hand-over is
/// observed (G08). A report without a final newline is printed as before.
fn print_report(project_root: &str, rendered: String) {
    let run = snapshot_run(project_root);
    match rendered.strip_suffix('\n') {
        Some(body) => {
            let body = body.to_owned();
            super::common::print_released(&run.deliver_text(|| body));
        }
        None => print!("{}", run.deliver_text(|| rendered)),
    }
}

/// Print a `--json` document through the run: valid JSON or nothing.
fn print_document(project_root: &str, document: String) {
    match snapshot_run(project_root).deliver_json(|| document) {
        Ok(document) => super::common::print_released(&document),
        Err(reason) => super::common::exit_withheld(&reason),
    }
}

fn cmd_create(args: &[String]) {
    let opts = SnapshotOptions {
        project_root: super::common::detect_project_root(args),
        sign: has_flag(args, "--sign"),
    };
    match context_snapshot::create(&opts) {
        Ok(snap) => print_report(&opts.project_root, render_summary(&snap)),
        Err(e) => fail(&e),
    }
}

fn cmd_list(args: &[String]) {
    use std::fmt::Write as _;
    let project_root = super::common::detect_project_root(args);
    let entries = context_snapshot::load_entries(&project_root);

    if has_flag(args, "--json") {
        match serde_json::to_string_pretty(&entries) {
            Ok(j) => print_document(&project_root, j),
            Err(e) => fail(&e.to_string()),
        }
        return;
    }
    if entries.is_empty() {
        println!("No snapshots yet. Create one with: lean-ctx snapshot create");
        return;
    }
    let mut listing = format!("{} snapshot(s):\n", entries.len());
    for e in &entries {
        let commit = e
            .git_commit
            .as_deref()
            .map_or_else(|| "-------".to_string(), short_commit);
        let branch = e.git_branch.as_deref().unwrap_or("-");
        let sig = if e.signed { " [signed]" } else { "" };
        let _ = writeln!(
            listing,
            "  {}  {}  {commit} {branch}  saved {} tok{sig}",
            short(&e.snapshot_id),
            e.created_at,
            e.tokens_saved
        );
    }
    print_report(&project_root, listing);
}

fn cmd_show(args: &[String]) {
    let project_root = super::common::detect_project_root(args);
    let Some(id) = id_arg(args) else {
        fail_usage("snapshot id required: lean-ctx snapshot show <id>");
        return;
    };
    let id = match context_snapshot::resolve_id(&project_root, &id) {
        Ok(full) => full,
        Err(e) => {
            fail(&e);
            return;
        }
    };
    match context_snapshot::read_snapshot(&project_root, &id) {
        Ok(snap) if has_flag(args, "--json") => match serde_json::to_string_pretty(&snap) {
            Ok(j) => print_document(&project_root, j),
            Err(e) => fail(&e.to_string()),
        },
        Ok(snap) => print_report(&project_root, render_summary(&snap)),
        Err(e) => fail(&e),
    }
}

fn cmd_verify(args: &[String]) {
    let project_root = super::common::detect_project_root(args);
    let Some(id) = id_arg(args) else {
        fail_usage("snapshot id required: lean-ctx snapshot verify <id>");
        return;
    };
    let id = match context_snapshot::resolve_id(&project_root, &id) {
        Ok(full) => full,
        Err(e) => {
            fail(&e);
            return;
        }
    };
    let snap = match context_snapshot::read_snapshot(&project_root, &id) {
        Ok(s) => s,
        Err(e) => {
            fail(&e);
            return;
        }
    };
    match context_snapshot::verify_snapshot(&snap) {
        Ok(true) => println!(
            "OK: {} verified (signature + integrity)",
            short(&snap.snapshot_id)
        ),
        Ok(false) => {
            if snap.signature.is_none() {
                println!("UNSIGNED: {} has no signature", short(&snap.snapshot_id));
            } else {
                println!(
                    "FAILED: {} signature or integrity check did not pass",
                    short(&snap.snapshot_id)
                );
            }
            std::process::exit(1);
        }
        Err(e) => fail(&e),
    }
}

fn cmd_restore(args: &[String]) {
    let project_root = super::common::detect_project_root(args);
    let Some(id) = id_arg(args) else {
        fail_usage("snapshot id required: lean-ctx snapshot restore <id>");
        return;
    };
    let id = match context_snapshot::resolve_id(&project_root, &id) {
        Ok(full) => full,
        Err(e) => {
            fail(&e);
            return;
        }
    };
    let snap = match context_snapshot::read_snapshot(&project_root, &id) {
        Ok(s) => s,
        Err(e) => {
            fail(&e);
            return;
        }
    };
    let opts = RestoreOptions {
        project_root,
        checkout_git: has_flag(args, "--git"),
    };
    match context_snapshot::restore(&snap, &opts) {
        Ok(outcome) => print_report(&opts.project_root, render_restore(&snap, &outcome)),
        Err(e) => fail(&e),
    }
}

fn render_restore(s: &ContextSnapshotV1, o: &RestoreOutcome) -> String {
    use std::fmt::Write;
    let mut out = String::new();
    let _ = writeln!(out, "restored from snapshot {}", short(&s.snapshot_id));

    if o.had_session_slice {
        if let Some(task) = o.session.task.as_deref() {
            let pct = o
                .session
                .progress_pct
                .map_or_else(String::new, |p| format!(" ({p}%)"));
            let _ = writeln!(out, "  session  task: {task}{pct}");
        }
        let _ = writeln!(
            out,
            "  session  +{} decision(s), +{} file(s) resumed",
            o.session.decisions_added, o.session.files_added
        );
    } else {
        let _ = writeln!(out, "  session  (snapshot carried no session slice)");
    }

    let git_line = match &o.git {
        GitRestore::Skipped => s.git.commit.as_deref().map_or_else(
            || "not touched".to_string(),
            |c| {
                format!(
                    "not touched — rerun with --git to check out {}",
                    short_commit(c)
                )
            },
        ),
        GitRestore::NoAnchor => "no commit anchor to check out".to_string(),
        GitRestore::DirtyTree => {
            "SKIPPED — working tree has uncommitted changes (commit or stash first)".to_string()
        }
        GitRestore::CheckedOut(c) => format!("checked out {}", short_commit(c)),
        GitRestore::Failed(e) => format!("checkout failed: {e}"),
    };
    let _ = writeln!(out, "  git      {git_line}");
    out
}

fn cmd_publish(args: &[String]) {
    let project_root = super::common::detect_project_root(args);
    let Some(id) = id_arg(args) else {
        fail_usage("snapshot id required: lean-ctx snapshot publish <id>");
        return;
    };
    let id = match context_snapshot::resolve_id(&project_root, &id) {
        Ok(full) => full,
        Err(e) => {
            fail(&e);
            return;
        }
    };
    let snap = match context_snapshot::read_snapshot(&project_root, &id) {
        Ok(s) => s,
        Err(e) => {
            fail(&e);
            return;
        }
    };
    let opts = PublishOptions {
        project_root,
        out: flag_value(args, "--out").map(std::path::PathBuf::from),
    };
    match context_snapshot::publish(&snap, &opts) {
        Ok(outcome) => print_report(&opts.project_root, render_publish(&snap, &outcome)),
        Err(e) => fail(&e),
    }
}

fn cmd_import(args: &[String]) {
    let project_root = super::common::detect_project_root(args);
    let Some(file) = id_arg(args) else {
        fail_usage("snapshot file required: lean-ctx snapshot import <file>");
        return;
    };
    match context_snapshot::import(std::path::Path::new(&file), &project_root) {
        Ok(outcome) => print_report(&project_root, render_import(&outcome)),
        Err(e) => fail(&e),
    }
}

fn render_publish(s: &ContextSnapshotV1, o: &PublishOutcome) -> String {
    use std::fmt::Write;
    let mut out = String::new();
    let _ = writeln!(out, "published snapshot {}", short(&s.snapshot_id));
    let _ = writeln!(out, "  file     {}", o.path.display());
    let _ = writeln!(
        out,
        "  signed   {} (publisher {})",
        if o.newly_signed { "now" } else { "already" },
        short(&o.public_key)
    );
    let _ = writeln!(
        out,
        "  share    send the file; the recipient runs: lean-ctx snapshot import <file>"
    );
    out
}

fn render_import(o: &ImportOutcome) -> String {
    use std::fmt::Write;
    let mut out = String::new();
    let verb = if o.already_present {
        "already in timeline"
    } else {
        "imported"
    };
    let _ = writeln!(out, "{verb}: snapshot {}", short(&o.snapshot_id));
    let provenance = if !o.signed {
        "unsigned — no provenance".to_string()
    } else if o.verified {
        "signature verified".to_string()
    } else {
        "signature INVALID".to_string()
    };
    let _ = writeln!(out, "  provenance {provenance}");
    if !o.already_present {
        let _ = writeln!(
            out,
            "  next     lean-ctx snapshot show {} | restore {}",
            short(&o.snapshot_id),
            short(&o.snapshot_id)
        );
    }
    out
}

fn render_summary(s: &ContextSnapshotV1) -> String {
    use std::fmt::Write;
    let mut out = String::new();
    let _ = writeln!(out, "snapshot {}", s.snapshot_id);
    let git = match (&s.git.commit, &s.git.branch) {
        (Some(c), Some(b)) => format!(
            "{} on {b}{}",
            short_commit(c),
            if s.git.dirty { " (dirty)" } else { "" }
        ),
        _ => "(no git anchor)".to_string(),
    };
    let _ = writeln!(out, "  git      {git}");
    let _ = writeln!(
        out,
        "  roi      saved {} tok, {:.1}% compression",
        s.roi.tokens_saved,
        s.roi.compression_rate * 100.0
    );
    let _ = writeln!(
        out,
        "  lineage  {} items (recorded {})",
        s.lineage.items.len(),
        s.lineage.items_recorded
    );
    let _ = writeln!(out, "  ledger   {} items", s.ledger.items.len());
    if let Some(task) = s.session.as_ref().and_then(|sess| sess.task.as_deref()) {
        let _ = writeln!(out, "  task     {task}");
    }
    let parent = s
        .parent_id
        .as_deref()
        .map_or_else(|| "(root)".to_string(), short);
    let _ = writeln!(out, "  parent   {parent}");
    let _ = writeln!(
        out,
        "  signed   {}",
        if s.signature.is_some() { "yes" } else { "no" }
    );
    out
}

fn short(id: &str) -> String {
    id.chars().take(12).collect()
}

fn short_commit(c: &str) -> String {
    c.chars().take(7).collect()
}

fn fail(msg: &str) {
    eprintln!("ERROR: {msg}");
    std::process::exit(1);
}

fn fail_usage(msg: &str) {
    eprintln!("ERROR: {msg}");
    usage();
    std::process::exit(2);
}

#[cfg(test)]
mod tests {
    use crate::cli::common::carrier_tests_support::{
        AWS_KEY, acquire_source, governed, lineage, project, source_file,
    };

    /// A snapshot summary or `--json` document is a report about stored
    /// session context: released, never registered as a delivery.
    #[test]
    fn a_snapshot_report_is_human_facing() {
        let _data = lean_ctx::core::data_dir::isolated_data_dir();
        let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
        governed();
        let (_project, root) = project();
        let path = source_file(&root, "lib.rs", "pub fn touched() {}\n");
        let summary = "snapshot 0123abcd\n  ledger   3 items\n";
        let printed = super::snapshot_run(&root).deliver_text(|| {
            acquire_source(&root, &path);
            summary.to_string()
        });
        assert_eq!(printed, summary);
        assert_eq!(lineage(&root, &printed), None);

        let document = serde_json::json!({ "snapshot_id": "0123abcd", "task": AWS_KEY });
        let pretty = serde_json::to_string_pretty(&document).expect("document");
        match super::snapshot_run(&root).deliver_json(|| pretty) {
            Ok(released) => {
                assert!(!released.contains(AWS_KEY), "{released}");
                let value: serde_json::Value = serde_json::from_str(&released).expect("valid JSON");
                assert_eq!(value["snapshot_id"], "0123abcd");
            }
            Err(reason) => assert!(!reason.contains(AWS_KEY), "{reason}"),
        }
    }
}