lean-ctx 3.12.6

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
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
// SPDX-License-Identifier: Apache-2.0
use lean_ctx::core::session::SessionState;
use lean_ctx::core::stats;
use lean_ctx_server::tools::ctx_session::{self, SessionToolOptions};

use super::common::{format_tokens_cli, load_shell_history};

pub fn cmd_session_action(args: &[String]) {
    let action = args.first().map(String::as_str);

    // Local Read v1: an app session's counters and cost as JSON.
    if let Some(kind @ ("stats" | "cost")) = action
        && super::local_read::wants_json(args)
    {
        super::local_read::session::run(kind, &args[1..]);
        return;
    }

    match action {
        Some("task") => {
            let desc = args.get(1).map_or("(no description)", String::as_str);
            #[cfg(unix)]
            {
                #[cfg(unix)]
                if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
                    "ctx_session",
                    Some(serde_json::json!({ "action": "task", "value": desc })),
                ) {
                    println!("{out}");
                    return;
                }
            }
            let mut session = load_or_create_session();
            let out = run_admitted_cli_action(&mut session, "task", desc);
            println!("{out}");
        }
        Some("finding") => {
            let summary = args.get(1).map_or("(no summary)", String::as_str);
            #[cfg(unix)]
            {
                #[cfg(unix)]
                if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
                    "ctx_session",
                    Some(serde_json::json!({ "action": "finding", "value": summary })),
                ) {
                    println!("{out}");
                    return;
                }
            }
            let mut session = load_or_create_session();
            let out = run_admitted_cli_action(&mut session, "finding", summary);
            println!("{out}");
        }
        Some("save") => {
            #[cfg(unix)]
            {
                #[cfg(unix)]
                if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
                    "ctx_session",
                    Some(serde_json::json!({ "action": "save" })),
                ) {
                    println!("{out}");
                    return;
                }
            }
            let mut session = load_or_create_session();
            match ctx_session::save_session(&mut session) {
                Ok(out) => println!("{out}"),
                Err(error) => {
                    eprintln!("Session was not saved: {error}");
                    std::process::exit(1);
                }
            }
        }
        Some("load") => {
            let id = args.get(1).map(String::as_str);
            #[cfg(unix)]
            {
                #[cfg(unix)]
                if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
                    "ctx_session",
                    Some(serde_json::json!({ "action": "load", "session_id": id })),
                ) {
                    println!("{out}");
                    return;
                }
            }
            let mut session = SessionState::new();
            stamp_current_project_root(&mut session);
            let out = released_session_text(&session_root(&session), || {
                ctx_session::handle(&mut session, &[], "load", None, id, default_opts())
            });
            super::common::print_released(&out);
        }
        Some("status") => {
            #[cfg(unix)]
            {
                #[cfg(unix)]
                if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
                    "ctx_session",
                    Some(serde_json::json!({ "action": "status" })),
                ) {
                    println!("{out}");
                    return;
                }
            }
            let mut session = load_or_create_session();
            let out = released_session_text(&session_root(&session), || {
                ctx_session::handle(&mut session, &[], "status", None, None, default_opts())
            });
            super::common::print_released(&out);
        }
        Some("decision") => {
            let desc = args.get(1).map_or("(no description)", String::as_str);
            #[cfg(unix)]
            {
                #[cfg(unix)]
                if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
                    "ctx_session",
                    Some(serde_json::json!({ "action": "decision", "value": desc })),
                ) {
                    println!("{out}");
                    return;
                }
            }
            let mut session = load_or_create_session();
            let out = run_admitted_cli_action(&mut session, "decision", desc);
            println!("{out}");
        }
        Some("reset" | "new") => {
            #[cfg(unix)]
            {
                #[cfg(unix)]
                if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
                    "ctx_session",
                    Some(serde_json::json!({ "action": "reset" })),
                ) {
                    println!("{out}");
                    return;
                }
            }
            let mut session = load_or_create_session();
            let out = released_session_text(&session_root(&session), || {
                ctx_session::handle(&mut session, &[], "reset", None, None, default_opts())
            });
            super::common::print_released(&out);
        }
        Some("readset") => cmd_session_readset(&args[1..]),
        None => {
            cmd_session_legacy();
        }
        Some(other) => {
            eprintln!("Unknown session action: {other}");
            print_session_help();
            std::process::exit(1);
        }
    }
}

/// `session readset --json [--root DIR] [--id ID]...`: the files the latest
/// session of DIR (default: the current directory), or the named sessions,
/// read, relative to DIR. Read by `scripts/eccp-envelope` (ECCP
/// `observed_reads`). Exit 1 when there is no such session.
fn cmd_session_readset(args: &[String]) {
    let mut root = None;
    let mut ids = Vec::new();
    let mut rest = args.iter();
    while let Some(arg) = rest.next() {
        match arg.as_str() {
            "--json" => {}
            "--root" => root = rest.next().map(std::path::PathBuf::from),
            "--id" => ids.extend(rest.next().cloned()),
            other => {
                eprintln!("session readset: unknown argument {other}");
                std::process::exit(2);
            }
        }
    }
    let Some(root) = root.or_else(|| std::env::current_dir().ok()) else {
        eprintln!("session readset: no project root");
        std::process::exit(2);
    };
    match lean_ctx::core::session_readset::load(&root, &ids) {
        Ok(set) => match serde_json::to_string_pretty(&set) {
            Ok(json) => println!("{json}"),
            Err(error) => {
                eprintln!("session readset: {error}");
                std::process::exit(1);
            }
        },
        Err(error) => {
            eprintln!("session readset: {error}");
            std::process::exit(1);
        }
    }
}

fn run_admitted_cli_action(session: &mut SessionState, action: &str, value: &str) -> String {
    let prepared = ctx_session::prepare_admitted_action(
        session,
        &[],
        action,
        Some(value),
        None,
        default_opts(),
    )
    .unwrap_or_else(|_| {
        eprintln!("Session content withheld by current project or content policy.");
        std::process::exit(1);
    });
    if !prepared.store_admission.is_current() {
        eprintln!("Session policy changed during content admission; retry the operation.");
        std::process::exit(1);
    }
    *session = prepared.candidate;
    if !prepared.store_admission.is_current() {
        eprintln!("Session policy changed before persistence; retry the operation.");
        std::process::exit(1);
    }
    require_session_save(session);

    lean_ctx::core::session::admission::admit_tool_value(session, &prepared.output)
        .unwrap_or_else(|_| "[lean-ctx gateway: session content withheld]".into())
}

fn require_session_save(session: &mut SessionState) {
    if let Err(error) = session.save() {
        eprintln!("Session was not saved: {error}");
        std::process::exit(1);
    }
}

/// The project a session's text is released for: the session's own root.
/// Empty when it names none — the tool run then binds no project.
fn session_root(session: &SessionState) -> String {
    session.project_root.clone().unwrap_or_default()
}

/// Stored session text (tasks, findings, decisions, file notes) printed by a
/// local `session` sub-command goes through the shared CLI tool run: request
/// scope, the MCP release point, output redaction. It is a status view for
/// the person at the terminal, not a tool-result carrier, so no lineage is
/// recorded for it.
fn released_session_text(project_root: &str, render: impl FnOnce() -> String) -> String {
    super::common::CliToolRun::new("ctx_session", project_root, None)
        .human_facing()
        .deliver_text(render)
}

fn load_or_create_session() -> SessionState {
    let mut session = SessionState::load_latest().unwrap_or_default();
    stamp_current_project_root(&mut session);
    session
}

fn stamp_current_project_root(session: &mut SessionState) {
    // Stamp the project root on bare-CLI sessions the way the MCP daemon does
    // from its roots handshake. Without it a CLI-only flow
    // (`session task … ; snapshot create`) saves a rootless session that
    // `load_latest_for_project_root` can never match — the snapshot would then
    // silently drop its session slice.
    if session.project_root.is_none()
        && let Ok(cwd) = std::env::current_dir()
        && !lean_ctx::core::pathutil::is_broad_or_unsafe_root(&cwd)
    {
        session.project_root = Some(cwd.to_string_lossy().to_string());
    }
}

fn default_opts() -> SessionToolOptions<'static> {
    SessionToolOptions {
        format: None,
        path: None,
        write: false,
        privacy: None,
        terse: None,
        agent_id: None,
    }
}

fn print_session_help() {
    eprintln!(
        "\
lean-ctx session — Session management

Usage:
  lean-ctx session                      Show adoption statistics
  lean-ctx session task <description>   Set current task
  lean-ctx session finding <summary>    Record a finding
  lean-ctx session decision <summary>   Record a decision
  lean-ctx session save                 Save current session
  lean-ctx session load [session-id]    Load a session (latest if no ID)
  lean-ctx session status               Show session status
  lean-ctx session reset|new            Reset session
  lean-ctx session readset --json [--root DIR] [--id ID]...
                                        Files the session read (ECCP observed_reads)

Examples:
  lean-ctx session task \"implement JWT authentication\"
  lean-ctx session finding \"auth.rs:42 — missing token validation\"
  lean-ctx session save
  lean-ctx session load"
    );
}

fn cmd_session_legacy() {
    let history = load_shell_history();
    let gain = stats::load_stats();

    let compressible_commands = [
        "git ",
        "npm ",
        "yarn ",
        "pnpm ",
        "cargo ",
        "docker ",
        "kubectl ",
        "gh ",
        "pip ",
        "pip3 ",
        "eslint",
        "prettier",
        "ruff ",
        "go ",
        "golangci-lint",
        "curl ",
        "wget ",
        "grep ",
        "rg ",
        "find ",
        "ls ",
    ];

    let mut total = 0u32;
    let mut via_hook = 0u32;

    for line in &history {
        let cmd = line.trim().to_lowercase();
        if cmd.starts_with("lean-ctx") {
            via_hook += 1;
            total += 1;
        } else {
            for p in &compressible_commands {
                if cmd.starts_with(p) {
                    total += 1;
                    break;
                }
            }
        }
    }

    let pct = if total > 0 {
        (via_hook as f64 / total as f64 * 100.0).round() as u32
    } else {
        0
    };

    println!("lean-ctx session statistics\n");
    println!("Adoption:    {pct}% ({via_hook}/{total} compressible commands)");
    println!("Saved:       {} tokens total", gain.total_saved);
    println!("Calls:       {} compressed", gain.total_calls);

    if total > via_hook {
        let missed = total - via_hook;
        let est = missed * 150;
        println!("Missed:      {missed} commands (~{est} tokens saveable)");
    }

    println!("\nRun 'lean-ctx discover' for details on missed commands.");
}

pub fn cmd_sessions(args: &[String]) {
    use lean_ctx::core::session::SessionState;

    let action = args.first().map_or("list", std::string::String::as_str);

    match action {
        "list" | "ls" => {
            let sessions = SessionState::list_sessions();
            if sessions.is_empty() {
                println!("No sessions found.");
                return;
            }
            println!("Sessions ({}):\n", sessions.len());
            for s in sessions.iter().take(20) {
                let task = s.task.as_deref().unwrap_or("(no task)");
                let task_short: String = task.chars().take(50).collect();
                let date = s.updated_at.format("%Y-%m-%d %H:%M");
                println!(
                    "  {} | v{:3} | {:5} calls | {:>8} tok | {} | {}",
                    s.id,
                    s.version,
                    s.tool_calls,
                    format_tokens_cli(s.tokens_saved),
                    date,
                    task_short
                );
            }
            if sessions.len() > 20 {
                println!("  ... +{} more", sessions.len() - 20);
            }
        }
        "show" => {
            let id = args.get(1);
            // An explicit id shows that session; without one only the current
            // project's latest — never whichever project was active last
            // (AP04-G8).
            let session = if let Some(id) = id {
                SessionState::load_by_id(id)
            } else {
                SessionState::load_latest()
            };
            match session {
                Some(s) => {
                    if id.is_none() {
                        // A person's inspection view, labelled: the latest
                        // saved session may belong to any agent (I07/S03).
                        println!(
                            "Latest saved session of this project ({}) — may belong to another agent:",
                            s.id
                        );
                    }
                    super::common::print_released(&released_session_text(
                        &session_root(&s),
                        || s.format_compact(),
                    ));
                }
                None => println!("Session not found."),
            }
        }
        "cleanup" => {
            let days = args
                .get(1)
                .and_then(|value| value.parse::<i64>().ok())
                .unwrap_or_else(|| {
                    i64::from(
                        lean_ctx::core::config::Config::load().session_retention_days_effective(),
                    )
                });
            let removed = SessionState::cleanup_old_sessions(days);
            let (wf_removed, wf_freed) = lean_ctx::core::workflow::cleanup_expired();
            println!("Cleaned up {removed} session(s) older than {days} days.");
            if wf_removed > 0 {
                println!(
                    "Cleaned up {wf_removed} expired workflow file(s) ({:.1} KB freed).",
                    wf_freed as f64 / 1024.0
                );
            }
        }
        "delete" | "rm" => {
            let Some(id) = args.get(1) else {
                eprintln!("Usage: lean-ctx sessions delete <id>");
                std::process::exit(1);
            };
            match SessionState::delete_session(id) {
                Ok(true) => println!("Deleted session {id}."),
                Ok(false) => {
                    eprintln!("Session not found: {id}");
                    std::process::exit(1);
                }
                Err(e) => {
                    eprintln!("Failed to delete session {id}: {e}");
                    std::process::exit(1);
                }
            }
        }
        "doctor" => {
            let apply = args.iter().any(|a| a == "--apply" || a == "--fix");
            let (found, quarantined) = SessionState::doctor_quarantine_unsafe_roots(apply);
            if found.is_empty() {
                println!("session doctor: no contaminated sessions found.");
            } else {
                println!(
                    "session doctor: {} session(s) rooted at a broad/unsafe path (HOME/'/'/agent dir):",
                    found.len()
                );
                for (id, root) in &found {
                    println!("  {id} | root: {root}");
                }
                if apply {
                    println!("\nQuarantined {quarantined} session(s) to sessions/quarantine/.");
                } else {
                    println!("\nRun `lean-ctx sessions doctor --apply` to quarantine them.");
                }
            }
        }
        _ => {
            eprintln!(
                "Usage: lean-ctx sessions [list|show [id]|delete <id>|cleanup [days]|doctor [--apply]]"
            );
            std::process::exit(1);
        }
    }
}