1use async_trait::async_trait;
13use serde_json::json;
14
15use crate::tools::session_memory::{
16 execute_session_memory_action, parse_session_note_action, SESSION_NOTE_ACTION_NAMES,
17};
18use bamboo_agent_core::{Tool, ToolError, ToolExecutionContext, ToolResult};
19use bamboo_memory::memory_store::MemoryStore;
20
21const TOOL_NAME: &str = "session_note";
22const TOOL_DESCRIPTION: &str = "Read or update the persistent session-scoped note (markdown). Use this for durable local context, user preferences, constraints, and compression-resistant reminders within the current session/workstream. Do not use it as the primary long-term knowledge base. Hard limit: 12000 characters; compress before append/replace if needed.";
23
24#[derive(Debug, Clone)]
25pub struct SessionNoteTool {
26 memory_store: MemoryStore,
27}
28
29impl SessionNoteTool {
30 pub fn new() -> Self {
31 Self {
32 memory_store: MemoryStore::with_defaults(),
33 }
34 }
35
36 #[cfg(test)]
37 fn with_memory_store(memory_store: MemoryStore) -> Self {
38 Self { memory_store }
39 }
40}
41
42impl Default for SessionNoteTool {
43 fn default() -> Self {
44 Self::new()
45 }
46}
47
48pub type MemoryNoteTool = SessionNoteTool;
51
52#[async_trait]
53impl Tool for SessionNoteTool {
54 fn name(&self) -> &str {
55 TOOL_NAME
56 }
57
58 fn description(&self) -> &str {
59 TOOL_DESCRIPTION
60 }
61
62 fn mutability(&self) -> crate::ToolMutability {
63 crate::ToolMutability::Mutating
64 }
65
66 fn call_mutability(&self, args: &serde_json::Value) -> crate::ToolMutability {
67 let action = args
68 .get("action")
69 .and_then(|v| v.as_str())
70 .unwrap_or("")
71 .trim()
72 .to_ascii_lowercase();
73 match action.as_str() {
74 "read" | "list_topics" => crate::ToolMutability::ReadOnly,
75 _ => crate::ToolMutability::Mutating,
76 }
77 }
78
79 fn call_concurrency_safe(&self, args: &serde_json::Value) -> bool {
80 matches!(self.call_mutability(args), crate::ToolMutability::ReadOnly)
81 }
82
83 fn parameters_schema(&self) -> serde_json::Value {
84 json!({
85 "type": "object",
86 "properties": {
87 "action": {
88 "type": "string",
89 "description": "Operation to perform on the note.",
90 "enum": ["read", "append", "replace", "clear", "list_topics"]
91 },
92 "content": {
93 "type": "string",
94 "description": "Note content to append/replace (markdown). Required for append/replace."
95 },
96 "topic": {
97 "type": "string",
98 "description": "Optional topic name (alphanumeric/dash/underscore, max 50 chars). Defaults to 'default'. Use separate topics for unrelated workstreams."
99 }
100 },
101 "required": ["action"]
102 })
103 }
104
105 async fn execute(&self, _args: serde_json::Value) -> Result<ToolResult, ToolError> {
106 Err(ToolError::Execution(format!(
107 "{TOOL_NAME} must be executed with ToolExecutionContext (session_id required)"
108 )))
109 }
110
111 async fn execute_with_context(
112 &self,
113 args: serde_json::Value,
114 ctx: ToolExecutionContext<'_>,
115 ) -> Result<ToolResult, ToolError> {
116 let Some(session_id) = ctx.session_id else {
117 return Err(ToolError::Execution(
118 "missing session_id in tool context".to_string(),
119 ));
120 };
121
122 let action_raw = args.get("action").and_then(|v| v.as_str()).unwrap_or("");
123 let action = parse_session_note_action(action_raw)?;
124 let topic = args.get("topic").and_then(|v| v.as_str());
125 let content = args.get("content").and_then(|v| v.as_str());
126
127 execute_session_memory_action(
128 &self.memory_store,
129 session_id,
130 action,
131 topic,
132 content,
133 None,
134 SESSION_NOTE_ACTION_NAMES,
135 )
136 .await
137 }
138}
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143
144 #[test]
145 fn session_note_schema_requires_action() {
146 let tool = SessionNoteTool::new();
147 let schema = tool.parameters_schema();
148 assert_eq!(schema["required"], json!(["action"]));
149 assert_eq!(tool.name(), TOOL_NAME);
150 assert_eq!(
151 schema["properties"]["action"]["enum"],
152 json!(["read", "append", "replace", "clear", "list_topics"])
153 );
154 }
155
156 #[test]
157 fn session_note_schema_has_topic_field() {
158 let tool = SessionNoteTool::new();
159 let schema = tool.parameters_schema();
160 assert!(schema["properties"]["topic"].is_object());
161 assert_eq!(schema["properties"]["topic"]["type"], "string");
162 }
163
164 #[tokio::test]
165 async fn session_note_requires_session_context() {
166 let tool = SessionNoteTool::new();
167 let result = tool
168 .execute_with_context(
169 json!({"action": "read"}),
170 ToolExecutionContext::none("tool_call"),
171 )
172 .await;
173
174 assert!(matches!(
175 result,
176 Err(ToolError::Execution(msg)) if msg.contains("session_id")
177 ));
178 }
179
180 #[tokio::test]
181 async fn session_note_validates_action_and_content_before_io() {
182 let tool = SessionNoteTool::new();
183
184 let unknown = tool
185 .execute_with_context(
186 json!({"action": "unknown"}),
187 ToolExecutionContext {
188 session_id: Some("session-1"),
189 tool_call_id: "tool_call_unknown",
190 event_tx: None,
191 available_tool_schemas: None,
192 bypass_permissions: false,
193 can_async_resume: false,
194 },
195 )
196 .await;
197 assert!(matches!(
198 unknown,
199 Err(ToolError::InvalidArguments(msg)) if msg.contains("action must be one of")
200 ));
201
202 let missing_content = tool
203 .execute_with_context(
204 json!({"action": "replace"}),
205 ToolExecutionContext {
206 session_id: Some("session-1"),
207 tool_call_id: "tool_call_replace",
208 event_tx: None,
209 available_tool_schemas: None,
210 bypass_permissions: false,
211 can_async_resume: false,
212 },
213 )
214 .await;
215 assert!(matches!(
216 missing_content,
217 Err(ToolError::InvalidArguments(msg)) if msg.contains("content is required")
218 ));
219 }
220
221 #[tokio::test]
222 async fn session_note_uses_memory_store_session_topics() {
223 let dir = tempfile::tempdir().unwrap();
224 let tool = SessionNoteTool::with_memory_store(MemoryStore::new(dir.path()));
225
226 let append = tool
227 .execute_with_context(
228 json!({"action": "append", "topic": "backend", "content": "API finalized"}),
229 ToolExecutionContext {
230 session_id: Some("session-1"),
231 tool_call_id: "tool_call_append",
232 event_tx: None,
233 available_tool_schemas: None,
234 bypass_permissions: false,
235 can_async_resume: false,
236 },
237 )
238 .await
239 .expect("append should succeed");
240 let append_json: serde_json::Value = serde_json::from_str(&append.result).unwrap();
241 assert_eq!(append_json["action"], "append");
242 assert_eq!(append_json["length_chars"], "API finalized".chars().count());
243
244 let read = tool
245 .execute_with_context(
246 json!({"action": "read", "topic": "backend"}),
247 ToolExecutionContext {
248 session_id: Some("session-1"),
249 tool_call_id: "tool_call_read",
250 event_tx: None,
251 available_tool_schemas: None,
252 bypass_permissions: false,
253 can_async_resume: false,
254 },
255 )
256 .await
257 .expect("read should succeed");
258 let read_json: serde_json::Value = serde_json::from_str(&read.result).unwrap();
259 assert_eq!(read_json["action"], "read");
260 assert_eq!(read_json["content"], "API finalized");
261 assert_eq!(read_json["length_chars"], "API finalized".chars().count());
262 assert_eq!(read_json["body_truncated"], false);
263
264 let list = tool
265 .execute_with_context(
266 json!({"action": "list_topics"}),
267 ToolExecutionContext {
268 session_id: Some("session-1"),
269 tool_call_id: "tool_call_list",
270 event_tx: None,
271 available_tool_schemas: None,
272 bypass_permissions: false,
273 can_async_resume: false,
274 },
275 )
276 .await
277 .expect("list should succeed");
278 let list_json: serde_json::Value = serde_json::from_str(&list.result).unwrap();
279 assert_eq!(list_json["topics"][0], "backend");
280 assert_eq!(list_json["count"], 1);
281
282 let clear = tool
283 .execute_with_context(
284 json!({"action": "clear", "topic": "backend"}),
285 ToolExecutionContext {
286 session_id: Some("session-1"),
287 tool_call_id: "tool_call_clear",
288 event_tx: None,
289 available_tool_schemas: None,
290 bypass_permissions: false,
291 can_async_resume: false,
292 },
293 )
294 .await
295 .expect("clear should succeed");
296 let clear_json: serde_json::Value = serde_json::from_str(&clear.result).unwrap();
297 assert_eq!(clear_json["action"], "clear");
298 assert_eq!(clear_json["deleted"], true);
299 }
300
301 #[tokio::test]
302 async fn session_note_read_reports_truncation_and_append_enforces_limit() {
303 let dir = tempfile::tempdir().unwrap();
304 let tool = SessionNoteTool::with_memory_store(MemoryStore::new(dir.path()));
305 let long_content = "x".repeat(32);
306
307 tool.execute_with_context(
308 json!({"action": "replace", "topic": "default", "content": long_content}),
309 ToolExecutionContext {
310 session_id: Some("session-2"),
311 tool_call_id: "tool_call_replace_long",
312 event_tx: None,
313 available_tool_schemas: None,
314 bypass_permissions: false,
315 can_async_resume: false,
316 },
317 )
318 .await
319 .expect("replace should succeed");
320
321 let read = tool
322 .execute_with_context(
323 json!({"action": "read", "topic": "default"}),
324 ToolExecutionContext {
325 session_id: Some("session-2"),
326 tool_call_id: "tool_call_read_long",
327 event_tx: None,
328 available_tool_schemas: None,
329 bypass_permissions: false,
330 can_async_resume: false,
331 },
332 )
333 .await
334 .expect("read should succeed");
335 let read_json: serde_json::Value = serde_json::from_str(&read.result).unwrap();
336 assert_eq!(read_json["length_chars"], 32);
337 assert_eq!(read_json["body_truncated"], false);
338
339 tool.execute_with_context(
340 json!({"action": "replace", "topic": "limit", "content": "x".repeat(crate::tools::session_memory::MAX_SESSION_NOTE_CHARS - 1)}),
341 ToolExecutionContext {
342 session_id: Some("session-3"),
343 tool_call_id: "tool_call_replace_limit",
344 event_tx: None,
345 available_tool_schemas: None,
346 bypass_permissions: false,
347 can_async_resume: false,
348 },
349 )
350 .await
351 .expect("replace near limit should succeed");
352
353 let append_err = tool
354 .execute_with_context(
355 json!({"action": "append", "topic": "limit", "content": "y"}),
356 ToolExecutionContext {
357 session_id: Some("session-3"),
358 tool_call_id: "tool_call_append_limit",
359 event_tx: None,
360 available_tool_schemas: None,
361 bypass_permissions: false,
362 can_async_resume: false,
363 },
364 )
365 .await
366 .expect_err("append should exceed limit");
367 assert!(append_err
368 .to_string()
369 .contains("session note would exceed the limit"));
370 }
371}