1use crate::core::session::SessionState;
4
5#[derive(Clone, Copy, Debug)]
6pub struct SessionToolOptions<'a> {
7 pub format: Option<&'a str>,
8 pub path: Option<&'a str>,
9 pub write: bool,
10 pub privacy: Option<&'a str>,
11 pub terse: Option<bool>,
13 pub agent_id: Option<&'a str>,
14}
15
16pub fn handle(
17 session: &mut SessionState,
18 tool_calls: &[(String, u64)],
19 action: &str,
20 value: Option<&str>,
21 session_id: Option<&str>,
22 opts: SessionToolOptions<'_>,
23) -> String {
24 if action == "handoff" {
25 return handle_handoff(session);
26 }
27
28 match action {
29 "status" | "show" => handle_status(session),
30 "load" => handle_load(session, session_id),
31 "save" => handle_save(session),
32 "export" => handle_export(session, value, opts),
33 "import" => handle_import(session, value, opts),
34 "task" => handle_task(session, tool_calls, value, opts),
35 "finding" => handle_finding(session, value),
36 "decision" => handle_decision(session, value),
37 "reset" => handle_reset(session),
38 "list" => handle_list(),
39 "cleanup" => handle_cleanup(),
40 "configure" => handle_configure(session, opts),
41 "snapshot" => handle_snapshot(session),
42 "restore" => handle_restore(session_id),
43 "resume" => handle_resume(session),
44 "profile" => handle_profile(value),
45 "budget" => handle_budget(),
46 "role" => handle_role(value),
47 "diff" => handle_diff(value),
48 "slo" => handle_slo(value),
49 "output_stats" => handle_output_stats(),
50 "verify" => handle_verify(),
51 "episodes" => handle_episodes(session, tool_calls, value, opts),
52 "procedures" => handle_procedures(session, value),
53 _ => handle_unknown(action),
54 }
55}
56
57pub fn handle_without_session(
62 action: &str,
63 value: Option<&str>,
64 session_id: Option<&str>,
65) -> Option<String> {
66 match action {
67 "list" => Some(handle_list()),
68 "cleanup" => Some(handle_cleanup()),
69 "restore" => Some(handle_restore(session_id)),
70 "profile" => Some(handle_profile(value)),
71 "budget" => Some(handle_budget()),
72 "role" => Some(handle_role(value)),
73 "diff" => Some(handle_diff(value)),
74 "slo" => Some(handle_slo(value)),
75 "output_stats" => Some(handle_output_stats()),
76 "verify" => Some(handle_verify()),
77 _ => None,
78 }
79}
80
81pub fn handle_read_only(session: &SessionState, action: &str) -> Option<String> {
84 match action {
85 "status" | "show" => Some(handle_status(session)),
86 "handoff" => Some(handle_handoff(session)),
87 _ => None,
88 }
89}
90
91pub fn handle_snapshot_read_action(
95 session: &SessionState,
96 action: &str,
97 value: Option<&str>,
98 opts: SessionToolOptions<'_>,
99) -> Option<String> {
100 match action {
101 "export" => Some(handle_export(session, value, opts)),
102 "resume" => Some(session.build_resume_block()),
103 "snapshot" => Some(session.save_compaction_snapshot().map_or_else(
104 |error| format!("Snapshot failed: {error}"),
105 |snapshot| {
106 format!(
107 "Compaction snapshot saved ({} bytes).\n{snapshot}",
108 snapshot.len()
109 )
110 },
111 )),
112 _ => None,
113 }
114}
115
116fn handle_status(session: &SessionState) -> String {
117 session.format_compact()
118}
119
120fn handle_handoff(session: &SessionState) -> String {
121 if session.handoff_context.is_empty() {
122 return "Handoff context: no recent cross-session decisions.".to_string();
123 }
124
125 let mut output = format!(
126 "Handoff context ({} recent cross-session decisions):",
127 session.handoff_context.len()
128 );
129 for fact in &session.handoff_context {
130 output.push_str(&format!(
131 "\n [{}] {} (confidence: {:.0}%)",
132 fact.category,
133 fact.value,
134 fact.confidence * 100.0
135 ));
136 }
137 output
138}
139
140fn handle_load(session: &mut SessionState, session_id: Option<&str>) -> String {
141 const SCOPE_DENIED: &str = "ERROR: session load denied: scoped session unavailable or mismatched; live session unchanged.";
142
143 let Some(receiving_root) = session.strict_project_root() else {
144 return SCOPE_DENIED.to_string();
145 };
146
147 let loaded = if let Some(id) = session_id {
148 SessionState::load_by_id_for_project_root(id, &receiving_root)
149 } else {
150 match SessionState::load_latest_for_project_root(&receiving_root) {
151 Some(selected) => {
152 SessionState::load_by_id_for_project_root(&selected.id, &receiving_root)
153 }
154 None => Ok(None),
155 }
156 };
157
158 let Ok(loaded) = loaded else {
159 return SCOPE_DENIED.to_string();
160 };
161
162 let Some(mut prev) = loaded else {
163 return SCOPE_DENIED.to_string();
164 };
165
166 prev.extra_roots.clone_from(&session.extra_roots);
169 prev.shell_cwd.clone_from(&session.shell_cwd);
170 let summary = prev.format_compact();
171 *session = prev;
172 format!("Session loaded.\n{summary}")
173}
174
175fn handle_save(session: &mut SessionState) -> String {
176 save_session(session).unwrap_or_else(|error| format!("Save failed: {error}"))
177}
178
179pub(crate) fn save_session(session: &mut SessionState) -> Result<String, String> {
180 match session.save() {
181 Ok(()) => {
182 let mut out = format!("Session {} saved (v{}).", session.id, session.version);
183 let messages = conversion_messages_for_session(session);
184 if !messages.is_empty() {
185 out.push_str("\n\nPro tip:");
186 for message in messages {
187 out.push_str(&format!("\n {}", message.message));
188 }
189 out.push_str("\n Dismiss: lean-ctx session dismiss-pro");
190 }
191 Ok(out)
192 }
193 Err(error) => Err(error),
194 }
195}
196
197fn conversion_messages_for_session(
198 session: &SessionState,
199) -> Vec<crate::core::pro_triggers::ProNudge> {
200 crate::core::pro_triggers::evaluate_triggers(&crate::core::pro_triggers::local_usage_signals(
201 session,
202 ))
203}
204
205fn handle_export(
206 session: &SessionState,
207 value: Option<&str>,
208 opts: SessionToolOptions<'_>,
209) -> String {
210 if session.canonical_checkpoint.is_some() {
211 return "ERROR: a canonical checkpoint requires a versioned carrier; legacy bundle export would discard its current lineage.".into();
212 }
213 {
214 let requested_privacy =
215 crate::core::ccp_session_bundle::BundlePrivacyV1::parse(opts.privacy);
216 if requested_privacy == crate::core::ccp_session_bundle::BundlePrivacyV1::Full
217 && crate::core::roles::active_role_name() != "admin"
218 {
219 return "ERROR: privacy=full requires role 'admin'.".to_string();
220 }
221
222 let bundle = crate::core::ccp_session_bundle::build_bundle_v1(session, requested_privacy);
223 let json = match crate::core::ccp_session_bundle::serialize_bundle_v1_pretty(&bundle) {
224 Ok(s) => s,
225 Err(e) => return e,
226 };
227
228 let format = opts
229 .format
230 .unwrap_or(if opts.write { "summary" } else { "json" });
231 let root = session.project_root.clone().unwrap_or_else(|| {
232 std::env::current_dir()
233 .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string())
234 });
235 let root_path = std::path::PathBuf::from(&root);
236
237 let mut written: Option<String> = None;
238 if opts.write || opts.path.is_some() {
239 let ts = chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string();
240 let candidate = if let Some(p) = opts.path.or(value) {
241 let p = std::path::PathBuf::from(p);
242 if p.is_absolute() {
243 p
244 } else {
245 root_path.join(p)
246 }
247 } else {
248 root_path
249 .join(".lean-ctx")
250 .join("session_bundles")
251 .join(format!(
252 "ccp-session-bundle-v1_{}_{}.json",
253 bundle.session.id, ts
254 ))
255 };
256
257 let jailed = match crate::core::io_boundary::jail_and_check_path(
258 "ctx_session.export",
259 candidate.as_path(),
260 root_path.as_path(),
261 ) {
262 Ok((p, _warning)) => p,
263 Err(e) => return e,
264 };
265
266 if let Err(e) = crate::core::pathjail::enforce_writable(&jailed) {
269 return format!("Export write failed: {e}");
270 }
271 if let Err(e) = crate::core::ccp_session_bundle::write_bundle_v1(&jailed, &json) {
272 return format!("Export write failed: {e}");
273 }
274 written = Some(jailed.to_string_lossy().to_string());
275 }
276
277 match format {
278 "summary" => {
279 let mut out = format!(
280 "CCP session bundle exported (v{}).\n\
281schema_version: {}\n\
282session_id: {}\n\
283bytes: {}\n",
284 bundle.session.version,
285 bundle.schema_version,
286 bundle.session.id,
287 json.len()
288 );
289 if let Some(p) = written {
290 out.push_str(&format!("path: {p}\n"));
291 }
292 if let Some(h) = bundle.project.project_root_hash {
293 out.push_str(&format!("project_root_hash: {h}\n"));
294 }
295 if let Some(h) = bundle.project.project_identity_hash {
296 out.push_str(&format!("project_identity_hash: {h}\n"));
297 }
298 out
299 }
300 _ => {
301 if let Some(p) = written {
302 format!("{json}\n\npath: {p}")
303 } else {
304 json
305 }
306 }
307 }
308 }
309}
310
311fn handle_import(
312 session: &mut SessionState,
313 value: Option<&str>,
314 opts: SessionToolOptions<'_>,
315) -> String {
316 {
317 let root = session.project_root.clone().unwrap_or_else(|| {
318 std::env::current_dir()
319 .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string())
320 });
321 let root_path = std::path::PathBuf::from(&root);
322
323 let Some(p) = opts.path.or(value) else {
324 return "ERROR: path is required for action=import".to_string();
325 };
326
327 let candidate = {
328 let p = std::path::PathBuf::from(p);
329 if p.is_absolute() {
330 p
331 } else {
332 root_path.join(p)
333 }
334 };
335 let jailed = match crate::core::io_boundary::jail_and_check_path(
336 "ctx_session.import",
337 candidate.as_path(),
338 root_path.as_path(),
339 ) {
340 Ok((p, _warning)) => p,
341 Err(e) => return e,
342 };
343
344 let bundle = match crate::core::ccp_session_bundle::read_bundle_v1(&jailed) {
345 Ok(b) => b,
346 Err(e) => return format!("Import failed: {e}"),
347 };
348
349 let current_root_hash = crate::core::project_hash::hash_project_root(&root);
352 let current_identity_hash = crate::core::project_hash::project_identity(&root)
353 .as_deref()
354 .map(crate::core::hasher::hash_str);
355
356 let matching_scope = match (
357 bundle.project.project_identity_hash.as_ref(),
358 current_identity_hash.as_ref(),
359 ) {
360 (Some(exported), Some(current)) => exported == current,
361 _ => bundle.project.project_root_hash.as_ref() == Some(¤t_root_hash),
362 };
363 if !matching_scope {
364 return "Import failed: project scope mismatch; live session unchanged.".to_string();
365 }
366
367 let mut candidate = session.clone();
368 let report = crate::core::ccp_session_bundle::import_bundle_v1_into_session(
369 &mut candidate,
370 &bundle,
371 Some(&root),
372 );
373 if let Err(error) = candidate.save_new() {
376 return format!(
377 "Import failed: {error}; live session unchanged; recovery candidate: {}.",
378 candidate.id
379 );
380 }
381 *session = candidate;
382
383 format!(
384 "CCP session bundle imported.\n\
385session_id: {}\n\
386source_session_id: {}\n\
387version: {}\n\
388files_touched: {}\n\
389stale_files: {}\n",
390 report.session_id,
391 report.source_session_id,
392 report.version,
393 report.files_touched,
394 report.stale_files
395 )
396 }
397}
398
399fn handle_task(
400 session: &mut SessionState,
401 tool_calls: &[(String, u64)],
402 value: Option<&str>,
403 opts: SessionToolOptions<'_>,
404) -> String {
405 {
406 let desc = value.unwrap_or("(no description)");
407 session.set_task(desc, None);
408 let lower = desc.to_lowercase();
412 let completed =
413 desc.contains("[100%]") || lower.contains("[done]") || lower.contains("[complete]");
414 let mut note = String::new();
415 if completed {
416 match auto_record_episode(session, tool_calls, opts.agent_id) {
417 Ok(Some(id)) => {
418 note = format!("\nEpisode auto-recorded: {id}");
419 }
420 Ok(None) => {} Err(e) => {
422 note = format!("\n(episode auto-record skipped: {e})");
423 }
424 }
425 }
426 format!("Task set: {desc}{note}")
427 }
428}
429
430fn handle_finding(session: &mut SessionState, value: Option<&str>) -> String {
431 {
432 let summary = value.unwrap_or("(no summary)");
433 let (file, line, text) = parse_finding_value(summary);
434 session.add_finding(file.as_deref(), line, text);
435 format!("Finding added: {summary}")
436 }
437}
438
439fn handle_decision(session: &mut SessionState, value: Option<&str>) -> String {
440 {
441 let desc = value.unwrap_or("(no description)");
442 session.add_decision(desc, None);
443 format!("Decision recorded: {desc}")
444 }
445}
446
447fn handle_reset(session: &mut SessionState) -> String {
448 {
449 if let Err(error) = session.save() {
450 return format!("Reset refused: current session was not saved: {error}");
451 }
452 let old_id = session.id.clone();
453 *session = SessionState::new();
454 crate::core::budget_tracker::BudgetTracker::global().reset();
455 let mut ledger = crate::core::context_ledger::ContextLedger::load();
457 ledger.reset();
458 ledger.save();
459 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
460 let radar_path = data_dir.join("context_radar.jsonl");
461 let prev = data_dir.join("context_radar.prev.jsonl");
462 let _ = std::fs::rename(&radar_path, &prev);
463 }
464 format!(
465 "Session reset. Previous: {old_id}. New: {}. Ledger cleared (0% pressure).",
466 session.id
467 )
468 }
469}
470
471fn handle_list() -> String {
472 {
473 let sessions = SessionState::list_sessions();
474 if sessions.is_empty() {
475 return "No sessions found.".to_string();
476 }
477 let mut lines = vec![format!("Sessions ({}):", sessions.len())];
478 for s in sessions.iter().take(10) {
479 let task = s.task.as_deref().unwrap_or("(no task)");
480 let task_short: String = task.chars().take(40).collect();
481 lines.push(format!(
482 " {} v{} | {} calls | {} tok | {}",
483 s.id, s.version, s.tool_calls, s.tokens_saved, task_short
484 ));
485 }
486 if sessions.len() > 10 {
487 lines.push(format!(" ... +{} more", sessions.len() - 10));
488 }
489 lines.join("\n")
490 }
491}
492
493fn handle_cleanup() -> String {
494 let days = crate::core::config::Config::load().session_retention_days_effective();
495 let removed = SessionState::cleanup_old_sessions(i64::from(days));
496 format!("Cleaned up {removed} old session(s) (>{days} days).")
497}
498
499fn handle_configure(session: &mut SessionState, opts: SessionToolOptions<'_>) -> String {
500 match opts.terse {
501 Some(enabled) => {
502 session.terse_mode = enabled;
503 session.increment();
504 format!("Session configured: terse_mode={enabled}")
505 }
506 None => format!("Session config: terse_mode={}", session.terse_mode),
507 }
508}
509
510fn handle_snapshot(session: &mut SessionState) -> String {
511 match session.save_compaction_snapshot() {
512 Ok(snapshot) => {
513 format!(
514 "Compaction snapshot saved ({} bytes).\n{snapshot}",
515 snapshot.len()
516 )
517 }
518 Err(e) => format!("Snapshot failed: {e}"),
519 }
520}
521
522fn handle_restore(session_id: Option<&str>) -> String {
523 {
524 let snapshot = if let Some(id) = session_id {
525 SessionState::load_compaction_snapshot(id)
526 } else {
527 SessionState::load_latest_snapshot()
528 };
529 match snapshot {
530 Some(s) => format!("Session restored from compaction snapshot:\n{s}"),
531 None => "No compaction snapshot found. Session continues fresh.".to_string(),
532 }
533 }
534}
535
536fn handle_resume(session: &mut SessionState) -> String {
537 session.build_resume_block()
538}
539
540fn handle_profile(value: Option<&str>) -> String {
541 {
542 use crate::core::profiles;
543 if let Some(name) = value {
544 if let Ok(p) = profiles::set_active_profile(name) {
545 format!(
546 "Profile switched to '{name}'.\n\
547 Read mode: {}, Budget: {} tokens, CRP: {}, Density: {}",
548 p.read.default_mode_effective(),
549 p.budget.max_context_tokens_effective(),
550 p.compression.crp_mode_effective(),
551 p.compression.output_density_effective(),
552 )
553 } else {
554 let available: Vec<String> = profiles::list_profiles()
555 .iter()
556 .map(|p| p.name.clone())
557 .collect();
558 format!(
559 "Profile '{name}' not found. Available: {}",
560 available.join(", ")
561 )
562 }
563 } else {
564 let name = profiles::active_profile_name();
565 let p = profiles::active_profile();
566 let list = profiles::list_profiles();
567 let mut out = format!(
568 "Active profile: {name}\n\
569 Read: {}, Budget: {} tok, CRP: {}, Density: {}\n\n\
570 Available profiles:",
571 p.read.default_mode_effective(),
572 p.budget.max_context_tokens_effective(),
573 p.compression.crp_mode_effective(),
574 p.compression.output_density_effective(),
575 );
576 for info in &list {
577 let marker = if info.name == name { " *" } else { " " };
578 out.push_str(&format!(
579 "\n{marker} {:<14} ({}) {}",
580 info.name, info.source, info.description
581 ));
582 }
583 out.push_str("\n\nSwitch: ctx_session action=profile value=<name>");
584 out
585 }
586 }
587}
588
589fn handle_budget() -> String {
590 {
591 use crate::core::budget_tracker::BudgetTracker;
592 let snap = BudgetTracker::global().check();
593 let mut out = snap.format_compact();
594
595 if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
596 let window = crate::core::context_radar::default_window_for_client("cursor");
597 let radar = crate::core::context_radar::ContextRadar::load(&data_dir, window);
598 let radar_display = radar.format_display();
599 if !radar_display.is_empty() {
600 out.push_str("\n\n");
601 out.push_str(&radar_display);
602 }
603 }
604 out
605 }
606}
607
608fn handle_role(value: Option<&str>) -> String {
609 {
610 use crate::core::roles;
611 if let Some(name) = value {
612 match roles::set_active_role(name) {
613 Ok(r) => {
614 crate::core::budget_tracker::BudgetTracker::global().reset();
615 format!(
616 "Role switched to '{name}'.\n\
617 Shell: {}, Budget: {} tokens / {} shell / ${:.2}\n\
618 Tools: {}",
619 r.role.shell_policy,
620 r.limits.max_context_tokens,
621 r.limits.max_shell_invocations,
622 r.limits.max_cost_usd,
623 if r.tools.allowed.iter().any(|a| a == "*") {
624 let denied = if r.tools.denied.is_empty() {
625 "none".to_string()
626 } else {
627 format!("denied: {}", r.tools.denied.join(", "))
628 };
629 format!("* (all), {denied}")
630 } else {
631 r.tools.allowed.join(", ")
632 }
633 )
634 }
635 Err(e) => {
636 let available: Vec<String> =
637 roles::list_roles().iter().map(|r| r.name.clone()).collect();
638 format!("{e}. Available: {}", available.join(", "))
639 }
640 }
641 } else {
642 let name = roles::active_role_name();
643 let r = roles::active_role();
644 let list = roles::list_roles();
645 let mut out = format!(
646 "Active role: {name}\n\
647 Description: {}\n\
648 Shell policy: {}, Budget: {} tokens / {} shell / ${:.2}\n\n\
649 Available roles:",
650 r.role.description,
651 r.role.shell_policy,
652 r.limits.max_context_tokens,
653 r.limits.max_shell_invocations,
654 r.limits.max_cost_usd,
655 );
656 for info in &list {
657 let marker = if info.is_active { " *" } else { " " };
658 out.push_str(&format!(
659 "\n{marker} {:<14} ({}) {}",
660 info.name, info.source, info.description
661 ));
662 }
663 out.push_str("\n\nSwitch: ctx_session action=role value=<name>");
664 out
665 }
666 }
667}
668
669fn handle_diff(value: Option<&str>) -> String {
670 {
671 let parts: Vec<&str> = value.unwrap_or("").split_whitespace().collect();
672 if parts.len() < 2 {
673 return "Usage: ctx_session diff <session_id_a> <session_id_b> [format]\n\
674 Formats: summary (default), json\n\
675 Example: ctx_session diff abc123 def456 json"
676 .to_string();
677 }
678 let id_a = parts[0];
679 let id_b = parts[1];
680 let format = parts.get(2).copied().unwrap_or("summary");
681
682 let sess_a = SessionState::load_by_id(id_a);
683 let sess_b = SessionState::load_by_id(id_b);
684
685 match (sess_a, sess_b) {
686 (Some(a), Some(b)) => {
687 let d = crate::core::session_diff::diff_sessions(&a, &b);
688 match format {
689 "json" => d.format_json(),
690 _ => d.format_summary(),
691 }
692 }
693 (None, _) => format!("Session not found: {id_a}"),
694 (_, None) => format!("Session not found: {id_b}"),
695 }
696 }
697}
698
699fn handle_slo(value: Option<&str>) -> String {
700 match value {
701 Some("reload") => {
702 crate::core::slo::reload();
703 "SLO definitions reloaded from disk.".to_string()
704 }
705 Some("history") => {
706 let hist = crate::core::slo::violation_history(20);
707 if hist.is_empty() {
708 "No SLO violations recorded.".to_string()
709 } else {
710 let mut out = format!("SLO violations (last {}):\n", hist.len());
711 for v in &hist {
712 out.push_str(&format!(
713 " {} {} ({}) {:.2} vs {:.2} → {}\n",
714 v.timestamp, v.slo_name, v.metric, v.actual, v.threshold, v.action
715 ));
716 }
717 out
718 }
719 }
720 Some("clear") => {
721 crate::core::slo::clear_violations();
722 "SLO violation history cleared.".to_string()
723 }
724 _ => {
725 let snap = crate::core::slo::evaluate_quiet();
726 snap.format_compact()
727 }
728 }
729}
730
731fn handle_output_stats() -> String {
732 {
733 let snap = crate::core::output_verification::stats_snapshot();
734 let mut out = snap.format_compact();
735 let echo = crate::core::output_echo::load_stats();
737 if !echo.reports.is_empty() {
738 out.push_str(&format!(
739 "\nOutput echo: {:.0}% avg over last {} replies ({} analyzed total)",
740 echo.avg_ratio(50) * 100.0,
741 echo.reports.len(),
742 echo.total_analyzed
743 ));
744 }
745 out
746 }
747}
748
749fn handle_verify() -> String {
750 {
751 let snap = crate::core::output_verification::stats_snapshot();
752 format!(
753 "DEPRECATION: action=\"verify\" is renamed to action=\"output_stats\" (ctx_verify is the full observability stack).\n{}",
754 snap.format_compact()
755 )
756 }
757}
758
759fn handle_episodes(
760 session: &mut SessionState,
761 tool_calls: &[(String, u64)],
762 value: Option<&str>,
763 opts: SessionToolOptions<'_>,
764) -> String {
765 {
766 let project_root = session.project_root.clone().unwrap_or_else(|| {
767 std::env::current_dir().map_or_else(
768 |_| "unknown".to_string(),
769 |p| p.to_string_lossy().to_string(),
770 )
771 });
772 let policy = match crate::core::config::Config::load().memory_policy_effective() {
773 Ok(p) => p,
774 Err(e) => {
775 let path = crate::core::config::Config::path().map_or_else(
776 || "~/.lean-ctx/config.toml".to_string(),
777 |p| p.display().to_string(),
778 );
779 return format!("Error: invalid memory policy: {e}\nFix: edit {path}");
780 }
781 };
782 let hash = crate::core::project_hash::hash_project_root(&project_root);
783 match value {
784 Some("record") => {
785 let id = match crate::core::episodic_memory::record_session_episode(
786 &hash,
787 session,
788 tool_calls,
789 opts.agent_id,
790 &policy.episodic,
791 false,
792 ) {
793 Ok(Some(id)) => id,
794 Ok(None) => return "Episode already recorded.".to_string(),
795 Err(e) => return format!("Episode record failed: {e}"),
796 };
797 crate::core::events::emit(crate::core::events::EventKind::KnowledgeUpdate {
798 category: "episodic".to_string(),
799 key: id.clone(),
800 action: "record".to_string(),
801 });
802 let learned = crate::core::procedural_memory::auto_detect_from_episodes(
805 &hash,
806 &policy.procedural,
807 );
808 match learned {
809 Some(n) if n > 0 => {
810 format!(
811 "Episode recorded: {id} (procedures auto-updated: {n} known workflows)"
812 )
813 }
814 _ => format!("Episode recorded: {id}"),
815 }
816 }
817 Some(v) if v.starts_with("search ") => {
818 let q = v.trim_start_matches("search ").trim();
819 let store = crate::core::episodic_memory::EpisodicStore::load_or_create(&hash);
820 let hits = store.search(q);
821 if hits.is_empty() {
822 return "No episodes matched.".to_string();
823 }
824 let mut out = format!("Episodes matched ({}):", hits.len());
825 for ep in hits.into_iter().take(10) {
826 let task: String = ep.task_description.chars().take(50).collect();
827 out.push_str(&format!(
828 "\n {} | {} | {} | {}",
829 ep.id,
830 ep.timestamp,
831 ep.outcome.label(),
832 task
833 ));
834 }
835 out
836 }
837 Some(v) if v.starts_with("file ") => {
838 let f = v.trim_start_matches("file ").trim();
839 let store = crate::core::episodic_memory::EpisodicStore::load_or_create(&hash);
840 let hits = store.by_file(f);
841 let mut out = format!("Episodes for file match '{f}' ({}):", hits.len());
842 for ep in hits.into_iter().take(10) {
843 let task: String = ep.task_description.chars().take(50).collect();
844 out.push_str(&format!(
845 "\n {} | {} | {} | {}",
846 ep.id,
847 ep.timestamp,
848 ep.outcome.label(),
849 task
850 ));
851 }
852 out
853 }
854 Some(v) if v.starts_with("outcome ") => {
855 let label = v.trim_start_matches("outcome ").trim();
856 let store = crate::core::episodic_memory::EpisodicStore::load_or_create(&hash);
857 let hits = store.by_outcome(label);
858 let mut out = format!("Episodes outcome '{label}' ({}):", hits.len());
859 for ep in hits.into_iter().take(10) {
860 let task: String = ep.task_description.chars().take(50).collect();
861 out.push_str(&format!("\n {} | {} | {}", ep.id, ep.timestamp, task));
862 }
863 out
864 }
865 _ => {
866 let store = crate::core::episodic_memory::EpisodicStore::load_or_create(&hash);
867 let stats = store.stats();
868 let recent = store.recent(10);
869 let mut out = format!(
870 "Episodic memory: {} episodes, success_rate={:.0}%, tokens_total={}\n\nRecent:",
871 stats.total_episodes,
872 stats.success_rate * 100.0,
873 stats.total_tokens
874 );
875 for ep in recent {
876 let task: String = ep.task_description.chars().take(60).collect();
877 out.push_str(&format!(
878 "\n {} | {} | {} | {}",
879 ep.id,
880 ep.timestamp,
881 ep.outcome.label(),
882 task
883 ));
884 }
885 out.push_str("\n\nActions: ctx_session action=episodes value=record|\"search <q>\"|\"file <path>\"|\"outcome success|failure|partial|unknown\"");
886 out
887 }
888 }
889 }
890}
891
892fn handle_procedures(session: &mut SessionState, value: Option<&str>) -> String {
893 {
894 let project_root = session.project_root.clone().unwrap_or_else(|| {
895 std::env::current_dir().map_or_else(
896 |_| "unknown".to_string(),
897 |p| p.to_string_lossy().to_string(),
898 )
899 });
900 let policy = match crate::core::config::Config::load().memory_policy_effective() {
901 Ok(p) => p,
902 Err(e) => {
903 let path = crate::core::config::Config::path().map_or_else(
904 || "~/.lean-ctx/config.toml".to_string(),
905 |p| p.display().to_string(),
906 );
907 return format!("Error: invalid memory policy: {e}\nFix: edit {path}");
908 }
909 };
910 let hash = crate::core::project_hash::hash_project_root(&project_root);
911 let episodes = crate::core::episodic_memory::EpisodicStore::load_or_create(&hash);
912 let mut procs = crate::core::procedural_memory::ProceduralStore::load_or_create(&hash);
913
914 match value {
915 Some("detect") => {
916 procs.detect_patterns(&episodes.episodes, &policy.procedural);
917 if let Err(e) = procs.save() {
918 return format!("Procedure detect failed: {e}");
919 }
920 crate::core::events::emit(crate::core::events::EventKind::KnowledgeUpdate {
921 category: "procedural".to_string(),
922 key: hash.clone(),
923 action: "detect".to_string(),
924 });
925 format!(
926 "Procedures updated. Total procedures: {} (episodes: {}).",
927 procs.procedures.len(),
928 episodes.episodes.len()
929 )
930 }
931 Some(v) if v.starts_with("suggest ") => {
932 let task = v.trim_start_matches("suggest ").trim();
933 let hits = procs.suggest(task);
934 if hits.is_empty() {
935 return "No procedures matched.".to_string();
936 }
937 let mut out = format!("Procedures suggested ({}):", hits.len());
938 for p in hits.into_iter().take(10) {
939 out.push_str(&format!(
940 "\n {} | conf={:.0}% | success={:.0}% | steps={}",
941 p.name,
942 p.confidence * 100.0,
943 p.success_rate() * 100.0,
944 p.steps.len()
945 ));
946 }
947 out
948 }
949 _ => {
950 let task = session
951 .task
952 .as_ref()
953 .map(|t| t.description.clone())
954 .unwrap_or_default();
955 let suggestions = if task.is_empty() {
956 Vec::new()
957 } else {
958 procs.suggest(&task)
959 };
960
961 let mut out = format!(
962 "Procedural memory: {} procedures (episodes: {})",
963 procs.procedures.len(),
964 episodes.episodes.len()
965 );
966
967 if !task.is_empty() {
968 out.push_str(&format!(
969 "\nTask: {}",
970 task.chars().take(80).collect::<String>()
971 ));
972 if !suggestions.is_empty() {
973 out.push_str("\n\nSuggested:");
974 for p in suggestions.into_iter().take(5) {
975 out.push_str(&format!(
976 "\n {} | conf={:.0}% | success={:.0}% | steps={}",
977 p.name,
978 p.confidence * 100.0,
979 p.success_rate() * 100.0,
980 p.steps.len()
981 ));
982 }
983 }
984 }
985
986 out.push_str(
987 "\n\nActions: ctx_session action=procedures value=detect|\"suggest <task>\"",
988 );
989 out
990 }
991 }
992 }
993}
994
995fn handle_unknown(action: &str) -> String {
996 format!(
997 "Unknown action: {action}. Use: status, handoff, load, save, task, finding, decision, reset, list, cleanup, snapshot, restore, resume, configure, profile, role, budget, slo, diff, output_stats, verify, export, import, episodes, procedures"
998 )
999}
1000
1001fn auto_record_episode(
1006 session: &SessionState,
1007 tool_calls: &[(String, u64)],
1008 agent_id: Option<&str>,
1009) -> Result<Option<String>, String> {
1010 let project_root = session.project_root.clone().unwrap_or_else(|| {
1011 std::env::current_dir().map_or_else(
1012 |_| "unknown".to_string(),
1013 |p| p.to_string_lossy().to_string(),
1014 )
1015 });
1016 let policy = crate::core::config::Config::load()
1017 .memory_policy_effective()
1018 .map_err(|e| format!("invalid memory policy: {e}"))?;
1019 let hash = crate::core::project_hash::hash_project_root(&project_root);
1020 let Some(id) = crate::core::episodic_memory::record_session_episode(
1021 &hash,
1022 session,
1023 tool_calls,
1024 agent_id,
1025 &policy.episodic,
1026 true,
1027 )?
1028 else {
1029 return Ok(None);
1030 };
1031 crate::core::events::emit(crate::core::events::EventKind::KnowledgeUpdate {
1032 category: "episodic".to_string(),
1033 key: id.clone(),
1034 action: "auto_record".to_string(),
1035 });
1036
1037 let store = crate::core::episodic_memory::EpisodicStore::load_or_create(&hash);
1041 let episodes: Vec<crate::core::episodic_memory::Episode> =
1042 store.recent(50).into_iter().cloned().collect();
1043 let mut procs = crate::core::procedural_memory::ProceduralStore::load_or_create(&hash);
1044 let before = procs.procedures.len();
1045 procs.detect_patterns(&episodes, &policy.procedural);
1046 if procs.procedures.len() > before && procs.save().is_ok() {
1047 crate::core::events::emit(crate::core::events::EventKind::KnowledgeUpdate {
1048 category: "procedural".to_string(),
1049 key: format!("{} new", procs.procedures.len() - before),
1050 action: "auto_learn".to_string(),
1051 });
1052 }
1053
1054 Ok(Some(id))
1055}
1056
1057fn parse_finding_value(value: &str) -> (Option<String>, Option<u32>, &str) {
1058 const EM_DASH_SEP: &str = " \u{2014} ";
1059 const ASCII_SEP: &str = " - ";
1060
1061 let (dash_pos, sep) = if let Some(p) = value.find(EM_DASH_SEP) {
1062 (Some(p), EM_DASH_SEP)
1063 } else {
1064 (value.find(ASCII_SEP), ASCII_SEP)
1065 };
1066
1067 if let Some(pos) = dash_pos {
1068 let location = &value[..pos];
1069 let text = &value[pos + sep.len()..];
1070
1071 if let Some(colon_pos) = location.rfind(':') {
1072 let file = &location[..colon_pos];
1073 if let Ok(line) = location[colon_pos + 1..].parse::<u32>() {
1074 return (Some(file.to_string()), Some(line), text);
1075 }
1076 }
1077 return (Some(location.to_string()), None, text);
1078 }
1079 (None, None, value)
1080}
1081
1082#[cfg(test)]
1083mod tests {
1084 use super::parse_finding_value;
1085
1086 #[test]
1087 fn finding_with_em_dash_and_file_line() {
1088 let (file, line, text) =
1089 parse_finding_value("auth.rs:42 \u{2014} missing token validation");
1090 assert_eq!(file.as_deref(), Some("auth.rs"));
1091 assert_eq!(line, Some(42));
1092 assert_eq!(text, "missing token validation");
1093 }
1094
1095 #[test]
1096 fn finding_with_ascii_dash_and_file_line() {
1097 let (file, line, text) = parse_finding_value("auth.rs:42 - missing token validation");
1098 assert_eq!(file.as_deref(), Some("auth.rs"));
1099 assert_eq!(line, Some(42));
1100 assert_eq!(text, "missing token validation");
1101 }
1102
1103 #[test]
1104 fn finding_with_em_dash_no_line() {
1105 let (file, line, text) = parse_finding_value("auth module \u{2014} needs refactoring");
1106 assert_eq!(file.as_deref(), Some("auth module"));
1107 assert_eq!(line, None);
1108 assert_eq!(text, "needs refactoring");
1109 }
1110
1111 #[test]
1112 fn finding_plain_text() {
1113 let (file, line, text) = parse_finding_value("plain text finding");
1114 assert_eq!(file, None);
1115 assert_eq!(line, None);
1116 assert_eq!(text, "plain text finding");
1117 }
1118
1119 #[test]
1120 fn finding_cyrillic_with_em_dash_issue_272() {
1121 let value = "ruff: pyproject.toml dev-group \u{2014} >=0.15.14,<0.16.0 (был 0.14.x)";
1122 let (file, line, text) = parse_finding_value(value);
1123 assert_eq!(file.as_deref(), Some("ruff: pyproject.toml dev-group"));
1124 assert_eq!(line, None);
1125 assert_eq!(text, ">=0.15.14,<0.16.0 (был 0.14.x)");
1126 }
1127
1128 #[test]
1129 fn finding_em_dash_at_start() {
1130 let (file, line, text) = parse_finding_value("src/main.rs:1 \u{2014} entry point");
1131 assert_eq!(file.as_deref(), Some("src/main.rs"));
1132 assert_eq!(line, Some(1));
1133 assert_eq!(text, "entry point");
1134 }
1135}