Skip to main content

lean_ctx/tools/registered/
ctx_knowledge.rs

1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{
6    McpTool, ToolContext, ToolOutput, get_f64, get_str, get_str_array,
7};
8use crate::tool_defs::tool_def;
9
10pub struct CtxKnowledgeTool;
11
12impl McpTool for CtxKnowledgeTool {
13    fn name(&self) -> &'static str {
14        "ctx_knowledge"
15    }
16
17    fn tool_def(&self) -> Tool {
18        tool_def(
19            "ctx_knowledge",
20            "Persistent memory across sessions — remember decisions, patterns, and facts for recall.\n\
21             WORKFLOW: save after completing significant tasks; recall at session start.\n\
22             action=remember key='X' value='Y' saves a fact (both required).\n\
23             action=recall query='X' retrieves it. action=status shows all categories.\n\
24action=consolidate imports latest session if present, runs lifecycle, then frees 25% facts/history/procedures capacity.\n\
25             action=gotcha trigger='X' resolution='Y' for known pitfalls.\n\
26             mode=semantic|exact for recall. category groups related facts.",
27            json!({
28                "type": "object",
29                "properties": {
30                    "action": {
31                        "type": "string",
32                        "description": "remember|recall|search|pattern|gotcha|relate|relations|consolidate|restore|status|timeline|rooms|wakeup|remove|export (also: feedback, unrelate, relations_diagram, health, lifecycle_report, policy, embeddings_*)"
33                    },
34                    "trigger": { "type": "string", "description": "gotcha trigger pattern" },
35                    "resolution": { "type": "string", "description": "gotcha resolution/fix" },
36                    "severity": { "type": "string", "description": "gotcha: critical|warning|info" },
37                    "category": { "type": "string", "description": "Fact category" },
38                    "key": { "type": "string" },
39                    "value": { "type": "string" },
40                    "query": { "type": "string", "description": "Query for recall/search/relate/restore" },
41                    "mode": { "type": "string", "description": "auto|exact|semantic|hybrid" },
42                    "as_of": { "type": "string", "description": "YYYY-MM-DD date filter" },
43                    "pattern_type": { "type": "string" },
44                    "examples": { "type": "array", "items": { "type": "string" } },
45                    "confidence": { "type": "number", "description": "0.0-1.0" },
46                    "store": { "type": "string", "description": "restore: facts|history|procedures|patterns (default: all)" },
47                    "limit": { "type": "number", "description": "restore: max items to recover (default 50)" },
48                    "dry_run": { "type": "boolean", "description": "consolidate: preview imports/reclaim without writing" }
49                },
50                "required": ["action"]
51            }),
52        )
53    }
54
55    fn handle(
56        &self,
57        args: &Map<String, Value>,
58        ctx: &ToolContext,
59    ) -> Result<ToolOutput, ErrorData> {
60        let action = get_str(args, "action")
61            .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
62        let category = get_str(args, "category");
63        let key = get_str(args, "key");
64        let value = get_str(args, "value");
65        let query = get_str(args, "query");
66        let mode = get_str(args, "mode");
67        let as_of = get_str(args, "as_of");
68        let pattern_type = get_str(args, "pattern_type");
69        let examples = get_str_array(args, "examples");
70        let confidence = get_f64(args, "confidence").map(|v| v as f32);
71
72        let session_handle = ctx
73            .session
74            .as_ref()
75            .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
76        let (session_id, project_root) = {
77            let timeout_dur =
78                crate::core::io_health::adaptive_timeout(std::time::Duration::from_secs(10));
79            let read_result = tokio::task::block_in_place(|| {
80                tokio::runtime::Handle::current()
81                    .block_on(tokio::time::timeout(timeout_dur, session_handle.read()))
82            });
83            if let Ok(session) = read_result {
84                let sid = session.id.clone();
85                let root = session
86                    .project_root
87                    .clone()
88                    .unwrap_or_else(|| ctx.project_root.clone());
89                (sid, root)
90            } else {
91                tracing::warn!("ctx_knowledge: session read-lock timeout, using fallback");
92                ("unknown".to_string(), ctx.project_root.clone())
93            }
94        };
95
96        if action == "gotcha" {
97            let trigger = get_str(args, "trigger").unwrap_or_default();
98            let resolution = get_str(args, "resolution").unwrap_or_default();
99            let severity = get_str(args, "severity").unwrap_or_default();
100            let cat = category.as_deref().unwrap_or("convention");
101
102            if trigger.is_empty() || resolution.is_empty() {
103                return Ok(text_output(
104                    &action,
105                    "ERROR: trigger and resolution are required for gotcha action".to_string(),
106                ));
107            }
108
109            let mut store = crate::core::gotcha_tracker::GotchaStore::load(&project_root);
110            let msg = match store.report_gotcha(&trigger, &resolution, cat, &severity, &session_id)
111            {
112                Some(gotcha) => {
113                    let conf = (gotcha.confidence * 100.0) as u32;
114                    let label = gotcha.category.short_label();
115                    format!("Gotcha recorded: [{label}] {trigger} (confidence: {conf}%)")
116                }
117                None => {
118                    format!("Gotcha noted: {trigger} (evicted by higher-confidence entries)")
119                }
120            };
121            let _ = store.save(&project_root);
122            return Ok(text_output(&action, msg));
123        }
124
125        // Restore (#995 Phase 6): explicit cross-store undo from archive. Handled
126        // inline (like `gotcha`) so `store`/`limit` can be passed without widening
127        // the shared `handle()` signature.
128        if action == "restore" {
129            let store = match get_str(args, "store").as_deref() {
130                Some(s) => match crate::core::memory_archive::MemoryStore::parse(s) {
131                    Some(ms) => Some(ms),
132                    None => {
133                        return Ok(text_output(
134                            &action,
135                            format!(
136                                "Unknown store: {s}. Use: facts, history, procedures, patterns"
137                            ),
138                        ));
139                    }
140                },
141                None => None,
142            };
143            let limit = get_f64(args, "limit")
144                .map_or(crate::tools::ctx_knowledge::DEFAULT_RESTORE_LIMIT, |v| {
145                    v as usize
146                });
147            let opts =
148                crate::tools::ctx_knowledge::RestoreOptions::new(store, query.clone(), limit);
149            let text = match crate::tools::ctx_knowledge::run_restore(&project_root, &opts) {
150                Ok(report) => crate::tools::ctx_knowledge::format_restore_report(&report),
151                Err(e) => e,
152            };
153            return Ok(text_output(&action, text));
154        }
155
156        // Dry-run consolidate: preview imports + reclaim with no writes.
157        let dry_run = args
158            .get("dry_run")
159            .and_then(Value::as_bool)
160            .unwrap_or(false);
161        if action == "consolidate" && dry_run {
162            let text = match crate::tools::ctx_knowledge::consolidate_project_knowledge_with(
163                &project_root,
164                &crate::core::consolidation_engine::ConsolidateOptions::manual().into_dry_run(),
165            ) {
166                Ok(report) => crate::tools::ctx_knowledge::format_consolidation_report(&report),
167                Err(e) => e,
168            };
169            return Ok(text_output(&action, text));
170        }
171
172        let result = crate::tools::ctx_knowledge::handle(
173            &project_root,
174            &action,
175            category.as_deref(),
176            key.as_deref(),
177            value.as_deref(),
178            query.as_deref(),
179            &session_id,
180            pattern_type.as_deref(),
181            examples,
182            confidence,
183            mode.as_deref(),
184            as_of.as_deref(),
185        );
186
187        Ok(text_output(&action, result))
188    }
189}
190
191/// A plain text `ToolOutput` tagged with the action as its mode. `ctx_knowledge`
192/// results are already compressed prose, so token accounting is left at zero.
193fn text_output(action: &str, text: String) -> ToolOutput {
194    ToolOutput {
195        text,
196        original_tokens: 0,
197        saved_tokens: 0,
198        mode: Some(action.to_string()),
199        path: None,
200        changed: false,
201        shell_outcome: None,
202    }
203}