Skip to main content

lean_ctx_cli/cli/
session_cmd.rs

1// SPDX-License-Identifier: Apache-2.0
2use lean_ctx::core::session::SessionState;
3use lean_ctx::core::stats;
4use lean_ctx_server::tools::ctx_session::{self, SessionToolOptions};
5
6use super::common::{format_tokens_cli, load_shell_history};
7
8pub fn cmd_session_action(args: &[String]) {
9    let action = args.first().map(String::as_str);
10
11    match action {
12        Some("task") => {
13            let desc = args.get(1).map_or("(no description)", String::as_str);
14            #[cfg(unix)]
15            {
16                #[cfg(unix)]
17                if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
18                    "ctx_session",
19                    Some(serde_json::json!({ "action": "task", "value": desc })),
20                ) {
21                    println!("{out}");
22                    return;
23                }
24            }
25            let mut session = load_or_create_session();
26            let out = run_admitted_cli_action(&mut session, "task", desc);
27            println!("{out}");
28        }
29        Some("finding") => {
30            let summary = args.get(1).map_or("(no summary)", String::as_str);
31            #[cfg(unix)]
32            {
33                #[cfg(unix)]
34                if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
35                    "ctx_session",
36                    Some(serde_json::json!({ "action": "finding", "value": summary })),
37                ) {
38                    println!("{out}");
39                    return;
40                }
41            }
42            let mut session = load_or_create_session();
43            let out = run_admitted_cli_action(&mut session, "finding", summary);
44            println!("{out}");
45        }
46        Some("save") => {
47            #[cfg(unix)]
48            {
49                #[cfg(unix)]
50                if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
51                    "ctx_session",
52                    Some(serde_json::json!({ "action": "save" })),
53                ) {
54                    println!("{out}");
55                    return;
56                }
57            }
58            let mut session = load_or_create_session();
59            match ctx_session::save_session(&mut session) {
60                Ok(out) => println!("{out}"),
61                Err(error) => {
62                    eprintln!("Session was not saved: {error}");
63                    std::process::exit(1);
64                }
65            }
66        }
67        Some("load") => {
68            let id = args.get(1).map(String::as_str);
69            #[cfg(unix)]
70            {
71                #[cfg(unix)]
72                if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
73                    "ctx_session",
74                    Some(serde_json::json!({ "action": "load", "session_id": id })),
75                ) {
76                    println!("{out}");
77                    return;
78                }
79            }
80            let mut session = SessionState::new();
81            stamp_current_project_root(&mut session);
82            let out = released_session_text(&session_root(&session), || {
83                ctx_session::handle(&mut session, &[], "load", None, id, default_opts())
84            });
85            super::common::print_released(&out);
86        }
87        Some("status") => {
88            #[cfg(unix)]
89            {
90                #[cfg(unix)]
91                if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
92                    "ctx_session",
93                    Some(serde_json::json!({ "action": "status" })),
94                ) {
95                    println!("{out}");
96                    return;
97                }
98            }
99            let mut session = load_or_create_session();
100            let out = released_session_text(&session_root(&session), || {
101                ctx_session::handle(&mut session, &[], "status", None, None, default_opts())
102            });
103            super::common::print_released(&out);
104        }
105        Some("decision") => {
106            let desc = args.get(1).map_or("(no description)", String::as_str);
107            #[cfg(unix)]
108            {
109                #[cfg(unix)]
110                if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
111                    "ctx_session",
112                    Some(serde_json::json!({ "action": "decision", "value": desc })),
113                ) {
114                    println!("{out}");
115                    return;
116                }
117            }
118            let mut session = load_or_create_session();
119            let out = run_admitted_cli_action(&mut session, "decision", desc);
120            println!("{out}");
121        }
122        Some("reset" | "new") => {
123            #[cfg(unix)]
124            {
125                #[cfg(unix)]
126                if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
127                    "ctx_session",
128                    Some(serde_json::json!({ "action": "reset" })),
129                ) {
130                    println!("{out}");
131                    return;
132                }
133            }
134            let mut session = load_or_create_session();
135            let out = released_session_text(&session_root(&session), || {
136                ctx_session::handle(&mut session, &[], "reset", None, None, default_opts())
137            });
138            super::common::print_released(&out);
139        }
140        None => {
141            cmd_session_legacy();
142        }
143        Some(other) => {
144            eprintln!("Unknown session action: {other}");
145            print_session_help();
146            std::process::exit(1);
147        }
148    }
149}
150
151fn run_admitted_cli_action(session: &mut SessionState, action: &str, value: &str) -> String {
152    let prepared = ctx_session::prepare_admitted_action(
153        session,
154        &[],
155        action,
156        Some(value),
157        None,
158        default_opts(),
159    )
160    .unwrap_or_else(|_| {
161        eprintln!("Session content withheld by current project or content policy.");
162        std::process::exit(1);
163    });
164    if !prepared.store_admission.is_current() {
165        eprintln!("Session policy changed during content admission; retry the operation.");
166        std::process::exit(1);
167    }
168    *session = prepared.candidate;
169    if !prepared.store_admission.is_current() {
170        eprintln!("Session policy changed before persistence; retry the operation.");
171        std::process::exit(1);
172    }
173    require_session_save(session);
174
175    lean_ctx::core::session::admission::admit_tool_value(session, &prepared.output)
176        .unwrap_or_else(|_| "[lean-ctx gateway: session content withheld]".into())
177}
178
179fn require_session_save(session: &mut SessionState) {
180    if let Err(error) = session.save() {
181        eprintln!("Session was not saved: {error}");
182        std::process::exit(1);
183    }
184}
185
186/// The project a session's text is released for: the session's own root.
187/// Empty when it names none — the tool run then binds no project.
188fn session_root(session: &SessionState) -> String {
189    session.project_root.clone().unwrap_or_default()
190}
191
192/// Stored session text (tasks, findings, decisions, file notes) printed by a
193/// local `session` sub-command goes through the shared CLI tool run: request
194/// scope, the MCP release point, output redaction. It is a status view for
195/// the person at the terminal, not a tool-result carrier, so no lineage is
196/// recorded for it.
197fn released_session_text(project_root: &str, render: impl FnOnce() -> String) -> String {
198    super::common::CliToolRun::new("ctx_session", project_root, None)
199        .human_facing()
200        .deliver_text(render)
201}
202
203fn load_or_create_session() -> SessionState {
204    let mut session = SessionState::load_latest().unwrap_or_default();
205    stamp_current_project_root(&mut session);
206    session
207}
208
209fn stamp_current_project_root(session: &mut SessionState) {
210    // Stamp the project root on bare-CLI sessions the way the MCP daemon does
211    // from its roots handshake. Without it a CLI-only flow
212    // (`session task … ; snapshot create`) saves a rootless session that
213    // `load_latest_for_project_root` can never match — the snapshot would then
214    // silently drop its session slice.
215    if session.project_root.is_none()
216        && let Ok(cwd) = std::env::current_dir()
217        && !lean_ctx::core::pathutil::is_broad_or_unsafe_root(&cwd)
218    {
219        session.project_root = Some(cwd.to_string_lossy().to_string());
220    }
221}
222
223fn default_opts() -> SessionToolOptions<'static> {
224    SessionToolOptions {
225        format: None,
226        path: None,
227        write: false,
228        privacy: None,
229        terse: None,
230        agent_id: None,
231    }
232}
233
234fn print_session_help() {
235    eprintln!(
236        "\
237lean-ctx session — Session management
238
239Usage:
240  lean-ctx session                      Show adoption statistics
241  lean-ctx session task <description>   Set current task
242  lean-ctx session finding <summary>    Record a finding
243  lean-ctx session decision <summary>   Record a decision
244  lean-ctx session save                 Save current session
245  lean-ctx session load [session-id]    Load a session (latest if no ID)
246  lean-ctx session status               Show session status
247  lean-ctx session reset|new            Reset session
248
249Examples:
250  lean-ctx session task \"implement JWT authentication\"
251  lean-ctx session finding \"auth.rs:42 — missing token validation\"
252  lean-ctx session save
253  lean-ctx session load"
254    );
255}
256
257fn cmd_session_legacy() {
258    let history = load_shell_history();
259    let gain = stats::load_stats();
260
261    let compressible_commands = [
262        "git ",
263        "npm ",
264        "yarn ",
265        "pnpm ",
266        "cargo ",
267        "docker ",
268        "kubectl ",
269        "gh ",
270        "pip ",
271        "pip3 ",
272        "eslint",
273        "prettier",
274        "ruff ",
275        "go ",
276        "golangci-lint",
277        "curl ",
278        "wget ",
279        "grep ",
280        "rg ",
281        "find ",
282        "ls ",
283    ];
284
285    let mut total = 0u32;
286    let mut via_hook = 0u32;
287
288    for line in &history {
289        let cmd = line.trim().to_lowercase();
290        if cmd.starts_with("lean-ctx") {
291            via_hook += 1;
292            total += 1;
293        } else {
294            for p in &compressible_commands {
295                if cmd.starts_with(p) {
296                    total += 1;
297                    break;
298                }
299            }
300        }
301    }
302
303    let pct = if total > 0 {
304        (via_hook as f64 / total as f64 * 100.0).round() as u32
305    } else {
306        0
307    };
308
309    println!("lean-ctx session statistics\n");
310    println!("Adoption:    {pct}% ({via_hook}/{total} compressible commands)");
311    println!("Saved:       {} tokens total", gain.total_saved);
312    println!("Calls:       {} compressed", gain.total_calls);
313
314    if total > via_hook {
315        let missed = total - via_hook;
316        let est = missed * 150;
317        println!("Missed:      {missed} commands (~{est} tokens saveable)");
318    }
319
320    println!("\nRun 'lean-ctx discover' for details on missed commands.");
321}
322
323pub fn cmd_sessions(args: &[String]) {
324    use lean_ctx::core::session::SessionState;
325
326    let action = args.first().map_or("list", std::string::String::as_str);
327
328    match action {
329        "list" | "ls" => {
330            let sessions = SessionState::list_sessions();
331            if sessions.is_empty() {
332                println!("No sessions found.");
333                return;
334            }
335            println!("Sessions ({}):\n", sessions.len());
336            for s in sessions.iter().take(20) {
337                let task = s.task.as_deref().unwrap_or("(no task)");
338                let task_short: String = task.chars().take(50).collect();
339                let date = s.updated_at.format("%Y-%m-%d %H:%M");
340                println!(
341                    "  {} | v{:3} | {:5} calls | {:>8} tok | {} | {}",
342                    s.id,
343                    s.version,
344                    s.tool_calls,
345                    format_tokens_cli(s.tokens_saved),
346                    date,
347                    task_short
348                );
349            }
350            if sessions.len() > 20 {
351                println!("  ... +{} more", sessions.len() - 20);
352            }
353        }
354        "show" => {
355            let id = args.get(1);
356            // An explicit id shows that session; without one only the current
357            // project's latest — never whichever project was active last
358            // (AP04-G8).
359            let session = if let Some(id) = id {
360                SessionState::load_by_id(id)
361            } else {
362                SessionState::load_latest()
363            };
364            match session {
365                Some(s) => {
366                    if id.is_none() {
367                        // A person's inspection view, labelled: the latest
368                        // saved session may belong to any agent (I07/S03).
369                        println!(
370                            "Latest saved session of this project ({}) — may belong to another agent:",
371                            s.id
372                        );
373                    }
374                    super::common::print_released(&released_session_text(
375                        &session_root(&s),
376                        || s.format_compact(),
377                    ));
378                }
379                None => println!("Session not found."),
380            }
381        }
382        "cleanup" => {
383            let days = args
384                .get(1)
385                .and_then(|value| value.parse::<i64>().ok())
386                .unwrap_or_else(|| {
387                    i64::from(
388                        lean_ctx::core::config::Config::load().session_retention_days_effective(),
389                    )
390                });
391            let removed = SessionState::cleanup_old_sessions(days);
392            let (wf_removed, wf_freed) = lean_ctx::core::workflow::cleanup_expired();
393            println!("Cleaned up {removed} session(s) older than {days} days.");
394            if wf_removed > 0 {
395                println!(
396                    "Cleaned up {wf_removed} expired workflow file(s) ({:.1} KB freed).",
397                    wf_freed as f64 / 1024.0
398                );
399            }
400        }
401        "delete" | "rm" => {
402            let Some(id) = args.get(1) else {
403                eprintln!("Usage: lean-ctx sessions delete <id>");
404                std::process::exit(1);
405            };
406            match SessionState::delete_session(id) {
407                Ok(true) => println!("Deleted session {id}."),
408                Ok(false) => {
409                    eprintln!("Session not found: {id}");
410                    std::process::exit(1);
411                }
412                Err(e) => {
413                    eprintln!("Failed to delete session {id}: {e}");
414                    std::process::exit(1);
415                }
416            }
417        }
418        "doctor" => {
419            let apply = args.iter().any(|a| a == "--apply" || a == "--fix");
420            let (found, quarantined) = SessionState::doctor_quarantine_unsafe_roots(apply);
421            if found.is_empty() {
422                println!("session doctor: no contaminated sessions found.");
423            } else {
424                println!(
425                    "session doctor: {} session(s) rooted at a broad/unsafe path (HOME/'/'/agent dir):",
426                    found.len()
427                );
428                for (id, root) in &found {
429                    println!("  {id} | root: {root}");
430                }
431                if apply {
432                    println!("\nQuarantined {quarantined} session(s) to sessions/quarantine/.");
433                } else {
434                    println!("\nRun `lean-ctx sessions doctor --apply` to quarantine them.");
435                }
436            }
437        }
438        _ => {
439            eprintln!(
440                "Usage: lean-ctx sessions [list|show [id]|delete <id>|cleanup [days]|doctor [--apply]]"
441            );
442            std::process::exit(1);
443        }
444    }
445}