Skip to main content

aidaemon_memory/full/
recall.rs

1//! [`FullRecall`]: the full memory system's recall, rendered as one system
2//! note by `aidaemon_policies::MemoryInjection`. It reads the SQLite memory
3//! (facts, episodes, procedures, people, the core profile) and scopes every
4//! section by the turn's audience: personal memory only in the owner's
5//! private chats, nothing on a public channel with outsiders.
6
7use std::collections::{HashMap, HashSet};
8use std::sync::Arc;
9
10use aidaemon_core::ChannelVisibility;
11use async_trait::async_trait;
12use serde_json::json;
13use tracing::{info, warn};
14
15use crate::records::Fact;
16use crate::render::{
17    MemoryContext, RecallGoal, build_critical_facts_prompt_block, extract_critical_fact_summary,
18    render_memory_section,
19};
20use crate::stores::MemoryStores;
21
22/// Identity/profile categories pinned as critical facts in owner DMs.
23pub const IDENTITY_CATEGORIES: &[&str] = &[
24    "identity",
25    "personal",
26    "profile",
27    "user",
28    "assistant",
29    "bot",
30    "relationship",
31    "preference",
32    "family",
33];
34
35/// What recall knows about one turn, as the host decided it.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct RecallTurn {
38    pub session_id: String,
39    pub task_id: String,
40    /// The user's message: recall is scoped to the current request. `None`
41    /// recalls for the latest user message of the request instead.
42    pub user_text: Option<String>,
43    /// The owner wrote the message.
44    pub owner: bool,
45    /// The owner wrote it in a private chat: personal memory (identity,
46    /// goals, profile, people) may be shown.
47    pub personal: bool,
48    pub visibility: ChannelVisibility,
49    pub channel_id: Option<String>,
50    /// The speaker's platform id, to recognise a known person.
51    pub sender_id: Option<String>,
52    /// The turn may read memory at all.
53    pub allowed: bool,
54    /// Sub-agent depth: the core profile is for the top-level run only.
55    pub depth: usize,
56    /// The project the turn works in: its notes are shown after the rest of
57    /// the block (see [`crate::project`]).
58    pub project: Option<aidaemon_core::ProjectRef>,
59}
60
61/// A recall decision the host may record for diagnostics.
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum RecallDecision {
64    /// Which entities the core profile selected (id and content hash each).
65    CoreProfileSelection,
66    /// What recall fetched and rendered.
67    MemoryRetrieval,
68}
69
70/// What [`FullRecall`] needs from its host beyond the memory stores.
71#[async_trait]
72pub trait RecallHost: Send + Sync {
73    /// The owner's active personal goals (owner private chats only).
74    async fn active_goals(&self) -> anyhow::Result<Vec<RecallGoal>>;
75
76    /// Whether people intelligence is on.
77    async fn people_enabled(&self) -> anyhow::Result<bool>;
78
79    /// The host offers `manage_automations` for scheduled tasks and
80    /// reminders, so the memory guide may point at it.
81    fn offers_scheduled_goals(&self) -> bool {
82        false
83    }
84
85    /// Whether [`RecallHost::relevance`] is used at all.
86    fn relevance_enabled(&self) -> bool {
87        false
88    }
89
90    /// For each `(key, question)`, the probability that the answer is yes,
91    /// for the questions the host's judge answered. `message` is what the
92    /// questions are about. Never fails: no answer leaves a key out.
93    async fn relevance(
94        &self,
95        _turn: &RecallTurn,
96        _message: String,
97        _questions: Vec<(String, String)>,
98    ) -> HashMap<String, f32> {
99        HashMap::new()
100    }
101
102    /// Record a recall decision for diagnostics.
103    async fn decision(
104        &self,
105        _turn: &RecallTurn,
106        _kind: RecallDecision,
107        _summary: String,
108        _metadata: serde_json::Value,
109    ) {
110    }
111}
112
113/// Settings of [`FullRecall`].
114#[derive(Debug, Clone, Default)]
115pub struct RecallSettings {
116    pub max_facts: usize,
117    /// The configured assistant name, pinned among the critical facts.
118    pub assistant_name: Option<String>,
119}
120
121/// State shared by every turn's [`FullRecall`].
122pub struct RecallSource {
123    store: Arc<dyn MemoryStores>,
124    settings: RecallSettings,
125    /// Per session, the entities the core profile selected last, so the
126    /// selection stays stable across turns.
127    core_profile_ids: tokio::sync::RwLock<HashMap<String, Vec<String>>>,
128    /// Project memory, shown on a turn that works in a project.
129    project_notes: Option<Arc<crate::project::ProjectNotes>>,
130    /// Where conversations are placed: an episode is recalled only on turns
131    /// in the same project as its conversation (or, for a conversation in
132    /// no project, on turns in none). `None`: every episode, as before.
133    session_projects: Option<Arc<dyn crate::project::SessionProjects>>,
134}
135
136/// Episodes shown per turn.
137const EPISODES_SHOWN: usize = 3;
138/// Episodes read when they are filtered by project, so the filter still
139/// leaves some to show.
140const EPISODES_READ_FOR_PROJECT: usize = 12;
141
142impl RecallSource {
143    pub fn new(store: Arc<dyn MemoryStores>, settings: RecallSettings) -> Self {
144        Self {
145            store,
146            settings,
147            core_profile_ids: tokio::sync::RwLock::new(HashMap::new()),
148            project_notes: None,
149            session_projects: None,
150        }
151    }
152
153    /// Recall an episode only on turns in its conversation's project.
154    pub fn with_session_projects(
155        mut self,
156        projects: Arc<dyn crate::project::SessionProjects>,
157    ) -> Self {
158        self.session_projects = Some(projects);
159        self
160    }
161
162    /// How many episodes to read for a turn.
163    fn episodes_to_read(&self) -> usize {
164        if self.session_projects.is_some() {
165            EPISODES_READ_FOR_PROJECT
166        } else {
167            EPISODES_SHOWN
168        }
169    }
170
171    /// The first [`EPISODES_SHOWN`] of `episodes` whose conversation is in
172    /// the turn's project (both in none counts).
173    async fn episodes_in_turn_project(
174        &self,
175        turn: &RecallTurn,
176        episodes: Vec<crate::records::Episode>,
177    ) -> Vec<crate::records::Episode> {
178        let Some(projects) = &self.session_projects else {
179            return episodes.into_iter().take(EPISODES_SHOWN).collect();
180        };
181        let want = turn.project.as_ref().map(|project| project.id.as_str());
182        let mut placed: HashMap<String, Option<String>> = HashMap::new();
183        let mut kept = Vec::new();
184        for episode in episodes {
185            if kept.len() >= EPISODES_SHOWN {
186                break;
187            }
188            let project = match placed.get(&episode.session_id) {
189                Some(project) => project.clone(),
190                None => {
191                    let project = projects.project_of(&episode.session_id).await;
192                    placed.insert(episode.session_id.clone(), project.clone());
193                    project
194                }
195            };
196            if project.as_deref() == want {
197                kept.push(episode);
198            }
199        }
200        kept
201    }
202
203    /// Show `notes` on turns that work in a project.
204    pub fn with_project_notes(mut self, notes: Arc<crate::project::ProjectNotes>) -> Self {
205        self.set_project_notes(notes);
206        self
207    }
208
209    pub(super) fn set_project_notes(&mut self, notes: Arc<crate::project::ProjectNotes>) {
210        self.project_notes = Some(notes);
211    }
212
213    /// The project section for `turn`, when it works in a project with
214    /// notes and may read memory.
215    async fn project_section(&self, turn: &RecallTurn) -> Option<String> {
216        if !turn.allowed {
217            return None;
218        }
219        let (notes, project) = (self.project_notes.clone()?, turn.project.clone()?);
220        tokio::task::spawn_blocking(move || notes.section(&project))
221            .await
222            .ok()
223            .flatten()
224    }
225}
226
227/// A recall read that fails soft: the section renders empty, and the error is
228/// logged so a broken store does not look like an empty memory.
229fn or_logged<T: Default, E: std::fmt::Display>(result: Result<T, E>, section: &str) -> T {
230    result.unwrap_or_else(|error| {
231        warn!(section, %error, "memory recall read failed; section left empty");
232        T::default()
233    })
234}
235
236/// Recall over the memory stores for one turn. It already knows the channel,
237/// role and memory policy, so the `Recall` contract's session and query are
238/// enough.
239pub struct FullRecall {
240    source: Arc<RecallSource>,
241    host: Arc<dyn RecallHost>,
242    turn: RecallTurn,
243    /// The turn's memory block, started by [`Self::prefetch`] or adopted
244    /// from a [`SpeculativeRecall`] before the first model call asks for
245    /// it, with the writes it left for this turn to make.
246    pub(super) prefetched: std::sync::Mutex<Option<tokio::task::JoinHandle<Rendered>>>,
247    /// Set while rendering speculatively: writes are kept here instead of
248    /// made, for the turn that adopts the block.
249    deferred: Option<Arc<std::sync::Mutex<Vec<RecallEffect>>>>,
250}
251
252/// A rendered block and the writes rendering it left undone.
253pub(super) type Rendered = (String, Vec<RecallEffect>);
254
255/// A write recall makes as it renders. A speculative render keeps them so
256/// that only a turn that shows the block records it.
257#[derive(Debug)]
258pub(super) enum RecallEffect {
259    /// The speaker is a known person: their last interaction is now.
260    TouchPerson(i64),
261    /// These facts and episodes were shown.
262    Recalled { facts: Vec<i64>, episodes: Vec<i64> },
263    /// A diagnostic decision point.
264    Decision {
265        kind: RecallDecision,
266        summary: String,
267        metadata: serde_json::Value,
268    },
269}
270
271/// Recall started when a message arrives, before the turn's memory policy
272/// is settled: it renders as if memory were allowed and makes no write.
273/// The turn adopts it only when it recalls with exactly these inputs and
274/// may read memory ([`Self::serves`]); otherwise it is dropped, which stops
275/// it, and nothing it read reaches the turn.
276pub struct SpeculativeRecall {
277    turn: RecallTurn,
278    handle: Option<tokio::task::JoinHandle<Rendered>>,
279}
280
281impl SpeculativeRecall {
282    /// Starts rendering `turn`'s block now. `None` outside a Tokio runtime
283    /// or for a turn with no request text.
284    pub fn start(
285        source: Arc<RecallSource>,
286        host: Arc<dyn RecallHost>,
287        turn: RecallTurn,
288    ) -> Option<Self> {
289        turn.user_text.as_ref()?;
290        let runtime = tokio::runtime::Handle::try_current().ok()?;
291        let mut speculative_turn = turn.clone();
292        speculative_turn.allowed = true;
293        let effects = Arc::new(std::sync::Mutex::new(Vec::new()));
294        let mut worker = FullRecall::new(source, host, speculative_turn.clone());
295        worker.deferred = Some(effects.clone());
296        let handle = runtime.spawn(async move {
297            let block = worker.render_block("").await;
298            let effects = effects
299                .lock()
300                .map(|mut effects| std::mem::take(&mut *effects))
301                .unwrap_or_default();
302            (block, effects)
303        });
304        Some(Self {
305            turn: speculative_turn,
306            handle: Some(handle),
307        })
308    }
309
310    /// The session this recall was started for.
311    pub fn session_id(&self) -> &str {
312        &self.turn.session_id
313    }
314
315    /// Whether this render is `turn`'s block: the turn may read memory and
316    /// recalls for the same text, speaker, audience and depth. The task id
317    /// is the one input that may differ (it did not exist yet).
318    pub fn serves(&self, turn: &RecallTurn) -> bool {
319        let started = &self.turn;
320        turn.allowed
321            && started.session_id == turn.session_id
322            && started.user_text == turn.user_text
323            && started.owner == turn.owner
324            && started.personal == turn.personal
325            && started.visibility == turn.visibility
326            && started.channel_id == turn.channel_id
327            && started.sender_id == turn.sender_id
328            && started.depth == turn.depth
329            && started.project == turn.project
330    }
331}
332
333impl Drop for SpeculativeRecall {
334    fn drop(&mut self) {
335        if let Some(handle) = self.handle.take() {
336            handle.abort();
337        }
338    }
339}
340
341impl FullRecall {
342    pub fn new(source: Arc<RecallSource>, host: Arc<dyn RecallHost>, turn: RecallTurn) -> Self {
343        Self {
344            source,
345            host,
346            turn,
347            prefetched: std::sync::Mutex::new(None),
348            deferred: None,
349        }
350    }
351
352    /// This turn's recall takes over `speculative`'s render; its writes
353    /// are made, as this turn's, when the block is taken.
354    pub fn adopt(self, mut speculative: SpeculativeRecall) -> Self {
355        if let (Some(handle), Ok(mut prefetched)) =
356            (speculative.handle.take(), self.prefetched.lock())
357        {
358            *prefetched = Some(handle);
359        }
360        self
361    }
362
363    /// Records `effect`, or keeps it for the adopting turn while rendering
364    /// speculatively.
365    async fn effect(&self, effect: RecallEffect) {
366        if let Some(deferred) = &self.deferred {
367            if let Ok(mut deferred) = deferred.lock() {
368                deferred.push(effect);
369            }
370            return;
371        }
372        self.apply(effect).await;
373    }
374
375    async fn apply(&self, effect: RecallEffect) {
376        let store = &self.source.store;
377        match effect {
378            RecallEffect::TouchPerson(person_id) => {
379                if let Err(error) = store.touch_person_interaction(person_id).await {
380                    warn!(%error, "failed to record person interaction");
381                }
382            }
383            RecallEffect::Recalled { facts, episodes } => {
384                if let Err(error) = store.record_memory_recall(&facts, &episodes).await {
385                    tracing::debug!(%error, "Failed to record rendered memory recall");
386                }
387            }
388            RecallEffect::Decision {
389                kind,
390                summary,
391                metadata,
392            } => {
393                self.host
394                    .decision(&self.turn, kind, summary, metadata)
395                    .await;
396            }
397        }
398    }
399
400    /// Starts rendering the turn's memory block now, so the first model
401    /// call finds it ready instead of waiting for every lookup. Only a turn
402    /// that names its request can: the block is rendered for that text,
403    /// whatever query the model call later passes. Outside a Tokio runtime
404    /// nothing starts and the block renders on demand as before.
405    pub fn prefetch(self) -> Self {
406        if self.turn.user_text.is_none() {
407            return self;
408        }
409        let Ok(runtime) = tokio::runtime::Handle::try_current() else {
410            return self;
411        };
412        let worker = Self::new(self.source.clone(), self.host.clone(), self.turn.clone());
413        let handle = runtime.spawn(async move { (worker.render_block("").await, Vec::new()) });
414        if let Ok(mut prefetched) = self.prefetched.lock() {
415            *prefetched = Some(handle);
416        }
417        self
418    }
419
420    /// The prefetched block, once; `None` when none was started or it
421    /// failed, so the caller renders it itself.
422    async fn take_prefetched(&self) -> Option<String> {
423        let handle = self.prefetched.lock().ok()?.take()?;
424        let (block, effects) = handle.await.ok()?;
425        for effect in effects {
426            self.apply(effect).await;
427        }
428        Some(block)
429    }
430
431    /// Starts the recall filter over `facts`, when the host judges
432    /// relevance. Resolves to the ids of facts to drop: only an answer with
433    /// P(relevant) below 0.5 drops one, and facts in identity categories are
434    /// never asked about, so they are always kept. On any failure nothing is
435    /// dropped.
436    fn spawn_fact_filter(
437        &self,
438        query: &str,
439        facts: &[Fact],
440    ) -> Option<tokio::task::JoinHandle<Option<HashSet<i64>>>> {
441        let host = self.host.clone();
442        if !host.relevance_enabled() {
443            return None;
444        }
445        let message = format!(
446            "User message:\n{}",
447            crate::text::truncate_chars(query, 3000)
448        );
449        let mut questions = Vec::new();
450        let mut asked = std::collections::BTreeMap::new();
451        for fact in facts
452            .iter()
453            .filter(|fact| !IDENTITY_CATEGORIES.contains(&fact.category.as_str()))
454        {
455            let key = format!("f{}", asked.len());
456            questions.push((
457                key.clone(),
458                format!(
459                    "Would this remembered fact help answer or carry out the user's message? Fact: [{}] {}: {}",
460                    fact.category,
461                    fact.key,
462                    crate::text::truncate_chars(&fact.value, 300)
463                ),
464            ));
465            asked.insert(key, fact.id);
466        }
467        if asked.is_empty() {
468            return None;
469        }
470        let turn = self.turn.clone();
471        Some(tokio::spawn(async move {
472            let answers = host.relevance(&turn, message, questions).await;
473            Some(
474                asked
475                    .iter()
476                    .filter(|(key, _)| answers.get(*key).is_some_and(|p| *p < 0.5))
477                    .map(|(_, id)| *id)
478                    .collect(),
479            )
480        }))
481    }
482
483    /// Core profile: owner DMs at the top level, with a per-session stable
484    /// entity selection.
485    async fn core_profile(&self, people_enabled: bool) -> String {
486        let turn = &self.turn;
487        let source = &self.source;
488        if !(turn.allowed && turn.personal && turn.depth == 0) {
489            return String::new();
490        }
491        let cached_ids = source
492            .core_profile_ids
493            .read()
494            .await
495            .get(&turn.session_id)
496            .cloned();
497        let (profile_str, new_ids, digest) = or_logged(
498            crate::profile::build_core_profile(source.store.as_ref(), cached_ids, people_enabled)
499                .await,
500            "core_profile",
501        );
502        if let Some(ids) = new_ids {
503            source
504                .core_profile_ids
505                .write()
506                .await
507                .insert(turn.session_id.clone(), ids);
508        }
509        // The selection digest (id + content hash per entity) makes a
510        // profile change self-explaining across turns.
511        if !digest.is_empty() {
512            self.effect(RecallEffect::Decision {
513                kind: RecallDecision::CoreProfileSelection,
514                summary: format!("Core profile selection: {} entities", digest.len()),
515                metadata: json!({
516                    "code": "core_profile_digest",
517                    "count": digest.len(),
518                    "entities": digest
519                        .iter()
520                        .map(|(id, h)| json!({ "id": id, "h": h }))
521                        .collect::<Vec<_>>(),
522                }),
523            })
524            .await;
525        }
526        profile_str
527    }
528
529    /// The memory block: critical facts, core profile, then the query-ranked
530    /// memory sections. Channel, role and policy scoping are applied here.
531    /// `query` is the request's latest user message, used when the turn
532    /// gives no user text.
533    pub async fn render_block(&self, query: &str) -> String {
534        let source = &self.source;
535        let turn = &self.turn;
536        let store = &source.store;
537        let host = &self.host;
538        let allowed = turn.allowed;
539        // Memory retrieval is current-request-scoped.
540        let query = turn.user_text.as_deref().unwrap_or(query);
541        let inject_personal = turn.personal;
542        let public_external = matches!(turn.visibility, ChannelVisibility::PublicExternal);
543
544        // Facts: always channel-scoped semantic retrieval, so unrelated facts
545        // never bleed into prompts for unrelated queries.
546        let recall_started = std::time::Instant::now();
547        let facts = if !allowed {
548            vec![]
549        } else {
550            or_logged(
551                store
552                    .get_relevant_facts_for_channel(
553                        query,
554                        source.settings.max_facts,
555                        turn.channel_id.as_deref(),
556                        turn.visibility,
557                        turn.owner,
558                    )
559                    .await,
560                "facts",
561            )
562        };
563
564        // The optional recall filter asks which of these facts matter to the
565        // message. It runs beside the lookups below and is awaited where the
566        // facts are rendered.
567        let facts_ms = recall_started.elapsed().as_millis() as u64;
568        let fact_filter = self.spawn_fact_filter(query, &facts);
569
570        // The sections below read independent stores, so they run together:
571        // run one after another they put ten round trips (and the query
572        // embeddings) in front of every turn's first model call.
573        let lookups_started = std::time::Instant::now();
574        let critical_facts = async {
575            // Critical facts (identity/profile): bounded identity categories
576            // only, owner DMs (delegated agents included).
577            if allowed && inject_personal {
578                let mut identity_facts = Vec::new();
579                for category in IDENTITY_CATEGORIES {
580                    identity_facts.append(&mut or_logged(
581                        store.get_facts(Some(category)).await,
582                        "critical_facts",
583                    ));
584                }
585                extract_critical_fact_summary(&identity_facts)
586            } else {
587                Default::default()
588            }
589        };
590        // Episodes: channel-scoped for non-DM channels, and kept to the
591        // turn's project when conversations are placed in projects.
592        let episodes = async {
593            let read = self.source.episodes_to_read();
594            let episodes = if !allowed {
595                vec![]
596            } else if inject_personal {
597                or_logged(store.get_relevant_episodes(query, read).await, "episodes")
598            } else if public_external {
599                vec![]
600            } else {
601                or_logged(
602                    store
603                        .get_relevant_episodes_for_channel(query, read, turn.channel_id.as_deref())
604                        .await,
605                    "episodes",
606                )
607            };
608            self.source.episodes_in_turn_project(turn, episodes).await
609        };
610        // Personal goals/profile remain DM-only. Operational failure patterns
611        // are safe more broadly: they encode agent-side recovery guidance, not
612        // user-private preferences.
613        let goals = async {
614            if allowed && inject_personal {
615                or_logged(host.active_goals().await, "goals")
616            } else {
617                vec![]
618            }
619        };
620        let patterns = async {
621            if !allowed || public_external {
622                vec![]
623            } else if inject_personal {
624                or_logged(store.get_behavior_patterns(0.5).await, "patterns")
625            } else {
626                or_logged(store.get_behavior_patterns(0.5).await, "patterns")
627                    .into_iter()
628                    .filter(|pattern| pattern.pattern_type == "failure")
629                    .collect()
630            }
631        };
632        // Procedures and error solutions are operational: always load, except
633        // on PublicExternal where everything is restricted.
634        let procedures = async {
635            if !allowed || public_external {
636                vec![]
637            } else {
638                or_logged(store.get_relevant_procedures(query, 5).await, "procedures")
639            }
640        };
641        let error_solutions = async {
642            if !allowed || public_external {
643                vec![]
644            } else {
645                or_logged(
646                    store.get_relevant_error_solutions(query, 5).await,
647                    "error_solutions",
648                )
649            }
650        };
651        let profile = async {
652            if allowed && inject_personal {
653                or_logged(store.get_user_profile().await, "profile")
654            } else {
655                None
656            }
657        };
658        // People context, then the core profile, which reads whether people
659        // are enabled.
660        let people_and_core = async {
661            // Resolve the current speaker (only when enabled).
662            let people_enabled =
663                allowed && or_logged(host.people_enabled().await, "people_enabled");
664            let (people, current_person, current_person_facts) = if !people_enabled {
665                (vec![], None, vec![])
666            } else if inject_personal {
667                // In owner DMs the people list only selects the privacy rules;
668                // the owner's own profile arrives through the core profile.
669                (
670                    or_logged(store.get_all_people().await, "people"),
671                    None,
672                    vec![],
673                )
674            } else if let Some(ref sender_id) = turn.sender_id {
675                match store.get_person_by_platform_id(sender_id).await {
676                    Ok(Some(person)) => {
677                        self.effect(RecallEffect::TouchPerson(person.id)).await;
678                        let facts = or_logged(
679                            store.get_person_facts(person.id, None).await,
680                            "person_facts",
681                        );
682                        (vec![], Some(person), facts)
683                    }
684                    Ok(None) => (vec![], None, vec![]),
685                    Err(error) => {
686                        warn!(%error, "memory recall read failed; section left empty");
687                        (vec![], None, vec![])
688                    }
689                }
690            } else {
691                (vec![], None, vec![])
692            };
693            let core_profile = self.core_profile(people_enabled).await;
694            (people, current_person, current_person_facts, core_profile)
695        };
696        let (
697            mut critical_fact_summary,
698            episodes,
699            goals,
700            patterns,
701            procedures,
702            error_solutions,
703            profile,
704            (people, current_person, current_person_facts, core_profile),
705        ) = tokio::join!(
706            critical_facts,
707            episodes,
708            goals,
709            patterns,
710            procedures,
711            error_solutions,
712            profile,
713            people_and_core
714        );
715        if let Some(configured_name) = source.settings.assistant_name.clone() {
716            critical_fact_summary.assistant_name = Some(configured_name);
717        }
718        let lookups_ms = lookups_started.elapsed().as_millis() as u64;
719
720        let filter_wait_started = std::time::Instant::now();
721        let facts = match fact_filter {
722            Some(filter) => match filter.await {
723                Ok(Some(drop)) if !drop.is_empty() => {
724                    let before = facts.len();
725                    let kept: Vec<_> = facts
726                        .into_iter()
727                        .filter(|fact| !drop.contains(&fact.id))
728                        .collect();
729                    info!(
730                        dropped = before - kept.len(),
731                        kept = kept.len(),
732                        "Recall filter dropped facts irrelevant to the message"
733                    );
734                    kept
735                }
736                _ => facts,
737            },
738            None => facts,
739        };
740        let filter_wait_ms = filter_wait_started.elapsed().as_millis() as u64;
741
742        let memory_context = MemoryContext {
743            facts: &facts,
744            episodes: &episodes,
745            goals: &goals,
746            patterns: &patterns,
747            procedures: &procedures,
748            error_solutions: &error_solutions,
749            profile: profile.as_ref(),
750            people: &people,
751            current_person: current_person.as_ref(),
752            current_person_facts: &current_person_facts,
753            scheduled_goals_tool: self.host.offers_scheduled_goals(),
754        };
755        let report = render_memory_section(&memory_context, source.settings.max_facts);
756        self.effect(RecallEffect::Recalled {
757            facts: report.rendered_fact_ids.clone(),
758            episodes: report.rendered_episode_ids.clone(),
759        })
760        .await;
761        self.effect(RecallEffect::Decision {
762            kind: RecallDecision::MemoryRetrieval,
763            summary: format!(
764                "Memory fetched/rendered: facts={}/{} episodes={}/{} procedures={}/{}",
765                facts.len(),
766                report.rendered_fact_ids.len(),
767                episodes.len(),
768                report.rendered_episode_ids.len(),
769                procedures.len(),
770                report.rendered_procedure_ids.len()
771            ),
772            metadata: json!({
773                "policy": if allowed { "allowed" } else { "suppressed" },
774                "pipeline_suppressed": !allowed,
775                "fetched": {
776                    "facts": facts.len(),
777                    "episodes": episodes.len(),
778                    "goals": goals.len(),
779                    "patterns": patterns.len(),
780                    "procedures": procedures.len(),
781                    "error_solutions": error_solutions.len(),
782                    "people": people.len(),
783                    "current_person_facts": current_person_facts.len()
784                },
785                "rendered": {
786                    "fact_ids": report.rendered_fact_ids,
787                    "episode_ids": report.rendered_episode_ids,
788                    "goal_ids": report.rendered_goal_ids,
789                    "procedure_ids": report.rendered_procedure_ids,
790                    "error_solution_ids": report.rendered_error_solution_ids,
791                    "pattern_ids": report.rendered_pattern_ids
792                }
793            }),
794        })
795        .await;
796        info!(
797            session_id = %turn.session_id,
798            facts = facts.len(),
799            episodes = episodes.len(),
800            goals = goals.len(),
801            patterns = patterns.len(),
802            procedures = procedures.len(),
803            elapsed_ms = recall_started.elapsed().as_millis() as u64,
804            facts_ms,
805            lookups_ms,
806            filter_wait_ms,
807            "Memory context loaded"
808        );
809        let mut block =
810            build_critical_facts_prompt_block(&critical_fact_summary).unwrap_or_default();
811        if !core_profile.is_empty() {
812            if !block.is_empty() {
813                block.push_str("\n\n");
814            }
815            block.push_str(&core_profile);
816        }
817        block.push_str(&report.prompt);
818        // Project notes come last, so the owner's own sections keep their
819        // place and a turn without a project renders exactly as before.
820        if let Some(section) = source.project_section(turn).await {
821            if !block.trim().is_empty() {
822                block.push_str("\n\n");
823            }
824            block.push_str(&section);
825        }
826        block.trim_start().to_string()
827    }
828}
829
830impl Drop for FullRecall {
831    /// A turn that ends before its first model call stops the prefetch.
832    fn drop(&mut self) {
833        if let Ok(mut prefetched) = self.prefetched.lock()
834            && let Some(handle) = prefetched.take()
835        {
836            handle.abort();
837        }
838    }
839}
840
841#[async_trait]
842impl aidaemon_policies::Recall for FullRecall {
843    /// Channel-scoped fact lines, for generic callers.
844    async fn recall(&self, _session_id: &str, query: &str, limit: usize) -> Vec<String> {
845        if !self.turn.allowed {
846            return Vec::new();
847        }
848        let facts = self
849            .source
850            .store
851            .get_relevant_facts_for_channel(
852                query,
853                limit,
854                self.turn.channel_id.as_deref(),
855                self.turn.visibility,
856                self.turn.owner,
857            )
858            .await;
859        or_logged(facts, "facts")
860            .into_iter()
861            .map(|fact| format!("[{}] {}: {}", fact.category, fact.key, fact.value))
862            .collect()
863    }
864
865    /// The full memory block with its section headings.
866    async fn render(&self, _session_id: &str, query: &str, _limit: usize) -> Option<String> {
867        let block = match self.take_prefetched().await {
868            Some(block) => block,
869            None => self.render_block(query).await,
870        };
871        (!block.trim().is_empty()).then_some(block)
872    }
873}