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 timeout_dur =
102                crate::core::io_health::adaptive_timeout(std::time::Duration::from_secs(10));
103            let read_result = tokio::task::block_in_place(|| {
104                tokio::runtime::Handle::current()
105                    .block_on(tokio::time::timeout(timeout_dur, session_handle.read()))
106            });
107            if let Ok(session) = read_result {
108                let sid = session.id.clone();
109                let root = session
110                    .project_root
111                    .clone()
112                    .unwrap_or_else(|| ctx.project_root.clone());
113                (sid, root)
114            } else {
115                tracing::warn!("ctx_knowledge: session read-lock timeout, using fallback");
116                ("unknown".to_string(), ctx.project_root.clone())
117            }
118        };
119
120        if action == "gotcha" {
121            let trigger = get_str(args, "trigger").unwrap_or_default();
122            let resolution = get_str(args, "resolution").unwrap_or_default();
123            let severity = get_str(args, "severity").unwrap_or_default();
124            let cat = category.as_deref().unwrap_or("convention");
125
126            if trigger.is_empty() || resolution.is_empty() {
127                return Ok(text_output(
128                    &action,
129                    "ERROR: trigger and resolution are required for gotcha action".to_string(),
130                ));
131            }
132
133            let mut store = crate::core::gotcha_tracker::GotchaStore::load(&project_root);
134            let msg = match store.report_gotcha(&trigger, &resolution, cat, &severity, &session_id)
135            {
136                Some(gotcha) => {
137                    let conf = (gotcha.confidence * 100.0) as u32;
138                    let label = gotcha.category.short_label();
139                    format!("Gotcha recorded: [{label}] {trigger} (confidence: {conf}%)")
140                }
141                None => {
142                    format!("Gotcha noted: {trigger} (evicted by higher-confidence entries)")
143                }
144            };
145            let _ = store.save(&project_root);
146            return Ok(text_output(&action, msg));
147        }
148
149        // Restore (#995 Phase 6): explicit cross-store undo from archive. Handled
150        // inline (like `gotcha`) so `store`/`limit` can be passed without widening
151        // the shared `handle()` signature.
152        if action == "restore" {
153            let store = match get_str(args, "store").as_deref() {
154                Some(s) => match crate::core::memory_archive::MemoryStore::parse(s) {
155                    Some(ms) => Some(ms),
156                    None => {
157                        return Ok(text_output(
158                            &action,
159                            format!(
160                                "Unknown store: {s}. Use: facts, history, procedures, patterns"
161                            ),
162                        ));
163                    }
164                },
165                None => None,
166            };
167            let limit = get_f64(args, "limit")
168                .map_or(crate::tools::ctx_knowledge::DEFAULT_RESTORE_LIMIT, |v| {
169                    v as usize
170                });
171            let opts =
172                crate::tools::ctx_knowledge::RestoreOptions::new(store, query.clone(), limit);
173            let text = match crate::tools::ctx_knowledge::run_restore(&project_root, &opts) {
174                Ok(report) => crate::tools::ctx_knowledge::format_restore_report(&report),
175                Err(e) => e,
176            };
177            return Ok(text_output(&action, text));
178        }
179
180        // Dry-run consolidate: preview imports + reclaim with no writes.
181        let dry_run = args
182            .get("dry_run")
183            .and_then(Value::as_bool)
184            .unwrap_or(false);
185        if action == "consolidate" && dry_run {
186            let text = match crate::tools::ctx_knowledge::consolidate_project_knowledge_with(
187                &project_root,
188                &crate::core::consolidation_engine::ConsolidateOptions::manual().into_dry_run(),
189            ) {
190                Ok(report) => crate::tools::ctx_knowledge::format_consolidation_report(&report),
191                Err(e) => e,
192            };
193            return Ok(text_output(&action, text));
194        }
195
196        // OKF export/import handled inline so `format`/`path`/`merge` stay off the
197        // shared handle() signature (same pattern as restore/gotcha above).
198        if action == "export" && get_str(args, "format").as_deref() == Some("okf") {
199            let out = get_str(args, "path").or_else(|| get_str(args, "output"));
200            return Ok(text_output(
201                &action,
202                crate::tools::ctx_knowledge::handle_export_okf(&project_root, out.as_deref()),
203            ));
204        }
205        if action == "import" {
206            let Some(path) = get_str(args, "path").or_else(|| query.clone()) else {
207                return Ok(text_output(
208                    &action,
209                    "ERROR: import requires `path` (a file or an OKF directory)".to_string(),
210                ));
211            };
212            let merge = get_str(args, "merge")
213                .and_then(|s| crate::core::knowledge::ImportMerge::parse(&s))
214                .unwrap_or(crate::core::knowledge::ImportMerge::SkipExisting);
215            return Ok(text_output(
216                &action,
217                crate::tools::ctx_knowledge::handle_import(
218                    &project_root,
219                    &path,
220                    merge,
221                    &session_id,
222                ),
223            ));
224        }
225
226        let result = crate::tools::ctx_knowledge::handle(
227            &project_root,
228            &action,
229            category.as_deref(),
230            key.as_deref(),
231            value.as_deref(),
232            query.as_deref(),
233            &session_id,
234            pattern_type.as_deref(),
235            examples,
236            confidence,
237            mode.as_deref(),
238            as_of.as_deref(),
239        );
240
241        Ok(text_output(&action, result))
242    }
243}
244
245/// A plain text `ToolOutput` tagged with the action as its mode. `ctx_knowledge`
246/// results are already compressed prose, so token accounting is left at zero.
247fn text_output(action: &str, text: String) -> ToolOutput {
248    ToolOutput {
249        text,
250        original_tokens: 0,
251        saved_tokens: 0,
252        mode: Some(action.to_string()),
253        path: None,
254        changed: false,
255        shell_outcome: None,
256        content_blocks: None,
257    }
258}