Skip to main content

aidaemon_memory/
writer.rs

1//! [`MemoryWriter`]: background fact extraction as an `on_run_end` hook.
2
3use std::collections::VecDeque;
4use std::sync::{Arc, Mutex};
5
6use aidaemon_core::{Hook, HookContext, RunOutcome};
7use async_trait::async_trait;
8use tokio::task::JoinHandle;
9
10use crate::memory::{IngestReport, Memory};
11
12/// Result of one background extraction.
13#[derive(Debug, Clone, PartialEq)]
14pub struct WriterReport {
15    pub run_id: String,
16    pub session_id: String,
17    /// The ingest result, or the error message. Errors never reach the run.
18    pub result: Result<IngestReport, String>,
19}
20
21const MAX_KEPT_REPORTS: usize = 64;
22
23#[derive(Default)]
24struct Shared {
25    reports: Mutex<VecDeque<WriterReport>>,
26}
27
28/// Extracts durable facts from the latest user turn once a run completes.
29/// Failed, cancelled and interrupted runs write nothing. The extraction runs
30/// on a spawned task and can neither block nor change the run, and because
31/// it fires at run end, hook order does not matter: an answer another hook
32/// rejected is never extracted.
33///
34/// Outcomes (including model usage) are logged with `tracing` and kept in
35/// a small buffer; [`MemoryWriter::drain`] waits for pending work and
36/// returns them, which is useful at shutdown and in tests.
37///
38/// Requires a [`Memory`] built with a [`crate::FactExtractor`]; without one
39/// the hook does nothing.
40pub struct MemoryWriter {
41    memory: Memory,
42    /// The turn's learning consent; an opted-out turn is not extracted.
43    learning: aidaemon_policies::TurnLearning,
44    shared: Arc<Shared>,
45    pending: Mutex<Vec<JoinHandle<()>>>,
46}
47
48impl MemoryWriter {
49    pub fn new(memory: Memory) -> Self {
50        Self {
51            memory,
52            learning: aidaemon_policies::TurnLearning::default(),
53            shared: Arc::new(Shared::default()),
54            pending: Mutex::new(Vec::new()),
55        }
56    }
57
58    /// Extract only while `learning` allows it: a turn opted out of
59    /// learning (see [`aidaemon_policies::Learning`]) is never extracted.
60    pub fn honoring(mut self, learning: aidaemon_policies::TurnLearning) -> Self {
61        self.learning = learning;
62        self
63    }
64
65    /// Number of extractions still running.
66    pub fn pending(&self) -> usize {
67        self.pending
68            .lock()
69            .map(|p| p.iter().filter(|h| !h.is_finished()).count())
70            .unwrap_or(0)
71    }
72
73    /// Wait for every spawned extraction, then return (and clear) the
74    /// buffered reports.
75    pub async fn drain(&self) -> Vec<WriterReport> {
76        let handles: Vec<JoinHandle<()>> = self
77            .pending
78            .lock()
79            .map(|mut p| std::mem::take(&mut *p))
80            .unwrap_or_default();
81        for handle in handles {
82            let _ = handle.await;
83        }
84        self.shared
85            .reports
86            .lock()
87            .map(|mut r| r.drain(..).collect())
88            .unwrap_or_default()
89    }
90}
91
92/// The run ended with an answer: the model's final reply, or a tool's
93/// finish with the work done or partly done.
94fn completed_with_work(outcome: &RunOutcome) -> bool {
95    matches!(
96        outcome.status,
97        aidaemon_core::RunStatus::Completed
98            | aidaemon_core::RunStatus::Finished {
99                outcome: aidaemon_core::FinishOutcome::Succeeded
100                    | aidaemon_core::FinishOutcome::Partial,
101                ..
102            }
103    )
104}
105
106#[async_trait]
107impl Hook for MemoryWriter {
108    async fn on_run_end(&self, ctx: &HookContext<'_>, outcome: &RunOutcome) {
109        if !completed_with_work(outcome)
110            || self.memory.extractor().is_none()
111            || !self.learning.allowed()
112        {
113            return;
114        }
115        let Some(index) = aidaemon_policies::last_user_message_index(ctx.messages) else {
116            return;
117        };
118        let run_id = ctx.run_id.to_string();
119        let turn = ctx.messages[index..].to_vec();
120        let session_id = ctx.session_id.to_string();
121        let memory = self.memory.clone();
122        let shared = self.shared.clone();
123        let handle = tokio::spawn(async move {
124            let result = memory
125                .ingest_turn(&session_id, Some(&run_id), &turn)
126                .await
127                .map_err(|e| e.to_string());
128            match &result {
129                Ok(report) => tracing::info!(
130                    session_id = %session_id,
131                    run_id = %run_id,
132                    stored = report.facts.len(),
133                    rejected = report.rejected,
134                    input_tokens = report.usage.input_tokens,
135                    output_tokens = report.usage.output_tokens,
136                    "memory extraction finished"
137                ),
138                Err(error) => tracing::warn!(
139                    session_id = %session_id,
140                    run_id = %run_id,
141                    %error,
142                    "memory extraction failed"
143                ),
144            }
145            if let Ok(mut reports) = shared.reports.lock() {
146                if reports.len() >= MAX_KEPT_REPORTS {
147                    reports.pop_front();
148                }
149                reports.push_back(WriterReport {
150                    run_id,
151                    session_id,
152                    result,
153                });
154            }
155        });
156        if let Ok(mut pending) = self.pending.lock() {
157            pending.retain(|h| !h.is_finished());
158            pending.push(handle);
159        }
160    }
161}