Skip to main content

lean_ctx/cli/
session_cmd.rs

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