Skip to main content

adk_harness/tools/
memory.rs

1//! `memory_read`, `memory_write` and `memory_delete` (spec 3.1 §7.15).
2
3use std::collections::HashMap;
4use std::path::PathBuf;
5use std::sync::{Arc, Mutex};
6
7use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result, Tool, ToolContext, ToolEffect};
8use async_trait::async_trait;
9use serde_json::{Value, json};
10
11use crate::audit::HarnessAudit;
12use crate::memory::{FileMemory, MemoryChange, MemoryConfig};
13use crate::policy::has_harness_layer;
14
15/// Opens the memory of the user a call runs for, one [`FileMemory`] per (app, user).
16#[derive(Debug)]
17pub(crate) struct MemoryResolver {
18    config: MemoryConfig,
19    workspace_root: PathBuf,
20    open: Mutex<HashMap<(String, String), FileMemory>>,
21}
22
23impl MemoryResolver {
24    pub(crate) fn new(config: MemoryConfig, workspace_root: PathBuf) -> Arc<Self> {
25        Arc::new(Self { config, workspace_root, open: Mutex::new(HashMap::new()) })
26    }
27
28    /// The memory of `user` of `app`.
29    pub(crate) fn memory(&self, app: &str, user: &str) -> Result<FileMemory> {
30        let key = (app.to_string(), user.to_string());
31        let mut open = self.open.lock().unwrap_or_else(|e| e.into_inner());
32        if let Some(memory) = open.get(&key) {
33            return Ok(memory.clone());
34        }
35        let memory = FileMemory::for_user(&self.config, app, user, &self.workspace_root)?;
36        if open.len() > 1024 {
37            open.clear();
38        }
39        open.insert(key, memory.clone());
40        Ok(memory)
41    }
42
43    /// `instruction` with the memory index of the run's user appended, inside its
44    /// delimited block (spec 3.1 §7.7 item 6). An unreadable memory adds nothing.
45    pub(crate) async fn append_index(
46        &self,
47        instruction: String,
48        ctx: &dyn adk_core::ReadonlyContext,
49    ) -> String {
50        let index = match self.memory(ctx.app_name(), ctx.user_id()) {
51            Ok(memory) => memory.index().await,
52            Err(error) => Err(error),
53        };
54        match index {
55            Ok(index) => format!("{instruction}\n\n{}", crate::memory::instruction_block(&index)),
56            Err(error) => {
57                tracing::warn!(error = %error, "memory index unavailable; the instruction carries none");
58                instruction
59            }
60        }
61    }
62}
63
64fn required<'a>(args: &'a Value, key: &str, tool: &str) -> Result<&'a str> {
65    args.get(key).and_then(Value::as_str).ok_or_else(|| {
66        AdkError::new(
67            ErrorComponent::Tool,
68            ErrorCategory::InvalidInput,
69            "harness.memory.invalid_args",
70            format!("{tool} needs a string '{key}'"),
71        )
72    })
73}
74
75/// Refuses a memory write outside a harness run: the write is non-waivable, so it must
76/// have passed the harness policy (spec 3.1 §9.2 I17, I33).
77fn require_harness_run(ctx: &dyn ToolContext, tool: &str) -> Result<()> {
78    let governed = ctx
79        .run_config()
80        .and_then(|config| config.tool_policy.as_deref())
81        .is_some_and(has_harness_layer);
82    if governed {
83        return Ok(());
84    }
85    Err(AdkError::new(
86        ErrorComponent::Tool,
87        ErrorCategory::Forbidden,
88        "harness.memory.ungoverned",
89        format!("{tool} runs only inside a harness run, under the harness policy"),
90    ))
91}
92
93/// Records `harness.memory.written` before the change is made (spec 3.1 §9.3).
94async fn record_change(ctx: &dyn ToolContext, change: &MemoryChange) -> Result<()> {
95    let Some(audit) = HarnessAudit::for_tool(ctx) else {
96        return Ok(());
97    };
98    audit
99        .record(
100            "harness.memory.written",
101            json!({
102                "logicalPath": change.path,
103                "beforeSha256": change.before_sha256,
104                "afterSha256": change.after_sha256,
105                "bytes": change.bytes,
106                "functionCallId": ctx.function_call_id(),
107            }),
108        )
109        .await
110}
111
112/// `memory_read`: the memory index, or one topic (spec 3.1 §7.15; class `Read`).
113///
114/// # Example
115///
116/// ```text
117/// // memory_read {}                      → the index
118/// // memory_read { "path": "build.md" }  → the topic's content
119/// ```
120pub struct MemoryReadTool {
121    resolver: Arc<MemoryResolver>,
122}
123
124impl MemoryReadTool {
125    pub(crate) fn new(resolver: Arc<MemoryResolver>) -> Self {
126        Self { resolver }
127    }
128}
129
130#[async_trait]
131impl Tool for MemoryReadTool {
132    fn name(&self) -> &str {
133        "memory_read"
134    }
135
136    /// Reaches only the memory store the harness was built with.
137    fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
138        adk_core::egress::ToolEgress::Configured
139    }
140
141    fn description(&self) -> &str {
142        "Read your memory from earlier sessions: without a path, the index of topics with \
143         their summaries; with a path, that topic's content."
144    }
145
146    fn parameters_schema(&self) -> Option<Value> {
147        Some(json!({
148            "type": "object",
149            "properties": {
150                "path": { "type": "string", "description": "Topic path from the index, such as 'build.md'. Omit it for the index." }
151            }
152        }))
153    }
154
155    fn is_read_only(&self) -> bool {
156        true
157    }
158
159    fn is_concurrency_safe(&self) -> bool {
160        true
161    }
162
163    fn effect(&self) -> ToolEffect {
164        ToolEffect::ReadOnly
165    }
166
167    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
168        let memory = self.resolver.memory(ctx.app_name(), ctx.user_id())?;
169        match args.get("path").and_then(Value::as_str) {
170            Some(path) => Ok(json!({ "path": path, "content": memory.read(path).await? })),
171            None => Ok(json!({ "index": memory.index().await? })),
172        }
173    }
174}
175
176/// `memory_write`: writes one topic (spec 3.1 §7.15; class `MemoryWrite`, a non-waivable
177/// approval in Ask and Auto, denied in ReadOnly and Plan).
178///
179/// # Example
180///
181/// ```text
182/// // memory_write { "path": "build.md", "summary": "how to build", "content": "cargo build" }
183/// ```
184pub struct MemoryWriteTool {
185    resolver: Arc<MemoryResolver>,
186}
187
188impl MemoryWriteTool {
189    pub(crate) fn new(resolver: Arc<MemoryResolver>) -> Self {
190        Self { resolver }
191    }
192}
193
194#[async_trait]
195impl Tool for MemoryWriteTool {
196    fn name(&self) -> &str {
197        "memory_write"
198    }
199
200    /// Reaches only the memory store the harness was built with.
201    fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
202        adk_core::egress::ToolEgress::Configured
203    }
204
205    fn description(&self) -> &str {
206        "Save something worth remembering in later sessions with this user in this \
207         workspace, as one topic file with a one-line summary. Replaces the topic if it \
208         exists. The user approves every write."
209    }
210
211    fn parameters_schema(&self) -> Option<Value> {
212        Some(json!({
213            "type": "object",
214            "properties": {
215                "path": { "type": "string", "description": "Topic path, such as 'build.md' or 'ci/flaky-tests.md'." },
216                "summary": { "type": "string", "description": "One line that says what the topic holds; it appears in the index." },
217                "content": { "type": "string", "description": "The topic's full content, in Markdown." }
218            },
219            "required": ["path", "summary", "content"]
220        }))
221    }
222
223    fn effect(&self) -> ToolEffect {
224        ToolEffect::Idempotent
225    }
226
227    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
228        require_harness_run(ctx.as_ref(), "memory_write")?;
229        let path = required(&args, "path", "memory_write")?;
230        let summary = required(&args, "summary", "memory_write")?;
231        let content = required(&args, "content", "memory_write")?;
232        let memory = self.resolver.memory(ctx.app_name(), ctx.user_id())?;
233        let planned = memory.plan_write(path, content, summary).await?;
234        record_change(ctx.as_ref(), &planned).await?;
235        let change = memory.write(path, content, summary).await?;
236        Ok(
237            json!({ "path": change.path, "bytes": change.bytes, "created": change.before_sha256.is_none() }),
238        )
239    }
240}
241
242/// `memory_delete`: deletes one topic (spec 3.1 §7.15; class `MemoryWrite`).
243///
244/// # Example
245///
246/// ```text
247/// // memory_delete { "path": "build.md" }
248/// ```
249pub struct MemoryDeleteTool {
250    resolver: Arc<MemoryResolver>,
251}
252
253impl MemoryDeleteTool {
254    pub(crate) fn new(resolver: Arc<MemoryResolver>) -> Self {
255        Self { resolver }
256    }
257}
258
259#[async_trait]
260impl Tool for MemoryDeleteTool {
261    fn name(&self) -> &str {
262        "memory_delete"
263    }
264
265    /// Reaches only the memory store the harness was built with.
266    fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
267        adk_core::egress::ToolEgress::Configured
268    }
269
270    fn description(&self) -> &str {
271        "Delete a memory topic that is wrong or no longer useful. The user approves every delete."
272    }
273
274    fn parameters_schema(&self) -> Option<Value> {
275        Some(json!({
276            "type": "object",
277            "properties": {
278                "path": { "type": "string", "description": "Topic path from the index." }
279            },
280            "required": ["path"]
281        }))
282    }
283
284    fn effect(&self) -> ToolEffect {
285        ToolEffect::Idempotent
286    }
287
288    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
289        require_harness_run(ctx.as_ref(), "memory_delete")?;
290        let path = required(&args, "path", "memory_delete")?;
291        let memory = self.resolver.memory(ctx.app_name(), ctx.user_id())?;
292        let planned = memory.plan_delete(path).await?;
293        if planned.before_sha256.is_some() {
294            record_change(ctx.as_ref(), &planned).await?;
295        }
296        let change = memory.delete(path).await?;
297        Ok(json!({ "path": change.path, "deleted": change.before_sha256.is_some() }))
298    }
299}