Skip to main content

lean_ctx/tools/
ctx_session.rs

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