Skip to main content

aidaemon_memory/full/
jobs.rs

1//! The full memory system's background jobs: embedding backfill, fact
2//! consolidation, decay, episodes for idle and long sessions, and pattern
3//! detection, with the schedule each runs on ([`MemoryJobs::services`]).
4//!
5//! The jobs read the host's conversation log through [`ActivityLog`] and
6//! leave what is the host's to [`JobsHost`]: which model runs each call,
7//! learning from a session's work trace, and filing the goals an episode
8//! mentions.
9
10use std::sync::{Arc, Mutex};
11use std::time::{Duration, Instant};
12
13use aidaemon_core::{FnService, Provider, Schedule, Service, ServiceError};
14use async_trait::async_trait;
15use chrono::{DateTime, Utc};
16use tracing::{info, warn};
17
18use crate::Embedder;
19use crate::episodes::TranscriptEntry;
20use crate::history::{ActivityLog, LoggedTurn, TurnRole, UncapturedSessions};
21use crate::stores::MemoryStores;
22
23/// A background model call the jobs make.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum JobCall {
26    /// Durable facts from owner history.
27    FactConsolidation,
28    /// Model-assisted review of overlapping/duplicate stored facts.
29    MemoryHygiene,
30    /// An episode's summary of a session.
31    SessionAnalysis,
32}
33
34/// What the jobs leave to the host.
35#[async_trait]
36pub trait JobsHost: Send + Sync {
37    /// The provider and model for `call`, asked on every pass.
38    fn model(&self, call: JobCall) -> (Arc<dyn Provider>, String);
39
40    /// Whether a model is connected. With none, the jobs that call a model
41    /// (consolidation, episodes) skip their pass quietly. Default: true.
42    fn has_model(&self) -> bool {
43        true
44    }
45
46    /// Learn from the work recorded in `session_id` (procedures, error
47    /// solutions, expertise) after its facts were consolidated. The host
48    /// owns its work trace. Default: nothing.
49    async fn learn_session(&self, _session_id: &str) -> anyhow::Result<()> {
50        Ok(())
51    }
52
53    /// File `goal`, which episode `episode_id` of `session_id` mentioned.
54    /// Goals are the host's. Default: nothing.
55    async fn file_goal(
56        &self,
57        _goal: &str,
58        _episode_id: i64,
59        _session_id: &str,
60    ) -> anyhow::Result<()> {
61        Ok(())
62    }
63}
64
65/// How often each job runs.
66#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub struct JobSchedule {
68    pub embeddings: Duration,
69    pub consolidation: Duration,
70    pub decay: Duration,
71    pub hygiene: Duration,
72    pub episodes: Duration,
73    pub pattern_detection: Duration,
74}
75
76impl Default for JobSchedule {
77    /// Embeddings every 5 s, consolidation every 6 h, decay daily, hygiene
78    /// every 12 h, episodes every 30 min, pattern detection every 6 h.
79    fn default() -> Self {
80        Self {
81            embeddings: Duration::from_secs(5),
82            consolidation: Duration::from_secs(6 * 3600),
83            decay: Duration::from_secs(24 * 3600),
84            hygiene: Duration::from_secs(12 * 3600),
85            episodes: Duration::from_secs(30 * 60),
86            pattern_detection: Duration::from_secs(6 * 3600),
87        }
88    }
89}
90
91/// A session goes idle this long after its last turn.
92const IDLE_AFTER: chrono::Duration = chrono::Duration::minutes(30);
93/// Uncaptured turns an idle session needs before it gets an episode.
94const IDLE_MIN_TURNS: usize = 5;
95/// Uncaptured turns that give an active session a mid-session episode.
96const LONG_MIN_TURNS: usize = 20;
97/// Turns an episode covers at most.
98const EPISODE_TURNS: usize = 100;
99/// Turns a mid-session episode needs once read.
100const LONG_MIN_MESSAGES: usize = 10;
101/// How far back pattern detection looks, and how much it reads.
102const PATTERN_WINDOW: chrono::Duration = chrono::Duration::hours(24);
103const PATTERN_TURNS: usize = 500;
104/// Longest wait between embedding passes that keep finding nothing.
105const EMBEDDINGS_IDLE_CAP: Duration = Duration::from_secs(5 * 60);
106
107/// Spaces out embedding passes that find nothing to embed: each empty pass
108/// doubles the wait before the next, up to [`EMBEDDINGS_IDLE_CAP`]; a pass
109/// that embeds something, or fails, goes back to the schedule's pace.
110/// The pass itself is a scan for rows without an embedding, so running it
111/// every few seconds on a fully embedded store only costs database time.
112#[derive(Debug)]
113struct IdleBackoff {
114    base: Duration,
115    cap: Duration,
116    wait: Duration,
117    next_due: Option<Instant>,
118}
119
120impl IdleBackoff {
121    fn new(base: Duration, cap: Duration) -> Self {
122        Self {
123            base,
124            cap: cap.max(base),
125            wait: Duration::ZERO,
126            next_due: None,
127        }
128    }
129
130    fn due(&self, now: Instant) -> bool {
131        self.next_due.is_none_or(|due| now >= due)
132    }
133
134    /// Record a pass at `now` that did (`true`) or did not find work.
135    fn record(&mut self, now: Instant, found_work: bool) {
136        if found_work {
137            self.wait = Duration::ZERO;
138            self.next_due = None;
139        } else {
140            self.wait = if self.wait.is_zero() {
141                self.base
142            } else {
143                (self.wait * 2).min(self.cap)
144            };
145            self.next_due = Some(now + self.wait);
146        }
147    }
148
149    fn reset(&mut self) {
150        self.wait = Duration::ZERO;
151        self.next_due = None;
152    }
153}
154
155/// The full memory system's background jobs over `store`.
156pub struct MemoryJobs {
157    store: Arc<dyn MemoryStores>,
158    log: Arc<dyn ActivityLog>,
159    host: Arc<dyn JobsHost>,
160    embedder: Arc<dyn Embedder>,
161    schedule: JobSchedule,
162    /// Project memory, for consolidation of sessions that work in a project.
163    project_notes: Option<Arc<crate::project::ProjectNotes>>,
164    /// Spaces out [`Self::embeddings`] passes while they find nothing.
165    embeddings_backoff: Mutex<IdleBackoff>,
166}
167
168impl MemoryJobs {
169    pub fn new(
170        store: Arc<dyn MemoryStores>,
171        log: Arc<dyn ActivityLog>,
172        host: Arc<dyn JobsHost>,
173        embedder: Arc<dyn Embedder>,
174    ) -> Self {
175        Self {
176            store,
177            log,
178            host,
179            embedder,
180            schedule: JobSchedule::default(),
181            project_notes: None,
182            embeddings_backoff: Mutex::new(IdleBackoff::new(
183                JobSchedule::default().embeddings,
184                EMBEDDINGS_IDLE_CAP,
185            )),
186        }
187    }
188
189    /// Consolidation keeps project facts of a session that works in a
190    /// project ([`ConversationSource::project`]) in `notes`.
191    ///
192    /// [`ConversationSource::project`]: crate::history::ConversationSource::project
193    pub fn with_project_notes(mut self, notes: Option<Arc<crate::project::ProjectNotes>>) -> Self {
194        self.project_notes = notes;
195        self
196    }
197
198    pub fn with_schedule(mut self, schedule: JobSchedule) -> Self {
199        self.schedule = schedule;
200        self.embeddings_backoff =
201            Mutex::new(IdleBackoff::new(schedule.embeddings, EMBEDDINGS_IDLE_CAP));
202        self
203    }
204
205    /// The jobs as services, named `embeddings`, `consolidation`,
206    /// `memory_decay`, `memory_hygiene`, `episodes` and `pattern_detection`.
207    pub fn services(self: &Arc<Self>) -> Vec<Arc<dyn Service>> {
208        fn every<F, Fut>(name: &str, interval: Duration, run: F) -> Arc<dyn Service>
209        where
210            F: Fn() -> Fut + Send + Sync + 'static,
211            Fut: std::future::Future<Output = anyhow::Result<()>> + Send + 'static,
212        {
213            Arc::new(FnService::new(name, Schedule::Every(interval), move || {
214                let run = run();
215                async move { run.await.map_err(|e| ServiceError::new(e.to_string())) }
216            }))
217        }
218        let schedule = self.schedule;
219        let jobs = self.clone();
220        let embeddings = every("embeddings", schedule.embeddings, move || {
221            let jobs = jobs.clone();
222            async move { jobs.embeddings().await.map(|_| ()) }
223        });
224        let jobs = self.clone();
225        let consolidation = every("consolidation", schedule.consolidation, move || {
226            let jobs = jobs.clone();
227            async move { jobs.consolidate(Utc::now()).await }
228        });
229        let jobs = self.clone();
230        // Poll hourly (or at schedule.decay if shorter) and let the persisted
231        // watermark enforce the true cadence, so startup queue jitter or a
232        // restart right before a run is due never skips a whole 24h cycle.
233        let decay_poll = schedule.decay.min(Duration::from_secs(3600));
234        let decay = every("memory_decay", decay_poll, move || {
235            let jobs = jobs.clone();
236            async move { jobs.decay_if_due(Utc::now()).await.map(|_| ()) }
237        });
238        let jobs = self.clone();
239        let hygiene_poll = schedule.hygiene.min(Duration::from_secs(3600));
240        let hygiene = every("memory_hygiene", hygiene_poll, move || {
241            let jobs = jobs.clone();
242            async move { jobs.hygiene_if_due(Utc::now()).await.map(|_| ()) }
243        });
244        let jobs = self.clone();
245        let episodes = every("episodes", schedule.episodes, move || {
246            let jobs = jobs.clone();
247            async move { jobs.episodes(Utc::now()).await }
248        });
249        let jobs = self.clone();
250        let patterns = every("pattern_detection", schedule.pattern_detection, move || {
251            let jobs = jobs.clone();
252            async move { jobs.detect_patterns(Utc::now()).await }
253        });
254        vec![
255            embeddings,
256            consolidation,
257            decay,
258            hygiene,
259            episodes,
260            patterns,
261        ]
262    }
263
264    /// Embed one batch of learned records still missing an embedding.
265    /// True when there was something to embed. While passes keep finding
266    /// nothing, later calls skip the scan (returning false) until the backoff
267    /// is due again (doubling from 5 s up to 5 min while passes stay empty).
268    pub async fn embeddings(&self) -> anyhow::Result<bool> {
269        if !self.backoff().due(Instant::now()) {
270            return Ok(false);
271        }
272        let result =
273            crate::backfill_learning_embeddings(self.store.as_ref(), self.embedder.as_ref()).await;
274        let mut backoff = self.backoff();
275        match &result {
276            Ok(found_work) => backoff.record(Instant::now(), *found_work),
277            Err(_) => backoff.reset(),
278        }
279        Ok(result?)
280    }
281
282    fn backoff(&self) -> std::sync::MutexGuard<'_, IdleBackoff> {
283        self.embeddings_backoff
284            .lock()
285            .unwrap_or_else(std::sync::PoisonError::into_inner)
286    }
287
288    /// Consolidate durable facts from owner history up to an hour before
289    /// `now` ([`FactConsolidator`](crate::consolidation::FactConsolidator)),
290    /// then let the host learn from the same sessions' work.
291    pub async fn consolidate(&self, now: DateTime<Utc>) -> anyhow::Result<()> {
292        if !self.host.has_model() {
293            tracing::debug!("Memory consolidation skipped: no model is connected");
294            return Ok(());
295        }
296        let (provider, model) = self.host.model(JobCall::FactConsolidation);
297        let report = crate::consolidation::FactConsolidator::new(provider, model)
298            .with_project_notes(self.project_notes.clone())
299            .consolidate(
300                self.log.as_ref(),
301                self.log.as_ref(),
302                self.store.as_ref(),
303                now,
304            )
305            .await?;
306        for session_id in &report.consolidated_sessions {
307            // Recheck, so a session classified isolated since never enters
308            // learning.
309            if self.log.is_memory_isolated(session_id).await? {
310                continue;
311            }
312            if let Err(e) = self.host.learn_session(session_id).await {
313                warn!(
314                    "Event consolidation failed for session {}: {}",
315                    session_id, e
316                );
317            }
318        }
319        Ok(())
320    }
321
322    /// Merge restated facts, resolve safe numeric conflicts, archive idle
323    /// low-authority facts, then let unrecalled memory fade.
324    pub async fn decay(&self) -> anyhow::Result<()> {
325        crate::stores::decay_memory(self.store.as_ref(), &crate::stores::DecayPolicy::default())
326            .await?;
327        info!("Applied memory decay");
328        Ok(())
329    }
330
331    /// Run [`Self::decay`] only when at least `schedule.decay` has elapsed
332    /// since the persisted `"memory_decay"` watermark. Keeps daemon restarts
333    /// from applying extra decay steps.
334    pub async fn decay_if_due(&self, now: DateTime<Utc>) -> anyhow::Result<bool> {
335        if !self
336            .watermark_due("memory_decay", self.schedule.decay, now)
337            .await?
338        {
339            tracing::debug!("Memory decay skipped: watermark is not due yet");
340            return Ok(false);
341        }
342        self.decay().await?;
343        self.store.record_job_run_at("memory_decay", now).await?;
344        Ok(true)
345    }
346
347    /// Run one bounded model-assisted hygiene pass over unreviewed overlapping
348    /// facts ([`crate::hygiene::MemoryHygiene`]). Skips quietly when no model
349    /// is connected.
350    pub async fn hygiene(&self) -> anyhow::Result<crate::hygiene::HygieneReport> {
351        if !self.host.has_model() {
352            tracing::debug!("Memory hygiene skipped: no model is connected");
353            return Ok(crate::hygiene::HygieneReport::default());
354        }
355        let (provider, model) = self.host.model(JobCall::MemoryHygiene);
356        crate::hygiene::MemoryHygiene::new(provider, model)
357            .review_overlaps(self.store.as_ref())
358            .await
359    }
360
361    /// Run [`Self::hygiene`] only when a model is connected and at least
362    /// `schedule.hygiene` has elapsed since the persisted `"memory_hygiene"`
363    /// watermark.
364    pub async fn hygiene_if_due(&self, now: DateTime<Utc>) -> anyhow::Result<bool> {
365        if !self.host.has_model() {
366            tracing::debug!("Memory hygiene skipped: no model is connected");
367            return Ok(false);
368        }
369        if !self
370            .watermark_due("memory_hygiene", self.schedule.hygiene, now)
371            .await?
372        {
373            tracing::debug!("Memory hygiene skipped: watermark is not due yet");
374            return Ok(false);
375        }
376        let report = self.hygiene().await?;
377        if !report.model_failed {
378            // Catch-up pacing: when more eligible clusters remain beyond one
379            // pass's cap, back-date the watermark so the next hourly poll keeps
380            // draining the backlog; once caught up, record `now` so steady
381            // state returns to the full `schedule.hygiene` cadence.
382            let catchup_step = Duration::from_secs(3600);
383            let watermark_at = if report.has_more_clusters && self.schedule.hygiene > catchup_step {
384                let backdate = chrono::Duration::from_std(self.schedule.hygiene - catchup_step)
385                    .unwrap_or_default();
386                now - backdate
387            } else {
388                now
389            };
390            self.store
391                .record_job_run_at("memory_hygiene", watermark_at)
392                .await?;
393        }
394        Ok(!report.model_failed)
395    }
396
397    async fn watermark_due(
398        &self,
399        job_name: &str,
400        interval: Duration,
401        now: DateTime<Utc>,
402    ) -> anyhow::Result<bool> {
403        let Some(last) = self.store.job_last_run_at(job_name).await? else {
404            return Ok(true);
405        };
406        let min_elapsed = chrono::Duration::from_std(interval).unwrap_or(chrono::Duration::MAX);
407        Ok(now.signed_duration_since(last) >= min_elapsed)
408    }
409
410    /// Episodes for sessions idle 30 minutes with 5+ uncaptured turns, then
411    /// mid-session ones for sessions with 20+.
412    pub async fn episodes(&self, now: DateTime<Utc>) -> anyhow::Result<()> {
413        if !self.host.has_model() {
414            tracing::debug!("Episode creation skipped: no model is connected");
415            return Ok(());
416        }
417        if let Err(e) = self.episodes_for_idle_sessions(now).await {
418            warn!(error = %e, "Failed to create episodes for idle sessions");
419        }
420        self.episodes_for_long_sessions().await
421    }
422
423    /// Record an episode of `session_id` from `turns`
424    /// ([`SessionAnalyst`](crate::episodes::SessionAnalyst)), then hand the
425    /// goals it found to the host.
426    pub async fn create_episode(
427        &self,
428        session_id: &str,
429        turns: &[LoggedTurn],
430    ) -> anyhow::Result<i64> {
431        anyhow::ensure!(
432            !self.log.is_memory_isolated(session_id).await?,
433            "Memory-isolated worker sessions cannot create global episodes"
434        );
435        let entries = transcript_entries(turns);
436        let start_time = turns.first().map(|t| t.created_at).unwrap_or_else(Utc::now);
437        let end_time = turns.last().map(|t| t.created_at).unwrap_or_else(Utc::now);
438        let (provider, model) = self.host.model(JobCall::SessionAnalysis);
439        let (episode_id, analysis) = crate::episodes::SessionAnalyst::new(provider, model)
440            .record_episode(
441                self.store.as_ref(),
442                session_id,
443                &entries,
444                turns.len(),
445                start_time,
446                end_time,
447                self.log.channel_id(session_id),
448            )
449            .await?;
450        for goal_text in &analysis.goals_mentioned {
451            if let Err(e) = self.host.file_goal(goal_text, episode_id, session_id).await {
452                warn!("Failed to extract goal '{}': {}", goal_text, e);
453            }
454        }
455        Ok(episode_id)
456    }
457
458    /// Habitual tool sequences and the owner's verbosity, from the last
459    /// day's activity.
460    pub async fn detect_patterns(&self, now: DateTime<Utc>) -> anyhow::Result<()> {
461        let since = now - PATTERN_WINDOW;
462        let recent = self.log.recent_turns(since, PATTERN_TURNS).await?;
463        let owner_messages = self.log.recent_owner_messages(since, PATTERN_TURNS).await?;
464        if recent.is_empty() {
465            return Ok(());
466        }
467        let tools: Vec<String> = recent
468            .iter()
469            .flat_map(|turn| turn.tool_calls.iter().cloned())
470            .collect();
471        let patterns = crate::record_tool_sequence_patterns(self.store.as_ref(), &tools).await?;
472        if !patterns.is_empty() {
473            info!(count = patterns.len(), "Detected behavior patterns");
474        }
475        let owner_texts: Vec<&str> = owner_messages
476            .iter()
477            .filter(|turn| turn.role == TurnRole::User)
478            .filter_map(|turn| turn.content.as_deref())
479            .collect();
480        if crate::update_communication_profile(self.store.as_ref(), &owner_texts)
481            .await?
482            .is_some()
483        {
484            info!("Updated user communication profile");
485        }
486        Ok(())
487    }
488
489    async fn uncaptured(&self, which: UncapturedSessions) -> anyhow::Result<Vec<String>> {
490        let ends = self.store.latest_episode_ends().await?;
491        let mut eligible = Vec::new();
492        for session_id in self.log.uncaptured_sessions(&ends, which).await? {
493            if !self.log.is_memory_isolated(&session_id).await? {
494                eligible.push(session_id);
495            }
496        }
497        Ok(eligible)
498    }
499
500    /// The session's turns since its latest episode, if they all came from
501    /// the owner; `None` otherwise.
502    async fn owner_turns_since_last_episode(
503        &self,
504        session_id: &str,
505    ) -> anyhow::Result<Option<Vec<LoggedTurn>>> {
506        let bound = self.store.last_episode_bound(session_id).await?;
507        if !self
508            .log
509            .owner_only_after(session_id, bound.as_ref())
510            .await?
511        {
512            return Ok(None);
513        }
514        Ok(Some(
515            self.log
516                .turns_after(session_id, bound.as_ref(), EPISODE_TURNS)
517                .await?,
518        ))
519    }
520
521    async fn episodes_for_idle_sessions(&self, now: DateTime<Utc>) -> anyhow::Result<()> {
522        let idle = self
523            .uncaptured(UncapturedSessions {
524                min_turns: IDLE_MIN_TURNS,
525                idle_before: Some(now - IDLE_AFTER),
526            })
527            .await?;
528        if idle.is_empty() {
529            return Ok(());
530        }
531        info!(count = idle.len(), "Creating episodes for idle sessions");
532        for session_id in idle {
533            let Some(turns) = self.owner_turns_since_last_episode(&session_id).await? else {
534                continue;
535            };
536            if turns.len() >= IDLE_MIN_TURNS {
537                match self.create_episode(&session_id, &turns).await {
538                    Ok(episode_id) => {
539                        info!(session_id, episode_id, "Created episode for idle session");
540                    }
541                    Err(e) => {
542                        warn!(session_id, error = %e, "Failed to create episode for idle session");
543                    }
544                }
545            }
546        }
547        Ok(())
548    }
549
550    /// Sessions with many turns since their last episode risk losing
551    /// context as the message window rotates: capture it now.
552    async fn episodes_for_long_sessions(&self) -> anyhow::Result<()> {
553        let long = self
554            .uncaptured(UncapturedSessions {
555                min_turns: LONG_MIN_TURNS,
556                idle_before: None,
557            })
558            .await?;
559        for session_id in long {
560            let Some(turns) = self.owner_turns_since_last_episode(&session_id).await? else {
561                continue;
562            };
563            if turns.len() >= LONG_MIN_MESSAGES {
564                match self.create_episode(&session_id, &turns).await {
565                    Ok(episode_id) => {
566                        info!(
567                            session_id,
568                            episode_id, "Created mid-session episode for long-running session"
569                        );
570                    }
571                    Err(e) => {
572                        warn!(
573                            session_id,
574                            error = %e,
575                            "Failed to create mid-session episode"
576                        );
577                    }
578                }
579            }
580        }
581        Ok(())
582    }
583}
584
585/// Logged turns as episode transcript entries.
586fn transcript_entries(turns: &[LoggedTurn]) -> Vec<TranscriptEntry> {
587    turns
588        .iter()
589        .map(|turn| TranscriptEntry {
590            role: turn.role,
591            content: turn.content.clone(),
592            tool_calls: turn.tool_calls.clone(),
593            tool_name: turn.tool_name.clone(),
594        })
595        .collect()
596}
597
598#[cfg(test)]
599mod tests {
600    use super::*;
601
602    const BASE: Duration = Duration::from_secs(5);
603    const CAP: Duration = Duration::from_secs(60);
604
605    #[test]
606    fn empty_passes_double_the_wait_up_to_the_cap() {
607        let start = Instant::now();
608        let mut backoff = IdleBackoff::new(BASE, CAP);
609        assert!(backoff.due(start));
610
611        let mut now = start;
612        let mut waits = Vec::new();
613        for _ in 0..6 {
614            backoff.record(now, false);
615            waits.push(backoff.wait);
616            assert!(!backoff.due(now + backoff.wait - Duration::from_millis(1)));
617            now += backoff.wait;
618            assert!(backoff.due(now));
619        }
620        let secs: Vec<u64> = waits.iter().map(Duration::as_secs).collect();
621        assert_eq!(secs, [5, 10, 20, 40, 60, 60]);
622    }
623
624    #[test]
625    fn a_pass_with_work_returns_to_the_schedule_pace() {
626        let now = Instant::now();
627        let mut backoff = IdleBackoff::new(BASE, CAP);
628        for _ in 0..4 {
629            backoff.record(now, false);
630        }
631        backoff.record(now, true);
632        assert!(backoff.due(now));
633        backoff.record(now, false);
634        assert_eq!(backoff.wait, BASE);
635    }
636
637    #[test]
638    fn a_failed_pass_clears_the_backoff() {
639        let now = Instant::now();
640        let mut backoff = IdleBackoff::new(BASE, CAP);
641        backoff.record(now, false);
642        backoff.reset();
643        assert!(backoff.due(now));
644    }
645
646    #[tokio::test]
647    async fn decay_and_hygiene_respect_persisted_watermarks_across_restarts() {
648        use aidaemon_core::testing::ScriptedProvider;
649        use sqlx::sqlite::SqlitePoolOptions;
650
651        struct EmptyLog;
652        #[async_trait]
653        impl crate::history::ConsolidationCursors for EmptyLog {
654            async fn cursor(&self, _session_id: &str) -> i64 {
655                0
656            }
657            async fn set_cursor(&self, _session_id: &str, _turn_id: i64) -> anyhow::Result<()> {
658                Ok(())
659            }
660        }
661        #[async_trait]
662        impl crate::history::ConversationSource for EmptyLog {
663            async fn sessions_with_turns_before(
664                &self,
665                _cutoff: DateTime<Utc>,
666            ) -> anyhow::Result<Vec<String>> {
667                Ok(Vec::new())
668            }
669            async fn owner_only_since(
670                &self,
671                _session_id: &str,
672                _after_id: i64,
673                _before: DateTime<Utc>,
674            ) -> anyhow::Result<bool> {
675                Ok(true)
676            }
677            async fn last_turn_id(
678                &self,
679                _session_id: &str,
680                _after_id: i64,
681                _before: DateTime<Utc>,
682            ) -> anyhow::Result<Option<i64>> {
683                Ok(None)
684            }
685            async fn turns(
686                &self,
687                _session_id: &str,
688                _after_id: i64,
689                _before: DateTime<Utc>,
690                _limit: usize,
691            ) -> anyhow::Result<Vec<crate::history::HistoryTurn>> {
692                Ok(Vec::new())
693            }
694            async fn is_memory_isolated(&self, _session_id: &str) -> anyhow::Result<bool> {
695                Ok(false)
696            }
697            async fn visibility(
698                &self,
699                _session_id: &str,
700            ) -> Option<aidaemon_core::ChannelVisibility> {
701                None
702            }
703            fn channel_id(&self, _session_id: &str) -> Option<String> {
704                None
705            }
706        }
707        #[async_trait]
708        impl ActivityLog for EmptyLog {
709            async fn uncaptured_sessions(
710                &self,
711                _episode_ends: &[(String, String)],
712                _which: UncapturedSessions,
713            ) -> anyhow::Result<Vec<String>> {
714                Ok(Vec::new())
715            }
716            async fn owner_only_after(
717                &self,
718                _session_id: &str,
719                _bound: Option<&crate::records::EpisodeBound>,
720            ) -> anyhow::Result<bool> {
721                Ok(true)
722            }
723            async fn turns_after(
724                &self,
725                _session_id: &str,
726                _bound: Option<&crate::records::EpisodeBound>,
727                _limit: usize,
728            ) -> anyhow::Result<Vec<LoggedTurn>> {
729                Ok(Vec::new())
730            }
731            async fn recent_turns(
732                &self,
733                _since: DateTime<Utc>,
734                _limit: usize,
735            ) -> anyhow::Result<Vec<LoggedTurn>> {
736                Ok(Vec::new())
737            }
738            async fn recent_owner_messages(
739                &self,
740                _since: DateTime<Utc>,
741                _limit: usize,
742            ) -> anyhow::Result<Vec<LoggedTurn>> {
743                Ok(Vec::new())
744            }
745        }
746
747        struct TestHost {
748            has_model: bool,
749            provider: Arc<dyn Provider>,
750        }
751        #[async_trait]
752        impl JobsHost for TestHost {
753            fn model(&self, _call: JobCall) -> (Arc<dyn Provider>, String) {
754                (self.provider.clone(), "mock".to_string())
755            }
756            fn has_model(&self) -> bool {
757                self.has_model
758            }
759        }
760
761        let pool = SqlitePoolOptions::new()
762            .max_connections(1)
763            .connect("sqlite::memory:")
764            .await
765            .unwrap();
766        crate::sqlite::migrate(&pool).await.unwrap();
767        let embedder: Arc<dyn Embedder> = Arc::new(crate::HashEmbedder::default());
768        let store: Arc<dyn MemoryStores> =
769            Arc::new(crate::sqlite::SqliteMemory::new(pool, embedder.clone()));
770        let provider: Arc<dyn Provider> = Arc::new(ScriptedProvider::new(vec![]));
771
772        let make_jobs = |has_model: bool| {
773            MemoryJobs::new(
774                store.clone(),
775                Arc::new(EmptyLog),
776                Arc::new(TestHost {
777                    has_model,
778                    provider: provider.clone(),
779                }),
780                embedder.clone(),
781            )
782        };
783
784        let t0 = Utc::now();
785        let jobs = make_jobs(true);
786        assert!(jobs.decay_if_due(t0).await.unwrap());
787        // Simulated restart 1 hour later: watermark prevents double decay.
788        let restarted = make_jobs(true);
789        assert!(
790            !restarted
791                .decay_if_due(t0 + chrono::Duration::hours(1))
792                .await
793                .unwrap()
794        );
795        // After 24 hours, decay runs again.
796        assert!(
797            restarted
798                .decay_if_due(t0 + chrono::Duration::hours(24))
799                .await
800                .unwrap()
801        );
802
803        // Hygiene skips when no model is connected without recording a watermark.
804        let no_model = make_jobs(false);
805        assert!(!no_model.hygiene_if_due(t0).await.unwrap());
806        // With a model, hygiene runs once, then skips until 12 hours elapse.
807        assert!(restarted.hygiene_if_due(t0).await.unwrap());
808        assert!(
809            !restarted
810                .hygiene_if_due(t0 + chrono::Duration::hours(6))
811                .await
812                .unwrap()
813        );
814        assert!(
815            restarted
816                .hygiene_if_due(t0 + chrono::Duration::hours(12))
817                .await
818                .unwrap()
819        );
820    }
821
822    #[tokio::test]
823    async fn hygiene_uses_hourly_catchup_when_more_clusters_remain() {
824        use crate::stores::FactStore;
825        use aidaemon_core::testing::{ScriptedProvider, text};
826        use sqlx::sqlite::SqlitePoolOptions;
827
828        struct EmptyLog;
829        #[async_trait]
830        impl crate::history::ConsolidationCursors for EmptyLog {
831            async fn cursor(&self, _session_id: &str) -> i64 {
832                0
833            }
834            async fn set_cursor(&self, _session_id: &str, _turn_id: i64) -> anyhow::Result<()> {
835                Ok(())
836            }
837        }
838        #[async_trait]
839        impl crate::history::ConversationSource for EmptyLog {
840            async fn sessions_with_turns_before(
841                &self,
842                _cutoff: DateTime<Utc>,
843            ) -> anyhow::Result<Vec<String>> {
844                Ok(Vec::new())
845            }
846            async fn owner_only_since(
847                &self,
848                _session_id: &str,
849                _after_id: i64,
850                _before: DateTime<Utc>,
851            ) -> anyhow::Result<bool> {
852                Ok(true)
853            }
854            async fn last_turn_id(
855                &self,
856                _session_id: &str,
857                _after_id: i64,
858                _before: DateTime<Utc>,
859            ) -> anyhow::Result<Option<i64>> {
860                Ok(None)
861            }
862            async fn turns(
863                &self,
864                _session_id: &str,
865                _after_id: i64,
866                _before: DateTime<Utc>,
867                _limit: usize,
868            ) -> anyhow::Result<Vec<crate::history::HistoryTurn>> {
869                Ok(Vec::new())
870            }
871            async fn is_memory_isolated(&self, _session_id: &str) -> anyhow::Result<bool> {
872                Ok(false)
873            }
874            async fn visibility(
875                &self,
876                _session_id: &str,
877            ) -> Option<aidaemon_core::ChannelVisibility> {
878                None
879            }
880            fn channel_id(&self, _session_id: &str) -> Option<String> {
881                None
882            }
883        }
884        #[async_trait]
885        impl ActivityLog for EmptyLog {
886            async fn uncaptured_sessions(
887                &self,
888                _episode_ends: &[(String, String)],
889                _which: UncapturedSessions,
890            ) -> anyhow::Result<Vec<String>> {
891                Ok(Vec::new())
892            }
893            async fn owner_only_after(
894                &self,
895                _session_id: &str,
896                _bound: Option<&crate::records::EpisodeBound>,
897            ) -> anyhow::Result<bool> {
898                Ok(true)
899            }
900            async fn turns_after(
901                &self,
902                _session_id: &str,
903                _bound: Option<&crate::records::EpisodeBound>,
904                _limit: usize,
905            ) -> anyhow::Result<Vec<LoggedTurn>> {
906                Ok(Vec::new())
907            }
908            async fn recent_turns(
909                &self,
910                _since: DateTime<Utc>,
911                _limit: usize,
912            ) -> anyhow::Result<Vec<LoggedTurn>> {
913                Ok(Vec::new())
914            }
915            async fn recent_owner_messages(
916                &self,
917                _since: DateTime<Utc>,
918                _limit: usize,
919            ) -> anyhow::Result<Vec<LoggedTurn>> {
920                Ok(Vec::new())
921            }
922        }
923
924        struct ClusterEmbedder;
925        #[async_trait]
926        impl Embedder for ClusterEmbedder {
927            fn model_id(&self) -> &str {
928                "test-clusters"
929            }
930            fn dimensions(&self) -> usize {
931                16
932            }
933            async fn embed(&self, texts: &[String]) -> crate::error::Result<Vec<Vec<f32>>> {
934                Ok(texts
935                    .iter()
936                    .map(|t| {
937                        let mut v = vec![0.0f32; 16];
938                        for idx in 0..14 {
939                            let tag = format!("topic{idx:02}");
940                            if t.contains(&tag) {
941                                if t.contains("variantb") {
942                                    v[idx] = 0.80;
943                                    v[15] = 0.60;
944                                } else {
945                                    v[idx] = 0.99;
946                                    v[15] = 0.14;
947                                }
948                                return v;
949                            }
950                        }
951                        v[15] = 1.0;
952                        v
953                    })
954                    .collect())
955            }
956        }
957
958        struct Host(Arc<dyn Provider>);
959        #[async_trait]
960        impl JobsHost for Host {
961            fn model(&self, _call: JobCall) -> (Arc<dyn Provider>, String) {
962                (self.0.clone(), "mock".to_string())
963            }
964        }
965
966        let pool = SqlitePoolOptions::new()
967            .max_connections(1)
968            .connect("sqlite::memory:")
969            .await
970            .unwrap();
971        crate::sqlite::migrate(&pool).await.unwrap();
972        let embedder: Arc<dyn Embedder> = Arc::new(ClusterEmbedder);
973        let mem = Arc::new(crate::sqlite::SqliteMemory::new(pool, embedder.clone()));
974        // 13 overlap clusters (> MAX_CLUSTERS_PER_PASS = 12) trigger catch-up pacing.
975        for idx in 0..13 {
976            mem.upsert_fact(
977                "preference",
978                &format!("topic{idx:02}_alpha_rule"),
979                &format!("Prefers topic{idx:02} alpha concise layout"),
980                "consolidation",
981                Some("app:conv-1"),
982                crate::records::FactPrivacy::Private,
983            )
984            .await
985            .unwrap();
986            mem.upsert_fact(
987                "preference",
988                &format!("topic{idx:02}_variantb_choice"),
989                &format!("Likes topic{idx:02} variantb polished visual design"),
990                "consolidation",
991                Some("app:conv-2"),
992                crate::records::FactPrivacy::Private,
993            )
994            .await
995            .unwrap();
996        }
997        let store: Arc<dyn MemoryStores> = mem;
998        let provider: Arc<dyn Provider> =
999            Arc::new(ScriptedProvider::new(vec![text("[]"), text("[]")]));
1000        let jobs = MemoryJobs::new(
1001            store,
1002            Arc::new(EmptyLog),
1003            Arc::new(Host(provider)),
1004            embedder,
1005        );
1006
1007        let t0 = Utc::now();
1008        assert!(jobs.hygiene_if_due(t0).await.unwrap());
1009        assert!(
1010            !jobs
1011                .hygiene_if_due(t0 + chrono::Duration::minutes(30))
1012                .await
1013                .unwrap()
1014        );
1015        // 1 hour later: drains the remaining 13th cluster.
1016        assert!(
1017            jobs.hygiene_if_due(t0 + chrono::Duration::hours(1))
1018                .await
1019                .unwrap()
1020        );
1021        // Caught up: waits the full 12-hour steady-state cadence.
1022        assert!(
1023            !jobs
1024                .hygiene_if_due(t0 + chrono::Duration::hours(7))
1025                .await
1026                .unwrap()
1027        );
1028        assert!(
1029            jobs.hygiene_if_due(t0 + chrono::Duration::hours(13))
1030                .await
1031                .unwrap()
1032        );
1033    }
1034}