Skip to main content

aidaemon_memory/full/
writer.rs

1//! The full memory system's run-end writer: once a run's outcome is final,
2//! extract durable facts from a completed turn and learn from the run
3//! (expertise, procedures, error solutions).
4//!
5//! [`FullWriter`] decides what to write; the host says how the run ended and
6//! runs the writes with its own models through [`WriterHost`]. The writes
7//! themselves are here: [`extract_progressive`] (with the host's provenance
8//! through [`ExtractionProvenance`]) and [`learn_from_run`].
9
10use std::sync::Arc;
11
12use aidaemon_core::{ChannelVisibility, Hook, HookContext, Provider, RunOutcome, UserRole};
13use aidaemon_policies::TurnLearning;
14use async_trait::async_trait;
15use chrono::{DateTime, Utc};
16use tracing::{debug, warn};
17
18use crate::progressive::{Exchange, ProgressiveExtractor, may_extract, owner_writes_during_run};
19use crate::stores::MemoryStores;
20
21/// What a finished run did, for learning.
22#[derive(Debug, Clone, Default)]
23pub struct RunLearning {
24    pub user_text: String,
25    /// False when the turn's policy suppresses automatic memory: nothing is
26    /// learned.
27    pub persistence_allowed: bool,
28    pub intent_domains: Vec<String>,
29    /// `"tool_name(summary)"` per call, in order.
30    pub tool_calls: Vec<String>,
31    /// Each error, and whether the run recovered from it.
32    pub errors: Vec<(String, bool)>,
33    /// The first error, for an error solution.
34    pub first_error: Option<String>,
35    pub recovery_actions: Vec<String>,
36    pub completed_naturally: bool,
37    /// The run's own verdict on its task, when it has one: authoritative.
38    pub succeeded: Option<bool>,
39}
40
41impl RunLearning {
42    /// Whether the run's task succeeded: its typed verdict, else a natural
43    /// completion with every error recovered. The words of the next user
44    /// message are never a verdict on this task.
45    pub fn task_success(&self) -> bool {
46        if let Some(succeeded) = self.succeeded {
47            succeeded
48        } else {
49            let unrecovered = self.errors.iter().filter(|(_, recovered)| !recovered);
50            self.completed_naturally && unrecovered.count() == 0
51        }
52    }
53}
54
55/// Learn from a finished run: expertise for its domains, the procedure it
56/// followed (successful or not, so repeated bad paths accumulate failures)
57/// and, when it recovered from an error, the solution.
58pub async fn learn_from_run(store: &dyn MemoryStores, run: RunLearning) -> anyhow::Result<()> {
59    if !run.persistence_allowed {
60        return Ok(());
61    }
62    let task_success = run.task_success();
63
64    let domains = crate::detect_domains(&run.intent_domains);
65    for domain in &domains {
66        let error = if !task_success {
67            run.errors.first().map(|(e, _)| e.as_str())
68        } else {
69            None
70        };
71        if let Err(e) = store.increment_expertise(domain, task_success, error).await {
72            warn!(domain = %domain, error = %e, "Failed to update expertise");
73        }
74    }
75
76    if run.tool_calls.len() >= 2 {
77        let generalized = crate::generalize_procedure(&run.tool_calls);
78        let base_name = crate::procedure_base_name(&generalized);
79        let keyed_name = crate::procedure_keyed_name(&base_name, &generalized);
80        let procedure = crate::new_procedure(
81            keyed_name,
82            crate::extract_trigger_pattern(&run.user_text),
83            generalized,
84            task_success,
85        );
86        if let Err(e) = store.upsert_procedure(&procedure).await {
87            warn!(procedure = %procedure.name, error = %e, "Failed to save procedure");
88        }
89    }
90
91    if let Some(error) = run.first_error.clone()
92        && !run.recovery_actions.is_empty()
93    {
94        let solution = crate::new_error_solution(
95            crate::error_pattern(&error),
96            domains.into_iter().next(),
97            crate::summarize_solution(&run.recovery_actions),
98            Some(run.recovery_actions.clone()),
99        );
100        if let Err(e) = store.insert_error_solution(&solution).await {
101            warn!(error_pattern = %solution.error_pattern, error = %e, "Failed to save error solution");
102        }
103    }
104
105    Ok(())
106}
107
108/// Whether a completed turn may be extracted from and summarized:
109/// `(extract, summarize)`. A turn with no memory (`no_memory`) or whose
110/// policy forbids automatic memory gets neither. Memory-isolated sessions
111/// (workers whose "user" turn is a delegated brief) keep their summaries
112/// but never extract owner facts.
113pub fn post_completion_plan(
114    no_memory: bool,
115    memory_isolated: bool,
116    persistence_allowed: bool,
117    progressive_facts: bool,
118    worth_extracting: bool,
119    summarization: bool,
120) -> (bool, bool) {
121    if no_memory || !persistence_allowed {
122        return (false, false);
123    }
124    (
125        !memory_isolated && progressive_facts && worth_extracting,
126        summarization,
127    )
128}
129
130/// One exchange to extract facts from.
131#[derive(Debug, Clone)]
132pub struct ExtractionRun {
133    /// The host's id for the task, for provenance.
134    pub task_id: String,
135    pub user_text: String,
136    pub reply: String,
137    pub channel_id: Option<String>,
138    pub visibility: ChannelVisibility,
139    pub user_role: UserRole,
140    /// Facts the agent stored itself since then are not extracted again.
141    pub run_started_at: DateTime<Utc>,
142    /// The project the turn works in, with where its notes are kept: what
143    /// the user says about the project is kept there (see
144    /// [`crate::project`]). `None` extracts exactly as before.
145    pub project: Option<(Arc<crate::project::ProjectNotes>, aidaemon_core::ProjectRef)>,
146}
147
148/// What an extraction stored, for the host's audit trail.
149#[derive(Debug, Clone)]
150pub struct ExtractionRecord {
151    pub source_task_id: String,
152    /// The host's event the facts came from, if it found one.
153    pub source_event_id: Option<i64>,
154    pub channel_id: Option<String>,
155    /// The facts written.
156    pub facts: Vec<serde_json::Value>,
157    /// The start of the user's message.
158    pub source_excerpt: String,
159}
160
161/// Where extracted facts came from, kept by the host (its event log).
162#[async_trait]
163pub trait ExtractionProvenance: Send + Sync {
164    /// The host's record of the user message `task_id` answered, bound to
165    /// the facts just written. `None` when it has none.
166    async fn source_event(&self, task_id: &str) -> anyhow::Result<Option<i64>>;
167
168    /// Keep a record of one extraction's writes.
169    async fn record(&self, record: ExtractionRecord) -> anyhow::Result<()>;
170}
171
172/// One extractor per process, so its two-call concurrency limit holds
173/// across every turn. The provider is given per call (the host may switch
174/// models), the limit is not.
175fn extractor(provider: Arc<dyn Provider>, model: &str) -> ProgressiveExtractor {
176    static PERMITS: std::sync::LazyLock<Arc<tokio::sync::Semaphore>> =
177        std::sync::LazyLock::new(|| Arc::new(tokio::sync::Semaphore::new(2)));
178    ProgressiveExtractor::with_permits(provider, model, PERMITS.clone())
179}
180
181/// Extract durable facts from one exchange and write them: the model
182/// proposes, the store keeps what is new, and `provenance` (if any) binds
183/// them to their source and records the write.
184/// Stored facts nearest the user's message shown to per-turn extraction.
185const NEARBY_FACTS_SHOWN: usize = 12;
186
187pub async fn extract_progressive(
188    provider: Arc<dyn Provider>,
189    model: &str,
190    store: Arc<dyn MemoryStores>,
191    provenance: Option<Arc<dyn ExtractionProvenance>>,
192    run: ExtractionRun,
193) {
194    if !may_extract(run.user_role, run.visibility) {
195        return;
196    }
197    let extractor = extractor(provider, model);
198    let already_stored = owner_writes_during_run(store.as_ref(), run.run_started_at).await;
199    // What recall would show in this channel, never another scope's facts.
200    let nearby = store
201        .get_relevant_facts_for_channel(
202            &run.user_text,
203            NEARBY_FACTS_SHOWN,
204            run.channel_id.as_deref(),
205            run.visibility,
206            true,
207        )
208        .await
209        .unwrap_or_default();
210    // On a turn in a project, its notes are shown first, so a restatement
211    // of one is not stored again and a correction lands on it.
212    let nearby = match &run.project {
213        Some((notes, project)) => {
214            let mut shown = crate::project::notes_as_shown_facts(&notes.entries(project));
215            shown.extend(nearby);
216            shown
217        }
218        None => nearby,
219    };
220    let exchange = Exchange {
221        user_text: &run.user_text,
222        assistant_reply: &run.reply,
223        channel_id: run.channel_id.as_deref(),
224        already_stored: &already_stored,
225        nearby: &nearby,
226        stated_at: run.run_started_at,
227        project: run
228            .project
229            .as_ref()
230            .map(|(notes, project)| (notes.as_ref(), project)),
231    };
232    let facts = match extractor.propose(&exchange).await {
233        Ok(facts) => facts,
234        Err(e) => {
235            debug!(error = %e, "Progressive fact extraction failed");
236            return;
237        }
238    };
239    if facts.is_empty() {
240        return; // Expected for most interactions.
241    }
242    let written = extractor.write(store.as_ref(), &exchange, facts).await;
243    if written.is_empty() {
244        return;
245    }
246    let Some(provenance) = provenance else {
247        return;
248    };
249    let source_task_id = run.task_id.clone();
250    let source_excerpt = crate::text::truncate_chars(&run.user_text, 200);
251    let source_event_id = match provenance.source_event(&source_task_id).await {
252        Ok(Some(event_id)) => {
253            if let Err(error) = store.repair_memory_projections().await {
254                debug!(%error, %source_task_id, "Failed to bind selected message provenance to extracted memory");
255            }
256            Some(event_id)
257        }
258        Ok(None) => {
259            debug!(%source_task_id, "Selected memory write had no policy-eligible canonical user event");
260            None
261        }
262        Err(error) => {
263            debug!(%error, %source_task_id, "Failed to project selected message provenance");
264            None
265        }
266    };
267    let record = ExtractionRecord {
268        source_task_id,
269        source_event_id,
270        channel_id: run.channel_id,
271        facts: written,
272        source_excerpt,
273    };
274    if let Err(e) = provenance.record(record).await {
275        debug!(error = %e, "Failed to record memory_write event");
276    }
277}
278
279/// Which writes a [`FullWriter`] owns.
280#[derive(Debug, Clone, Copy)]
281pub struct WriterSettings {
282    /// Extract facts from a completed turn.
283    pub progressive_facts: bool,
284    /// Ask the host to summarize the conversation after a completed turn.
285    pub summarization: bool,
286    /// Learn from every run.
287    pub learning: bool,
288}
289
290/// What the writer knows about its turn.
291#[derive(Debug, Clone)]
292pub struct WriterTurn {
293    /// The turn has no memory at all (nothing is written or learned).
294    pub no_memory: bool,
295    /// A worker session: summaries, but no owner facts.
296    pub memory_isolated: bool,
297    /// The turn's policy allows automatic memory.
298    pub persistence_allowed: bool,
299    /// The user's message.
300    pub user_text: String,
301    /// Whether the turn may be learned from ("don't remember this").
302    pub consent: TurnLearning,
303}
304
305/// How a run ended, as the host judges it.
306#[derive(Debug, Clone)]
307pub struct RunEnd {
308    /// The reply the user saw.
309    pub reply: String,
310    /// The turn completed (its reply stands).
311    pub completed: bool,
312}
313
314/// The host side of the run-end writer: how the run ended, and the writes
315/// run with the host's models and records.
316pub trait WriterHost: Send + Sync {
317    /// The run as it ended. Called once, at run end.
318    fn run_end(&self, outcome: &RunOutcome) -> RunEnd;
319    /// Extract facts from the turn's exchange, in the background (see
320    /// [`extract_progressive`]).
321    fn extract_facts(&self, reply: &str, run_started_at: DateTime<Utc>);
322    /// The host's conversation summary, after a completed turn. The
323    /// conversation is the host's, so the writer only says when.
324    fn summarize(&self) {}
325    /// Learn from the run, in the background (see [`learn_from_run`]).
326    fn learn(&self, completed: bool);
327}
328
329/// Writes memory once per run, after the outcome is final: extraction and
330/// summarization only for a completed turn, learning for every run. A turn
331/// opted out of learning is neither extracted nor learned from; its summary
332/// is the host's to keep clean.
333pub struct FullWriter {
334    turn: WriterTurn,
335    settings: WriterSettings,
336    host: Arc<dyn WriterHost>,
337    /// When the run began: the writer is built as the run is assembled,
338    /// before any tool call, so every memory write the run makes is at or
339    /// after it.
340    run_started_at: DateTime<Utc>,
341}
342
343impl FullWriter {
344    pub fn new(turn: WriterTurn, settings: WriterSettings, host: Arc<dyn WriterHost>) -> Self {
345        Self {
346            turn,
347            settings,
348            host,
349            run_started_at: Utc::now(),
350        }
351    }
352}
353
354#[async_trait]
355impl Hook for FullWriter {
356    async fn on_run_end(&self, _ctx: &HookContext<'_>, outcome: &RunOutcome) {
357        let turn = &self.turn;
358        let end = self.host.run_end(outcome);
359        if end.completed {
360            let (extract, summarize) = post_completion_plan(
361                turn.no_memory,
362                turn.memory_isolated,
363                turn.persistence_allowed,
364                self.settings.progressive_facts,
365                crate::progressive::worth_extracting(&turn.user_text),
366                self.settings.summarization,
367            );
368            if extract && turn.consent.allowed() {
369                self.host.extract_facts(&end.reply, self.run_started_at);
370            }
371            if summarize {
372                self.host.summarize();
373            }
374        }
375        if turn.no_memory || !self.settings.learning || !turn.consent.allowed() {
376            return;
377        }
378        self.host.learn(end.completed);
379    }
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385
386    #[test]
387    fn a_turn_without_memory_writes_nothing() {
388        assert_eq!(
389            post_completion_plan(true, false, true, true, true, true),
390            (false, false)
391        );
392        assert_eq!(
393            post_completion_plan(false, false, true, true, true, true),
394            (true, true)
395        );
396        assert_eq!(
397            post_completion_plan(false, false, false, true, true, true),
398            (false, false)
399        );
400        assert_eq!(
401            post_completion_plan(false, true, true, true, true, true),
402            (false, true)
403        );
404    }
405
406    #[test]
407    fn the_runs_verdict_decides_success_when_it_has_one() {
408        let run = RunLearning {
409            completed_naturally: true,
410            succeeded: Some(false),
411            ..RunLearning::default()
412        };
413        assert!(!run.task_success());
414        let run = RunLearning {
415            succeeded: None,
416            ..run
417        };
418        assert!(run.task_success());
419        let run = RunLearning {
420            errors: vec![("boom".into(), false)],
421            ..run
422        };
423        assert!(!run.task_success());
424    }
425
426    #[tokio::test]
427    async fn learning_records_the_procedure_a_run_followed() {
428        let store = crate::full::tools::test_support::memory().await;
429        learn_from_run(
430            store.as_ref(),
431            RunLearning {
432                user_text: "deploy the site".into(),
433                persistence_allowed: true,
434                tool_calls: vec!["terminal(git)".into(), "terminal(npm)".into()],
435                completed_naturally: true,
436                ..RunLearning::default()
437            },
438        )
439        .await
440        .unwrap();
441        let procedures = crate::LearningStore::get_relevant_procedures(store.as_ref(), "deploy", 5)
442            .await
443            .unwrap();
444        assert_eq!(procedures.len(), 1, "{procedures:?}");
445    }
446}