zeptoclaw 0.3.1

Ultra-lightweight personal AI assistant framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
//! Long-term memory tool.
//!
//! Exposes the `LongTermMemory` store to the AI agent, allowing it to remember
//! facts, preferences, and learnings that persist across sessions.

use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use serde_json::{json, Value};

use crate::error::{Result, ZeptoError};
use crate::memory::longterm::LongTermMemory;

use super::{Tool, ToolContext};

/// Tool for storing and retrieving long-term memories across sessions.
pub struct LongTermMemoryTool {
    memory: Arc<Mutex<LongTermMemory>>,
}

impl LongTermMemoryTool {
    /// Create a new long-term memory tool.
    ///
    /// Initializes the underlying `LongTermMemory` store, loading any
    /// previously persisted entries from `~/.zeptoclaw/memory/longterm.json`.
    pub fn new() -> Result<Self> {
        let memory = LongTermMemory::new()?;
        Ok(Self {
            memory: Arc::new(Mutex::new(memory)),
        })
    }

    /// Create a long-term memory tool with a pre-existing memory instance.
    /// Useful for testing or shared ownership scenarios.
    pub fn with_memory(memory: Arc<Mutex<LongTermMemory>>) -> Self {
        Self { memory }
    }
}

#[async_trait]
impl Tool for LongTermMemoryTool {
    fn name(&self) -> &str {
        "longterm_memory"
    }

    fn description(&self) -> &str {
        "Store and retrieve long-term memories (facts, preferences, learnings) that persist across sessions. Use 'set' to remember something, 'get' to recall by key, 'search' to find memories by keyword."
    }

    fn parameters(&self) -> Value {
        json!({
            "type": "object",
            "properties": {
                "action": {
                    "type": "string",
                    "enum": ["set", "get", "search", "delete", "list", "categories"],
                    "description": "Action to perform"
                },
                "key": {
                    "type": "string",
                    "description": "Memory key (e.g., 'user:name', 'preference:language')"
                },
                "value": {
                    "type": "string",
                    "description": "Memory value/content to store"
                },
                "category": {
                    "type": "string",
                    "description": "Category for grouping (e.g., 'user', 'preference', 'fact', 'learning')"
                },
                "tags": {
                    "type": "array",
                    "items": { "type": "string" },
                    "description": "Optional tags for search and organization"
                },
                "query": {
                    "type": "string",
                    "description": "Search query (searches across key, value, category, and tags)"
                }
            },
            "required": ["action"]
        })
    }

    async fn execute(&self, args: Value, _ctx: &ToolContext) -> Result<String> {
        let action = args
            .get("action")
            .and_then(|v| v.as_str())
            .ok_or_else(|| ZeptoError::Tool("Missing 'action' parameter".to_string()))?;

        match action {
            "set" => self.execute_set(&args),
            "get" => self.execute_get(&args),
            "search" => self.execute_search(&args),
            "delete" => self.execute_delete(&args),
            "list" => self.execute_list(&args),
            "categories" => self.execute_categories(),
            other => Err(ZeptoError::Tool(format!(
                "Unknown longterm_memory action '{}'. Valid actions: set, get, search, delete, list, categories",
                other
            ))),
        }
    }
}

impl LongTermMemoryTool {
    fn execute_set(&self, args: &Value) -> Result<String> {
        let key = args
            .get("key")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| {
                ZeptoError::Tool("Missing 'key' parameter for set action".to_string())
            })?;

        let value = args
            .get("value")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| {
                ZeptoError::Tool("Missing 'value' parameter for set action".to_string())
            })?;

        let category = args
            .get("category")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| {
                ZeptoError::Tool("Missing 'category' parameter for set action".to_string())
            })?;

        let tags: Vec<String> = args
            .get("tags")
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str())
                    .map(|s| s.trim().to_string())
                    .filter(|s| !s.is_empty())
                    .collect()
            })
            .unwrap_or_default();

        let mut memory = self
            .memory
            .lock()
            .map_err(|e| ZeptoError::Tool(format!("Failed to acquire memory lock: {}", e)))?;

        // Check if this is an update or a new entry.
        let is_update = memory.get_readonly(key).is_some();
        memory.set(key, value, category, tags)?;

        if is_update {
            Ok(format!("Updated memory '{}'", key))
        } else {
            Ok(format!(
                "Stored memory '{}' in category '{}'",
                key, category
            ))
        }
    }

    fn execute_get(&self, args: &Value) -> Result<String> {
        let key = args
            .get("key")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| {
                ZeptoError::Tool("Missing 'key' parameter for get action".to_string())
            })?;

        let mut memory = self
            .memory
            .lock()
            .map_err(|e| ZeptoError::Tool(format!("Failed to acquire memory lock: {}", e)))?;

        match memory.get(key) {
            Some(entry) => {
                let entry_json = serde_json::to_string_pretty(entry).map_err(|e| {
                    ZeptoError::Tool(format!("Failed to serialize memory entry: {}", e))
                })?;
                Ok(entry_json)
            }
            None => Ok(format!("No memory found for key '{}'", key)),
        }
    }

    fn execute_search(&self, args: &Value) -> Result<String> {
        let query = args
            .get("query")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| {
                ZeptoError::Tool("Missing 'query' parameter for search action".to_string())
            })?;

        let memory = self
            .memory
            .lock()
            .map_err(|e| ZeptoError::Tool(format!("Failed to acquire memory lock: {}", e)))?;

        let results = memory.search(query);

        if results.is_empty() {
            return Ok(format!("No memories found matching '{}'", query));
        }

        let entries: Vec<&crate::memory::longterm::MemoryEntry> = results;
        let json = serde_json::to_string_pretty(&entries)
            .map_err(|e| ZeptoError::Tool(format!("Failed to serialize search results: {}", e)))?;

        Ok(format!(
            "Found {} matching memor{}:\n{}",
            entries.len(),
            if entries.len() == 1 { "y" } else { "ies" },
            json
        ))
    }

    fn execute_delete(&self, args: &Value) -> Result<String> {
        let key = args
            .get("key")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| {
                ZeptoError::Tool("Missing 'key' parameter for delete action".to_string())
            })?;

        let mut memory = self
            .memory
            .lock()
            .map_err(|e| ZeptoError::Tool(format!("Failed to acquire memory lock: {}", e)))?;

        if memory.delete(key)? {
            Ok(format!("Deleted memory '{}'", key))
        } else {
            Ok(format!("No memory found for key '{}'", key))
        }
    }

    fn execute_list(&self, args: &Value) -> Result<String> {
        let category = args
            .get("category")
            .and_then(|v| v.as_str())
            .map(str::trim)
            .filter(|s| !s.is_empty());

        let memory = self
            .memory
            .lock()
            .map_err(|e| ZeptoError::Tool(format!("Failed to acquire memory lock: {}", e)))?;

        let results: Vec<&crate::memory::longterm::MemoryEntry> = if let Some(cat) = category {
            memory.list_by_category(cat)
        } else {
            memory.list_all()
        };

        if results.is_empty() {
            return if let Some(cat) = category {
                Ok(format!("No memories in category '{}'", cat))
            } else {
                Ok("No memories stored yet".to_string())
            };
        }

        let json = serde_json::to_string_pretty(&results)
            .map_err(|e| ZeptoError::Tool(format!("Failed to serialize memory entries: {}", e)))?;

        let label = if let Some(cat) = category {
            format!(
                "{} memor{} in category '{}'",
                results.len(),
                if results.len() == 1 { "y" } else { "ies" },
                cat
            )
        } else {
            format!(
                "{} total memor{}",
                results.len(),
                if results.len() == 1 { "y" } else { "ies" }
            )
        };

        Ok(format!("{}:\n{}", label, json))
    }

    fn execute_categories(&self) -> Result<String> {
        let memory = self
            .memory
            .lock()
            .map_err(|e| ZeptoError::Tool(format!("Failed to acquire memory lock: {}", e)))?;

        let categories = memory.categories();

        if categories.is_empty() {
            return Ok("No categories yet (memory is empty)".to_string());
        }

        let summary = memory.summary();
        let json = serde_json::to_string_pretty(&categories)
            .map_err(|e| ZeptoError::Tool(format!("Failed to serialize categories: {}", e)))?;

        Ok(format!("{}\nCategories:\n{}", summary, json))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    /// Helper: create a LongTermMemoryTool backed by a temp directory.
    fn temp_tool() -> (LongTermMemoryTool, TempDir) {
        let dir = TempDir::new().expect("failed to create temp dir");
        let path = dir.path().join("longterm.json");
        let memory = LongTermMemory::with_path(path).expect("failed to create memory");
        let tool = LongTermMemoryTool::with_memory(Arc::new(Mutex::new(memory)));
        (tool, dir)
    }

    fn ctx() -> ToolContext {
        ToolContext::new()
    }

    #[test]
    fn test_tool_name() {
        let (tool, _dir) = temp_tool();
        assert_eq!(tool.name(), "longterm_memory");
    }

    #[test]
    fn test_tool_description() {
        let (tool, _dir) = temp_tool();
        assert!(tool.description().contains("long-term memories"));
        assert!(tool.description().contains("persist across sessions"));
    }

    #[test]
    fn test_tool_parameters_schema() {
        let (tool, _dir) = temp_tool();
        let params = tool.parameters();
        assert_eq!(params["type"], "object");
        assert!(params["properties"]["action"].is_object());
        assert!(params["properties"]["key"].is_object());
        assert!(params["properties"]["value"].is_object());
        assert!(params["properties"]["category"].is_object());
        assert!(params["properties"]["tags"].is_object());
        assert!(params["properties"]["query"].is_object());
        assert_eq!(params["required"], json!(["action"]));
    }

    #[tokio::test]
    async fn test_set_and_get() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool
            .execute(
                json!({
                    "action": "set",
                    "key": "user:name",
                    "value": "Alice",
                    "category": "user",
                    "tags": ["identity"]
                }),
                &c,
            )
            .await
            .unwrap();
        assert!(result.contains("Stored memory 'user:name'"));
        assert!(result.contains("category 'user'"));

        let result = tool
            .execute(json!({"action": "get", "key": "user:name"}), &c)
            .await
            .unwrap();
        assert!(result.contains("Alice"));
        assert!(result.contains("user:name"));
    }

    #[tokio::test]
    async fn test_set_update() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        tool.execute(
            json!({"action": "set", "key": "k1", "value": "v1", "category": "test"}),
            &c,
        )
        .await
        .unwrap();

        let result = tool
            .execute(
                json!({"action": "set", "key": "k1", "value": "v2", "category": "test"}),
                &c,
            )
            .await
            .unwrap();
        assert!(result.contains("Updated memory 'k1'"));
    }

    #[tokio::test]
    async fn test_get_nonexistent() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool
            .execute(json!({"action": "get", "key": "nope"}), &c)
            .await
            .unwrap();
        assert!(result.contains("No memory found for key 'nope'"));
    }

    #[tokio::test]
    async fn test_search() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        tool.execute(
            json!({"action": "set", "key": "fact:lang", "value": "Rust is fast", "category": "fact"}),
            &c,
        )
        .await
        .unwrap();

        tool.execute(
            json!({"action": "set", "key": "fact:db", "value": "PostgreSQL is reliable", "category": "fact"}),
            &c,
        )
        .await
        .unwrap();

        let result = tool
            .execute(json!({"action": "search", "query": "Rust"}), &c)
            .await
            .unwrap();
        assert!(result.contains("Found 1 matching memory"));
        assert!(result.contains("Rust is fast"));
    }

    #[tokio::test]
    async fn test_search_no_results() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool
            .execute(json!({"action": "search", "query": "nonexistent"}), &c)
            .await
            .unwrap();
        assert!(result.contains("No memories found matching 'nonexistent'"));
    }

    #[tokio::test]
    async fn test_delete() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        tool.execute(
            json!({"action": "set", "key": "k1", "value": "v1", "category": "test"}),
            &c,
        )
        .await
        .unwrap();

        let result = tool
            .execute(json!({"action": "delete", "key": "k1"}), &c)
            .await
            .unwrap();
        assert!(result.contains("Deleted memory 'k1'"));

        let result = tool
            .execute(json!({"action": "get", "key": "k1"}), &c)
            .await
            .unwrap();
        assert!(result.contains("No memory found"));
    }

    #[tokio::test]
    async fn test_delete_nonexistent() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool
            .execute(json!({"action": "delete", "key": "nope"}), &c)
            .await
            .unwrap();
        assert!(result.contains("No memory found for key 'nope'"));
    }

    #[tokio::test]
    async fn test_list_all() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        tool.execute(
            json!({"action": "set", "key": "k1", "value": "v1", "category": "a"}),
            &c,
        )
        .await
        .unwrap();

        tool.execute(
            json!({"action": "set", "key": "k2", "value": "v2", "category": "b"}),
            &c,
        )
        .await
        .unwrap();

        let result = tool.execute(json!({"action": "list"}), &c).await.unwrap();
        assert!(result.contains("2 total memories"));
        assert!(result.contains("k1"));
        assert!(result.contains("k2"));
    }

    #[tokio::test]
    async fn test_list_by_category() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        tool.execute(
            json!({"action": "set", "key": "k1", "value": "v1", "category": "user"}),
            &c,
        )
        .await
        .unwrap();

        tool.execute(
            json!({"action": "set", "key": "k2", "value": "v2", "category": "fact"}),
            &c,
        )
        .await
        .unwrap();

        let result = tool
            .execute(json!({"action": "list", "category": "user"}), &c)
            .await
            .unwrap();
        assert!(result.contains("1 memory in category 'user'"));
        assert!(result.contains("k1"));
        assert!(!result.contains("k2"));
    }

    #[tokio::test]
    async fn test_list_empty() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool.execute(json!({"action": "list"}), &c).await.unwrap();
        assert!(result.contains("No memories stored yet"));
    }

    #[tokio::test]
    async fn test_list_empty_category() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool
            .execute(json!({"action": "list", "category": "nope"}), &c)
            .await
            .unwrap();
        assert!(result.contains("No memories in category 'nope'"));
    }

    #[tokio::test]
    async fn test_categories() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        tool.execute(
            json!({"action": "set", "key": "k1", "value": "v1", "category": "user"}),
            &c,
        )
        .await
        .unwrap();

        tool.execute(
            json!({"action": "set", "key": "k2", "value": "v2", "category": "fact"}),
            &c,
        )
        .await
        .unwrap();

        tool.execute(
            json!({"action": "set", "key": "k3", "value": "v3", "category": "user"}),
            &c,
        )
        .await
        .unwrap();

        let result = tool
            .execute(json!({"action": "categories"}), &c)
            .await
            .unwrap();
        assert!(result.contains("fact"));
        assert!(result.contains("user"));
        assert!(result.contains("3 entries"));
        assert!(result.contains("2 categories"));
    }

    #[tokio::test]
    async fn test_categories_empty() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool
            .execute(json!({"action": "categories"}), &c)
            .await
            .unwrap();
        assert!(result.contains("No categories yet"));
    }

    #[tokio::test]
    async fn test_unknown_action() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool.execute(json!({"action": "invalid"}), &c).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Unknown longterm_memory action 'invalid'"));
    }

    #[tokio::test]
    async fn test_missing_action() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool.execute(json!({}), &c).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Missing 'action' parameter"));
    }

    #[tokio::test]
    async fn test_set_missing_key() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool
            .execute(
                json!({"action": "set", "value": "v1", "category": "test"}),
                &c,
            )
            .await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Missing 'key'"));
    }

    #[tokio::test]
    async fn test_set_missing_value() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool
            .execute(
                json!({"action": "set", "key": "k1", "category": "test"}),
                &c,
            )
            .await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Missing 'value'"));
    }

    #[tokio::test]
    async fn test_set_missing_category() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool
            .execute(json!({"action": "set", "key": "k1", "value": "v1"}), &c)
            .await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Missing 'category'"));
    }

    #[tokio::test]
    async fn test_get_missing_key() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool.execute(json!({"action": "get"}), &c).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Missing 'key'"));
    }

    #[tokio::test]
    async fn test_search_missing_query() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool.execute(json!({"action": "search"}), &c).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Missing 'query'"));
    }

    #[tokio::test]
    async fn test_delete_missing_key() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool.execute(json!({"action": "delete"}), &c).await;
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Missing 'key'"));
    }

    #[tokio::test]
    async fn test_set_with_tags() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        tool.execute(
            json!({
                "action": "set",
                "key": "pref:theme",
                "value": "dark mode",
                "category": "preference",
                "tags": ["ui", "visual", "display"]
            }),
            &c,
        )
        .await
        .unwrap();

        let result = tool
            .execute(json!({"action": "search", "query": "visual"}), &c)
            .await
            .unwrap();
        assert!(result.contains("dark mode"));
    }

    #[tokio::test]
    async fn test_set_without_tags() {
        let (tool, _dir) = temp_tool();
        let c = ctx();

        let result = tool
            .execute(
                json!({
                    "action": "set",
                    "key": "fact:color",
                    "value": "blue",
                    "category": "fact"
                }),
                &c,
            )
            .await
            .unwrap();
        assert!(result.contains("Stored memory 'fact:color'"));

        let result = tool
            .execute(json!({"action": "get", "key": "fact:color"}), &c)
            .await
            .unwrap();
        assert!(result.contains("blue"));
    }
}