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