1use 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 if let Some(kind @ ("stats" | "cost")) = action
13 && super::local_read::wants_json(args)
14 {
15 super::local_read::session::run(kind, &args[1..]);
16 return;
17 }
18 if action == Some("usage") && super::local_read::wants_json(args) {
20 super::local_read::session_usage::run(&args[1..]);
21 return;
22 }
23
24 match action {
25 Some("task") => {
26 let desc = args.get(1).map_or("(no description)", String::as_str);
27 #[cfg(unix)]
28 {
29 #[cfg(unix)]
30 if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
31 "ctx_session",
32 Some(serde_json::json!({ "action": "task", "value": desc })),
33 ) {
34 println!("{out}");
35 return;
36 }
37 }
38 let mut session = load_or_create_session();
39 let out = run_admitted_cli_action(&mut session, "task", desc);
40 println!("{out}");
41 }
42 Some("finding") => {
43 let summary = args.get(1).map_or("(no summary)", String::as_str);
44 #[cfg(unix)]
45 {
46 #[cfg(unix)]
47 if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
48 "ctx_session",
49 Some(serde_json::json!({ "action": "finding", "value": summary })),
50 ) {
51 println!("{out}");
52 return;
53 }
54 }
55 let mut session = load_or_create_session();
56 let out = run_admitted_cli_action(&mut session, "finding", summary);
57 println!("{out}");
58 }
59 Some("save") => {
60 #[cfg(unix)]
61 {
62 #[cfg(unix)]
63 if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
64 "ctx_session",
65 Some(serde_json::json!({ "action": "save" })),
66 ) {
67 println!("{out}");
68 return;
69 }
70 }
71 let mut session = load_or_create_session();
72 match ctx_session::save_session(&mut session) {
73 Ok(out) => println!("{out}"),
74 Err(error) => {
75 eprintln!("Session was not saved: {error}");
76 std::process::exit(1);
77 }
78 }
79 }
80 Some("load") => {
81 let id = args.get(1).map(String::as_str);
82 #[cfg(unix)]
83 {
84 #[cfg(unix)]
85 if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
86 "ctx_session",
87 Some(serde_json::json!({ "action": "load", "session_id": id })),
88 ) {
89 println!("{out}");
90 return;
91 }
92 }
93 let mut session = SessionState::new();
94 stamp_current_project_root(&mut session);
95 let out = released_session_text(&session_root(&session), || {
96 ctx_session::handle(&mut session, &[], "load", None, id, default_opts())
97 });
98 super::common::print_released(&out);
99 }
100 Some("status") => {
101 #[cfg(unix)]
102 {
103 #[cfg(unix)]
104 if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
105 "ctx_session",
106 Some(serde_json::json!({ "action": "status" })),
107 ) {
108 println!("{out}");
109 return;
110 }
111 }
112 let mut session = load_or_create_session();
113 let out = released_session_text(&session_root(&session), || {
114 ctx_session::handle(&mut session, &[], "status", None, None, default_opts())
115 });
116 super::common::print_released(&out);
117 }
118 Some("decision") => {
119 let desc = args.get(1).map_or("(no description)", String::as_str);
120 #[cfg(unix)]
121 {
122 #[cfg(unix)]
123 if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
124 "ctx_session",
125 Some(serde_json::json!({ "action": "decision", "value": desc })),
126 ) {
127 println!("{out}");
128 return;
129 }
130 }
131 let mut session = load_or_create_session();
132 let out = run_admitted_cli_action(&mut session, "decision", desc);
133 println!("{out}");
134 }
135 Some("reset" | "new") => {
136 #[cfg(unix)]
137 {
138 #[cfg(unix)]
139 if let Some(out) = lean_ctx::daemon_client::try_daemon_tool_call_blocking_text(
140 "ctx_session",
141 Some(serde_json::json!({ "action": "reset" })),
142 ) {
143 println!("{out}");
144 return;
145 }
146 }
147 let mut session = load_or_create_session();
148 let out = released_session_text(&session_root(&session), || {
149 ctx_session::handle(&mut session, &[], "reset", None, None, default_opts())
150 });
151 super::common::print_released(&out);
152 }
153 Some("readset") => cmd_session_readset(&args[1..]),
154 None => {
155 cmd_session_legacy();
156 }
157 Some(other) => {
158 eprintln!("Unknown session action: {other}");
159 print_session_help();
160 std::process::exit(1);
161 }
162 }
163}
164
165fn cmd_session_readset(args: &[String]) {
170 let mut root = None;
171 let mut ids = Vec::new();
172 let mut rest = args.iter();
173 while let Some(arg) = rest.next() {
174 match arg.as_str() {
175 "--json" => {}
176 "--root" => root = rest.next().map(std::path::PathBuf::from),
177 "--id" => ids.extend(rest.next().cloned()),
178 other => {
179 eprintln!("session readset: unknown argument {other}");
180 std::process::exit(2);
181 }
182 }
183 }
184 let Some(root) = root.or_else(|| std::env::current_dir().ok()) else {
185 eprintln!("session readset: no project root");
186 std::process::exit(2);
187 };
188 match lean_ctx_ext::core::session_readset::load(&root, &ids) {
189 Ok(set) => match serde_json::to_string_pretty(&set) {
190 Ok(json) => println!("{json}"),
191 Err(error) => {
192 eprintln!("session readset: {error}");
193 std::process::exit(1);
194 }
195 },
196 Err(error) => {
197 eprintln!("session readset: {error}");
198 std::process::exit(1);
199 }
200 }
201}
202
203fn run_admitted_cli_action(session: &mut SessionState, action: &str, value: &str) -> String {
204 let prepared = ctx_session::prepare_admitted_action(
205 session,
206 &[],
207 action,
208 Some(value),
209 None,
210 default_opts(),
211 )
212 .unwrap_or_else(|_| {
213 eprintln!("Session content withheld by current project or content policy.");
214 std::process::exit(1);
215 });
216 if !prepared.store_admission.is_current() {
217 eprintln!("Session policy changed during content admission; retry the operation.");
218 std::process::exit(1);
219 }
220 *session = prepared.candidate;
221 if !prepared.store_admission.is_current() {
222 eprintln!("Session policy changed before persistence; retry the operation.");
223 std::process::exit(1);
224 }
225 require_session_save(session);
226
227 lean_ctx::core::session::admission::admit_tool_value(session, &prepared.output)
228 .unwrap_or_else(|_| "[lean-ctx gateway: session content withheld]".into())
229}
230
231fn require_session_save(session: &mut SessionState) {
232 if let Err(error) = session.save() {
233 eprintln!("Session was not saved: {error}");
234 std::process::exit(1);
235 }
236}
237
238fn session_root(session: &SessionState) -> String {
241 session.project_root.clone().unwrap_or_default()
242}
243
244fn released_session_text(project_root: &str, render: impl FnOnce() -> String) -> String {
250 super::common::CliToolRun::new("ctx_session", project_root, None)
251 .human_facing()
252 .deliver_text(render)
253}
254
255fn load_or_create_session() -> SessionState {
256 let mut session = SessionState::load_latest().unwrap_or_default();
257 stamp_current_project_root(&mut session);
258 session
259}
260
261fn stamp_current_project_root(session: &mut SessionState) {
262 if session.project_root.is_none()
268 && let Ok(cwd) = std::env::current_dir()
269 && !lean_ctx::core::pathutil::is_broad_or_unsafe_root(&cwd)
270 {
271 session.project_root = Some(cwd.to_string_lossy().to_string());
272 }
273}
274
275fn default_opts() -> SessionToolOptions<'static> {
276 SessionToolOptions {
277 format: None,
278 path: None,
279 write: false,
280 privacy: None,
281 terse: None,
282 agent_id: None,
283 }
284}
285
286fn print_session_help() {
287 eprintln!(
288 "\
289lean-ctx session — Session management
290
291Usage:
292 lean-ctx session Show adoption statistics
293 lean-ctx session task <description> Set current task
294 lean-ctx session finding <summary> Record a finding
295 lean-ctx session decision <summary> Record a decision
296 lean-ctx session save Save current session
297 lean-ctx session load [session-id] Load a session (latest if no ID)
298 lean-ctx session status Show session status
299 lean-ctx session reset|new Reset session
300 lean-ctx session readset --json [--root DIR] [--id ID]...
301 Files the session read (ECCP observed_reads)
302
303Examples:
304 lean-ctx session task \"implement JWT authentication\"
305 lean-ctx session finding \"auth.rs:42 — missing token validation\"
306 lean-ctx session save
307 lean-ctx session load"
308 );
309}
310
311fn cmd_session_legacy() {
312 let history = load_shell_history();
313 let gain = stats::load_stats();
314
315 let compressible_commands = [
316 "git ",
317 "npm ",
318 "yarn ",
319 "pnpm ",
320 "cargo ",
321 "docker ",
322 "kubectl ",
323 "gh ",
324 "pip ",
325 "pip3 ",
326 "eslint",
327 "prettier",
328 "ruff ",
329 "go ",
330 "golangci-lint",
331 "curl ",
332 "wget ",
333 "grep ",
334 "rg ",
335 "find ",
336 "ls ",
337 ];
338
339 let mut total = 0u32;
340 let mut via_hook = 0u32;
341
342 for line in &history {
343 let cmd = line.trim().to_lowercase();
344 if cmd.starts_with("lean-ctx") {
345 via_hook += 1;
346 total += 1;
347 } else {
348 for p in &compressible_commands {
349 if cmd.starts_with(p) {
350 total += 1;
351 break;
352 }
353 }
354 }
355 }
356
357 let pct = if total > 0 {
358 (via_hook as f64 / total as f64 * 100.0).round() as u32
359 } else {
360 0
361 };
362
363 println!("lean-ctx session statistics\n");
364 println!("Adoption: {pct}% ({via_hook}/{total} compressible commands)");
365 println!("Saved: {} tokens total", gain.total_saved);
366 println!("Calls: {} compressed", gain.total_calls);
367
368 if total > via_hook {
369 let missed = total - via_hook;
370 let est = missed * 150;
371 println!("Missed: {missed} commands (~{est} tokens saveable)");
372 }
373
374 println!("\nRun 'lean-ctx discover' for details on missed commands.");
375}
376
377pub fn cmd_sessions(args: &[String]) {
378 use lean_ctx::core::session::SessionState;
379
380 let action = args.first().map_or("list", std::string::String::as_str);
381
382 match action {
383 "list" | "ls" => {
384 let sessions = SessionState::list_sessions();
385 if sessions.is_empty() {
386 println!("No sessions found.");
387 return;
388 }
389 println!("Sessions ({}):\n", sessions.len());
390 for s in sessions.iter().take(20) {
391 let task = s.task.as_deref().unwrap_or("(no task)");
392 let task_short: String = task.chars().take(50).collect();
393 let date = s.updated_at.format("%Y-%m-%d %H:%M");
394 println!(
395 " {} | v{:3} | {:5} calls | {:>8} tok | {} | {}",
396 s.id,
397 s.version,
398 s.tool_calls,
399 format_tokens_cli(s.tokens_saved),
400 date,
401 task_short
402 );
403 }
404 if sessions.len() > 20 {
405 println!(" ... +{} more", sessions.len() - 20);
406 }
407 }
408 "show" => {
409 let id = args.get(1);
410 let session = if let Some(id) = id {
414 SessionState::load_by_id(id)
415 } else {
416 SessionState::load_latest()
417 };
418 match session {
419 Some(s) => {
420 if id.is_none() {
421 println!(
424 "Latest saved session of this project ({}) — may belong to another agent:",
425 s.id
426 );
427 }
428 super::common::print_released(&released_session_text(
429 &session_root(&s),
430 || s.format_compact(),
431 ));
432 }
433 None => println!("Session not found."),
434 }
435 }
436 "cleanup" => {
437 let days = args
438 .get(1)
439 .and_then(|value| value.parse::<i64>().ok())
440 .unwrap_or_else(|| {
441 i64::from(
442 lean_ctx::core::config::Config::load().session_retention_days_effective(),
443 )
444 });
445 let removed = SessionState::cleanup_old_sessions(days);
446 let (wf_removed, wf_freed) = lean_ctx::core::workflow::cleanup_expired();
447 println!("Cleaned up {removed} session(s) older than {days} days.");
448 if wf_removed > 0 {
449 println!(
450 "Cleaned up {wf_removed} expired workflow file(s) ({:.1} KB freed).",
451 wf_freed as f64 / 1024.0
452 );
453 }
454 }
455 "delete" | "rm" => {
456 let Some(id) = args.get(1) else {
457 eprintln!("Usage: lean-ctx sessions delete <id>");
458 std::process::exit(1);
459 };
460 match SessionState::delete_session(id) {
461 Ok(true) => println!("Deleted session {id}."),
462 Ok(false) => {
463 eprintln!("Session not found: {id}");
464 std::process::exit(1);
465 }
466 Err(e) => {
467 eprintln!("Failed to delete session {id}: {e}");
468 std::process::exit(1);
469 }
470 }
471 }
472 "doctor" => {
473 let apply = args.iter().any(|a| a == "--apply" || a == "--fix");
474 let (found, quarantined) = SessionState::doctor_quarantine_unsafe_roots(apply);
475 if found.is_empty() {
476 println!("session doctor: no contaminated sessions found.");
477 } else {
478 println!(
479 "session doctor: {} session(s) rooted at a broad/unsafe path (HOME/'/'/agent dir):",
480 found.len()
481 );
482 for (id, root) in &found {
483 println!(" {id} | root: {root}");
484 }
485 if apply {
486 println!("\nQuarantined {quarantined} session(s) to sessions/quarantine/.");
487 } else {
488 println!("\nRun `lean-ctx sessions doctor --apply` to quarantine them.");
489 }
490 }
491 }
492 _ => {
493 eprintln!(
494 "Usage: lean-ctx sessions [list|show [id]|delete <id>|cleanup [days]|doctor [--apply]]"
495 );
496 std::process::exit(1);
497 }
498 }
499}