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
245/// How many facts recall renders at most, by default (the daemon's
246/// default too).
247pub const DEFAULT_MAX_FACTS: usize = 20;
248
249/// A host with nothing of its own: no goals, people intelligence off.
250struct NoHost;
251
252#[async_trait]
253impl RecallHost for NoHost {
254    async fn active_goals(&self) -> anyhow::Result<Vec<RecallGoal>> {
255        Ok(Vec::new())
256    }
257
258    async fn people_enabled(&self) -> anyhow::Result<bool> {
259        Ok(false)
260    }
261}
262
263/// The turn's audience as call facts for its memory tools: the owner in
264/// their own chat sees every fact, anyone else what recall would show them.
265fn call_facts(turn: &RecallTurn) -> aidaemon_tools::semantics::ToolCallContext {
266    aidaemon_tools::semantics::ToolCallContext {
267        session_id: turn.session_id.clone(),
268        user_role: Some(if turn.owner {
269            aidaemon_core::UserRole::Owner
270        } else {
271            aidaemon_core::UserRole::Guest
272        }),
273        channel_visibility: Some(turn.visibility),
274        channel_id: turn.channel_id.clone(),
275        ..Default::default()
276    }
277}
278
279/// What recall knows about a turn given only the [`MemoryTurn`].
280fn plain_turn(turn: &MemoryTurn) -> RecallTurn {
281    let owner = turn.scope == "owner";
282    RecallTurn {
283        session_id: turn.session_id.clone(),
284        task_id: String::new(),
285        user_text: None,
286        owner,
287        personal: owner,
288        visibility: if owner {
289            ChannelVisibility::Private
290        } else {
291            ChannelVisibility::PrivateGroup
292        },
293        channel_id: None,
294        sender_id: None,
295        allowed: turn.read,
296        depth: usize::from(turn.explicit_writes_only),
297        project: turn.project.clone(),
298    }
299}
300
301#[async_trait]
302impl MemorySystem for FullMemory {
303    async fn turn(&self, turn: &MemoryTurn) -> MemoryParts {
304        let (recall_turn, host, extra): (RecallTurn, Arc<dyn RecallHost>, Vec<Arc<dyn Hook>>) =
305            match turn.host.get::<FullTurn>() {
306                Some(full) => (full.recall.clone(), full.host.clone(), full.hooks.clone()),
307                None => (plain_turn(turn), Arc::new(NoHost), Vec::new()),
308            };
309        // Recall starts now, beside the rest of the turn's setup; the
310        // injection hook awaits it at the first model call.
311        let facts = call_facts(&recall_turn);
312        let recall = match self.claim_speculative(&recall_turn) {
313            Some(speculative) => {
314                FullRecall::new(self.recall.clone(), host, recall_turn).adopt(speculative)
315            }
316            None => FullRecall::new(self.recall.clone(), host, recall_turn).prefetch(),
317        };
318        let mut hooks: Vec<Arc<dyn Hook>> = vec![Arc::new(MemoryInjection::new(recall))];
319        hooks.extend(extra);
320        // Only the owner's own turns teach the jobs.
321        if let Some(recorder) = &self.recorder
322            && turn.write
323            && turn.scope == "owner"
324        {
325            hooks.push(recorder.clone());
326        }
327        let mut tools = if turn.read || turn.write {
328            let mut tools = self.tools.clone();
329            tools.extend(self.own_tools.iter().map(|tool| {
330                Arc::new(
331                    aidaemon_tools::KernelAdapter::new(tool.clone()).with_call_facts(facts.clone()),
332                ) as Arc<dyn Tool>
333            }));
334            tools
335        } else {
336            Vec::new()
337        };
338        // A turn in a project gets a `remember_fact` that knows it.
339        if let (Some(project), Some(notes), Some(store)) =
340            (&turn.project, &self.project_notes, &self.store)
341            && let Some(slot) = tools
342                .iter_mut()
343                .find(|tool| tool.spec().name == "remember_fact")
344        {
345            let tool = tools::RememberFactTool::new(store.clone())
346                .with_project_notes(notes.clone())
347                .for_project(Some(project.clone()));
348            *slot = Arc::new(
349                aidaemon_tools::KernelAdapter::new(Arc::new(tool)).with_call_facts(facts.clone()),
350            );
351        }
352        MemoryParts { hooks, tools }
353    }
354
355    fn services(&self) -> Vec<Arc<dyn Service>> {
356        self.jobs
357            .as_ref()
358            .map(MemoryJobs::services)
359            .unwrap_or_default()
360    }
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366    use crate::sqlite::SqliteMemory;
367
368    #[tokio::test]
369    async fn an_owner_turn_recalls_its_facts_without_host_facts() {
370        let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
371        crate::sqlite::migrate(&pool).await.unwrap();
372        let store = SqliteMemory::new(pool, Arc::new(crate::HashEmbedder::new(384)));
373        crate::stores::FactStore::upsert_fact(
374            &store,
375            "preference",
376            "favorite_color",
377            "teal",
378            "user",
379            None,
380            crate::records::FactPrivacy::Global,
381        )
382        .await
383        .unwrap();
384        let source = Arc::new(RecallSource::new(
385            Arc::new(store),
386            RecallSettings {
387                max_facts: 10,
388                assistant_name: None,
389            },
390        ));
391        let turn = MemoryTurn {
392            session_id: "test:synthetic-user".into(),
393            project: None,
394            scope: "owner".into(),
395            read: true,
396            write: true,
397            explicit_writes_only: false,
398            learning: Default::default(),
399            host: Default::default(),
400        };
401        let parts = FullMemory::new(source.clone()).turn(&turn).await;
402        assert_eq!(parts.hooks.len(), 1);
403        assert!(parts.tools.is_empty());
404        let recall = FullRecall::new(source, Arc::new(NoHost), plain_turn(&turn));
405        let note = aidaemon_policies::Recall::render(
406            &recall,
407            "test:synthetic-user",
408            "what is my favorite color?",
409            5,
410        )
411        .await
412        .unwrap();
413        assert!(note.contains("teal"), "{note}");
414    }
415
416    /// A turn in a project sees its notes after the owner's own sections;
417    /// a turn without one, and a turn in another project, renders exactly
418    /// what it rendered before; and the turn's `remember_fact` writes notes.
419    #[tokio::test]
420    async fn a_project_turn_sees_its_notes_and_keeps_the_rest() {
421        use crate::project::{NoteKind, NoteSource, NoteWrite, ProjectNotes};
422        let dir = tempfile::tempdir().unwrap();
423        let notes = Arc::new(ProjectNotes::new(dir.path()));
424        let system = FullMemory::open(None)
425            .await
426            .unwrap()
427            .with_project_notes(notes.clone());
428        let store = system.store.clone().unwrap();
429        crate::stores::FactStore::upsert_fact(
430            store.as_ref(),
431            "preference",
432            "favorite_color",
433            "teal",
434            "user",
435            None,
436            crate::records::FactPrivacy::Global,
437        )
438        .await
439        .unwrap();
440        let project = aidaemon_core::ProjectRef::new("project-a", "Acme Site", None).unwrap();
441        let other = aidaemon_core::ProjectRef::new("project-b", "Other", None).unwrap();
442        notes
443            .write(
444                &project,
445                &NoteWrite {
446                    kind: NoteKind::Fact,
447                    key: "test_command".into(),
448                    category: Some("technical".into()),
449                    description: None,
450                    body: "Tests run with make test.".into(),
451                    source: NoteSource::Agent,
452                },
453            )
454            .unwrap();
455        let render = |project: Option<aidaemon_core::ProjectRef>| {
456            let source = system.recall.clone();
457            async move {
458                let turn = MemoryTurn {
459                    project,
460                    ..MemoryTurn::owner("test:synthetic-user")
461                };
462                let recall = FullRecall::new(source, Arc::new(NoHost), plain_turn(&turn));
463                recall.render_block("what is my favorite color?").await
464            }
465        };
466        let plain = render(None).await;
467        let in_other = render(Some(other)).await;
468        let in_project = render(Some(project.clone())).await;
469        assert!(plain.contains("teal"), "{plain}");
470        assert!(!plain.contains("Project Memory"), "{plain}");
471        assert_eq!(plain, in_other);
472        assert!(in_project.starts_with(&plain), "{in_project}");
473        assert!(
474            in_project.contains("## Project Memory (Acme Site)"),
475            "{in_project}"
476        );
477        assert!(in_project.contains("fact-test_command.md"), "{in_project}");
478
479        // The project turn's remember_fact keeps the project's facts apart.
480        let turn = MemoryTurn {
481            project: Some(project.clone()),
482            ..MemoryTurn::owner("test:synthetic-user")
483        };
484        let parts = system.turn(&turn).await;
485        let tool = parts
486            .tools
487            .iter()
488            .find(|t| t.spec().name == "remember_fact")
489            .unwrap()
490            .clone();
491        let ctx = aidaemon_core::testing::tool_context();
492        tool.call(
493            serde_json::json!({"category": "technical", "key": "db", "value": "Postgres 16"}),
494            &ctx,
495        )
496        .await
497        .unwrap();
498        assert!(notes.read(&project, NoteKind::Fact, "db").is_some());
499        let facts = crate::stores::FactStore::get_facts(store.as_ref(), None)
500            .await
501            .unwrap();
502        assert!(facts.iter().all(|f| f.key != "db"), "{facts:?}");
503    }
504
505    /// With conversations placed in projects, an episode is recalled only on
506    /// turns in its conversation's project: one project's history stays out
507    /// of other projects and of plain chats, and plain chats keep theirs.
508    /// Without placement every episode is recalled, as before.
509    #[tokio::test]
510    async fn episodes_are_recalled_only_in_their_conversations_project() {
511        struct Placed;
512        #[async_trait]
513        impl crate::project::SessionProjects for Placed {
514            async fn project_of(&self, session_id: &str) -> Option<String> {
515                match session_id {
516                    "app:in-a" => Some("project-a".into()),
517                    "app:in-b" => Some("project-b".into()),
518                    _ => None,
519                }
520            }
521        }
522        let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
523        crate::sqlite::migrate(&pool).await.unwrap();
524        let store = SqliteMemory::new(pool, Arc::new(crate::HashEmbedder::new(384)));
525        for (session, summary) in [
526            ("app:in-a", "Alpha history: deployed the Acme site."),
527            ("app:in-b", "Beta history: tuned the ledger tests."),
528            (
529                "app:plain",
530                "Gamma history: planned a birthday dinner for Mia.",
531            ),
532        ] {
533            let now = chrono::Utc::now();
534            crate::stores::EpisodeStore::record_session_episode(
535                &store,
536                &crate::episodes::SessionEpisode {
537                    session_id: session.into(),
538                    summary: summary.into(),
539                    topics: vec![],
540                    emotional_tone: "neutral".into(),
541                    outcome: "done".into(),
542                    importance: 0.5,
543                    message_count: 4,
544                    start_time: now,
545                    end_time: now,
546                    channel_id: None,
547                },
548            )
549            .await
550            .unwrap();
551        }
552        let store: Arc<dyn MemoryStores> = Arc::new(store);
553        let settings = RecallSettings {
554            max_facts: 10,
555            assistant_name: None,
556        };
557        let render = |source: Arc<RecallSource>, project: Option<&'static str>| async move {
558            let turn = MemoryTurn {
559                project: project.map(|id| aidaemon_core::ProjectRef::new(id, id, None).unwrap()),
560                ..MemoryTurn::owner("test:synthetic-user")
561            };
562            FullRecall::new(source, Arc::new(NoHost), plain_turn(&turn))
563                .render_block("history")
564                .await
565        };
566
567        let found = store.get_relevant_episodes("history", 12).await.unwrap();
568        assert_eq!(found.len(), 3, "{found:?}");
569        let unplaced = Arc::new(RecallSource::new(store.clone(), settings.clone()));
570        let all = render(unplaced, None).await;
571        assert!(
572            ["Alpha", "Beta", "Gamma"]
573                .iter()
574                .any(|history| all.contains(history)),
575            "{all}"
576        );
577
578        let placed =
579            Arc::new(RecallSource::new(store, settings).with_session_projects(Arc::new(Placed)));
580        let in_a = render(placed.clone(), Some("project-a")).await;
581        assert!(in_a.contains("Alpha"), "{in_a}");
582        assert!(!in_a.contains("Beta") && !in_a.contains("Gamma"), "{in_a}");
583        let in_b = render(placed.clone(), Some("project-b")).await;
584        assert!(in_b.contains("Beta"), "{in_b}");
585        assert!(!in_b.contains("Alpha") && !in_b.contains("Gamma"), "{in_b}");
586        let plain = render(placed, None).await;
587        assert!(plain.contains("Gamma"), "{plain}");
588        assert!(
589            !plain.contains("Alpha") && !plain.contains("Beta"),
590            "{plain}"
591        );
592    }
593
594    /// A recall started early renders the same block the model call would
595    /// have rendered itself, and the first render takes it.
596    /// Counts the decision points recorded through it.
597    #[derive(Default)]
598    struct CountingHost {
599        decisions: std::sync::atomic::AtomicUsize,
600    }
601
602    #[async_trait]
603    impl RecallHost for CountingHost {
604        async fn active_goals(&self) -> anyhow::Result<Vec<RecallGoal>> {
605            Ok(Vec::new())
606        }
607
608        async fn people_enabled(&self) -> anyhow::Result<bool> {
609            Ok(false)
610        }
611
612        async fn decision(
613            &self,
614            _turn: &RecallTurn,
615            _kind: super::super::recall::RecallDecision,
616            _summary: String,
617            _metadata: serde_json::Value,
618        ) {
619            self.decisions
620                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
621        }
622    }
623
624    async fn teal_source() -> Arc<RecallSource> {
625        let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
626        crate::sqlite::migrate(&pool).await.unwrap();
627        let store = SqliteMemory::new(pool, Arc::new(crate::HashEmbedder::new(384)));
628        crate::stores::FactStore::upsert_fact(
629            &store,
630            "preference",
631            "favorite_color",
632            "teal",
633            "user",
634            None,
635            crate::records::FactPrivacy::Global,
636        )
637        .await
638        .unwrap();
639        Arc::new(RecallSource::new(
640            Arc::new(store),
641            RecallSettings {
642                max_facts: 10,
643                assistant_name: None,
644            },
645        ))
646    }
647
648    fn arriving_turn() -> RecallTurn {
649        RecallTurn {
650            user_text: Some("what is my favorite color?".into()),
651            ..plain_turn(&MemoryTurn {
652                session_id: "test:synthetic-user".into(),
653                project: None,
654                scope: "owner".into(),
655                read: true,
656                write: false,
657                explicit_writes_only: false,
658                learning: Default::default(),
659                host: Default::default(),
660            })
661        }
662    }
663
664    /// Recall started on arrival renders the turn's block, and its writes
665    /// (here the decision points) are made by the turn that adopts it, on
666    /// that turn's host, only when the block is used.
667    #[tokio::test]
668    async fn an_adopted_speculative_recall_renders_the_block_and_writes_as_its_turn() {
669        let source = teal_source().await;
670        let mut turn = arriving_turn();
671        turn.task_id = "task-synthetic-1".into();
672        let plain = FullRecall::new(source.clone(), Arc::new(NoHost), turn.clone())
673            .render_block("")
674            .await;
675
676        let early_host = Arc::new(CountingHost::default());
677        let speculative =
678            SpeculativeRecall::start(source.clone(), early_host.clone(), arriving_turn()).unwrap();
679        assert!(speculative.serves(&turn));
680        let turn_host = Arc::new(CountingHost::default());
681        let adopted = FullRecall::new(source, turn_host.clone(), turn).adopt(speculative);
682        let note = aidaemon_policies::Recall::render(&adopted, "test:synthetic-user", "", 5)
683            .await
684            .unwrap();
685        assert_eq!(note, plain);
686        assert!(note.contains("teal"), "{note}");
687        let decisions =
688            |host: &CountingHost| host.decisions.load(std::sync::atomic::Ordering::SeqCst);
689        assert_eq!(
690            decisions(&early_host),
691            0,
692            "a speculative render writes nothing"
693        );
694        assert!(
695            decisions(&turn_host) >= 1,
696            "the adopting turn records its recall"
697        );
698    }
699
700    /// Only the turn it was started for may take it: a turn that may not
701    /// read memory, or recalls for other inputs, never sees what it read.
702    #[tokio::test]
703    async fn a_speculative_recall_serves_only_its_own_allowed_turn() {
704        let source = teal_source().await;
705        let speculative =
706            SpeculativeRecall::start(source, Arc::new(NoHost), arriving_turn()).unwrap();
707        let mut forbidden = arriving_turn();
708        forbidden.allowed = false;
709        assert!(!speculative.serves(&forbidden));
710        let mut other_text = arriving_turn();
711        other_text.user_text = Some("and my favorite food?".into());
712        assert!(!speculative.serves(&other_text));
713        let mut public = arriving_turn();
714        public.visibility = ChannelVisibility::PublicExternal;
715        public.personal = false;
716        assert!(!speculative.serves(&public));
717        let mut child = arriving_turn();
718        child.depth = 1;
719        assert!(!speculative.serves(&child));
720        let mut later_task = arriving_turn();
721        later_task.task_id = "task-synthetic-2".into();
722        assert!(speculative.serves(&later_task));
723    }
724
725    /// A newer message replaces an unclaimed recall, and a turn that is not
726    /// the speculative one's drops it and recalls on its own.
727    #[tokio::test]
728    async fn the_memory_system_hands_a_speculative_recall_only_to_a_matching_turn() {
729        let memory = FullMemory::new(teal_source().await);
730        memory.speculate(arriving_turn(), Arc::new(NoHost));
731        let mut forbidden = arriving_turn();
732        forbidden.allowed = false;
733        assert!(memory.claim_speculative(&forbidden).is_none());
734        assert!(
735            memory.claim_speculative(&arriving_turn()).is_none(),
736            "dropped on mismatch"
737        );
738        memory.speculate(arriving_turn(), Arc::new(NoHost));
739        assert!(memory.claim_speculative(&arriving_turn()).is_some());
740    }
741
742    #[tokio::test]
743    async fn a_prefetched_recall_renders_the_same_block() {
744        let pool = sqlx::SqlitePool::connect("sqlite::memory:").await.unwrap();
745        crate::sqlite::migrate(&pool).await.unwrap();
746        let store = SqliteMemory::new(pool, Arc::new(crate::HashEmbedder::new(384)));
747        crate::stores::FactStore::upsert_fact(
748            &store,
749            "preference",
750            "favorite_color",
751            "teal",
752            "user",
753            None,
754            crate::records::FactPrivacy::Global,
755        )
756        .await
757        .unwrap();
758        let source = Arc::new(RecallSource::new(
759            Arc::new(store),
760            RecallSettings {
761                max_facts: 10,
762                assistant_name: None,
763            },
764        ));
765        let mut turn = RecallTurn {
766            user_text: Some("what is my favorite color?".into()),
767            ..plain_turn(&MemoryTurn {
768                session_id: "test:synthetic-user".into(),
769                project: None,
770                scope: "owner".into(),
771                read: true,
772                write: false,
773                explicit_writes_only: false,
774                learning: Default::default(),
775                host: Default::default(),
776            })
777        };
778        turn.task_id = "task-synthetic-1".into();
779        let plain = FullRecall::new(source.clone(), Arc::new(NoHost), turn.clone())
780            .render_block("")
781            .await;
782        let prefetched = FullRecall::new(source, Arc::new(NoHost), turn).prefetch();
783        assert!(prefetched.prefetched.lock().unwrap().is_some());
784        let note = aidaemon_policies::Recall::render(&prefetched, "test:synthetic-user", "", 5)
785            .await
786            .unwrap();
787        assert!(note.contains("teal"), "{note}");
788        assert_eq!(note, plain);
789        assert!(prefetched.prefetched.lock().unwrap().is_none());
790    }
791
792    #[tokio::test]
793    async fn the_whole_system_offers_its_tools_on_a_memory_turn() {
794        let store = crate::full::tools::test_support::memory().await;
795        let system = FullMemory::over(
796            store,
797            RecallSettings {
798                max_facts: 10,
799                assistant_name: None,
800            },
801            Arc::new(crate::full::tools::test_support::Settings::default()),
802        );
803        let mut turn = MemoryTurn {
804            session_id: "test:synthetic-user".into(),
805            project: None,
806            scope: "owner".into(),
807            read: true,
808            write: true,
809            explicit_writes_only: false,
810            learning: Default::default(),
811            host: Default::default(),
812        };
813        let names = |parts: &MemoryParts| -> Vec<String> {
814            parts.tools.iter().map(|tool| tool.spec().name).collect()
815        };
816        let parts = system.turn(&turn).await;
817        let mut offered = names(&parts);
818        offered.sort();
819        let mut expected: Vec<String> = crate::full::tools::TOOL_NAMES
820            .iter()
821            .map(|name| name.to_string())
822            .collect();
823        expected.sort();
824        assert_eq!(offered, expected);
825
826        turn.read = false;
827        turn.write = false;
828        assert!(system.turn(&turn).await.tools.is_empty());
829    }
830}