1use std::sync::Arc;
4
5use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result, Tool, ToolContext, ToolEffect};
6use async_trait::async_trait;
7use serde_json::{Value, json};
8
9use crate::audit::HarnessAudit;
10use crate::facts::runtime::FactsRuntime;
11use crate::facts::writer::{AdmitContext, Admitted, FactCandidate};
12use crate::facts::{FactKind, FactStatus, MemoryFact};
13use crate::mode::HarnessMode;
14use crate::policy::has_harness_layer;
15
16pub(crate) const REMEMBER_CONFIDENCE: f32 = 0.5;
18pub(crate) const SEARCH_MAX: usize = 20;
20
21fn unavailable(message: &str) -> AdkError {
22 AdkError::new(
23 ErrorComponent::Tool,
24 ErrorCategory::Forbidden,
25 "harness.memory.unavailable",
26 message,
27 )
28}
29
30fn invalid(message: impl Into<String>) -> AdkError {
31 AdkError::new(
32 ErrorComponent::Tool,
33 ErrorCategory::InvalidInput,
34 "harness.memory.invalid_args",
35 message,
36 )
37}
38
39pub(crate) fn describe(fact: &MemoryFact) -> Value {
40 json!({
41 "id": fact.id,
42 "status": fact.status.label(),
43 "kind": fact.kind.as_str(),
44 "text": fact.text,
45 "source": fact.provenance.source.as_str(),
46 "since": fact.valid_from.format("%Y-%m-%d").to_string(),
47 "scope": if fact.scope.project.is_some() { "project" } else { "user" },
48 })
49}
50
51pub struct MemorySearchTool {
62 facts: Arc<FactsRuntime>,
63}
64
65impl MemorySearchTool {
66 pub(crate) fn new(facts: Arc<FactsRuntime>) -> Self {
67 Self { facts }
68 }
69}
70
71#[async_trait]
72impl Tool for MemorySearchTool {
73 fn name(&self) -> &str {
74 "memory_search"
75 }
76
77 fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
79 adk_core::egress::ToolEgress::Configured
80 }
81
82 fn description(&self) -> &str {
83 "Search what you remember about this user and project from earlier sessions: \
84 preferences, how the project builds and tests, what fixed past failures, decisions. \
85 known facts were stated by the user; assumed facts are inferences to check."
86 }
87
88 fn parameters_schema(&self) -> Option<Value> {
89 Some(json!({
90 "type": "object",
91 "properties": {
92 "query": { "type": "string", "description": "What to look for." },
93 "kind": { "type": "string", "enum": ["preference", "project_fact", "procedure", "outcome", "decision", "correction"], "description": "Only facts of this kind." },
94 "limit": { "type": "integer", "minimum": 1, "maximum": SEARCH_MAX, "description": "Most facts to return (default 8)." }
95 },
96 "required": ["query"]
97 }))
98 }
99
100 fn is_read_only(&self) -> bool {
101 true
102 }
103
104 fn is_concurrency_safe(&self) -> bool {
105 true
106 }
107
108 fn effect(&self) -> ToolEffect {
109 ToolEffect::ReadOnly
110 }
111
112 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
113 if !self.facts.serves(ctx.as_ref()) {
114 return Err(unavailable(
115 "long-term memory serves the harness's own agent for an authenticated user; \
116 ask the coordinator for what you need",
117 ));
118 }
119 let query = args
120 .get("query")
121 .and_then(Value::as_str)
122 .ok_or_else(|| invalid("memory_search needs a string 'query'"))?;
123 let kind = match args.get("kind").and_then(Value::as_str) {
124 Some(kind) => Some(kind.parse::<FactKind>()?),
125 None => None,
126 };
127 let limit = args
128 .get("limit")
129 .and_then(Value::as_u64)
130 .map_or(self.facts.config.recall_limit, |limit| limit as usize)
131 .clamp(1, SEARCH_MAX);
132 let scope = self.facts.scope(ctx.app_name(), ctx.user_id());
133 let recalled = self.facts.recall(&scope, query, kind, limit, None).await?;
134 let audit = HarnessAudit::for_tool(ctx.as_ref());
135 self.facts.record_recalled(audit.as_ref(), &recalled, query).await?;
136 Ok(json!({
137 "facts": recalled.facts.iter().map(|(fact, _)| describe(fact)).collect::<Vec<_>>(),
138 }))
139 }
140}
141
142pub struct MemoryRememberTool {
162 facts: Arc<FactsRuntime>,
163}
164
165impl MemoryRememberTool {
166 pub(crate) fn new(facts: Arc<FactsRuntime>) -> Self {
167 Self { facts }
168 }
169}
170
171#[async_trait]
172impl Tool for MemoryRememberTool {
173 fn name(&self) -> &str {
174 "memory_remember"
175 }
176
177 fn egress(&self, _args: &serde_json::Value) -> adk_core::egress::ToolEgress {
179 adk_core::egress::ToolEgress::Configured
180 }
181
182 fn description(&self) -> &str {
183 "Remember a fact for later sessions with this user: a preference, how this project \
184 builds or tests, what fixed a failure, a decision. When the user stated it outright \
185 in this conversation, copy their exact words into 'quote': the fact is then kept as \
186 the user's own words. Anything else is kept as an assumption until the user \
187 confirms it. Keep it to one short, self-contained fact; never secrets."
188 }
189
190 fn parameters_schema(&self) -> Option<Value> {
191 Some(json!({
192 "type": "object",
193 "properties": {
194 "text": { "type": "string", "description": "One fact, at most 500 characters." },
195 "kind": { "type": "string", "enum": ["preference", "project_fact", "procedure", "outcome", "decision", "correction"] },
196 "quote": { "type": "string", "description": "The user's own words, copied verbatim from one of their messages in this conversation, when they stated the fact outright. Leave it out for anything inferred or read elsewhere." },
197 "supersedes": { "type": "string", "description": "Id of an assumed fact this one replaces." }
198 },
199 "required": ["text", "kind"]
200 }))
201 }
202
203 fn effect(&self) -> ToolEffect {
204 ToolEffect::Idempotent
205 }
206
207 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
208 let governed = ctx
209 .run_config()
210 .and_then(|config| config.tool_policy.as_deref())
211 .is_some_and(has_harness_layer);
212 if !governed {
213 return Err(AdkError::new(
214 ErrorComponent::Tool,
215 ErrorCategory::Forbidden,
216 "harness.memory.ungoverned",
217 "memory_remember runs only inside a harness run, under the harness policy",
218 ));
219 }
220 if !self.facts.serves(ctx.as_ref()) {
221 return Err(unavailable(
222 "long-term memory serves the harness's own agent for an authenticated user; \
223 tell the coordinator what is worth remembering",
224 ));
225 }
226 let mode = self.facts.mode(ctx.app_name(), ctx.user_id(), ctx.session_id()).await;
228 if matches!(mode, HarnessMode::ReadOnly | HarnessMode::Plan) {
229 return Err(unavailable("read-only and plan modes write no facts"));
230 }
231 let text = args
232 .get("text")
233 .and_then(Value::as_str)
234 .ok_or_else(|| invalid("memory_remember needs a string 'text'"))?;
235 let kind = args
236 .get("kind")
237 .and_then(Value::as_str)
238 .ok_or_else(|| invalid("memory_remember needs a string 'kind'"))?;
239 let quote =
240 args.get("quote").and_then(Value::as_str).filter(|quote| !quote.trim().is_empty());
241 let candidate = FactCandidate {
242 text: text.to_string(),
243 kind: kind.to_string(),
244 source: Some("agent_inferred".to_string()),
245 quote: quote.map(str::to_string),
246 confidence: Some(REMEMBER_CONFIDENCE),
247 supersedes: args.get("supersedes").and_then(Value::as_str).map(str::to_string),
248 };
249 #[cfg(feature = "runner")]
252 let said = match quote {
253 Some(_) => {
254 self.facts.person_messages(ctx.app_name(), ctx.user_id(), ctx.session_id()).await
255 }
256 None => Vec::new(),
257 };
258 #[cfg(not(feature = "runner"))]
259 let said: Vec<crate::facts::writer::UserMessage> = Vec::new();
260 let run_id = ctx.run_config().and_then(|config| config.durable_run_id.clone());
261 let context = AdmitContext {
262 app: ctx.app_name(),
263 user: ctx.user_id(),
264 session_id: ctx.session_id(),
265 invocation_id: ctx.invocation_id(),
266 run_id,
267 user_messages: &said,
268 audit: HarnessAudit::for_tool(ctx.as_ref()),
269 tick: None,
270 };
271 let answer = |fact: &MemoryFact, already: bool| {
272 let mut answer = json!({ "remembered": describe(fact) });
273 if already {
274 answer["alreadyKnown"] = json!(true);
275 }
276 if quote.is_some() && fact.status != FactStatus::Known {
277 answer["note"] = json!(
278 "the quote was not found verbatim in the user's own messages in this \
279 conversation, or shares no word with the fact, so the fact is kept as an \
280 assumption"
281 );
282 }
283 answer
284 };
285 match self.facts.admit(&candidate, &context).await? {
286 Admitted::Stored(fact) => Ok(answer(&fact, false)),
287 Admitted::Duplicate(fact) => Ok(answer(&fact, true)),
288 Admitted::Rejected { reason, .. } => {
290 Ok(json!({ "error": format!("the fact was not remembered: {reason}") }))
291 }
292 }
293 }
294}