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