nenjo_tools/
memory_forget.rs1use crate::memory::AgentMemory;
4use crate::{Tool, ToolCategory, ToolResult};
5use async_trait::async_trait;
6use serde_json::json;
7use std::sync::Arc;
8
9pub struct MemoryForgetTool {
13 memory: Arc<dyn AgentMemory>,
14 role_namespace: String,
16 core_namespace: Option<String>,
18 shared_namespace: String,
20}
21
22impl MemoryForgetTool {
23 pub fn new(
24 memory: Arc<dyn AgentMemory>,
25 role_namespace: String,
26 core_namespace: Option<String>,
27 shared_namespace: String,
28 ) -> Self {
29 Self {
30 memory,
31 role_namespace,
32 core_namespace,
33 shared_namespace,
34 }
35 }
36
37 fn namespaces_for_scope(&self, scope: &str) -> Vec<String> {
39 match scope {
40 "core" => self.core_namespace.iter().cloned().collect(),
41 "shared" => vec![self.shared_namespace.clone()],
42 "all" => {
43 let mut ns = vec![self.role_namespace.clone()];
44 if let Some(ref core) = self.core_namespace
45 && !ns.contains(core)
46 {
47 ns.push(core.clone());
48 }
49 if !ns.contains(&self.shared_namespace) {
50 ns.push(self.shared_namespace.clone());
51 }
52 ns
53 }
54 _ => vec![self.role_namespace.clone()], }
56 }
57}
58
59#[async_trait]
60impl Tool for MemoryForgetTool {
61 fn category(&self) -> ToolCategory {
62 ToolCategory::ReadWrite
63 }
64
65 fn name(&self) -> &str {
66 "forget_memory"
67 }
68
69 fn description(&self) -> &str {
70 "Remove memories. Use 'query' to search and delete matching facts, 'id' to delete a specific item, or 'prune_older_than_days' to prune old memories. Use 'scope' to target: 'project' (default), 'core', 'shared', or 'all' namespaces."
71 }
72
73 fn parameters_schema(&self) -> serde_json::Value {
74 json!({
75 "type": "object",
76 "properties": {
77 "query": {
78 "type": "string",
79 "description": "Search query — all matching memory items will be deleted. Use this when the user asks to forget something (e.g. 'forget my name')."
80 },
81 "id": {
82 "type": "string",
83 "description": "The ID of a specific memory item to delete"
84 },
85 "prune_older_than_days": {
86 "type": "integer",
87 "description": "Delete items older than this many days with low access counts"
88 },
89 "scope": {
90 "type": "string",
91 "enum": ["project", "core", "shared", "all"],
92 "description": "Memory scope to search: 'project' (default), 'core', 'shared', or 'all' to search everywhere"
93 }
94 }
95 })
96 }
97
98 async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
99 let scope = args.get("scope").and_then(|v| v.as_str()).unwrap_or("all");
100
101 let namespaces = self.namespaces_for_scope(scope);
102 if namespaces.is_empty() {
103 return Ok(ToolResult {
104 success: false,
105 output: String::new(),
106 error: Some("No namespace available for the requested scope.".into()),
107 });
108 }
109
110 if let Some(query) = args.get("query").and_then(|v| v.as_str()) {
112 let mut all_items = Vec::new();
113 for ns in &namespaces {
114 if let Ok(items) = self.memory.search_items(ns, query, 20).await {
115 all_items.extend(items)
116 }
117 }
118
119 if all_items.is_empty() {
120 return Ok(ToolResult {
121 success: true,
122 output: format!("No memories found matching '{query}'."),
123 error: None,
124 });
125 }
126
127 let mut deleted = 0u32;
128 let mut facts = Vec::new();
129 let mut affected_categories: std::collections::HashMap<
130 String,
131 std::collections::HashSet<String>,
132 > = std::collections::HashMap::new();
133
134 for item in &all_items {
135 affected_categories
136 .entry(item.namespace.clone())
137 .or_default()
138 .insert(item.category.clone());
139 if let Ok(true) = self.memory.delete_item(&item.id).await {
140 deleted += 1;
141 facts.push(item.fact.clone());
142 }
143 }
144
145 for (ns, categories) in &affected_categories {
147 for category in categories {
148 let remaining = self
149 .memory
150 .list_items_by_category(ns, category)
151 .await
152 .unwrap_or_default();
153 if remaining.is_empty() {
154 let _ = self.memory.delete_summary(ns, category).await;
155 } else {
156 let summary: String = remaining
158 .iter()
159 .map(|item| item.fact.as_str())
160 .collect::<Vec<_>>()
161 .join(". ");
162 #[allow(clippy::cast_possible_truncation)]
163 let _ = self
164 .memory
165 .upsert_summary(ns, category, &summary, remaining.len() as u32)
166 .await;
167 }
168 }
169 }
170
171 let facts_list = facts.join("\n - ");
172 return Ok(ToolResult {
173 success: true,
174 output: format!(
175 "Deleted {deleted} memory item(s) matching '{query}':\n - {facts_list}"
176 ),
177 error: None,
178 });
179 }
180
181 if let Some(id) = args.get("id").and_then(|v| v.as_str()) {
183 return match self.memory.delete_item(id).await {
184 Ok(true) => Ok(ToolResult {
185 success: true,
186 output: format!("Deleted memory item: {id}"),
187 error: None,
188 }),
189 Ok(false) => Ok(ToolResult {
190 success: true,
191 output: format!("No memory item found with id: {id}"),
192 error: None,
193 }),
194 Err(e) => Ok(ToolResult {
195 success: false,
196 output: String::new(),
197 error: Some(format!("Failed to delete memory: {e}")),
198 }),
199 };
200 }
201
202 if let Some(days) = args.get("prune_older_than_days").and_then(|v| v.as_u64()) {
204 #[allow(clippy::cast_possible_truncation)]
205 let days = days as u32;
206 let mut total = 0u64;
207 for ns in &namespaces {
208 if let Ok(count) = self.memory.delete_stale_items(ns, days, 2).await {
209 total += count
210 }
211 }
212 return Ok(ToolResult {
213 success: true,
214 output: format!("Pruned {total} stale memory items older than {days} days"),
215 error: None,
216 });
217 }
218
219 Ok(ToolResult {
220 success: false,
221 output: String::new(),
222 error: Some("Provide 'query' to search and delete, 'id' to delete a specific item, or 'prune_older_than_days' to prune old items.".into()),
223 })
224 }
225}