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 value='Y' saves a fact (key optional — derived from value; content= is an accepted alias).\n\
23             action=recall query='X' retrieves it (bare recall lists recent facts). 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|import (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                    "content": { "type": "string", "description": "Alias for value (remember)" },
41                    "query": { "type": "string", "description": "Query for recall/search/relate/restore" },
42                    "mode": { "type": "string", "description": "auto|exact|semantic|hybrid" },
43                    "as_of": { "type": "string", "description": "YYYY-MM-DD date filter" },
44                    "pattern_type": { "type": "string" },
45                    "examples": { "type": "array", "items": { "type": "string" } },
46                    "confidence": { "type": "number", "description": "0.0-1.0" },
47                    "store": { "type": "string", "description": "restore: facts|history|procedures|patterns (default: all)" },
48                    "limit": { "type": "number", "description": "restore: max items to recover (default 50)" },
49                    "dry_run": { "type": "boolean", "description": "consolidate: preview imports/reclaim without writing" },
50                    "format": { "type": "string", "description": "export: json|okf (okf = portable Markdown bundle)" },
51                    "path": { "type": "string", "description": "export/import: bundle directory (OKF) or file path" },
52                    "merge": { "type": "string", "description": "import: replace|append|skip-existing (default skip-existing)" }
53                },
54                "allOf": [
55                    {
56                        "if": { "properties": { "action": { "const": "remember" } }, "required": ["action"] },
57                        "then": { "required": ["category"], "anyOf": [{ "required": ["value"] }, { "required": ["content"] }] }
58                    },
59                    {
60                        "if": { "properties": { "action": { "const": "pattern" } }, "required": ["action"] },
61                        "then": { "required": ["value"] }
62                    },
63                    {
64                        "if": { "properties": { "action": { "const": "search" } }, "required": ["action"] },
65                        "then": { "required": ["query"] }
66                    },
67                    {
68                        "if": { "properties": { "action": { "const": "gotcha" } }, "required": ["action"] },
69                        "then": { "required": ["trigger", "resolution"] }
70                    }
71                ],
72                "required": ["action"]
73            }),
74        )
75    }
76
77    fn handle(
78        &self,
79        args: &Map<String, Value>,
80        ctx: &ToolContext,
81    ) -> Result<ToolOutput, ErrorData> {
82        let action = get_str(args, "action")
83            .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
84        let category = get_str(args, "category");
85        let key = get_str(args, "key");
86        // `content` is the wording our own workflow docs use for remember;
87        // accept it as an alias so agents following those docs succeed (#658).
88        let value = get_str(args, "value").or_else(|| get_str(args, "content"));
89        let query = get_str(args, "query");
90        let mode = get_str(args, "mode");
91        let as_of = get_str(args, "as_of");
92        let pattern_type = get_str(args, "pattern_type");
93        let examples = get_str_array(args, "examples");
94        let confidence = get_f64(args, "confidence").map(|v| v as f32);
95
96        let session_handle = ctx
97            .session
98            .as_ref()
99            .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
100        let (session_id, project_root) = {
101            let read_result =
102                crate::server::bounded_lock::read(session_handle, "ctx_knowledge session read");
103            if let Some(session) = read_result {
104                let sid = session.id.clone();
105                let root = session
106                    .project_root
107                    .clone()
108                    .unwrap_or_else(|| ctx.project_root.clone());
109                (sid, root)
110            } else {
111                tracing::warn!("ctx_knowledge: session read-lock timeout, using fallback");
112                ("unknown".to_string(), ctx.project_root.clone())
113            }
114        };
115
116        if action == "gotcha" {
117            let trigger = get_str(args, "trigger").unwrap_or_default();
118            let resolution = get_str(args, "resolution").unwrap_or_default();
119            let severity = get_str(args, "severity").unwrap_or_default();
120            let cat = category.as_deref().unwrap_or("convention");
121
122            if trigger.is_empty() || resolution.is_empty() {
123                return Ok(text_output(
124                    &action,
125                    "ERROR: trigger and resolution are required for gotcha action".to_string(),
126                ));
127            }
128
129            let mut store = crate::core::gotcha_tracker::GotchaStore::load(&project_root);
130            let msg = match store.report_gotcha(&trigger, &resolution, cat, &severity, &session_id)
131            {
132                Some(gotcha) => {
133                    let conf = (gotcha.confidence * 100.0) as u32;
134                    let label = gotcha.category.short_label();
135                    format!("Gotcha recorded: [{label}] {trigger} (confidence: {conf}%)")
136                }
137                None => {
138                    format!("Gotcha noted: {trigger} (evicted by higher-confidence entries)")
139                }
140            };
141            let _ = store.save(&project_root);
142            return Ok(text_output(&action, msg));
143        }
144
145        // Restore (#995 Phase 6): explicit cross-store undo from archive. Handled
146        // inline (like `gotcha`) so `store`/`limit` can be passed without widening
147        // the shared `handle()` signature.
148        if action == "restore" {
149            let store = match get_str(args, "store").as_deref() {
150                Some(s) => match crate::core::memory_archive::MemoryStore::parse(s) {
151                    Some(ms) => Some(ms),
152                    None => {
153                        return Ok(text_output(
154                            &action,
155                            format!(
156                                "Unknown store: {s}. Use: facts, history, procedures, patterns"
157                            ),
158                        ));
159                    }
160                },
161                None => None,
162            };
163            let limit = get_f64(args, "limit")
164                .map_or(crate::tools::ctx_knowledge::DEFAULT_RESTORE_LIMIT, |v| {
165                    v as usize
166                });
167            let opts =
168                crate::tools::ctx_knowledge::RestoreOptions::new(store, query.clone(), limit);
169            let text = match crate::tools::ctx_knowledge::run_restore(&project_root, &opts) {
170                Ok(report) => crate::tools::ctx_knowledge::format_restore_report(&report),
171                Err(e) => e,
172            };
173            return Ok(text_output(&action, text));
174        }
175
176        // Dry-run consolidate: preview imports + reclaim with no writes.
177        let dry_run = args
178            .get("dry_run")
179            .and_then(Value::as_bool)
180            .unwrap_or(false);
181        if action == "consolidate" && dry_run {
182            let text = match crate::tools::ctx_knowledge::consolidate_project_knowledge_with(
183                &project_root,
184                &crate::core::consolidation_engine::ConsolidateOptions::manual().into_dry_run(),
185            ) {
186                Ok(report) => crate::tools::ctx_knowledge::format_consolidation_report(&report),
187                Err(e) => e,
188            };
189            return Ok(text_output(&action, text));
190        }
191
192        // OKF export/import handled inline so `format`/`path`/`merge` stay off the
193        // shared handle() signature (same pattern as restore/gotcha above).
194        if action == "export" && get_str(args, "format").as_deref() == Some("okf") {
195            let out = get_str(args, "path").or_else(|| get_str(args, "output"));
196            return Ok(text_output(
197                &action,
198                crate::tools::ctx_knowledge::handle_export_okf(&project_root, out.as_deref()),
199            ));
200        }
201        if action == "import" {
202            let Some(path) = get_str(args, "path").or_else(|| query.clone()) else {
203                return Ok(text_output(
204                    &action,
205                    "ERROR: import requires `path` (a file or an OKF directory)".to_string(),
206                ));
207            };
208            let merge = get_str(args, "merge")
209                .and_then(|s| crate::core::knowledge::ImportMerge::parse(&s))
210                .unwrap_or(crate::core::knowledge::ImportMerge::SkipExisting);
211            return Ok(text_output(
212                &action,
213                crate::tools::ctx_knowledge::handle_import(
214                    &project_root,
215                    &path,
216                    merge,
217                    &session_id,
218                ),
219            ));
220        }
221
222        let result = crate::tools::ctx_knowledge::handle(
223            &project_root,
224            &action,
225            category.as_deref(),
226            key.as_deref(),
227            value.as_deref(),
228            query.as_deref(),
229            &session_id,
230            pattern_type.as_deref(),
231            examples,
232            confidence,
233            mode.as_deref(),
234            as_of.as_deref(),
235        );
236
237        Ok(text_output(&action, result))
238    }
239}
240
241/// A plain text `ToolOutput` tagged with the action as its mode. `ctx_knowledge`
242/// results are already compressed prose, so token accounting is left at zero.
243fn text_output(action: &str, text: String) -> ToolOutput {
244    ToolOutput {
245        text,
246        original_tokens: 0,
247        saved_tokens: 0,
248        mode: Some(action.to_string()),
249        path: None,
250        changed: false,
251        shell_outcome: None,
252        content_blocks: None,
253    }
254}