Skip to main content

lean_ctx_server/tools/
ctx_session.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use lean_ctx::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    /// For `action=configure`: set terse output mode when `Some`.
12    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    match prepare_admitted_action(session, tool_calls, action, value, session_id, opts) {
25        Err(_) => "ERROR: session action withheld by current project or content policy.".into(),
26        Ok(prepared) => {
27            if !prepared.store_admission.is_current() {
28                return "ERROR: session policy changed; retry the operation.".into();
29            }
30            let PreparedSessionAction {
31                candidate, output, ..
32            } = prepared;
33            *session = candidate;
34            lean_ctx::core::session::admission::admit_tool_value(session, &output).unwrap_or_else(
35                |error| {
36                    // Two different refusals. The gateway withheld the reply's
37                    // content: its notice (`[lean-ctx …]`). Or no policy scope
38                    // could be established for this session at all (no usable
39                    // project root): that is a failed action, reported in the
40                    // tool's own `ERROR:` form like every other scope denial —
41                    // never the action's unadmitted output.
42                    if error.starts_with("[lean-ctx") {
43                        "[lean-ctx gateway: session content withheld]".into()
44                    } else {
45                        "ERROR: session action withheld by current project or content policy."
46                            .into()
47                    }
48                },
49            )
50        }
51    }
52}
53
54pub struct PreparedSessionAction {
55    pub candidate: SessionState,
56    pub output: String,
57    pub store_admission: lean_ctx::core::context_admission::stores::StoreAdmission,
58}
59
60/// Prepare content-bearing actions from a detached snapshot. Callers with a
61/// live session lock commit candidate only after checking snapshot identity.
62pub fn prepare_admitted_action(
63    session: &SessionState,
64    tool_calls: &[(String, u64)],
65    action: &str,
66    value: Option<&str>,
67    session_id: Option<&str>,
68    opts: SessionToolOptions<'_>,
69) -> Result<PreparedSessionAction, String> {
70    let store_admission = lean_ctx::core::context_admission::stores::StoreAdmission::current();
71    let mut candidate = session.clone();
72    let output = match action {
73        "task" | "finding" | "decision" => {
74            let fallback = match action {
75                "finding" => "(no summary)",
76                _ => "(no description)",
77            };
78            let admitted = lean_ctx::core::session::admission::admit_storable_session_text(
79                session,
80                value.unwrap_or(fallback),
81            )?;
82            match action {
83                "task" => handle_task(&mut candidate, tool_calls, Some(&admitted), opts),
84                "finding" => handle_finding(&mut candidate, Some(&admitted)),
85                _ => handle_decision(&mut candidate, Some(&admitted)),
86            }
87        }
88        "list" => handle_scoped_list(session)?,
89        "restore" => handle_scoped_restore(session, session_id)?,
90        _ => handle_legacy(&mut candidate, tool_calls, action, value, session_id, opts),
91    };
92    if !store_admission.is_current() {
93        return Err("session admission policy changed; retry".into());
94    }
95    Ok(PreparedSessionAction {
96        candidate,
97        output,
98        store_admission,
99    })
100}
101
102fn handle_legacy(
103    session: &mut SessionState,
104    tool_calls: &[(String, u64)],
105    action: &str,
106    value: Option<&str>,
107    session_id: Option<&str>,
108    opts: SessionToolOptions<'_>,
109) -> String {
110    if action == "handoff" {
111        return handle_handoff(session);
112    }
113
114    match action {
115        "status" | "show" => handle_status(session),
116        "load" => handle_load(session, session_id),
117        "save" => handle_save(session),
118        "export" => handle_export(session, value, opts),
119        "import" => handle_import(session, value, opts),
120        "task" => handle_task(session, tool_calls, value, opts),
121        "finding" => handle_finding(session, value),
122        "decision" => handle_decision(session, value),
123        "reset" => handle_reset(session),
124        "list" => handle_list(session),
125        "cleanup" => handle_cleanup(),
126        "configure" => handle_configure(session, opts),
127        "snapshot" => handle_snapshot(session),
128        "restore" => handle_restore(session, session_id),
129        "resume" => handle_resume(session),
130        "profile" => handle_profile(value),
131        "role" => handle_role(value),
132        "diff" => handle_diff(value),
133        "output_stats" => handle_output_stats(),
134        "verify" => handle_verify(),
135        "episodes" | "procedures" => handle_retired_memory(action),
136        _ => handle_unknown(action),
137    }
138}
139
140/// Handle actions that do not access live-session state. Keeping them outside
141/// the live session lock prevents an explicit `list`/`cleanup` request from
142/// stalling unrelated reads and shells behind an O(session-store) operation.
143/// Some actions intentionally update independent process-global configuration.
144pub fn handle_without_session(
145    action: &str,
146    value: Option<&str>,
147    _session_id: Option<&str>,
148) -> Option<String> {
149    match action {
150        "cleanup" => Some(handle_cleanup()),
151        "profile" => Some(handle_profile(value)),
152        "role" => Some(handle_role(value)),
153        "diff" => Some(handle_diff(value)),
154        "output_stats" => Some(handle_output_stats()),
155        "verify" => Some(handle_verify()),
156        "episodes" | "procedures" => Some(handle_retired_memory(action)),
157        _ => None,
158    }
159}
160
161/// Handle session reads after rechecking all recalled content under the
162/// current project and Gateway policies.
163pub fn handle_read_only(session: &SessionState, action: &str) -> Option<String> {
164    let Ok(projected) = lean_ctx::core::session::admission::for_delivery(session) else {
165        return Some("[lean-ctx gateway: session content withheld]".into());
166    };
167    let text = match action {
168        "status" | "show" => handle_status(&projected),
169        "handoff" => handle_handoff(&projected),
170        _ => return None,
171    };
172    Some(
173        lean_ctx::core::session::admission::admit_tool_value(&projected, &text)
174            .unwrap_or_else(|_| "[lean-ctx gateway: session content withheld]".into()),
175    )
176}
177
178/// Run snapshot/export work after the caller cloned live state and released its
179/// lock. Persisted projections are admitted before they reach an archive writer.
180pub fn handle_snapshot_read_action(
181    session: &SessionState,
182    action: &str,
183    value: Option<&str>,
184    opts: SessionToolOptions<'_>,
185) -> Option<String> {
186    match action {
187        "export" => {
188            let Ok(projected) = lean_ctx::core::session::admission::for_storage(session) else {
189                return Some("ERROR: session export withheld by current policy.".into());
190            };
191            let output = handle_export(&projected, value, opts);
192            // The default export is structural JSON from the already-admitted
193            // typed projection; masking that serialization would corrupt it.
194            let structural_json =
195                opts.format
196                    .unwrap_or(if opts.write { "summary" } else { "json" })
197                    != "summary";
198            Some(if structural_json {
199                output
200            } else {
201                lean_ctx::core::session::admission::admit_tool_value(&projected, &output)
202                    .unwrap_or_else(|_| "ERROR: session export withheld by current policy.".into())
203            })
204        }
205        "resume" => {
206            let Ok(projected) = lean_ctx::core::session::admission::for_delivery(session) else {
207                return Some("[lean-ctx gateway: session content withheld]".into());
208            };
209            let output = projected.build_resume_block();
210            Some(
211                lean_ctx::core::session::admission::admit_tool_value(&projected, &output)
212                    .unwrap_or_else(|_| "[lean-ctx gateway: session content withheld]".into()),
213            )
214        }
215        "snapshot" => {
216            let Ok(projected) = lean_ctx::core::session::admission::for_storage(session) else {
217                return Some("ERROR: session snapshot withheld by current policy.".into());
218            };
219            let output = projected.save_compaction_snapshot().map_or_else(
220                |error| format!("Snapshot failed: {error}"),
221                |snapshot| {
222                    format!(
223                        "Compaction snapshot saved ({} bytes).\n{snapshot}",
224                        snapshot.len()
225                    )
226                },
227            );
228            Some(
229                lean_ctx::core::session::admission::admit_tool_value(&projected, &output)
230                    .unwrap_or_else(|_| {
231                        "ERROR: session snapshot withheld by current policy.".into()
232                    }),
233            )
234        }
235        _ => None,
236    }
237}
238
239/// The session summary as a delivery: findings publish their sources or mark
240/// the call's capture, and any other session text marks it incomplete
241/// (`SessionState::format_compact_delivered`).
242///
243/// When the session's root was chosen among several workspace roots, a line
244/// names the choice, the other roots and how to change it (AP04-G7).
245fn handle_status(session: &SessionState) -> String {
246    let summary = session.format_compact_delivered();
247    // Under a launcher Workspace its binding is the root line (#2120).
248    match lean_ctx::core::workspace_authority::current() {
249        lean_ctx::core::workspace_authority::Authority::Legacy => {}
250        lean_ctx::core::workspace_authority::Authority::Workspace(snapshot) => {
251            return format!("{summary}\n{}", snapshot.status_line());
252        }
253        lean_ctx::core::workspace_authority::Authority::Unavailable(reason) => {
254            return format!(
255                "{summary}\n{}",
256                lean_ctx::core::workspace_authority::unavailable_reason(&reason)
257            );
258        }
259    }
260    match session
261        .project_root
262        .as_deref()
263        .and_then(lean_ctx::core::root_selection::recorded_for)
264    {
265        Some(selection) => format!("{summary}\n{}", selection.notice()),
266        None => summary,
267    }
268}
269
270fn handle_handoff(session: &SessionState) -> String {
271    // What this session changed in the knowledge store, from its journal:
272    // the successor reads the changeset instead of diffing the store.
273    let changeset = session
274        .project_root
275        .as_deref()
276        .map(|root| crate::tools::ctx_knowledge::session_change_count(root, &session.id))
277        .filter(|count| *count > 0)
278        .map(|count| {
279            format!(
280                "\nKnowledge written by this session: {count} change(s) — ctx_knowledge action=changes query=session:{}",
281                session.id
282            )
283        })
284        .unwrap_or_default();
285    if session.handoff_context.is_empty() {
286        return format!("Handoff context: no recent cross-session decisions.{changeset}");
287    }
288
289    let mut output = format!(
290        "Handoff context ({} recent cross-session decisions):",
291        session.handoff_context.len()
292    );
293    for fact in &session.handoff_context {
294        output.push_str(&format!(
295            "\n  [{}] {} (confidence: {:.0}%)",
296            fact.category,
297            fact.value,
298            fact.confidence * 100.0
299        ));
300    }
301    output.push_str(&changeset);
302    output
303}
304
305fn handle_load(session: &mut SessionState, session_id: Option<&str>) -> String {
306    match prepare_load(session, session_id) {
307        Ok((loaded, output)) => {
308            *session = loaded;
309            output
310        }
311        Err(error) => error,
312    }
313}
314
315/// Load and admit a detached candidate. The caller may commit it only after
316/// confirming that the live session identity and version still match.
317pub(crate) fn prepare_load(
318    session: &SessionState,
319    session_id: Option<&str>,
320) -> Result<(SessionState, String), String> {
321    const SCOPE_DENIED: &str = "ERROR: session load denied: scoped session unavailable or mismatched; live session unchanged.";
322
323    let receiving_root = session.strict_project_root().ok_or(SCOPE_DENIED)?;
324    // Without an id: the caller's own saved session — never the project's
325    // latest, which may be another agent's (I07/S03). Another session is
326    // loaded only by naming it, e.g. the id a handoff gave.
327    let id = session_id.unwrap_or(session.id.as_str());
328    let loaded =
329        SessionState::load_by_id_for_project_root(id, &receiving_root).map_err(|_| SCOPE_DENIED)?;
330
331    let Some(mut loaded) = loaded else {
332        return Err(SCOPE_DENIED.into());
333    };
334    if loaded.strict_project_root().as_deref() != Some(receiving_root.as_str()) {
335        return Err(SCOPE_DENIED.into());
336    }
337
338    // These fields come from live MCP roots/shell and must not be replaced by
339    // persisted state. Validate root scope before this policy lookup.
340    loaded.extra_roots.clone_from(&session.extra_roots);
341    loaded.shell_cwd.clone_from(&session.shell_cwd);
342    let admitted = lean_ctx::core::session::admission::for_storage(&loaded)
343        .map_err(|_| "ERROR: session load withheld by current policy; live session unchanged.")?;
344    let summary = handle_status(&admitted);
345    let output = lean_ctx::core::session::admission::admit_tool_value(
346        &admitted,
347        &format!("Session loaded.\n{summary}"),
348    )
349    .map_err(|_| "ERROR: session load withheld by current policy; live session unchanged.")?;
350    Ok((admitted, output))
351}
352
353fn handle_save(session: &mut SessionState) -> String {
354    let result = save_session(session);
355    if result.is_ok()
356        && let Some(root) = session.project_root.as_deref()
357    {
358        // Queue learnings for Cloud, debounced per project (local only).
359        lean_ctx_cloud::knowledge::draft::on_session_event(
360            root,
361            &session.id,
362            lean_ctx_cloud::knowledge::draft::Trigger::Save,
363        );
364    }
365    result.unwrap_or_else(|error| format!("Save failed: {error}"))
366}
367
368pub fn save_session(session: &mut SessionState) -> Result<String, String> {
369    match session.save() {
370        Ok(()) => Ok(format!(
371            "Session {} saved (v{}).",
372            session.id, session.version
373        )),
374        Err(error) => Err(error),
375    }
376}
377
378fn handle_export(
379    session: &SessionState,
380    value: Option<&str>,
381    opts: SessionToolOptions<'_>,
382) -> String {
383    if session.canonical_checkpoint.is_some() {
384        return "ERROR: a canonical checkpoint requires a versioned carrier; legacy bundle export would discard its current lineage.".into();
385    }
386    {
387        let requested_privacy =
388            lean_ctx_ext::core::ccp_session_bundle::BundlePrivacyV1::parse(opts.privacy);
389        if requested_privacy == lean_ctx_ext::core::ccp_session_bundle::BundlePrivacyV1::Full
390            && lean_ctx::core::roles::active_role_name() != "admin"
391        {
392            return "ERROR: privacy=full requires role 'admin'.".to_string();
393        }
394
395        let bundle =
396            lean_ctx_ext::core::ccp_session_bundle::build_bundle_v1(session, requested_privacy);
397        let json = match lean_ctx_ext::core::ccp_session_bundle::serialize_bundle_v1_pretty(&bundle)
398        {
399            Ok(s) => s,
400            Err(e) => return e,
401        };
402
403        let format = opts
404            .format
405            .unwrap_or(if opts.write { "summary" } else { "json" });
406        let root = session.project_root.clone().unwrap_or_else(|| {
407            std::env::current_dir()
408                .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string())
409        });
410        let root_path = std::path::PathBuf::from(&root);
411
412        let mut written: Option<String> = None;
413        if opts.write || opts.path.is_some() {
414            let ts = lean_ctx_time::UtcDateTime::now()
415                .format("%Y%m%dT%H%M%SZ")
416                .to_string();
417            let candidate = if let Some(p) = opts.path.or(value) {
418                let p = std::path::PathBuf::from(p);
419                if p.is_absolute() {
420                    p
421                } else {
422                    root_path.join(p)
423                }
424            } else {
425                root_path
426                    .join(".lean-ctx")
427                    .join("session_bundles")
428                    .join(format!(
429                        "ccp-session-bundle-v1_{}_{}.json",
430                        bundle.session.id, ts
431                    ))
432            };
433
434            let jailed = match lean_ctx::core::io_boundary::jail_and_check_path(
435                "ctx_session.export",
436                candidate.as_path(),
437                root_path.as_path(),
438            ) {
439                Ok((p, _warning)) => p,
440                Err(e) => return e,
441            };
442
443            // Read-only-roots choke point (#475): export must not write a
444            // bundle into a read-only root even when the jail allows reads.
445            if let Err(e) = lean_ctx::core::pathjail::enforce_writable(&jailed) {
446                return format!("Export write failed: {e}");
447            }
448            if let Err(e) = lean_ctx_ext::core::ccp_session_bundle::write_bundle_v1(
449                &root_path, &candidate, &jailed, &json,
450            ) {
451                return format!("Export write failed: {e}");
452            }
453            written = Some(jailed.to_string_lossy().to_string());
454        }
455
456        match format {
457            "summary" => {
458                let mut out = format!(
459                    "CCP session bundle exported (v{}).\n\
460schema_version: {}\n\
461session_id: {}\n\
462bytes: {}\n",
463                    bundle.session.version,
464                    bundle.schema_version,
465                    bundle.session.id,
466                    json.len()
467                );
468                if let Some(p) = written {
469                    out.push_str(&format!("path: {p}\n"));
470                }
471                if let Some(h) = bundle.project.project_root_hash {
472                    out.push_str(&format!("project_root_hash: {h}\n"));
473                }
474                if let Some(h) = bundle.project.project_identity_hash {
475                    out.push_str(&format!("project_identity_hash: {h}\n"));
476                }
477                out
478            }
479            _ => {
480                if let Some(p) = written {
481                    format!("{json}\n\npath: {p}")
482                } else {
483                    json
484                }
485            }
486        }
487    }
488}
489
490fn handle_import(
491    session: &mut SessionState,
492    value: Option<&str>,
493    opts: SessionToolOptions<'_>,
494) -> String {
495    {
496        let root = session.project_root.clone().unwrap_or_else(|| {
497            std::env::current_dir()
498                .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string())
499        });
500        let root_path = std::path::PathBuf::from(&root);
501
502        let Some(p) = opts.path.or(value) else {
503            return "ERROR: path is required for action=import".to_string();
504        };
505
506        let candidate = {
507            let p = std::path::PathBuf::from(p);
508            if p.is_absolute() {
509                p
510            } else {
511                root_path.join(p)
512            }
513        };
514        let jailed = match lean_ctx::core::io_boundary::jail_and_check_path(
515            "ctx_session.import",
516            candidate.as_path(),
517            root_path.as_path(),
518        ) {
519            Ok((p, _warning)) => p,
520            Err(e) => return e,
521        };
522
523        let bundle = match lean_ctx_ext::core::ccp_session_bundle::read_bundle_v1(&jailed) {
524            Ok(b) => b,
525            Err(e) => return format!("Import failed: {e}"),
526        };
527
528        // A legacy identity hash is a scope check, not signer admission. Never
529        // overwrite a foreign project's session after only displaying a warning.
530        let current_root_hash = lean_ctx::core::project_hash::hash_project_root(&root);
531        let current_identity_hash = lean_ctx::core::project_hash::project_identity(&root)
532            .as_deref()
533            .map(lean_ctx::core::hasher::hash_str);
534
535        let matching_scope = match (
536            bundle.project.project_identity_hash.as_ref(),
537            current_identity_hash.as_ref(),
538        ) {
539            (Some(exported), Some(current)) => exported == current,
540            _ => bundle.project.project_root_hash.as_ref() == Some(&current_root_hash),
541        };
542        if !matching_scope {
543            return "Import failed: project scope mismatch; live session unchanged.".to_string();
544        }
545
546        let mut candidate = session.clone();
547        let report = lean_ctx_ext::core::ccp_session_bundle::import_bundle_v1_into_session(
548            &mut candidate,
549            &bundle,
550            Some(&root),
551        );
552        // Import into a new identity, preserving both the current session and
553        // any existing archive bearing the untrusted source identity.
554        if let Err(error) = candidate.save_new() {
555            return format!(
556                "Import failed: {error}; live session unchanged; recovery candidate: {}.",
557                candidate.id
558            );
559        }
560        *session = candidate;
561
562        format!(
563            "CCP session bundle imported.\n\
564session_id: {}\n\
565source_session_id: {}\n\
566version: {}\n\
567files_touched: {}\n\
568stale_files: {}\n",
569            report.session_id,
570            report.source_session_id,
571            report.version,
572            report.files_touched,
573            report.stale_files
574        )
575    }
576}
577
578fn handle_task(
579    session: &mut SessionState,
580    _tool_calls: &[(String, u64)],
581    value: Option<&str>,
582    _opts: SessionToolOptions<'_>,
583) -> String {
584    {
585        let desc = value.unwrap_or("(no description)");
586        session.set_task(desc, None);
587        format!("Task set: {desc}")
588    }
589}
590
591fn handle_finding(session: &mut SessionState, value: Option<&str>) -> String {
592    {
593        let summary = value.unwrap_or("(no summary)");
594        let (file, line, text) = parse_finding_value(summary);
595        session.add_finding_for_file(file.as_deref(), line, text);
596        format!("Finding added: {summary}")
597    }
598}
599
600fn handle_decision(session: &mut SessionState, value: Option<&str>) -> String {
601    {
602        let desc = value.unwrap_or("(no description)");
603        session.add_decision(desc, None);
604        format!("Decision recorded: {desc}")
605    }
606}
607
608fn handle_reset(session: &mut SessionState) -> String {
609    if let Err(error) = session.save() {
610        return format!("Reset refused: current session was not saved: {error}");
611    }
612    reset_after_save(session)
613}
614
615pub(crate) fn reset_after_save(session: &mut SessionState) -> String {
616    let old_id = session.id.clone();
617    *session = SessionState::new();
618    // Clear the persistent context ledger so pressure resets to 0%
619    let mut ledger = lean_ctx::core::context_ledger::ContextLedger::load();
620    ledger.reset();
621    ledger.save();
622    if let Ok(data_dir) = lean_ctx::core::data_dir::lean_ctx_data_dir() {
623        let radar_path = data_dir.join("context_radar.jsonl");
624        let prev = data_dir.join("context_radar.prev.jsonl");
625        let _ = std::fs::rename(&radar_path, &prev);
626    }
627    format!(
628        "Session reset. Previous: {old_id}. New: {}. Ledger cleared (0% pressure).",
629        session.id
630    )
631}
632
633fn handle_list(session: &SessionState) -> String {
634    handle_scoped_list(session).unwrap_or_else(|_| {
635        "ERROR: session list withheld by project scope or content policy.".into()
636    })
637}
638
639fn handle_scoped_list(session: &SessionState) -> Result<String, String> {
640    let text = lean_ctx::core::session::admission::with_store_admission(session, |admission| {
641        let root = session
642            .strict_project_root()
643            .ok_or_else(|| "session project scope unavailable".to_string())?;
644        let mut rows = Vec::new();
645        for summary in SessionState::list_sessions() {
646            let Ok(Some(owner)) = SessionState::load_by_id_for_project_root(&summary.id, &root)
647            else {
648                continue;
649            };
650            let task = owner
651                .task
652                .as_ref()
653                .map(|task| task.description.as_str())
654                .unwrap_or("(no task)");
655            let Some(admitted_task) =
656                lean_ctx::core::session::admission::admit_store_text(admission, task)
657            else {
658                continue;
659            };
660            rows.push((summary, admitted_task));
661        }
662        if rows.is_empty() {
663            return Ok("No sessions found.".into());
664        }
665        let count = rows.len();
666        let mut lines = vec![format!("Sessions ({count}):")];
667        for (summary, task) in rows.iter().take(10) {
668            let task_short: String = task.chars().take(40).collect();
669            lines.push(format!(
670                "  {} v{} | {} calls | {} tok | {}",
671                summary.id, summary.version, summary.tool_calls, summary.tokens_saved, task_short
672            ));
673        }
674        if count > 10 {
675            lines.push(format!("  ... +{} more", count - 10));
676        }
677        Ok(lines.join("\n"))
678    })?;
679    lean_ctx::core::session::admission::admit_tool_value(session, &text)
680}
681
682fn handle_cleanup() -> String {
683    let days = lean_ctx::core::config::Config::load().session_retention_days_effective();
684    let removed = SessionState::cleanup_old_sessions(i64::from(days));
685    format!("Cleaned up {removed} old session(s) (>{days} days).")
686}
687
688fn handle_configure(session: &mut SessionState, opts: SessionToolOptions<'_>) -> String {
689    match opts.terse {
690        Some(enabled) => {
691            session.terse_mode = enabled;
692            session.increment();
693            format!("Session configured: terse_mode={enabled}")
694        }
695        None => format!("Session config: terse_mode={}", session.terse_mode),
696    }
697}
698
699fn handle_snapshot(session: &mut SessionState) -> String {
700    match session.save_compaction_snapshot() {
701        Ok(snapshot) => {
702            format!(
703                "Compaction snapshot saved ({} bytes).\n{snapshot}",
704                snapshot.len()
705            )
706        }
707        Err(e) => format!("Snapshot failed: {e}"),
708    }
709}
710
711fn handle_restore(session: &SessionState, session_id: Option<&str>) -> String {
712    handle_scoped_restore(session, session_id).unwrap_or_else(|_| {
713        "ERROR: session restore withheld by project scope or content policy.".into()
714    })
715}
716
717fn handle_scoped_restore(
718    session: &SessionState,
719    session_id: Option<&str>,
720) -> Result<String, String> {
721    let root = session
722        .strict_project_root()
723        .ok_or_else(|| "session project scope unavailable".to_string())?;
724    // Without an id: the caller's own snapshot, never the project's latest
725    // session's (I07/S03).
726    let id = session_id.unwrap_or(session.id.as_str());
727    let owner = SessionState::load_by_id_for_project_root(id, &root)
728        .map_err(|_| "session project scope mismatch".to_string())?;
729    let Some(owner) = owner else {
730        return Ok("No compaction snapshot found. Session continues fresh.".into());
731    };
732    let Some(snapshot) = SessionState::load_compaction_snapshot(&owner.id) else {
733        return Ok("No compaction snapshot found. Session continues fresh.".into());
734    };
735    let output = format!("Session restored from compaction snapshot:\n{snapshot}");
736    lean_ctx::core::session::admission::admit_tool_value(session, &output)
737}
738
739fn handle_resume(session: &mut SessionState) -> String {
740    session.build_resume_block()
741}
742
743fn handle_profile(value: Option<&str>) -> String {
744    {
745        use lean_ctx::core::profiles;
746        if let Some(name) = value {
747            if let Ok(p) = profiles::set_active_profile(name) {
748                format!(
749                    "Profile switched to '{name}'.\n\
750                         Read mode: {}, CRP: {}",
751                    p.read.default_mode_effective(),
752                    p.compression.crp_mode_effective(),
753                )
754            } else {
755                let available: Vec<String> = profiles::list_profiles()
756                    .iter()
757                    .map(|p| p.name.clone())
758                    .collect();
759                format!(
760                    "Profile '{name}' not found. Available: {}",
761                    available.join(", ")
762                )
763            }
764        } else {
765            let name = profiles::active_profile_name();
766            let p = profiles::active_profile();
767            let list = profiles::list_profiles();
768            let mut out = format!(
769                "Active profile: {name}\n\
770                     Read: {}, CRP: {}\n\n\
771                     Available profiles:",
772                p.read.default_mode_effective(),
773                p.compression.crp_mode_effective(),
774            );
775            for info in &list {
776                let marker = if info.name == name { " *" } else { "  " };
777                out.push_str(&format!(
778                    "\n{marker} {:<14} ({}) {}",
779                    info.name, info.source, info.description
780                ));
781            }
782            out.push_str("\n\nSwitch: ctx_session action=profile value=<name>");
783            out
784        }
785    }
786}
787
788fn handle_role(value: Option<&str>) -> String {
789    {
790        use lean_ctx::core::roles;
791        if let Some(name) = value {
792            match roles::set_active_role(name) {
793                Ok(r) => {
794                    format!(
795                        "Role switched to '{name}'.\n\
796                             Shell: {}\n\
797                             Tools: {}",
798                        r.role.shell_policy,
799                        if r.tools.allowed.iter().any(|a| a == "*") {
800                            let denied = if r.tools.denied.is_empty() {
801                                "none".to_string()
802                            } else {
803                                format!("denied: {}", r.tools.denied.join(", "))
804                            };
805                            format!("* (all), {denied}")
806                        } else {
807                            r.tools.allowed.join(", ")
808                        }
809                    )
810                }
811                Err(e) => {
812                    let available: Vec<String> =
813                        roles::list_roles().iter().map(|r| r.name.clone()).collect();
814                    format!("{e}. Available: {}", available.join(", "))
815                }
816            }
817        } else {
818            let name = roles::active_role_name();
819            let r = roles::active_role();
820            let list = roles::list_roles();
821            let mut out = format!(
822                "Active role: {name}\n\
823                     Description: {}\n\
824                     Shell policy: {}\n\n\
825                     Available roles:",
826                r.role.description, r.role.shell_policy,
827            );
828            for info in &list {
829                let marker = if info.is_active { " *" } else { "  " };
830                out.push_str(&format!(
831                    "\n{marker} {:<14} ({}) {}",
832                    info.name, info.source, info.description
833                ));
834            }
835            out.push_str("\n\nSwitch: ctx_session action=role value=<name>");
836            out
837        }
838    }
839}
840
841fn handle_diff(value: Option<&str>) -> String {
842    {
843        let parts: Vec<&str> = value.unwrap_or("").split_whitespace().collect();
844        if parts.len() < 2 {
845            return "Usage: ctx_session diff <session_id_a> <session_id_b> [format]\n\
846                        Formats: summary (default), json\n\
847                        Example: ctx_session diff abc123 def456 json"
848                .to_string();
849        }
850        let id_a = parts[0];
851        let id_b = parts[1];
852        let format = parts.get(2).copied().unwrap_or("summary");
853
854        // Only sessions of the request's own project are compared; a foreign
855        // session reads as absent rather than confirming it exists (AP04-G8).
856        let Some(project) = lean_ctx::core::policy::runtime::REQUEST_PROJECT
857            .try_with(|slot| slot.borrow().clone())
858            .ok()
859            .flatten()
860        else {
861            return "ERROR: project_unresolved — session diff needs the request's project."
862                .to_string();
863        };
864        let project = project.to_string_lossy();
865        let load = |id: &str| {
866            SessionState::load_by_id_for_project_root(id, &project)
867                .ok()
868                .flatten()
869        };
870
871        match (load(id_a), load(id_b)) {
872            (Some(a), Some(b)) => {
873                let d = lean_ctx_ext::core::session_diff::diff_sessions(&a, &b);
874                match format {
875                    "json" => d.format_json(),
876                    _ => d.format_summary(),
877                }
878            }
879            (None, _) => format!("Session not found: {id_a}"),
880            (_, None) => format!("Session not found: {id_b}"),
881        }
882    }
883}
884
885fn handle_output_stats() -> String {
886    {
887        let snap = lean_ctx::core::output_verification::stats_snapshot();
888        let mut out = snap.format_compact();
889        // Agent-output echo summary (#501).
890        let echo = lean_ctx_ext::core::output_echo::load_stats();
891        if !echo.reports.is_empty() {
892            out.push_str(&format!(
893                "\nOutput echo: {:.0}% avg over last {} replies ({} analyzed total)",
894                echo.avg_ratio(50) * 100.0,
895                echo.reports.len(),
896                echo.total_analyzed
897            ));
898        }
899        out
900    }
901}
902
903fn handle_verify() -> String {
904    {
905        let snap = lean_ctx::core::output_verification::stats_snapshot();
906        format!(
907            "DEPRECATION: action=\"verify\" is renamed to action=\"output_stats\" (ctx_verify is the full observability stack).\n{}",
908            snap.format_compact()
909        )
910    }
911}
912
913/// `ctx_session action=episodes|procedures` (any value): retired with the
914/// episode and procedure memory. Accepted as a no-op until its removal
915/// (`rust/data/DEPRECATIONS.toml`); files under `memory/episodes` and
916/// `memory/procedures` stay on disk untouched.
917fn handle_retired_memory(action: &str) -> String {
918    format!(
919        "DEPRECATION: action=\"{action}\" is retired with the episode and procedure memory and has no effect. Decisions, findings and gotchas live in ctx_knowledge (action=recall or action=search)."
920    )
921}
922
923fn handle_unknown(action: &str) -> String {
924    format!(
925        "Unknown action: {action}. Use: status, handoff, load, save, task, finding, decision, reset, list, cleanup, snapshot, restore, resume, configure, profile, role, diff, output_stats, verify, export, import"
926    )
927}
928
929fn parse_finding_value(value: &str) -> (Option<String>, Option<u32>, &str) {
930    const EM_DASH_SEP: &str = " \u{2014} ";
931    const ASCII_SEP: &str = " - ";
932
933    let (dash_pos, sep) = if let Some(p) = value.find(EM_DASH_SEP) {
934        (Some(p), EM_DASH_SEP)
935    } else {
936        (value.find(ASCII_SEP), ASCII_SEP)
937    };
938
939    if let Some(pos) = dash_pos {
940        let location = &value[..pos];
941        let text = &value[pos + sep.len()..];
942
943        if let Some(colon_pos) = location.rfind(':') {
944            let file = &location[..colon_pos];
945            if let Ok(line) = location[colon_pos + 1..].parse::<u32>() {
946                return (Some(file.to_string()), Some(line), text);
947            }
948        }
949        return (Some(location.to_string()), None, text);
950    }
951    (None, None, value)
952}
953
954#[cfg(test)]
955mod tests;