Skip to main content

nenjo_tools/
memory_store.rs

1//! Store facts, preferences, and insights in the agent's long-term memory.
2
3use crate::memory::AgentMemory;
4use crate::{Tool, ToolCategory, ToolResult};
5use async_trait::async_trait;
6use serde_json::json;
7use std::sync::Arc;
8
9/// Let the agent store facts in memory with configurable scope.
10///
11/// Scopes:
12/// - `"project"` (default) — role-specific, project-scoped namespace
13/// - `"core"` — cross-project role knowledge (requires a role)
14/// - `"shared"` — project-wide, visible to all roles
15pub struct MemoryStoreTool {
16    memory: Arc<dyn AgentMemory>,
17    /// Role-specific, project-scoped namespace (default target).
18    role_namespace: String,
19    /// Cross-project role knowledge namespace (`None` for shared/anonymous contexts).
20    core_namespace: Option<String>,
21    /// Project-wide shared namespace.
22    shared_namespace: String,
23}
24
25impl MemoryStoreTool {
26    pub fn new(
27        memory: Arc<dyn AgentMemory>,
28        role_namespace: String,
29        core_namespace: Option<String>,
30        shared_namespace: String,
31    ) -> Self {
32        Self {
33            memory,
34            role_namespace,
35            core_namespace,
36            shared_namespace,
37        }
38    }
39}
40
41#[async_trait]
42impl Tool for MemoryStoreTool {
43    fn category(&self) -> ToolCategory {
44        ToolCategory::ReadWrite
45    }
46
47    fn name(&self) -> &str {
48        "save_memory"
49    }
50
51    fn description(&self) -> &str {
52        "Store a fact, preference, or insight in long-term memory. Use category to organize: 'decisions' for choices made, 'requirements' for project needs, 'preferences' for user preferences, 'architecture' for system design. Use scope to control visibility: 'project' (default) for this project, 'core' for cross-project expertise, 'shared' for team-visible facts."
53    }
54
55    fn parameters_schema(&self) -> serde_json::Value {
56        json!({
57            "type": "object",
58            "properties": {
59                "fact": {
60                    "type": "string",
61                    "description": "The fact or insight to remember"
62                },
63                "category": {
64                    "type": "string",
65                    "description": "Category for organizing this fact (e.g. 'decisions', 'requirements', 'preferences', 'architecture')"
66                },
67                "confidence": {
68                    "type": "number",
69                    "description": "Confidence level 0.0-1.0 (default: 0.9)"
70                },
71                "scope": {
72                    "type": "string",
73                    "enum": ["project", "core", "shared"],
74                    "description": "Memory scope: 'project' (default) for project-specific, 'core' for cross-project role expertise, 'shared' for team-visible facts"
75                }
76            },
77            "required": ["fact", "category"]
78        })
79    }
80
81    async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
82        let fact = args
83            .get("fact")
84            .and_then(|v| v.as_str())
85            .ok_or_else(|| anyhow::anyhow!("Missing 'fact' parameter"))?;
86
87        let category = args
88            .get("category")
89            .and_then(|v| v.as_str())
90            .ok_or_else(|| anyhow::anyhow!("Missing 'category' parameter"))?;
91
92        #[allow(clippy::cast_possible_truncation)]
93        let confidence = args
94            .get("confidence")
95            .and_then(|v| v.as_f64())
96            .map_or(0.9, |v| v as f32);
97
98        let scope = args
99            .get("scope")
100            .and_then(|v| v.as_str())
101            .unwrap_or("project");
102
103        let namespace = match scope {
104            "core" => {
105                if let Some(ref ns) = self.core_namespace {
106                    ns.clone()
107                } else {
108                    return Ok(ToolResult {
109                        success: false,
110                        output: String::new(),
111                        error: Some("No core namespace available (no role assigned). Use 'project' or 'shared' scope instead.".into()),
112                    });
113                }
114            }
115            "shared" => self.shared_namespace.clone(),
116            _ => self.role_namespace.clone(),
117        };
118
119        let scope_label = match scope {
120            "core" => "core",
121            "shared" => "shared",
122            _ => "project",
123        };
124
125        match self
126            .memory
127            .store_item(&namespace, fact, category, confidence, None)
128            .await
129        {
130            Ok(id) => Ok(ToolResult {
131                success: true,
132                output: format!("Stored {scope_label} fact in '{category}' (id: {id})"),
133                error: None,
134            }),
135            Err(e) => Ok(ToolResult {
136                success: false,
137                output: String::new(),
138                error: Some(format!("Failed to store memory: {e}")),
139            }),
140        }
141    }
142}