Skip to main content

aidaemon_memory/full/
system.rs

1//! [`FullMemory`]: the full memory system as an
2//! `aidaemon_policies::MemorySystem`.
3
4use std::sync::Arc;
5
6use aidaemon_core::{ChannelVisibility, Hook, Provider, Service, Tool};
7use aidaemon_policies::{MemoryInjection, MemoryParts, MemorySystem, MemoryTurn};
8use aidaemon_tools::services::SettingsStore;
9use async_trait::async_trait;
10
11use super::jobs::{JobCall, JobsHost, MemoryJobs};
12use super::recall::{
13    FullRecall, RecallHost, RecallSettings, RecallSource, RecallTurn, SpeculativeRecall,
14};
15use super::tools;
16use super::transcript::{TranscriptLog, TranscriptRecorder};
17use crate::render::RecallGoal;
18use crate::stores::MemoryStores;
19
20/// The host's facts about one turn, given to [`FullMemory`] as the turn's
21/// [`HostTurn`](aidaemon_policies::HostTurn). Without them the system works
22/// from the [`MemoryTurn`] alone: the `"owner"` scope is the owner's private
23/// chat, any other a private group, with no goals and people off.
24#[derive(Clone)]
25pub struct FullTurn {
26    pub recall: RecallTurn,
27    pub host: Arc<dyn RecallHost>,
28    /// Further run hooks the host adds with this memory (its run-end
29    /// writer).
30    pub hooks: Vec<Arc<dyn Hook>>,
31}
32
33/// The full memory system over the memory stores: per turn, the memory
34/// block injected into the request (see [`FullRecall`]) and, on a turn that
35/// may read or write memory, its tools.
36pub struct FullMemory {
37    recall: Arc<RecallSource>,
38    tools: Vec<Arc<dyn Tool>>,
39    /// Its background jobs, when it runs them.
40    jobs: Option<Arc<MemoryJobs>>,
41    /// Records owner turns for the jobs, when the host keeps no log.
42    recorder: Option<Arc<TranscriptRecorder>>,
43    /// What [`FullMemory::open`] opened, for [`FullMemory::with_background`].
44    opened: Option<Opened>,
45    /// Recall started when a session's latest message arrived
46    /// ([`FullMemory::speculate`]), waiting for that turn.
47    speculative: std::sync::Mutex<std::collections::HashMap<String, SpeculativeRecall>>,
48    /// The store its tools write, for the per-turn `remember_fact` of a turn
49    /// that works in a project ([`FullMemory::with_project_notes`]).
50    store: Option<Arc<dyn MemoryStores>>,
51    /// Project memory, when on.
52    project_notes: Option<Arc<crate::project::ProjectNotes>>,
53}
54
55struct Opened {
56    pool: sqlx::SqlitePool,
57    store: Arc<dyn MemoryStores>,
58    embedder: Arc<dyn crate::Embedder>,
59}
60
61/// One provider and model for every background call.
62struct OneModel {
63    provider: Arc<dyn Provider>,
64    model: String,
65}
66
67#[async_trait]
68impl JobsHost for OneModel {
69    fn model(&self, _call: JobCall) -> (Arc<dyn Provider>, String) {
70        (self.provider.clone(), self.model.clone())
71    }
72}
73
74impl FullMemory {
75    /// Recall only. A host that offers the memory tools through its own
76    /// dispatcher (see [`tools::outcome_tools`]) starts here.
77    pub fn new(recall: Arc<RecallSource>) -> Self {
78        Self {
79            recall,
80            tools: Vec::new(),
81            jobs: None,
82            recorder: None,
83            opened: None,
84            speculative: std::sync::Mutex::default(),
85            store: None,
86            project_notes: None,
87        }
88    }
89
90    /// Keep what a turn that works in a project learns about it in `notes`
91    /// (see [`crate::project`]): recall shows the project's notes, and the
92    /// turn's `remember_fact` writes project facts there instead of in the
93    /// fact store. A turn without a project is unaffected. For a system
94    /// from [`FullMemory::open`] or [`FullMemory::over`]; one built from a
95    /// shared [`RecallSource`] gives the notes to that source with
96    /// [`RecallSource::with_project_notes`] instead.
97    pub fn with_project_notes(mut self, notes: Arc<crate::project::ProjectNotes>) -> Self {
98        match Arc::get_mut(&mut self.recall) {
99            Some(source) => source.set_project_notes(notes.clone()),
100            None => tracing::warn!(
101                "FullMemory::with_project_notes: the recall source is shared; \
102                 give it the notes with RecallSource::with_project_notes"
103            ),
104        }
105        self.project_notes = Some(notes);
106        self
107    }
108
109    /// Starts recall for a message as it arrives, before its turn's memory
110    /// policy is settled, so the turn's first model call finds the block
111    /// ready. Nothing is written and nothing reaches a turn unless that
112    /// turn may read memory and recalls for exactly these inputs; a newer
113    /// message in the session replaces (and stops) an unclaimed one.
114    pub fn speculate(&self, turn: RecallTurn, host: Arc<dyn RecallHost>) {
115        let Some(speculative) = SpeculativeRecall::start(self.recall.clone(), host, turn) else {
116            return;
117        };
118        if let Ok(mut pending) = self.speculative.lock() {
119            pending.insert(speculative.session_id().to_string(), speculative);
120        }
121    }
122
123    /// The session's speculative recall, when it is `turn`'s block. One
124    /// that is not is dropped, which stops it.
125    fn claim_speculative(&self, turn: &RecallTurn) -> Option<SpeculativeRecall> {
126        let speculative = self.speculative.lock().ok()?.remove(&turn.session_id)?;
127        let serves = speculative.serves(turn);
128        tracing::info!(
129            session_id = %turn.session_id,
130            adopted = serves,
131            "Speculative recall claimed"
132        );
133        serves.then_some(speculative)
134    }
135
136    /// Run `jobs` as this system's [`services`](MemorySystem::services).
137    pub fn with_jobs(mut self, jobs: Arc<MemoryJobs>) -> Self {
138        self.jobs = Some(jobs);
139        self
140    }
141
142    /// For a system from [`FullMemory::open`]: record the owner's turns in
143    /// the memory database ([`TranscriptLog`]) and run the background jobs
144    /// over them, their model calls on `provider` with `model`. A system
145    /// built another way is returned as it is.
146    pub async fn with_background(
147        mut self,
148        provider: Arc<dyn Provider>,
149        model: impl Into<String>,
150    ) -> anyhow::Result<Self> {
151        let Some(opened) = &self.opened else {
152            return Ok(self);
153        };
154        let log = Arc::new(TranscriptLog::open(opened.pool.clone()).await?);
155        self.recorder = Some(Arc::new(log.recorder()));
156        let host = Arc::new(OneModel {
157            provider,
158            model: model.into(),
159        });
160        let jobs = MemoryJobs::new(opened.store.clone(), log, host, opened.embedder.clone());
161        self.jobs = Some(Arc::new(jobs));
162        Ok(self)
163    }
164
165    /// Its background jobs, when it runs them.
166    pub fn jobs(&self) -> Option<&Arc<MemoryJobs>> {
167        self.jobs.as_ref()
168    }
169
170    /// The whole system over `store`: recall with `settings`, and the four
171    /// memory tools ([`tools::kernel_tools`]). `host_settings` holds the
172    /// `people_enabled` switch.
173    pub fn over(
174        store: Arc<dyn MemoryStores>,
175        settings: RecallSettings,
176        host_settings: Arc<dyn SettingsStore>,
177    ) -> Self {
178        let mut system = Self::new(Arc::new(RecallSource::new(store.clone(), settings)))
179            .with_tools(tools::kernel_tools(store.clone(), host_settings));
180        system.store = Some(store);
181        system
182    }
183
184    /// The whole system in a SQLite file (created and migrated if needed),
185    /// or in a private in-memory database when `path` is `None`. Embeddings
186    /// come from `FastEmbedder` with the `fastembed` feature, else from
187    /// [`HashEmbedder`](crate::HashEmbedder); people intelligence's switch is
188    /// kept in memory ([`tools::LocalSettings`]).
189    pub async fn open(path: Option<&std::path::Path>) -> anyhow::Result<Self> {
190        use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions};
191        let pool = match path {
192            Some(path) => {
193                let options = SqliteConnectOptions::new()
194                    .filename(path)
195                    .create_if_missing(true)
196                    .journal_mode(SqliteJournalMode::Wal)
197                    .busy_timeout(std::time::Duration::from_secs(10));
198                SqlitePoolOptions::new()
199                    .max_connections(4)
200                    .connect_with(options)
201                    .await?
202            }
203            None => {
204                // One connection that never closes: the database lives in it.
205                SqlitePoolOptions::new()
206                    .max_connections(1)
207                    .min_connections(1)
208                    .idle_timeout(None)
209                    .max_lifetime(None)
210                    .connect("sqlite::memory:")
211                    .await?
212            }
213        };
214        crate::sqlite::migrate(&pool).await?;
215        #[cfg(feature = "fastembed")]
216        let embedder: Arc<dyn crate::Embedder> = Arc::new(crate::FastEmbedder::new());
217        #[cfg(not(feature = "fastembed"))]
218        let embedder: Arc<dyn crate::Embedder> = Arc::new(crate::HashEmbedder::new(384));
219        let store: Arc<dyn MemoryStores> = Arc::new(crate::sqlite::SqliteMemory::new(
220            pool.clone(),
221            embedder.clone(),
222        ));
223        let mut system = Self::over(
224            store.clone(),
225            RecallSettings {
226                max_facts: DEFAULT_MAX_FACTS,
227                assistant_name: None,
228            },
229            Arc::new(tools::LocalSettings::default()),
230        );
231        system.opened = Some(Opened {
232            pool,
233            store,
234            embedder,
235        });
236        Ok(system)
237    }
238
239    /// Offer `tools` on every turn that may read or write memory.
240    pub fn with_tools(mut self, tools: Vec<Arc<dyn Tool>>) -> Self {
241        self.tools = tools;
242        self
243    }
244}
245
246/// How many facts recall renders at most, by default (the daemon's
247/// default too).
248pub const DEFAULT_MAX_FACTS: usize = 20;
249
250/// A host with nothing of its own: no goals, people intelligence off.
251struct NoHost;
252
253#[async_trait]
254impl RecallHost for NoHost {
255    async fn active_goals(&self) -> anyhow::Result<Vec<RecallGoal>> {
256        Ok(Vec::new())
257    }
258
259    async fn people_enabled(&self) -> anyhow::Result<bool> {
260        Ok(false)
261    }
262}
263
264/// What recall knows about a turn given only the [`MemoryTurn`].
265fn plain_turn(turn: &MemoryTurn) -> RecallTurn {
266    let owner = turn.scope == "owner";
267    RecallTurn {
268        session_id: turn.session_id.clone(),
269        task_id: String::new(),
270        user_text: None,
271        owner,
272        personal: owner,
273        visibility: if owner {
274            ChannelVisibility::Private
275        } else {
276            ChannelVisibility::PrivateGroup
277        },
278        channel_id: None,
279        sender_id: None,
280        allowed: turn.read,
281        depth: usize::from(turn.explicit_writes_only),
282        project: turn.project.clone(),
283    }
284}
285
286#[async_trait]
287impl MemorySystem for FullMemory {
288    async fn turn(&self, turn: &MemoryTurn) -> MemoryParts {
289        let (recall_turn, host, extra): (RecallTurn, Arc<dyn RecallHost>, Vec<Arc<dyn Hook>>) =
290            match turn.host.get::<FullTurn>() {
291                Some(full) => (full.recall.clone(), full.host.clone(), full.hooks.clone()),
292                None => (plain_turn(turn), Arc::new(NoHost), Vec::new()),
293            };
294        // Recall starts now, beside the rest of the turn's setup; the
295        // injection hook awaits it at the first model call.
296        let recall = match self.claim_speculative(&recall_turn) {
297            Some(speculative) => {
298                FullRecall::new(self.recall.clone(), host, recall_turn).adopt(speculative)
299            }
300            None => FullRecall::new(self.recall.clone(), host, recall_turn).prefetch(),
301        };
302        let mut hooks: Vec<Arc<dyn Hook>> = vec![Arc::new(MemoryInjection::new(recall))];
303        hooks.extend(extra);
304        // Only the owner's own turns teach the jobs.
305        if let Some(recorder) = &self.recorder
306            && turn.write
307            && turn.scope == "owner"
308        {
309            hooks.push(recorder.clone());
310        }
311        let mut tools = if turn.read || turn.write {
312            self.tools.clone()
313        } else {
314            Vec::new()
315        };
316        // A turn in a project gets a `remember_fact` that knows it.
317        if let (Some(project), Some(notes), Some(store)) =
318            (&turn.project, &self.project_notes, &self.store)
319            && let Some(slot) = tools
320                .iter_mut()
321                .find(|tool| tool.spec().name == "remember_fact")
322        {
323            let tool = tools::RememberFactTool::new(store.clone())
324                .with_project_notes(notes.clone())
325                .for_project(Some(project.clone()));
326            *slot = Arc::new(aidaemon_tools::KernelAdapter::new(Arc::new(tool)));
327        }
328        MemoryParts { hooks, tools }
329    }
330
331    fn services(&self) -> Vec<Arc<dyn Service>> {
332        self.jobs
333            .as_ref()
334            .map(MemoryJobs::services)
335            .unwrap_or_default()
336    }
337}
338
339#[cfg(test)]
340mod tests {
341    use super::*;
342    use crate::sqlite::SqliteMemory;
343
344    #[tokio::test]
345    async fn an_owner_turn_recalls_its_facts_without_host_facts() {
346        let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
347        crate::sqlite::migrate(&pool).await.unwrap();
348        let store = SqliteMemory::new(pool, Arc::new(crate::HashEmbedder::new(384)));
349        crate::stores::FactStore::upsert_fact(
350            &store,
351            "preference",
352            "favorite_color",
353            "teal",
354            "user",
355            None,
356            crate::records::FactPrivacy::Global,
357        )
358        .await
359        .unwrap();
360        let source = Arc::new(RecallSource::new(
361            Arc::new(store),
362            RecallSettings {
363                max_facts: 10,
364                assistant_name: None,
365            },
366        ));
367        let turn = MemoryTurn {
368            session_id: "test:synthetic-user".into(),
369            project: None,
370            scope: "owner".into(),
371            read: true,
372            write: true,
373            explicit_writes_only: false,
374            learning: Default::default(),
375            host: Default::default(),
376        };
377        let parts = FullMemory::new(source.clone()).turn(&turn).await;
378        assert_eq!(parts.hooks.len(), 1);
379        assert!(parts.tools.is_empty());
380        let recall = FullRecall::new(source, Arc::new(NoHost), plain_turn(&turn));
381        let note = aidaemon_policies::Recall::render(
382            &recall,
383            "test:synthetic-user",
384            "what is my favorite color?",
385            5,
386        )
387        .await
388        .unwrap();
389        assert!(note.contains("teal"), "{note}");
390    }
391
392    /// A turn in a project sees its notes after the owner's own sections;
393    /// a turn without one, and a turn in another project, renders exactly
394    /// what it rendered before; and the turn's `remember_fact` writes notes.
395    #[tokio::test]
396    async fn a_project_turn_sees_its_notes_and_keeps_the_rest() {
397        use crate::project::{NoteKind, NoteSource, NoteWrite, ProjectNotes};
398        let dir = tempfile::tempdir().unwrap();
399        let notes = Arc::new(ProjectNotes::new(dir.path()));
400        let system = FullMemory::open(None)
401            .await
402            .unwrap()
403            .with_project_notes(notes.clone());
404        let store = system.store.clone().unwrap();
405        crate::stores::FactStore::upsert_fact(
406            store.as_ref(),
407            "preference",
408            "favorite_color",
409            "teal",
410            "user",
411            None,
412            crate::records::FactPrivacy::Global,
413        )
414        .await
415        .unwrap();
416        let project = aidaemon_core::ProjectRef::new("project-a", "Acme Site", None).unwrap();
417        let other = aidaemon_core::ProjectRef::new("project-b", "Other", None).unwrap();
418        notes
419            .write(
420                &project,
421                &NoteWrite {
422                    kind: NoteKind::Fact,
423                    key: "test_command".into(),
424                    category: Some("technical".into()),
425                    description: None,
426                    body: "Tests run with make test.".into(),
427                    source: NoteSource::Agent,
428                },
429            )
430            .unwrap();
431        let render = |project: Option<aidaemon_core::ProjectRef>| {
432            let source = system.recall.clone();
433            async move {
434                let turn = MemoryTurn {
435                    project,
436                    ..MemoryTurn::owner("test:synthetic-user")
437                };
438                let recall = FullRecall::new(source, Arc::new(NoHost), plain_turn(&turn));
439                recall.render_block("what is my favorite color?").await
440            }
441        };
442        let plain = render(None).await;
443        let in_other = render(Some(other)).await;
444        let in_project = render(Some(project.clone())).await;
445        assert!(plain.contains("teal"), "{plain}");
446        assert!(!plain.contains("Project Memory"), "{plain}");
447        assert_eq!(plain, in_other);
448        assert!(in_project.starts_with(&plain), "{in_project}");
449        assert!(
450            in_project.contains("## Project Memory (Acme Site)"),
451            "{in_project}"
452        );
453        assert!(in_project.contains("fact-test_command.md"), "{in_project}");
454
455        // The project turn's remember_fact keeps the project's facts apart.
456        let turn = MemoryTurn {
457            project: Some(project.clone()),
458            ..MemoryTurn::owner("test:synthetic-user")
459        };
460        let parts = system.turn(&turn).await;
461        let tool = parts
462            .tools
463            .iter()
464            .find(|t| t.spec().name == "remember_fact")
465            .unwrap()
466            .clone();
467        let ctx = aidaemon_core::testing::tool_context();
468        tool.call(
469            serde_json::json!({"category": "technical", "key": "db", "value": "Postgres 16"}),
470            &ctx,
471        )
472        .await
473        .unwrap();
474        assert!(notes.read(&project, NoteKind::Fact, "db").is_some());
475        let facts = crate::stores::FactStore::get_facts(store.as_ref(), None)
476            .await
477            .unwrap();
478        assert!(facts.iter().all(|f| f.key != "db"), "{facts:?}");
479    }
480
481    /// With conversations placed in projects, an episode is recalled only on
482    /// turns in its conversation's project: one project's history stays out
483    /// of other projects and of plain chats, and plain chats keep theirs.
484    /// Without placement every episode is recalled, as before.
485    #[tokio::test]
486    async fn episodes_are_recalled_only_in_their_conversations_project() {
487        struct Placed;
488        #[async_trait]
489        impl crate::project::SessionProjects for Placed {
490            async fn project_of(&self, session_id: &str) -> Option<String> {
491                match session_id {
492                    "app:in-a" => Some("project-a".into()),
493                    "app:in-b" => Some("project-b".into()),
494                    _ => None,
495                }
496            }
497        }
498        let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
499        crate::sqlite::migrate(&pool).await.unwrap();
500        let store = SqliteMemory::new(pool, Arc::new(crate::HashEmbedder::new(384)));
501        for (session, summary) in [
502            ("app:in-a", "Alpha history: deployed the Acme site."),
503            ("app:in-b", "Beta history: tuned the ledger tests."),
504            (
505                "app:plain",
506                "Gamma history: planned a birthday dinner for Mia.",
507            ),
508        ] {
509            let now = chrono::Utc::now();
510            crate::stores::EpisodeStore::record_session_episode(
511                &store,
512                &crate::episodes::SessionEpisode {
513                    session_id: session.into(),
514                    summary: summary.into(),
515                    topics: vec![],
516                    emotional_tone: "neutral".into(),
517                    outcome: "done".into(),
518                    importance: 0.5,
519                    message_count: 4,
520                    start_time: now,
521                    end_time: now,
522                    channel_id: None,
523                },
524            )
525            .await
526            .unwrap();
527        }
528        let store: Arc<dyn MemoryStores> = Arc::new(store);
529        let settings = RecallSettings {
530            max_facts: 10,
531            assistant_name: None,
532        };
533        let render = |source: Arc<RecallSource>, project: Option<&'static str>| async move {
534            let turn = MemoryTurn {
535                project: project.map(|id| aidaemon_core::ProjectRef::new(id, id, None).unwrap()),
536                ..MemoryTurn::owner("test:synthetic-user")
537            };
538            FullRecall::new(source, Arc::new(NoHost), plain_turn(&turn))
539                .render_block("history")
540                .await
541        };
542
543        let found = store.get_relevant_episodes("history", 12).await.unwrap();
544        assert_eq!(found.len(), 3, "{found:?}");
545        let unplaced = Arc::new(RecallSource::new(store.clone(), settings.clone()));
546        let all = render(unplaced, None).await;
547        assert!(
548            ["Alpha", "Beta", "Gamma"]
549                .iter()
550                .any(|history| all.contains(history)),
551            "{all}"
552        );
553
554        let placed =
555            Arc::new(RecallSource::new(store, settings).with_session_projects(Arc::new(Placed)));
556        let in_a = render(placed.clone(), Some("project-a")).await;
557        assert!(in_a.contains("Alpha"), "{in_a}");
558        assert!(!in_a.contains("Beta") && !in_a.contains("Gamma"), "{in_a}");
559        let in_b = render(placed.clone(), Some("project-b")).await;
560        assert!(in_b.contains("Beta"), "{in_b}");
561        assert!(!in_b.contains("Alpha") && !in_b.contains("Gamma"), "{in_b}");
562        let plain = render(placed, None).await;
563        assert!(plain.contains("Gamma"), "{plain}");
564        assert!(
565            !plain.contains("Alpha") && !plain.contains("Beta"),
566            "{plain}"
567        );
568    }
569
570    /// A recall started early renders the same block the model call would
571    /// have rendered itself, and the first render takes it.
572    /// Counts the decision points recorded through it.
573    #[derive(Default)]
574    struct CountingHost {
575        decisions: std::sync::atomic::AtomicUsize,
576    }
577
578    #[async_trait]
579    impl RecallHost for CountingHost {
580        async fn active_goals(&self) -> anyhow::Result<Vec<RecallGoal>> {
581            Ok(Vec::new())
582        }
583
584        async fn people_enabled(&self) -> anyhow::Result<bool> {
585            Ok(false)
586        }
587
588        async fn decision(
589            &self,
590            _turn: &RecallTurn,
591            _kind: super::super::recall::RecallDecision,
592            _summary: String,
593            _metadata: serde_json::Value,
594        ) {
595            self.decisions
596                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
597        }
598    }
599
600    async fn teal_source() -> Arc<RecallSource> {
601        let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
602        crate::sqlite::migrate(&pool).await.unwrap();
603        let store = SqliteMemory::new(pool, Arc::new(crate::HashEmbedder::new(384)));
604        crate::stores::FactStore::upsert_fact(
605            &store,
606            "preference",
607            "favorite_color",
608            "teal",
609            "user",
610            None,
611            crate::records::FactPrivacy::Global,
612        )
613        .await
614        .unwrap();
615        Arc::new(RecallSource::new(
616            Arc::new(store),
617            RecallSettings {
618                max_facts: 10,
619                assistant_name: None,
620            },
621        ))
622    }
623
624    fn arriving_turn() -> RecallTurn {
625        RecallTurn {
626            user_text: Some("what is my favorite color?".into()),
627            ..plain_turn(&MemoryTurn {
628                session_id: "test:synthetic-user".into(),
629                project: None,
630                scope: "owner".into(),
631                read: true,
632                write: false,
633                explicit_writes_only: false,
634                learning: Default::default(),
635                host: Default::default(),
636            })
637        }
638    }
639
640    /// Recall started on arrival renders the turn's block, and its writes
641    /// (here the decision points) are made by the turn that adopts it, on
642    /// that turn's host, only when the block is used.
643    #[tokio::test]
644    async fn an_adopted_speculative_recall_renders_the_block_and_writes_as_its_turn() {
645        let source = teal_source().await;
646        let mut turn = arriving_turn();
647        turn.task_id = "task-synthetic-1".into();
648        let plain = FullRecall::new(source.clone(), Arc::new(NoHost), turn.clone())
649            .render_block("")
650            .await;
651
652        let early_host = Arc::new(CountingHost::default());
653        let speculative =
654            SpeculativeRecall::start(source.clone(), early_host.clone(), arriving_turn()).unwrap();
655        assert!(speculative.serves(&turn));
656        let turn_host = Arc::new(CountingHost::default());
657        let adopted = FullRecall::new(source, turn_host.clone(), turn).adopt(speculative);
658        let note = aidaemon_policies::Recall::render(&adopted, "test:synthetic-user", "", 5)
659            .await
660            .unwrap();
661        assert_eq!(note, plain);
662        assert!(note.contains("teal"), "{note}");
663        let decisions =
664            |host: &CountingHost| host.decisions.load(std::sync::atomic::Ordering::SeqCst);
665        assert_eq!(
666            decisions(&early_host),
667            0,
668            "a speculative render writes nothing"
669        );
670        assert!(
671            decisions(&turn_host) >= 1,
672            "the adopting turn records its recall"
673        );
674    }
675
676    /// Only the turn it was started for may take it: a turn that may not
677    /// read memory, or recalls for other inputs, never sees what it read.
678    #[tokio::test]
679    async fn a_speculative_recall_serves_only_its_own_allowed_turn() {
680        let source = teal_source().await;
681        let speculative =
682            SpeculativeRecall::start(source, Arc::new(NoHost), arriving_turn()).unwrap();
683        let mut forbidden = arriving_turn();
684        forbidden.allowed = false;
685        assert!(!speculative.serves(&forbidden));
686        let mut other_text = arriving_turn();
687        other_text.user_text = Some("and my favorite food?".into());
688        assert!(!speculative.serves(&other_text));
689        let mut public = arriving_turn();
690        public.visibility = ChannelVisibility::PublicExternal;
691        public.personal = false;
692        assert!(!speculative.serves(&public));
693        let mut child = arriving_turn();
694        child.depth = 1;
695        assert!(!speculative.serves(&child));
696        let mut later_task = arriving_turn();
697        later_task.task_id = "task-synthetic-2".into();
698        assert!(speculative.serves(&later_task));
699    }
700
701    /// A newer message replaces an unclaimed recall, and a turn that is not
702    /// the speculative one's drops it and recalls on its own.
703    #[tokio::test]
704    async fn the_memory_system_hands_a_speculative_recall_only_to_a_matching_turn() {
705        let memory = FullMemory::new(teal_source().await);
706        memory.speculate(arriving_turn(), Arc::new(NoHost));
707        let mut forbidden = arriving_turn();
708        forbidden.allowed = false;
709        assert!(memory.claim_speculative(&forbidden).is_none());
710        assert!(
711            memory.claim_speculative(&arriving_turn()).is_none(),
712            "dropped on mismatch"
713        );
714        memory.speculate(arriving_turn(), Arc::new(NoHost));
715        assert!(memory.claim_speculative(&arriving_turn()).is_some());
716    }
717
718    #[tokio::test]
719    async fn a_prefetched_recall_renders_the_same_block() {
720        let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
721        crate::sqlite::migrate(&pool).await.unwrap();
722        let store = SqliteMemory::new(pool, Arc::new(crate::HashEmbedder::new(384)));
723        crate::stores::FactStore::upsert_fact(
724            &store,
725            "preference",
726            "favorite_color",
727            "teal",
728            "user",
729            None,
730            crate::records::FactPrivacy::Global,
731        )
732        .await
733        .unwrap();
734        let source = Arc::new(RecallSource::new(
735            Arc::new(store),
736            RecallSettings {
737                max_facts: 10,
738                assistant_name: None,
739            },
740        ));
741        let mut turn = RecallTurn {
742            user_text: Some("what is my favorite color?".into()),
743            ..plain_turn(&MemoryTurn {
744                session_id: "test:synthetic-user".into(),
745                project: None,
746                scope: "owner".into(),
747                read: true,
748                write: false,
749                explicit_writes_only: false,
750                learning: Default::default(),
751                host: Default::default(),
752            })
753        };
754        turn.task_id = "task-synthetic-1".into();
755        let plain = FullRecall::new(source.clone(), Arc::new(NoHost), turn.clone())
756            .render_block("")
757            .await;
758        let prefetched = FullRecall::new(source, Arc::new(NoHost), turn).prefetch();
759        assert!(prefetched.prefetched.lock().unwrap().is_some());
760        let note = aidaemon_policies::Recall::render(&prefetched, "test:synthetic-user", "", 5)
761            .await
762            .unwrap();
763        assert!(note.contains("teal"), "{note}");
764        assert_eq!(note, plain);
765        assert!(prefetched.prefetched.lock().unwrap().is_none());
766    }
767
768    #[tokio::test]
769    async fn the_whole_system_offers_its_tools_on_a_memory_turn() {
770        let store = crate::full::tools::test_support::memory().await;
771        let system = FullMemory::over(
772            store,
773            RecallSettings {
774                max_facts: 10,
775                assistant_name: None,
776            },
777            Arc::new(crate::full::tools::test_support::Settings::default()),
778        );
779        let mut turn = MemoryTurn {
780            session_id: "test:synthetic-user".into(),
781            project: None,
782            scope: "owner".into(),
783            read: true,
784            write: true,
785            explicit_writes_only: false,
786            learning: Default::default(),
787            host: Default::default(),
788        };
789        let names = |parts: &MemoryParts| -> Vec<String> {
790            parts.tools.iter().map(|tool| tool.spec().name).collect()
791        };
792        let parts = system.turn(&turn).await;
793        let mut offered = names(&parts);
794        offered.sort();
795        let mut expected: Vec<String> = crate::full::tools::TOOL_NAMES
796            .iter()
797            .map(|name| name.to_string())
798            .collect();
799        expected.sort();
800        assert_eq!(offered, expected);
801
802        turn.read = false;
803        turn.write = false;
804        assert!(system.turn(&turn).await.tools.is_empty());
805    }
806}