1use std::collections::{HashMap, HashSet};
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::{Arc, Mutex};
8
9use aidaemon_core::{Hook, HookContext, Message, ModelRequest, Service, Tool};
10use async_trait::async_trait;
11
12use crate::{insert_after_system, last_user_message_index};
13
14#[async_trait]
24pub trait MemorySystem: Send + Sync {
25 async fn turn(&self, turn: &MemoryTurn) -> MemoryParts;
27
28 fn guidance(&self) -> Option<String> {
32 None
33 }
34
35 async fn absorb_history(&self, _messages: &[PastMessage]) -> Result<HistoryIntake, String> {
40 Ok(HistoryIntake::NotSupported)
41 }
42
43 fn services(&self) -> Vec<Arc<dyn Service>> {
46 Vec::new()
47 }
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum PastRole {
53 User,
54 Assistant,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct PastMessage {
60 pub session_id: String,
61 pub scope: String,
63 pub role: PastRole,
64 pub text: String,
65 pub at: String,
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum HistoryIntake {
72 Absorbed,
73 NotSupported,
75}
76
77#[derive(Debug, Clone, PartialEq, Eq)]
79pub struct MemoryTurn {
80 pub session_id: String,
82 pub scope: String,
86 pub read: bool,
88 pub write: bool,
90 pub explicit_writes_only: bool,
93 pub learning: TurnLearning,
97 pub project: Option<aidaemon_core::ProjectRef>,
105 pub host: HostTurn,
108}
109
110impl MemoryTurn {
111 pub fn owner(session_id: impl Into<String>) -> Self {
114 Self {
115 session_id: session_id.into(),
116 scope: "owner".to_string(),
117 read: true,
118 write: true,
119 explicit_writes_only: false,
120 learning: Default::default(),
121 project: None,
122 host: Default::default(),
123 }
124 }
125}
126
127#[derive(Clone, Default)]
133pub struct HostTurn(Option<Arc<dyn std::any::Any + Send + Sync>>);
134
135impl HostTurn {
136 pub fn new<T: std::any::Any + Send + Sync>(facts: T) -> Self {
137 Self(Some(Arc::new(facts)))
138 }
139
140 pub fn get<T: std::any::Any>(&self) -> Option<&T> {
142 self.0.as_deref().and_then(|facts| facts.downcast_ref())
143 }
144}
145
146impl std::fmt::Debug for HostTurn {
147 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148 f.write_str(if self.0.is_some() {
149 "HostTurn(..)"
150 } else {
151 "HostTurn(none)"
152 })
153 }
154}
155
156impl PartialEq for HostTurn {
157 fn eq(&self, _other: &Self) -> bool {
158 true
159 }
160}
161
162impl Eq for HostTurn {}
163
164#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
166pub enum Learning {
167 #[default]
168 Allowed,
169 OptedOut,
174}
175
176#[derive(Clone, Default)]
182pub struct TurnLearning(Arc<AtomicBool>);
183
184impl TurnLearning {
185 pub fn new(learning: Learning) -> Self {
186 let handle = Self::default();
187 if learning == Learning::OptedOut {
188 handle.opt_out();
189 }
190 handle
191 }
192
193 pub fn get(&self) -> Learning {
194 if self.0.load(Ordering::Acquire) {
195 Learning::OptedOut
196 } else {
197 Learning::Allowed
198 }
199 }
200
201 pub fn allowed(&self) -> bool {
202 self.get() == Learning::Allowed
203 }
204
205 pub fn opt_out(&self) -> bool {
207 !self.0.swap(true, Ordering::AcqRel)
208 }
209}
210
211impl std::fmt::Debug for TurnLearning {
212 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213 f.debug_tuple("TurnLearning").field(&self.get()).finish()
214 }
215}
216
217impl PartialEq for TurnLearning {
219 fn eq(&self, other: &Self) -> bool {
220 self.get() == other.get()
221 }
222}
223
224impl Eq for TurnLearning {}
225
226#[derive(Default)]
228pub struct MemoryParts {
229 pub hooks: Vec<Arc<dyn Hook>>,
230 pub tools: Vec<Arc<dyn Tool>>,
231}
232
233impl std::fmt::Debug for MemoryParts {
234 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235 f.debug_struct("MemoryParts")
236 .field("hooks", &self.hooks.len())
237 .field(
238 "tools",
239 &self
240 .tools
241 .iter()
242 .map(|tool| tool.spec().name)
243 .collect::<Vec<_>>(),
244 )
245 .finish()
246 }
247}
248
249#[async_trait]
251pub trait Recall: Send + Sync {
252 async fn recall(&self, session_id: &str, query: &str, limit: usize) -> Vec<String>;
253
254 async fn render(&self, session_id: &str, query: &str, limit: usize) -> Option<String> {
259 let snippets = self.recall(session_id, query, limit).await;
260 if snippets.is_empty() {
261 return None;
262 }
263 let mut note = String::from(
264 "[Recalled memory — background that may be outdated or irrelevant. Use it only if it \
265 helps with the current request, and prefer what the user says now.]",
266 );
267 for snippet in snippets.iter().take(limit) {
268 note.push_str("\n- ");
269 note.push_str(snippet.trim());
270 }
271 Some(note)
272 }
273}
274
275pub struct MemoryInjection<R: Recall> {
283 recall: R,
284 limit: usize,
285 cache: Mutex<HashMap<String, (String, Option<String>)>>,
286}
287
288impl<R: Recall> MemoryInjection<R> {
289 pub fn new(recall: R) -> Self {
290 Self {
291 recall,
292 limit: 5,
293 cache: Mutex::new(HashMap::new()),
294 }
295 }
296
297 pub fn limit(mut self, limit: usize) -> Self {
298 self.limit = limit;
299 self
300 }
301
302 pub fn backend(&self) -> &R {
303 &self.recall
304 }
305
306 async fn note(&self, session_id: &str, query: &str) -> Option<String> {
307 if let Some((cached_query, note)) = self
308 .cache
309 .lock()
310 .ok()
311 .and_then(|c| c.get(session_id).cloned())
312 && cached_query == query
313 {
314 return note;
315 }
316 let note = self.recall.render(session_id, query, self.limit).await;
317 if let Ok(mut cache) = self.cache.lock() {
318 cache.insert(session_id.to_string(), (query.to_string(), note.clone()));
319 }
320 note
321 }
322}
323
324#[async_trait]
325impl<R: Recall> Hook for MemoryInjection<R> {
326 async fn before_model(&self, ctx: &HookContext<'_>, request: &mut ModelRequest) {
327 let Some(index) = last_user_message_index(ctx.messages) else {
328 return;
329 };
330 let query = ctx.messages[index].content.clone();
331 if let Some(note) = self.note(ctx.session_id, &query).await {
332 insert_after_system(&mut request.messages, Message::hook_note(note));
333 }
334 }
335}
336
337#[derive(Default)]
340pub struct InMemoryRecall {
341 entries: Mutex<Vec<(Option<String>, String)>>,
342 queries: Mutex<u32>,
343}
344
345impl InMemoryRecall {
346 pub fn new() -> Self {
347 Self::default()
348 }
349
350 pub fn remember(&self, session_id: &str, text: impl Into<String>) {
352 if let Ok(mut e) = self.entries.lock() {
353 e.push((Some(session_id.to_string()), text.into()));
354 }
355 }
356
357 pub fn remember_global(&self, text: impl Into<String>) {
359 if let Ok(mut e) = self.entries.lock() {
360 e.push((None, text.into()));
361 }
362 }
363
364 pub fn query_count(&self) -> u32 {
366 self.queries.lock().map(|q| *q).unwrap_or(0)
367 }
368}
369
370fn words(text: &str) -> HashSet<String> {
371 text.split(|c: char| !c.is_alphanumeric())
372 .filter(|w| w.chars().count() >= 3)
373 .map(str::to_lowercase)
374 .collect()
375}
376
377#[async_trait]
378impl Recall for InMemoryRecall {
379 async fn recall(&self, session_id: &str, query: &str, limit: usize) -> Vec<String> {
380 if let Ok(mut q) = self.queries.lock() {
381 *q += 1;
382 }
383 let query_words = words(query);
384 let entries = self.entries.lock().map(|e| e.clone()).unwrap_or_default();
385 let mut scored: Vec<(usize, usize, String)> = entries
386 .into_iter()
387 .enumerate()
388 .filter(|(_, (session, _))| session.as_deref().is_none_or(|s| s == session_id))
389 .map(|(i, (_, text))| (words(&text).intersection(&query_words).count(), i, text))
390 .filter(|(score, _, _)| *score > 0)
391 .collect();
392 scored.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
393 scored.into_iter().take(limit).map(|(_, _, t)| t).collect()
394 }
395}
396
397#[cfg(test)]
398mod tests {
399 use super::*;
400
401 #[test]
402 fn opting_out_is_shared_by_every_holder_of_the_turn() {
403 let host = TurnLearning::default();
404 let system = host.clone();
405 assert_eq!(system.get(), Learning::Allowed);
406 assert!(host.opt_out());
407 assert!(!host.opt_out(), "already opted out");
408 assert_eq!(system.get(), Learning::OptedOut);
409 assert!(!system.allowed());
410 assert!(!TurnLearning::new(Learning::OptedOut).allowed());
411 }
412
413 #[tokio::test]
414 async fn word_overlap_ranks_and_scopes_by_session() {
415 let recall = InMemoryRecall::new();
416 recall.remember(
417 "telegram:synthetic-user-1",
418 "Alice Rivera prefers window seats",
419 );
420 recall.remember(
421 "telegram:synthetic-user-1",
422 "Alice Rivera's daughters are Mia and Zoe",
423 );
424 recall.remember(
425 "telegram:synthetic-user-2",
426 "Jordan Lee prefers aisle seats",
427 );
428 recall.remember_global("Acme Corp travel policy requires economy seats");
429
430 let got = recall
431 .recall("telegram:synthetic-user-1", "Book seats for Alice", 5)
432 .await;
433 assert_eq!(got[0], "Alice Rivera prefers window seats");
434 assert!(got.contains(&"Acme Corp travel policy requires economy seats".to_string()));
435 assert!(!got.iter().any(|s| s.contains("Jordan")));
436 assert!(
437 recall
438 .recall("telegram:synthetic-user-1", "zzz", 5)
439 .await
440 .is_empty()
441 );
442 }
443}