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