Skip to main content

zeph_core/
memory_tools.rs

1// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4use std::fmt::Write as _;
5use std::sync::Arc;
6
7use zeph_memory::embedding_store::SearchFilter;
8use zeph_memory::semantic::SemanticMemory;
9use zeph_memory::types::ConversationId;
10use zeph_tools::executor::{ToolCall, ToolError, ToolExecutor, ToolOutput, deserialize_params};
11use zeph_tools::registry::{InvocationHint, ToolDef};
12
13use zeph_sanitizer::memory_validation::MemoryWriteValidator;
14
15#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
16struct MemorySearchParams {
17    /// Natural language query to search memory for relevant past messages and facts.
18    query: String,
19    /// Maximum number of results to return (default: 5, max: 20).
20    #[serde(default = "default_limit")]
21    limit: u32,
22}
23
24fn default_limit() -> u32 {
25    5
26}
27
28#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
29struct MemorySaveParams {
30    /// The content to save to long-term memory. Should be a concise, self-contained fact or note.
31    content: String,
32    /// Role label for the saved message (default: "assistant").
33    #[serde(default = "default_role")]
34    role: String,
35}
36
37fn default_role() -> String {
38    "assistant".into()
39}
40
41/// Executes `memory_search` and `memory_save` tool calls on behalf of the agent.
42pub struct MemoryToolExecutor {
43    memory: Arc<SemanticMemory>,
44    conversation_id: ConversationId,
45    validator: MemoryWriteValidator,
46    /// When `true` the backing store is in-memory (bare mode) and saves do not persist across sessions.
47    ephemeral: bool,
48}
49
50impl MemoryToolExecutor {
51    /// Create with default validator and persistent (non-ephemeral) semantics.
52    #[must_use]
53    pub fn new(memory: Arc<SemanticMemory>, conversation_id: ConversationId) -> Self {
54        Self {
55            memory,
56            conversation_id,
57            validator: MemoryWriteValidator::new(
58                zeph_sanitizer::memory_validation::MemoryWriteValidationConfig::default(),
59            ),
60            ephemeral: false,
61        }
62    }
63
64    /// Create with a custom validator (used when security config is loaded).
65    #[must_use]
66    pub fn with_validator(
67        memory: Arc<SemanticMemory>,
68        conversation_id: ConversationId,
69        validator: MemoryWriteValidator,
70    ) -> Self {
71        Self {
72            memory,
73            conversation_id,
74            validator,
75            ephemeral: false,
76        }
77    }
78
79    /// Mark this executor as ephemeral (bare mode).
80    ///
81    /// When set, `memory_save` reports that the content is session-only and will not be
82    /// available after the session ends.
83    #[must_use]
84    pub fn ephemeral(mut self) -> Self {
85        self.ephemeral = true;
86        self
87    }
88}
89
90impl ToolExecutor for MemoryToolExecutor {
91    fn tool_definitions(&self) -> Vec<ToolDef> {
92        vec![
93            ToolDef {
94                id: "memory_search".into(),
95                description: "Search long-term memory for relevant past messages, facts, and session summaries. Use to recall facts, preferences, or information the user provided during this or previous conversations.\n\nParameters: query (string, required) - natural language search query; limit (integer, optional) - max results 1-20 (default: 5)\nReturns: ranked list of memory entries with similarity scores and timestamps\nErrors: Execution on database failure\nExample: {\"query\": \"user preference for output format\", \"limit\": 5}".into(),
96                schema: schemars::schema_for!(MemorySearchParams),
97                invocation: InvocationHint::ToolCall,
98                output_schema: None,
99                server_id: None,
100            },
101            ToolDef {
102                id: "memory_save".into(),
103                description: "Save a fact or note to long-term memory for cross-session recall. Use sparingly for key decisions, user preferences, or critical context worth remembering across sessions.\n\nParameters: content (string, required) - concise, self-contained fact or note; role (string, optional) - message role label (default: \"assistant\")\nReturns: confirmation with saved entry ID\nErrors: Execution on database failure; InvalidParams if content is empty\nExample: {\"content\": \"User prefers JSON output over YAML\", \"role\": \"assistant\"}".into(),
104                schema: schemars::schema_for!(MemorySaveParams),
105                invocation: InvocationHint::ToolCall,
106                output_schema: None,
107                server_id: None,
108            },
109        ]
110    }
111
112    async fn execute(&self, _response: &str) -> Result<Option<ToolOutput>, ToolError> {
113        Ok(None)
114    }
115
116    #[allow(clippy::too_many_lines)] // two tools with validation, search, and multi-source aggregation
117    async fn execute_tool_call(&self, call: &ToolCall) -> Result<Option<ToolOutput>, ToolError> {
118        match call.tool_id.as_str() {
119            "memory_search" => {
120                let params: MemorySearchParams = deserialize_params(&call.params)?;
121                let limit = params.limit.clamp(1, 20) as usize;
122
123                let filter = Some(SearchFilter {
124                    conversation_id: Some(self.conversation_id),
125                    role: None,
126                    category: None,
127                });
128
129                let recalled = self
130                    .memory
131                    .recall(&params.query, limit, filter)
132                    .await
133                    .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())))?;
134
135                let key_facts = self
136                    .memory
137                    .search_key_facts(&params.query, limit, Some(self.conversation_id))
138                    .await
139                    .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())))?;
140
141                let summaries = self
142                    .memory
143                    .search_session_summaries(&params.query, limit, Some(self.conversation_id))
144                    .await
145                    .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())))?;
146
147                let mut output = String::new();
148
149                let _ = writeln!(output, "## Recalled Messages ({} results)", recalled.len());
150                for r in &recalled {
151                    let role = match r.message.role {
152                        zeph_llm::provider::Role::Assistant => "assistant",
153                        zeph_llm::provider::Role::System => "system",
154                        zeph_llm::provider::Role::User | _ => "user",
155                    };
156                    let content = r.message.content.trim();
157                    let _ = writeln!(output, "[score: {:.2}] {role}: {content}", r.score);
158                }
159
160                let _ = writeln!(output);
161                let _ = writeln!(output, "## Key Facts ({} results)", key_facts.len());
162                for fact in &key_facts {
163                    let _ = writeln!(output, "- {fact}");
164                }
165
166                let _ = writeln!(output);
167                let _ = writeln!(output, "## Session Summaries ({} results)", summaries.len());
168                for s in &summaries {
169                    let _ = writeln!(
170                        output,
171                        "[conv #{}, score: {:.2}] {}",
172                        s.conversation_id, s.score, s.summary_text
173                    );
174                }
175
176                Ok(Some(ToolOutput {
177                    tool_name: zeph_common::ToolName::new("memory_search"),
178                    summary: output,
179                    blocks_executed: 1,
180                    filter_stats: None,
181                    diff: None,
182                    streamed: false,
183                    terminal_id: None,
184                    locations: None,
185                    raw_response: None,
186                    claim_source: Some(zeph_tools::ClaimSource::Memory),
187                }))
188            }
189            "memory_save" => {
190                let params: MemorySaveParams = deserialize_params(&call.params)?;
191
192                if params.content.is_empty() {
193                    return Err(ToolError::InvalidParams {
194                        message: "content must not be empty".to_owned(),
195                    });
196                }
197                if params.content.len() > 4096 {
198                    return Err(ToolError::InvalidParams {
199                        message: "content exceeds maximum length of 4096 characters".to_owned(),
200                    });
201                }
202
203                // Schema validation: check content before writing to memory.
204                if let Err(e) = self.validator.validate_memory_save(&params.content) {
205                    return Err(ToolError::InvalidParams {
206                        message: format!("memory write rejected: {e}"),
207                    });
208                }
209
210                let role = params.role.as_str();
211
212                // Explicit user-directed saves bypass goal-conditioned scoring (goal_text = None).
213                let message_id_opt = self
214                    .memory
215                    .remember(self.conversation_id, role, &params.content, None)
216                    .await
217                    .map_err(|e| ToolError::Execution(std::io::Error::other(e.to_string())))?;
218
219                let summary = match message_id_opt {
220                    Some(message_id) => {
221                        if self.ephemeral {
222                            format!(
223                                "Saved to session memory (message_id: {message_id}, conversation: {}). Ephemeral — not available after session ends.",
224                                self.conversation_id
225                            )
226                        } else {
227                            format!(
228                                "Saved to memory (message_id: {message_id}, conversation: {}). Content will be available for future recall.",
229                                self.conversation_id
230                            )
231                        }
232                    }
233                    None => "Memory admission rejected: message did not meet quality threshold."
234                        .to_owned(),
235                };
236
237                Ok(Some(ToolOutput {
238                    tool_name: zeph_common::ToolName::new("memory_save"),
239                    summary,
240                    blocks_executed: 1,
241                    filter_stats: None,
242                    diff: None,
243                    streamed: false,
244                    terminal_id: None,
245                    locations: None,
246                    raw_response: None,
247                    claim_source: Some(zeph_tools::ClaimSource::Memory),
248                }))
249            }
250            _ => Ok(None),
251        }
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258    use zeph_llm::any::AnyProvider;
259    use zeph_llm::mock::MockProvider;
260    use zeph_memory::semantic::SemanticMemory;
261
262    async fn make_memory() -> SemanticMemory {
263        SemanticMemory::with_sqlite_backend(
264            ":memory:",
265            AnyProvider::Mock(MockProvider::default()),
266            "test-model",
267            0.7,
268            0.3,
269        )
270        .await
271        .unwrap()
272    }
273
274    fn make_executor(memory: SemanticMemory) -> MemoryToolExecutor {
275        MemoryToolExecutor::new(Arc::new(memory), ConversationId(1))
276    }
277
278    #[tokio::test]
279    async fn tool_definitions_returns_two_tools() {
280        let memory = make_memory().await;
281        let executor = make_executor(memory);
282        let defs = executor.tool_definitions();
283        assert_eq!(defs.len(), 2);
284        assert_eq!(defs[0].id.as_ref(), "memory_search");
285        assert_eq!(defs[1].id.as_ref(), "memory_save");
286    }
287
288    #[tokio::test]
289    async fn execute_always_returns_none() {
290        let memory = make_memory().await;
291        let executor = make_executor(memory);
292        let result = executor.execute("any response").await.unwrap();
293        assert!(result.is_none());
294    }
295
296    #[tokio::test]
297    async fn execute_tool_call_unknown_returns_none() {
298        let memory = make_memory().await;
299        let executor = make_executor(memory);
300        let call = ToolCall {
301            tool_id: zeph_common::ToolName::new("unknown_tool"),
302            params: serde_json::Map::new(),
303            caller_id: None,
304            context: None,
305
306            tool_call_id: String::new(),
307            skill_name: None,
308        };
309        let result = executor.execute_tool_call(&call).await.unwrap();
310        assert!(result.is_none());
311    }
312
313    #[tokio::test]
314    async fn memory_search_returns_output() {
315        let memory = make_memory().await;
316        let executor = make_executor(memory);
317        let mut params = serde_json::Map::new();
318        params.insert(
319            "query".into(),
320            serde_json::Value::String("test query".into()),
321        );
322        let call = ToolCall {
323            tool_id: zeph_common::ToolName::new("memory_search"),
324            params,
325            caller_id: None,
326            context: None,
327
328            tool_call_id: String::new(),
329            skill_name: None,
330        };
331        let result = executor.execute_tool_call(&call).await.unwrap();
332        assert!(result.is_some());
333        let output = result.unwrap();
334        assert_eq!(output.tool_name, "memory_search");
335        assert!(output.summary.contains("Recalled Messages"));
336        assert!(output.summary.contains("Key Facts"));
337        assert!(output.summary.contains("Session Summaries"));
338    }
339
340    #[tokio::test]
341    async fn memory_save_stores_and_returns_confirmation() {
342        let memory = make_memory().await;
343        let sqlite = memory.sqlite().clone();
344        // Create conversation first
345        let cid = sqlite.create_conversation().await.unwrap();
346        let executor = MemoryToolExecutor::new(Arc::new(memory), cid);
347
348        let mut params = serde_json::Map::new();
349        params.insert(
350            "content".into(),
351            serde_json::Value::String("User prefers dark mode".into()),
352        );
353        let call = ToolCall {
354            tool_id: zeph_common::ToolName::new("memory_save"),
355            params,
356            caller_id: None,
357            context: None,
358
359            tool_call_id: String::new(),
360            skill_name: None,
361        };
362        let result = executor.execute_tool_call(&call).await.unwrap();
363        assert!(result.is_some());
364        let output = result.unwrap();
365        assert!(output.summary.contains("Saved to memory"));
366        assert!(output.summary.contains("message_id:"));
367    }
368
369    #[tokio::test]
370    async fn memory_save_empty_content_returns_error() {
371        let memory = make_memory().await;
372        let executor = make_executor(memory);
373        let mut params = serde_json::Map::new();
374        params.insert("content".into(), serde_json::Value::String(String::new()));
375        let call = ToolCall {
376            tool_id: zeph_common::ToolName::new("memory_save"),
377            params,
378            caller_id: None,
379            context: None,
380
381            tool_call_id: String::new(),
382            skill_name: None,
383        };
384        let result = executor.execute_tool_call(&call).await;
385        assert!(result.is_err());
386    }
387
388    #[tokio::test]
389    async fn memory_save_oversized_content_returns_error() {
390        let memory = make_memory().await;
391        let executor = make_executor(memory);
392        let mut params = serde_json::Map::new();
393        params.insert(
394            "content".into(),
395            serde_json::Value::String("x".repeat(4097)),
396        );
397        let call = ToolCall {
398            tool_id: zeph_common::ToolName::new("memory_save"),
399            params,
400            caller_id: None,
401            context: None,
402
403            tool_call_id: String::new(),
404            skill_name: None,
405        };
406        let result = executor.execute_tool_call(&call).await;
407        assert!(result.is_err());
408    }
409
410    #[tokio::test]
411    async fn memory_save_ephemeral_returns_session_only_message() {
412        let memory = make_memory().await;
413        let sqlite = memory.sqlite().clone();
414        let cid = sqlite.create_conversation().await.unwrap();
415        let executor = MemoryToolExecutor::new(Arc::new(memory), cid).ephemeral();
416
417        let mut params = serde_json::Map::new();
418        params.insert(
419            "content".into(),
420            serde_json::Value::String("temp fact".into()),
421        );
422        let call = ToolCall {
423            tool_id: zeph_common::ToolName::new("memory_save"),
424            params,
425            caller_id: None,
426            context: None,
427            tool_call_id: String::new(),
428            skill_name: None,
429        };
430        let output = executor.execute_tool_call(&call).await.unwrap().unwrap();
431        assert!(
432            output.summary.contains("Ephemeral"),
433            "bare-mode save must mention ephemeral semantics; got: {}",
434            output.summary
435        );
436        assert!(
437            !output.summary.contains("available for future recall"),
438            "bare-mode save must not claim cross-session persistence; got: {}",
439            output.summary
440        );
441    }
442
443    /// `memory_search` description must mention user-provided facts so the model
444    /// prefers it over `search_code` for recalling information from conversation (#2475).
445    #[tokio::test]
446    async fn memory_search_description_mentions_user_provided_facts() {
447        let memory = make_memory().await;
448        let executor = make_executor(memory);
449        let defs = executor.tool_definitions();
450        let memory_search = defs
451            .iter()
452            .find(|d| d.id.as_ref() == "memory_search")
453            .unwrap();
454        assert!(
455            memory_search
456                .description
457                .contains("user provided during this or previous conversations"),
458            "memory_search description must contain disambiguation phrase; got: {}",
459            memory_search.description
460        );
461    }
462}