Skip to main content

lean_ctx/tools/
ctx_session.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use 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    /// 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,
32                mut output,
33                completed_task,
34                ..
35            } = prepared;
36            *session = candidate;
37            if let Some(note) = record_completed_task_after_commit(
38                session,
39                completed_task,
40                tool_calls,
41                opts.agent_id,
42            ) {
43                output.push_str(&note);
44            }
45            crate::core::session::admission::admit_tool_value(session, &output).unwrap_or_else(
46                |error| {
47                    // Two different refusals. The gateway withheld the reply's
48                    // content: its notice (`[lean-ctx …]`). Or no policy scope
49                    // could be established for this session at all (no usable
50                    // project root): that is a failed action, reported in the
51                    // tool's own `ERROR:` form like every other scope denial —
52                    // never the action's unadmitted output.
53                    if error.starts_with("[lean-ctx") {
54                        "[lean-ctx gateway: session content withheld]".into()
55                    } else {
56                        "ERROR: session action withheld by current project or content policy."
57                            .into()
58                    }
59                },
60            )
61        }
62    }
63}
64
65pub(crate) struct PreparedSessionAction {
66    pub(crate) candidate: SessionState,
67    pub(crate) output: String,
68    pub(crate) completed_task: bool,
69    pub(crate) store_admission: crate::core::context_admission::stores::StoreAdmission,
70}
71
72/// Prepare content-bearing actions from a detached snapshot. Callers with a
73/// live session lock commit candidate only after checking snapshot identity.
74pub(crate) fn prepare_admitted_action(
75    session: &SessionState,
76    tool_calls: &[(String, u64)],
77    action: &str,
78    value: Option<&str>,
79    session_id: Option<&str>,
80    opts: SessionToolOptions<'_>,
81) -> Result<PreparedSessionAction, String> {
82    let store_admission = crate::core::context_admission::stores::StoreAdmission::current();
83    let mut candidate = session.clone();
84    let (output, completed_task) = match action {
85        "task" | "finding" | "decision" => {
86            let fallback = match action {
87                "finding" => "(no summary)",
88                _ => "(no description)",
89            };
90            let admitted = crate::core::session::admission::admit_storable_session_text(
91                session,
92                value.unwrap_or(fallback),
93            )?;
94            let completed = action == "task" && task_is_complete(&admitted);
95            let output = match action {
96                "task" => handle_task(&mut candidate, tool_calls, Some(&admitted), opts),
97                "finding" => handle_finding(&mut candidate, Some(&admitted)),
98                _ => handle_decision(&mut candidate, Some(&admitted)),
99            };
100            (output, completed)
101        }
102        "list" => (handle_scoped_list(session)?, false),
103        "restore" => (handle_scoped_restore(session, session_id)?, false),
104        "episodes" => (
105            handle_episodes_scoped(session, tool_calls, value, opts)?,
106            false,
107        ),
108        "procedures" => (handle_procedures_scoped(session, value)?, false),
109        _ => (
110            handle_legacy(&mut candidate, tool_calls, action, value, session_id, opts),
111            false,
112        ),
113    };
114    if !store_admission.is_current() {
115        return Err("session admission policy changed; retry".into());
116    }
117    Ok(PreparedSessionAction {
118        candidate,
119        output,
120        completed_task,
121        store_admission,
122    })
123}
124
125/// Run completion learning only after the caller commits or saves the updated
126/// session. Storage failures never roll back the successful session update.
127pub(crate) fn record_completed_task_after_commit(
128    session: &SessionState,
129    completed_task: bool,
130    tool_calls: &[(String, u64)],
131    agent_id: Option<&str>,
132) -> Option<String> {
133    if !completed_task {
134        return None;
135    }
136    auto_record_episode(session, tool_calls, agent_id)
137        .ok()
138        .flatten()
139        .map(|id| format!("\nEpisode auto-recorded: {id}"))
140}
141
142fn task_is_complete(description: &str) -> bool {
143    let lower = description.to_lowercase();
144    description.contains("[100%]") || lower.contains("[done]") || lower.contains("[complete]")
145}
146
147fn handle_legacy(
148    session: &mut SessionState,
149    tool_calls: &[(String, u64)],
150    action: &str,
151    value: Option<&str>,
152    session_id: Option<&str>,
153    opts: SessionToolOptions<'_>,
154) -> String {
155    if action == "handoff" {
156        return handle_handoff(session);
157    }
158
159    match action {
160        "status" | "show" => handle_status(session),
161        "load" => handle_load(session, session_id),
162        "save" => handle_save(session),
163        "export" => handle_export(session, value, opts),
164        "import" => handle_import(session, value, opts),
165        "task" => handle_task(session, tool_calls, value, opts),
166        "finding" => handle_finding(session, value),
167        "decision" => handle_decision(session, value),
168        "reset" => handle_reset(session),
169        "list" => handle_list(session),
170        "cleanup" => handle_cleanup(),
171        "configure" => handle_configure(session, opts),
172        "snapshot" => handle_snapshot(session),
173        "restore" => handle_restore(session, session_id),
174        "resume" => handle_resume(session),
175        "profile" => handle_profile(value),
176        "role" => handle_role(value),
177        "diff" => handle_diff(value),
178        "output_stats" => handle_output_stats(),
179        "verify" => handle_verify(),
180        "episodes" => handle_episodes(session, tool_calls, value, opts),
181        "procedures" => handle_procedures(session, value),
182        _ => handle_unknown(action),
183    }
184}
185
186/// Handle actions that do not access live-session state. Keeping them outside
187/// the live session lock prevents an explicit `list`/`cleanup` request from
188/// stalling unrelated reads and shells behind an O(session-store) operation.
189/// Some actions intentionally update independent process-global configuration.
190pub fn handle_without_session(
191    action: &str,
192    value: Option<&str>,
193    _session_id: Option<&str>,
194) -> Option<String> {
195    match action {
196        "cleanup" => Some(handle_cleanup()),
197        "profile" => Some(handle_profile(value)),
198        "role" => Some(handle_role(value)),
199        "diff" => Some(handle_diff(value)),
200        "output_stats" => Some(handle_output_stats()),
201        "verify" => Some(handle_verify()),
202        _ => None,
203    }
204}
205
206/// Handle session reads after rechecking all recalled content under the
207/// current project and Gateway policies.
208pub fn handle_read_only(session: &SessionState, action: &str) -> Option<String> {
209    let Ok(projected) = crate::core::session::admission::for_delivery(session) else {
210        return Some("[lean-ctx gateway: session content withheld]".into());
211    };
212    let text = match action {
213        "status" | "show" => handle_status(&projected),
214        "handoff" => handle_handoff(&projected),
215        _ => return None,
216    };
217    Some(
218        crate::core::session::admission::admit_tool_value(&projected, &text)
219            .unwrap_or_else(|_| "[lean-ctx gateway: session content withheld]".into()),
220    )
221}
222
223/// Run snapshot/export work after the caller cloned live state and released its
224/// lock. Persisted projections are admitted before they reach an archive writer.
225pub fn handle_snapshot_read_action(
226    session: &SessionState,
227    action: &str,
228    value: Option<&str>,
229    opts: SessionToolOptions<'_>,
230) -> Option<String> {
231    match action {
232        "export" => {
233            let Ok(projected) = crate::core::session::admission::for_storage(session) else {
234                return Some("ERROR: session export withheld by current policy.".into());
235            };
236            let output = handle_export(&projected, value, opts);
237            // The default export is structural JSON from the already-admitted
238            // typed projection; masking that serialization would corrupt it.
239            let structural_json =
240                opts.format
241                    .unwrap_or(if opts.write { "summary" } else { "json" })
242                    != "summary";
243            Some(if structural_json {
244                output
245            } else {
246                crate::core::session::admission::admit_tool_value(&projected, &output)
247                    .unwrap_or_else(|_| "ERROR: session export withheld by current policy.".into())
248            })
249        }
250        "resume" => {
251            let Ok(projected) = crate::core::session::admission::for_delivery(session) else {
252                return Some("[lean-ctx gateway: session content withheld]".into());
253            };
254            let output = projected.build_resume_block();
255            Some(
256                crate::core::session::admission::admit_tool_value(&projected, &output)
257                    .unwrap_or_else(|_| "[lean-ctx gateway: session content withheld]".into()),
258            )
259        }
260        "snapshot" => {
261            let Ok(projected) = crate::core::session::admission::for_storage(session) else {
262                return Some("ERROR: session snapshot withheld by current policy.".into());
263            };
264            let output = projected.save_compaction_snapshot().map_or_else(
265                |error| format!("Snapshot failed: {error}"),
266                |snapshot| {
267                    format!(
268                        "Compaction snapshot saved ({} bytes).\n{snapshot}",
269                        snapshot.len()
270                    )
271                },
272            );
273            Some(
274                crate::core::session::admission::admit_tool_value(&projected, &output)
275                    .unwrap_or_else(|_| {
276                        "ERROR: session snapshot withheld by current policy.".into()
277                    }),
278            )
279        }
280        _ => None,
281    }
282}
283
284/// The session summary as a delivery: findings publish their sources or mark
285/// the call's capture, and any other session text marks it incomplete
286/// (`SessionState::format_compact_delivered`).
287///
288/// When the session's root was chosen among several workspace roots, a line
289/// names the choice, the other roots and how to change it (AP04-G7).
290fn handle_status(session: &SessionState) -> String {
291    let summary = session.format_compact_delivered();
292    // Under a launcher Workspace its binding is the root line (#2120).
293    match crate::core::workspace_authority::current() {
294        crate::core::workspace_authority::Authority::Legacy => {}
295        crate::core::workspace_authority::Authority::Workspace(snapshot) => {
296            return format!("{summary}\n{}", snapshot.status_line());
297        }
298        crate::core::workspace_authority::Authority::Unavailable(reason) => {
299            return format!(
300                "{summary}\n{}",
301                crate::core::workspace_authority::unavailable_reason(&reason)
302            );
303        }
304    }
305    match session
306        .project_root
307        .as_deref()
308        .and_then(crate::core::root_selection::recorded_for)
309    {
310        Some(selection) => format!("{summary}\n{}", selection.notice()),
311        None => summary,
312    }
313}
314
315fn handle_handoff(session: &SessionState) -> String {
316    if session.handoff_context.is_empty() {
317        return "Handoff context: no recent cross-session decisions.".to_string();
318    }
319
320    let mut output = format!(
321        "Handoff context ({} recent cross-session decisions):",
322        session.handoff_context.len()
323    );
324    for fact in &session.handoff_context {
325        output.push_str(&format!(
326            "\n  [{}] {} (confidence: {:.0}%)",
327            fact.category,
328            fact.value,
329            fact.confidence * 100.0
330        ));
331    }
332    output
333}
334
335fn handle_load(session: &mut SessionState, session_id: Option<&str>) -> String {
336    match prepare_load(session, session_id) {
337        Ok((loaded, output)) => {
338            *session = loaded;
339            output
340        }
341        Err(error) => error,
342    }
343}
344
345/// Load and admit a detached candidate. The caller may commit it only after
346/// confirming that the live session identity and version still match.
347pub(crate) fn prepare_load(
348    session: &SessionState,
349    session_id: Option<&str>,
350) -> Result<(SessionState, String), String> {
351    const SCOPE_DENIED: &str = "ERROR: session load denied: scoped session unavailable or mismatched; live session unchanged.";
352
353    let receiving_root = session.strict_project_root().ok_or(SCOPE_DENIED)?;
354    // Without an id: the caller's own saved session — never the project's
355    // latest, which may be another agent's (I07/S03). Another session is
356    // loaded only by naming it, e.g. the id a handoff gave.
357    let id = session_id.unwrap_or(session.id.as_str());
358    let loaded =
359        SessionState::load_by_id_for_project_root(id, &receiving_root).map_err(|_| SCOPE_DENIED)?;
360
361    let Some(mut loaded) = loaded else {
362        return Err(SCOPE_DENIED.into());
363    };
364    if loaded.strict_project_root().as_deref() != Some(receiving_root.as_str()) {
365        return Err(SCOPE_DENIED.into());
366    }
367
368    // These fields come from live MCP roots/shell and must not be replaced by
369    // persisted state. Validate root scope before this policy lookup.
370    loaded.extra_roots.clone_from(&session.extra_roots);
371    loaded.shell_cwd.clone_from(&session.shell_cwd);
372    let admitted = crate::core::session::admission::for_storage(&loaded)
373        .map_err(|_| "ERROR: session load withheld by current policy; live session unchanged.")?;
374    let summary = handle_status(&admitted);
375    let output = crate::core::session::admission::admit_tool_value(
376        &admitted,
377        &format!("Session loaded.\n{summary}"),
378    )
379    .map_err(|_| "ERROR: session load withheld by current policy; live session unchanged.")?;
380    Ok((admitted, output))
381}
382
383fn handle_save(session: &mut SessionState) -> String {
384    let result = save_session(session);
385    if result.is_ok()
386        && let Some(root) = session.project_root.as_deref()
387    {
388        // Queue learnings for Hive, debounced per project (local only).
389        crate::core::hive::knowledge::draft::on_session_event(
390            root,
391            &session.id,
392            crate::core::hive::knowledge::draft::Trigger::Save,
393        );
394    }
395    result.unwrap_or_else(|error| format!("Save failed: {error}"))
396}
397
398pub(crate) fn save_session(session: &mut SessionState) -> Result<String, String> {
399    match session.save() {
400        Ok(()) => Ok(format!(
401            "Session {} saved (v{}).",
402            session.id, session.version
403        )),
404        Err(error) => Err(error),
405    }
406}
407
408fn handle_export(
409    session: &SessionState,
410    value: Option<&str>,
411    opts: SessionToolOptions<'_>,
412) -> String {
413    if session.canonical_checkpoint.is_some() {
414        return "ERROR: a canonical checkpoint requires a versioned carrier; legacy bundle export would discard its current lineage.".into();
415    }
416    {
417        let requested_privacy =
418            crate::core::ccp_session_bundle::BundlePrivacyV1::parse(opts.privacy);
419        if requested_privacy == crate::core::ccp_session_bundle::BundlePrivacyV1::Full
420            && crate::core::roles::active_role_name() != "admin"
421        {
422            return "ERROR: privacy=full requires role 'admin'.".to_string();
423        }
424
425        let bundle = crate::core::ccp_session_bundle::build_bundle_v1(session, requested_privacy);
426        let json = match crate::core::ccp_session_bundle::serialize_bundle_v1_pretty(&bundle) {
427            Ok(s) => s,
428            Err(e) => return e,
429        };
430
431        let format = opts
432            .format
433            .unwrap_or(if opts.write { "summary" } else { "json" });
434        let root = session.project_root.clone().unwrap_or_else(|| {
435            std::env::current_dir()
436                .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string())
437        });
438        let root_path = std::path::PathBuf::from(&root);
439
440        let mut written: Option<String> = None;
441        if opts.write || opts.path.is_some() {
442            let ts = chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string();
443            let candidate = if let Some(p) = opts.path.or(value) {
444                let p = std::path::PathBuf::from(p);
445                if p.is_absolute() {
446                    p
447                } else {
448                    root_path.join(p)
449                }
450            } else {
451                root_path
452                    .join(".lean-ctx")
453                    .join("session_bundles")
454                    .join(format!(
455                        "ccp-session-bundle-v1_{}_{}.json",
456                        bundle.session.id, ts
457                    ))
458            };
459
460            let jailed = match crate::core::io_boundary::jail_and_check_path(
461                "ctx_session.export",
462                candidate.as_path(),
463                root_path.as_path(),
464            ) {
465                Ok((p, _warning)) => p,
466                Err(e) => return e,
467            };
468
469            // Read-only-roots choke point (#475): export must not write a
470            // bundle into a read-only root even when the jail allows reads.
471            if let Err(e) = crate::core::pathjail::enforce_writable(&jailed) {
472                return format!("Export write failed: {e}");
473            }
474            if let Err(e) = crate::core::ccp_session_bundle::write_bundle_v1(&jailed, &json) {
475                return format!("Export write failed: {e}");
476            }
477            written = Some(jailed.to_string_lossy().to_string());
478        }
479
480        match format {
481            "summary" => {
482                let mut out = format!(
483                    "CCP session bundle exported (v{}).\n\
484schema_version: {}\n\
485session_id: {}\n\
486bytes: {}\n",
487                    bundle.session.version,
488                    bundle.schema_version,
489                    bundle.session.id,
490                    json.len()
491                );
492                if let Some(p) = written {
493                    out.push_str(&format!("path: {p}\n"));
494                }
495                if let Some(h) = bundle.project.project_root_hash {
496                    out.push_str(&format!("project_root_hash: {h}\n"));
497                }
498                if let Some(h) = bundle.project.project_identity_hash {
499                    out.push_str(&format!("project_identity_hash: {h}\n"));
500                }
501                out
502            }
503            _ => {
504                if let Some(p) = written {
505                    format!("{json}\n\npath: {p}")
506                } else {
507                    json
508                }
509            }
510        }
511    }
512}
513
514fn handle_import(
515    session: &mut SessionState,
516    value: Option<&str>,
517    opts: SessionToolOptions<'_>,
518) -> String {
519    {
520        let root = session.project_root.clone().unwrap_or_else(|| {
521            std::env::current_dir()
522                .map_or_else(|_| ".".to_string(), |p| p.to_string_lossy().to_string())
523        });
524        let root_path = std::path::PathBuf::from(&root);
525
526        let Some(p) = opts.path.or(value) else {
527            return "ERROR: path is required for action=import".to_string();
528        };
529
530        let candidate = {
531            let p = std::path::PathBuf::from(p);
532            if p.is_absolute() {
533                p
534            } else {
535                root_path.join(p)
536            }
537        };
538        let jailed = match crate::core::io_boundary::jail_and_check_path(
539            "ctx_session.import",
540            candidate.as_path(),
541            root_path.as_path(),
542        ) {
543            Ok((p, _warning)) => p,
544            Err(e) => return e,
545        };
546
547        let bundle = match crate::core::ccp_session_bundle::read_bundle_v1(&jailed) {
548            Ok(b) => b,
549            Err(e) => return format!("Import failed: {e}"),
550        };
551
552        // A legacy identity hash is a scope check, not signer admission. Never
553        // overwrite a foreign project's session after only displaying a warning.
554        let current_root_hash = crate::core::project_hash::hash_project_root(&root);
555        let current_identity_hash = crate::core::project_hash::project_identity(&root)
556            .as_deref()
557            .map(crate::core::hasher::hash_str);
558
559        let matching_scope = match (
560            bundle.project.project_identity_hash.as_ref(),
561            current_identity_hash.as_ref(),
562        ) {
563            (Some(exported), Some(current)) => exported == current,
564            _ => bundle.project.project_root_hash.as_ref() == Some(&current_root_hash),
565        };
566        if !matching_scope {
567            return "Import failed: project scope mismatch; live session unchanged.".to_string();
568        }
569
570        let mut candidate = session.clone();
571        let report = crate::core::ccp_session_bundle::import_bundle_v1_into_session(
572            &mut candidate,
573            &bundle,
574            Some(&root),
575        );
576        // Import into a new identity, preserving both the current session and
577        // any existing archive bearing the untrusted source identity.
578        if let Err(error) = candidate.save_new() {
579            return format!(
580                "Import failed: {error}; live session unchanged; recovery candidate: {}.",
581                candidate.id
582            );
583        }
584        *session = candidate;
585
586        format!(
587            "CCP session bundle imported.\n\
588session_id: {}\n\
589source_session_id: {}\n\
590version: {}\n\
591files_touched: {}\n\
592stale_files: {}\n",
593            report.session_id,
594            report.source_session_id,
595            report.version,
596            report.files_touched,
597            report.stale_files
598        )
599    }
600}
601
602fn handle_task(
603    session: &mut SessionState,
604    _tool_calls: &[(String, u64)],
605    value: Option<&str>,
606    _opts: SessionToolOptions<'_>,
607) -> String {
608    {
609        let desc = value.unwrap_or("(no description)");
610        session.set_task(desc, None);
611        format!("Task set: {desc}")
612    }
613}
614
615fn handle_finding(session: &mut SessionState, value: Option<&str>) -> String {
616    {
617        let summary = value.unwrap_or("(no summary)");
618        let (file, line, text) = parse_finding_value(summary);
619        session.add_finding_for_file(file.as_deref(), line, text);
620        format!("Finding added: {summary}")
621    }
622}
623
624fn handle_decision(session: &mut SessionState, value: Option<&str>) -> String {
625    {
626        let desc = value.unwrap_or("(no description)");
627        session.add_decision(desc, None);
628        format!("Decision recorded: {desc}")
629    }
630}
631
632fn handle_reset(session: &mut SessionState) -> String {
633    if let Err(error) = session.save() {
634        return format!("Reset refused: current session was not saved: {error}");
635    }
636    reset_after_save(session)
637}
638
639pub(crate) fn reset_after_save(session: &mut SessionState) -> String {
640    let old_id = session.id.clone();
641    *session = SessionState::new();
642    // Clear the persistent context ledger so pressure resets to 0%
643    let mut ledger = crate::core::context_ledger::ContextLedger::load();
644    ledger.reset();
645    ledger.save();
646    if let Ok(data_dir) = crate::core::data_dir::lean_ctx_data_dir() {
647        let radar_path = data_dir.join("context_radar.jsonl");
648        let prev = data_dir.join("context_radar.prev.jsonl");
649        let _ = std::fs::rename(&radar_path, &prev);
650    }
651    format!(
652        "Session reset. Previous: {old_id}. New: {}. Ledger cleared (0% pressure).",
653        session.id
654    )
655}
656
657fn handle_list(session: &SessionState) -> String {
658    handle_scoped_list(session).unwrap_or_else(|_| {
659        "ERROR: session list withheld by project scope or content policy.".into()
660    })
661}
662
663fn handle_scoped_list(session: &SessionState) -> Result<String, String> {
664    let text = crate::core::session::admission::with_store_admission(session, |admission| {
665        let root = session
666            .strict_project_root()
667            .ok_or_else(|| "session project scope unavailable".to_string())?;
668        let mut rows = Vec::new();
669        for summary in SessionState::list_sessions() {
670            let Ok(Some(owner)) = SessionState::load_by_id_for_project_root(&summary.id, &root)
671            else {
672                continue;
673            };
674            let task = owner
675                .task
676                .as_ref()
677                .map(|task| task.description.as_str())
678                .unwrap_or("(no task)");
679            let Some(admitted_task) =
680                crate::core::session::admission::admit_store_text(admission, task)
681            else {
682                continue;
683            };
684            rows.push((summary, admitted_task));
685        }
686        if rows.is_empty() {
687            return Ok("No sessions found.".into());
688        }
689        let count = rows.len();
690        let mut lines = vec![format!("Sessions ({count}):")];
691        for (summary, task) in rows.iter().take(10) {
692            let task_short: String = task.chars().take(40).collect();
693            lines.push(format!(
694                "  {} v{} | {} calls | {} tok | {}",
695                summary.id, summary.version, summary.tool_calls, summary.tokens_saved, task_short
696            ));
697        }
698        if count > 10 {
699            lines.push(format!("  ... +{} more", count - 10));
700        }
701        Ok(lines.join("\n"))
702    })?;
703    crate::core::session::admission::admit_tool_value(session, &text)
704}
705
706fn handle_cleanup() -> String {
707    let days = crate::core::config::Config::load().session_retention_days_effective();
708    let removed = SessionState::cleanup_old_sessions(i64::from(days));
709    format!("Cleaned up {removed} old session(s) (>{days} days).")
710}
711
712fn handle_configure(session: &mut SessionState, opts: SessionToolOptions<'_>) -> String {
713    match opts.terse {
714        Some(enabled) => {
715            session.terse_mode = enabled;
716            session.increment();
717            format!("Session configured: terse_mode={enabled}")
718        }
719        None => format!("Session config: terse_mode={}", session.terse_mode),
720    }
721}
722
723fn handle_snapshot(session: &mut SessionState) -> String {
724    match session.save_compaction_snapshot() {
725        Ok(snapshot) => {
726            format!(
727                "Compaction snapshot saved ({} bytes).\n{snapshot}",
728                snapshot.len()
729            )
730        }
731        Err(e) => format!("Snapshot failed: {e}"),
732    }
733}
734
735fn handle_restore(session: &SessionState, session_id: Option<&str>) -> String {
736    handle_scoped_restore(session, session_id).unwrap_or_else(|_| {
737        "ERROR: session restore withheld by project scope or content policy.".into()
738    })
739}
740
741fn handle_scoped_restore(
742    session: &SessionState,
743    session_id: Option<&str>,
744) -> Result<String, String> {
745    let root = session
746        .strict_project_root()
747        .ok_or_else(|| "session project scope unavailable".to_string())?;
748    // Without an id: the caller's own snapshot, never the project's latest
749    // session's (I07/S03).
750    let id = session_id.unwrap_or(session.id.as_str());
751    let owner = SessionState::load_by_id_for_project_root(id, &root)
752        .map_err(|_| "session project scope mismatch".to_string())?;
753    let Some(owner) = owner else {
754        return Ok("No compaction snapshot found. Session continues fresh.".into());
755    };
756    let Some(snapshot) = SessionState::load_compaction_snapshot(&owner.id) else {
757        return Ok("No compaction snapshot found. Session continues fresh.".into());
758    };
759    let output = format!("Session restored from compaction snapshot:\n{snapshot}");
760    crate::core::session::admission::admit_tool_value(session, &output)
761}
762
763fn handle_resume(session: &mut SessionState) -> String {
764    session.build_resume_block()
765}
766
767fn handle_profile(value: Option<&str>) -> String {
768    {
769        use crate::core::profiles;
770        if let Some(name) = value {
771            if let Ok(p) = profiles::set_active_profile(name) {
772                format!(
773                    "Profile switched to '{name}'.\n\
774                         Read mode: {}, CRP: {}",
775                    p.read.default_mode_effective(),
776                    p.compression.crp_mode_effective(),
777                )
778            } else {
779                let available: Vec<String> = profiles::list_profiles()
780                    .iter()
781                    .map(|p| p.name.clone())
782                    .collect();
783                format!(
784                    "Profile '{name}' not found. Available: {}",
785                    available.join(", ")
786                )
787            }
788        } else {
789            let name = profiles::active_profile_name();
790            let p = profiles::active_profile();
791            let list = profiles::list_profiles();
792            let mut out = format!(
793                "Active profile: {name}\n\
794                     Read: {}, CRP: {}\n\n\
795                     Available profiles:",
796                p.read.default_mode_effective(),
797                p.compression.crp_mode_effective(),
798            );
799            for info in &list {
800                let marker = if info.name == name { " *" } else { "  " };
801                out.push_str(&format!(
802                    "\n{marker} {:<14} ({}) {}",
803                    info.name, info.source, info.description
804                ));
805            }
806            out.push_str("\n\nSwitch: ctx_session action=profile value=<name>");
807            out
808        }
809    }
810}
811
812fn handle_role(value: Option<&str>) -> String {
813    {
814        use crate::core::roles;
815        if let Some(name) = value {
816            match roles::set_active_role(name) {
817                Ok(r) => {
818                    format!(
819                        "Role switched to '{name}'.\n\
820                             Shell: {}\n\
821                             Tools: {}",
822                        r.role.shell_policy,
823                        if r.tools.allowed.iter().any(|a| a == "*") {
824                            let denied = if r.tools.denied.is_empty() {
825                                "none".to_string()
826                            } else {
827                                format!("denied: {}", r.tools.denied.join(", "))
828                            };
829                            format!("* (all), {denied}")
830                        } else {
831                            r.tools.allowed.join(", ")
832                        }
833                    )
834                }
835                Err(e) => {
836                    let available: Vec<String> =
837                        roles::list_roles().iter().map(|r| r.name.clone()).collect();
838                    format!("{e}. Available: {}", available.join(", "))
839                }
840            }
841        } else {
842            let name = roles::active_role_name();
843            let r = roles::active_role();
844            let list = roles::list_roles();
845            let mut out = format!(
846                "Active role: {name}\n\
847                     Description: {}\n\
848                     Shell policy: {}\n\n\
849                     Available roles:",
850                r.role.description, r.role.shell_policy,
851            );
852            for info in &list {
853                let marker = if info.is_active { " *" } else { "  " };
854                out.push_str(&format!(
855                    "\n{marker} {:<14} ({}) {}",
856                    info.name, info.source, info.description
857                ));
858            }
859            out.push_str("\n\nSwitch: ctx_session action=role value=<name>");
860            out
861        }
862    }
863}
864
865fn handle_diff(value: Option<&str>) -> String {
866    {
867        let parts: Vec<&str> = value.unwrap_or("").split_whitespace().collect();
868        if parts.len() < 2 {
869            return "Usage: ctx_session diff <session_id_a> <session_id_b> [format]\n\
870                        Formats: summary (default), json\n\
871                        Example: ctx_session diff abc123 def456 json"
872                .to_string();
873        }
874        let id_a = parts[0];
875        let id_b = parts[1];
876        let format = parts.get(2).copied().unwrap_or("summary");
877
878        // Only sessions of the request's own project are compared; a foreign
879        // session reads as absent rather than confirming it exists (AP04-G8).
880        let Some(project) = crate::core::policy::runtime::REQUEST_PROJECT
881            .try_with(|slot| slot.borrow().clone())
882            .ok()
883            .flatten()
884        else {
885            return "ERROR: project_unresolved — session diff needs the request's project."
886                .to_string();
887        };
888        let project = project.to_string_lossy();
889        let load = |id: &str| {
890            SessionState::load_by_id_for_project_root(id, &project)
891                .ok()
892                .flatten()
893        };
894
895        match (load(id_a), load(id_b)) {
896            (Some(a), Some(b)) => {
897                let d = crate::core::session_diff::diff_sessions(&a, &b);
898                match format {
899                    "json" => d.format_json(),
900                    _ => d.format_summary(),
901                }
902            }
903            (None, _) => format!("Session not found: {id_a}"),
904            (_, None) => format!("Session not found: {id_b}"),
905        }
906    }
907}
908
909fn handle_output_stats() -> String {
910    {
911        let snap = crate::core::output_verification::stats_snapshot();
912        let mut out = snap.format_compact();
913        // Agent-output echo summary (#501).
914        let echo = crate::core::output_echo::load_stats();
915        if !echo.reports.is_empty() {
916            out.push_str(&format!(
917                "\nOutput echo: {:.0}% avg over last {} replies ({} analyzed total)",
918                echo.avg_ratio(50) * 100.0,
919                echo.reports.len(),
920                echo.total_analyzed
921            ));
922        }
923        out
924    }
925}
926
927fn handle_verify() -> String {
928    {
929        let snap = crate::core::output_verification::stats_snapshot();
930        format!(
931            "DEPRECATION: action=\"verify\" is renamed to action=\"output_stats\" (ctx_verify is the full observability stack).\n{}",
932            snap.format_compact()
933        )
934    }
935}
936
937fn handle_episodes(
938    session: &mut SessionState,
939    tool_calls: &[(String, u64)],
940    value: Option<&str>,
941    opts: SessionToolOptions<'_>,
942) -> String {
943    handle_episodes_scoped(session, tool_calls, value, opts).unwrap_or_else(|_| {
944        "ERROR: episodic operation withheld by project scope or content policy.".into()
945    })
946}
947
948fn handle_episodes_scoped(
949    session: &SessionState,
950    tool_calls: &[(String, u64)],
951    value: Option<&str>,
952    opts: SessionToolOptions<'_>,
953) -> Result<String, String> {
954    let (_, hash) = trusted_memory_scope(session)?;
955    let policy = crate::core::config::Config::load()
956        .memory_policy_effective()
957        .map_err(|error| format!("invalid memory policy: {error}"))?;
958
959    match value {
960        Some("record") => {
961            let id = crate::core::episodic_memory::record_session_episode(
962                &hash,
963                session,
964                tool_calls,
965                opts.agent_id,
966                &policy.episodic,
967                false,
968            )?
969            .ok_or_else(|| "episode not recorded".to_string())?;
970            crate::core::events::emit(crate::core::events::EventKind::KnowledgeUpdate {
971                category: "episodic".to_string(),
972                key: id.clone(),
973                action: "record".to_string(),
974            });
975            let learned = auto_detect_admitted_procedures(session, &hash, &policy.procedural).ok();
976            let output = match learned {
977                Some(count) if count > 0 => format!(
978                    "Episode recorded: {id} (procedures auto-updated: {count} known workflows)"
979                ),
980                _ => format!("Episode recorded: {id}"),
981            };
982            crate::core::session::admission::admit_tool_value(session, &output)
983        }
984        Some(v) if v.starts_with("search ") => {
985            let query = v.trim_start_matches("search ").trim();
986            let query =
987                crate::core::session::admission::admit_storable_session_text(session, query)?;
988            let output =
989                crate::core::session::admission::with_store_admission(session, |admission| {
990                    let store = crate::core::episodic_memory::EpisodicStore::load_admitted(
991                        &hash, admission,
992                    )?;
993                    let hits = store.search(&query);
994                    if hits.is_empty() {
995                        return Ok("No episodes matched.".to_string());
996                    }
997                    let mut out = format!("Episodes matched ({}):", hits.len());
998                    for episode in hits.into_iter().take(10) {
999                        let task: String = episode.task_description.chars().take(50).collect();
1000                        out.push_str(&format!(
1001                            "\n  {} | {} | {} | {}",
1002                            episode.id,
1003                            episode.timestamp,
1004                            episode.outcome.label(),
1005                            task
1006                        ));
1007                    }
1008                    Ok(out)
1009                })?;
1010            crate::core::session::admission::admit_tool_value(session, &output)
1011        }
1012        Some(v) if v.starts_with("file ") => {
1013            let file = v.trim_start_matches("file ").trim();
1014            let file = crate::core::session::admission::admit_storable_session_text(session, file)?;
1015            let output =
1016                crate::core::session::admission::with_store_admission(session, |admission| {
1017                    let store = crate::core::episodic_memory::EpisodicStore::load_admitted(
1018                        &hash, admission,
1019                    )?;
1020                    let hits = store.by_file(&file);
1021                    let mut out = format!("Episodes for file match '{file}' ({}):", hits.len());
1022                    for episode in hits.into_iter().take(10) {
1023                        let task: String = episode.task_description.chars().take(50).collect();
1024                        out.push_str(&format!(
1025                            "\n  {} | {} | {} | {}",
1026                            episode.id,
1027                            episode.timestamp,
1028                            episode.outcome.label(),
1029                            task
1030                        ));
1031                    }
1032                    Ok(out)
1033                })?;
1034            crate::core::session::admission::admit_tool_value(session, &output)
1035        }
1036        Some(v) if v.starts_with("outcome ") => {
1037            let label = v.trim_start_matches("outcome ").trim();
1038            if !matches!(label, "success" | "failure" | "partial" | "unknown") {
1039                return Err("unsupported episode outcome".into());
1040            }
1041            let output =
1042                crate::core::session::admission::with_store_admission(session, |admission| {
1043                    let store = crate::core::episodic_memory::EpisodicStore::load_admitted(
1044                        &hash, admission,
1045                    )?;
1046                    let hits = store.by_outcome(label);
1047                    let mut out = format!("Episodes outcome '{label}' ({}):", hits.len());
1048                    for episode in hits.into_iter().take(10) {
1049                        let task: String = episode.task_description.chars().take(50).collect();
1050                        out.push_str(&format!(
1051                            "\n  {} | {} | {}",
1052                            episode.id, episode.timestamp, task
1053                        ));
1054                    }
1055                    Ok(out)
1056                })?;
1057            crate::core::session::admission::admit_tool_value(session, &output)
1058        }
1059        _ => {
1060            let output = crate::core::session::admission::with_store_admission(
1061                session,
1062                |admission| {
1063                    let store = crate::core::episodic_memory::EpisodicStore::load_admitted(
1064                        &hash, admission,
1065                    )?;
1066                    let stats = store.stats();
1067                    let recent = store.recent(10);
1068                    let mut out = format!(
1069                        "Episodic memory: {} episodes, success_rate={:.0}%, tokens_total={}\n\nRecent:",
1070                        stats.total_episodes,
1071                        stats.success_rate * 100.0,
1072                        stats.total_tokens
1073                    );
1074                    for episode in recent {
1075                        let task: String = episode.task_description.chars().take(60).collect();
1076                        out.push_str(&format!(
1077                            "\n  {} | {} | {} | {}",
1078                            episode.id,
1079                            episode.timestamp,
1080                            episode.outcome.label(),
1081                            task
1082                        ));
1083                    }
1084                    out.push_str("\n\nActions: ctx_session action=episodes value=record|\"search <q>\"|\"file <path>\"|\"outcome success|failure|partial|unknown\"");
1085                    Ok(out)
1086                },
1087            )?;
1088            crate::core::session::admission::admit_tool_value(session, &output)
1089        }
1090    }
1091}
1092
1093fn trusted_memory_scope(session: &SessionState) -> Result<(String, String), String> {
1094    let root = session
1095        .strict_project_root()
1096        .ok_or_else(|| "session project scope unavailable".to_string())?;
1097    let hash = crate::core::project_hash::hash_project_root(&root);
1098    Ok((root, hash))
1099}
1100
1101fn auto_detect_admitted_procedures(
1102    session: &SessionState,
1103    project_hash: &str,
1104    policy: &crate::core::memory_policy::ProceduralPolicy,
1105) -> Result<usize, String> {
1106    crate::core::session::admission::with_store_admission(session, |admission| {
1107        let episodes =
1108            crate::core::episodic_memory::EpisodicStore::load_admitted(project_hash, admission)?;
1109        if episodes.episodes.is_empty() {
1110            return Ok(0);
1111        }
1112        let (procedures, before) =
1113            crate::core::procedural_memory::ProceduralStore::mutate_locked_admitted_with_authority(
1114                project_hash,
1115                admission,
1116                |procedures, authority| {
1117                    let before = procedures.procedures.len();
1118                    procedures.detect_patterns_admitted(
1119                        &episodes.episodes,
1120                        policy,
1121                        admission,
1122                        authority,
1123                    )?;
1124                    Ok(before)
1125                },
1126            )?;
1127        let learned = procedures.procedures.len().saturating_sub(before);
1128        if learned > 0 {
1129            crate::core::events::emit(crate::core::events::EventKind::KnowledgeUpdate {
1130                category: "procedural".to_string(),
1131                key: format!("{learned} new"),
1132                action: "auto_learn".to_string(),
1133            });
1134        }
1135        Ok(learned)
1136    })
1137}
1138
1139fn handle_procedures(session: &mut SessionState, value: Option<&str>) -> String {
1140    handle_procedures_scoped(session, value).unwrap_or_else(|_| {
1141        "ERROR: procedural operation withheld by project scope or content policy.".into()
1142    })
1143}
1144
1145fn handle_procedures_scoped(session: &SessionState, value: Option<&str>) -> Result<String, String> {
1146    let (_, hash) = trusted_memory_scope(session)?;
1147    let policy = crate::core::config::Config::load()
1148        .memory_policy_effective()
1149        .map_err(|error| format!("invalid memory policy: {error}"))?;
1150
1151    if value == Some("detect") {
1152        let (procedure_count, episode_count) =
1153            crate::core::session::admission::with_store_admission(session, |admission| {
1154                let episodes =
1155                    crate::core::episodic_memory::EpisodicStore::load_admitted(&hash, admission)?;
1156                let (procedures, ()) =
1157                    crate::core::procedural_memory::ProceduralStore::mutate_locked_admitted_with_authority(
1158                        &hash,
1159                        admission,
1160                        |procedures, authority| {
1161                            procedures.detect_patterns_admitted(
1162                                &episodes.episodes,
1163                                &policy.procedural,
1164                                admission,
1165                                authority,
1166                            )
1167                        },
1168                    )?;
1169                Ok((procedures.procedures.len(), episodes.episodes.len()))
1170            })?;
1171        crate::core::events::emit(crate::core::events::EventKind::KnowledgeUpdate {
1172            category: "procedural".to_string(),
1173            key: hash,
1174            action: "detect".to_string(),
1175        });
1176        let output = format!(
1177            "Procedures updated. Total procedures: {procedure_count} (episodes: {episode_count})."
1178        );
1179        return crate::core::session::admission::admit_tool_value(session, &output);
1180    }
1181
1182    if let Some(value) = value.filter(|value| value.starts_with("suggest ")) {
1183        let task = value.trim_start_matches("suggest ").trim();
1184        let task = crate::core::session::admission::admit_storable_session_text(session, task)?;
1185        let output = crate::core::session::admission::with_store_admission(session, |admission| {
1186            let procedures =
1187                crate::core::procedural_memory::ProceduralStore::load_admitted(&hash, admission)?;
1188            let hits = procedures.suggest(&task);
1189            if hits.is_empty() {
1190                return Ok("No procedures matched.".to_string());
1191            }
1192            let mut out = format!("Procedures suggested ({}):", hits.len());
1193            for procedure in hits.into_iter().take(10) {
1194                out.push_str(&format!(
1195                    "\n  {} | conf={:.0}% | success={:.0}% | steps={}",
1196                    procedure.name,
1197                    procedure.confidence * 100.0,
1198                    procedure.success_rate() * 100.0,
1199                    procedure.steps.len()
1200                ));
1201            }
1202            Ok(out)
1203        })?;
1204        return crate::core::session::admission::admit_tool_value(session, &output);
1205    }
1206
1207    let output = crate::core::session::admission::with_store_admission(session, |admission| {
1208        let projected = crate::core::session::admission::for_storage(session)?;
1209        let episodes =
1210            crate::core::episodic_memory::EpisodicStore::load_admitted(&hash, admission)?;
1211        let procedures =
1212            crate::core::procedural_memory::ProceduralStore::load_admitted(&hash, admission)?;
1213        let task = projected
1214            .task
1215            .as_ref()
1216            .map(|task| task.description.clone())
1217            .unwrap_or_default();
1218        let suggestions = if task.is_empty() {
1219            Vec::new()
1220        } else {
1221            procedures.suggest(&task)
1222        };
1223        let mut out = format!(
1224            "Procedural memory: {} procedures (episodes: {})",
1225            procedures.procedures.len(),
1226            episodes.episodes.len()
1227        );
1228        if !task.is_empty() {
1229            out.push_str(&format!(
1230                "\nTask: {}",
1231                task.chars().take(80).collect::<String>()
1232            ));
1233            if !suggestions.is_empty() {
1234                out.push_str("\n\nSuggested:");
1235                for procedure in suggestions.into_iter().take(5) {
1236                    out.push_str(&format!(
1237                        "\n  {} | conf={:.0}% | success={:.0}% | steps={}",
1238                        procedure.name,
1239                        procedure.confidence * 100.0,
1240                        procedure.success_rate() * 100.0,
1241                        procedure.steps.len()
1242                    ));
1243                }
1244            }
1245        }
1246        out.push_str("\n\nActions: ctx_session action=procedures value=detect|\"suggest <task>\"");
1247        Ok(out)
1248    })?;
1249    crate::core::session::admission::admit_tool_value(session, &output)
1250}
1251
1252fn handle_unknown(action: &str) -> String {
1253    format!(
1254        "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, episodes, procedures"
1255    )
1256}
1257
1258/// Records an episode only after a completed task has been committed.
1259fn auto_record_episode(
1260    session: &SessionState,
1261    tool_calls: &[(String, u64)],
1262    agent_id: Option<&str>,
1263) -> Result<Option<String>, String> {
1264    let (_, hash) = trusted_memory_scope(session)?;
1265    let policy = crate::core::config::Config::load()
1266        .memory_policy_effective()
1267        .map_err(|error| format!("invalid memory policy: {error}"))?;
1268    let Some(id) = crate::core::episodic_memory::record_session_episode(
1269        &hash,
1270        session,
1271        tool_calls,
1272        agent_id,
1273        &policy.episodic,
1274        true,
1275    )?
1276    else {
1277        return Ok(None);
1278    };
1279    crate::core::events::emit(crate::core::events::EventKind::KnowledgeUpdate {
1280        category: "episodic".to_string(),
1281        key: id.clone(),
1282        action: "auto_record".to_string(),
1283    });
1284    let _ = auto_detect_admitted_procedures(session, &hash, &policy.procedural);
1285    Ok(Some(id))
1286}
1287
1288fn parse_finding_value(value: &str) -> (Option<String>, Option<u32>, &str) {
1289    const EM_DASH_SEP: &str = " \u{2014} ";
1290    const ASCII_SEP: &str = " - ";
1291
1292    let (dash_pos, sep) = if let Some(p) = value.find(EM_DASH_SEP) {
1293        (Some(p), EM_DASH_SEP)
1294    } else {
1295        (value.find(ASCII_SEP), ASCII_SEP)
1296    };
1297
1298    if let Some(pos) = dash_pos {
1299        let location = &value[..pos];
1300        let text = &value[pos + sep.len()..];
1301
1302        if let Some(colon_pos) = location.rfind(':') {
1303            let file = &location[..colon_pos];
1304            if let Ok(line) = location[colon_pos + 1..].parse::<u32>() {
1305                return (Some(file.to_string()), Some(line), text);
1306            }
1307        }
1308        return (Some(location.to_string()), None, text);
1309    }
1310    (None, None, value)
1311}
1312
1313#[cfg(test)]
1314mod tests;