Skip to main content

aidaemon_memory/
task_learning.rs

1//! Learning from finished tasks: a model reads what a task did and how it
2//! ended, and the procedures and error solutions it finds are stored for
3//! future tasks.
4//!
5//! It learns no facts about the owner. Its evidence is a model-written brief
6//! and tool output, never the owner's words, so it is the lowest-provenance
7//! writer there is; owner facts come from per-turn extraction.
8
9use std::sync::Arc;
10
11use aidaemon_core::{Message, ModelRequest, Provider};
12use serde::Deserialize;
13use tracing::{info, warn};
14
15use crate::learning::{ErrorSolution, LearningStore, Procedure, procedure_keyed_name};
16
17/// How long an extracted fact stays true, as declared by the extractor.
18///
19/// Background extractors see raw tool output, so without this they file run
20/// state ("last command", "disk check result") as durable owner memory.
21/// Transient observations are dropped at write time instead of being stored
22/// and pinned. Anything unrecognised is durable, so an extractor that never
23/// emits the field keeps its old behaviour.
24#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
25#[serde(rename_all = "lowercase")]
26pub enum FactLifetime {
27    #[default]
28    Durable,
29    Transient,
30}
31
32impl FactLifetime {
33    pub fn is_transient(self) -> bool {
34        self == Self::Transient
35    }
36}
37
38impl<'de> serde::Deserialize<'de> for FactLifetime {
39    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
40        let raw = Option::<serde_json::Value>::deserialize(deserializer)?;
41        Ok(match raw.as_ref().and_then(serde_json::Value::as_str) {
42            Some(value) if value.trim().eq_ignore_ascii_case("transient") => Self::Transient,
43            _ => Self::Durable,
44        })
45    }
46}
47
48/// Extractor prompt sentence that defines the `lifetime` field.
49pub const FACT_LIFETIME_INSTRUCTION: &str = "Set \"lifetime\":\"transient\" on any fact that \
50     describes state likely to change within days: the last command run, a single run's status \
51     or result, current disk/CPU/queue numbers, a draft in progress, or today's plan; and on any \
52     rule or constraint the user limits to this chat, this task or this request (\"for this chat\", \
53     \"this time\", \"don't install anything for this one\"). Omit \"lifetime\" for facts that stay \
54     true (names, preferences, project locations, tech stacks).";
55
56/// What a finished task did, as the host renders it.
57#[derive(Debug, Clone, Copy)]
58pub struct FinishedTask<'a> {
59    pub description: &'a str,
60    pub result: Option<&'a str>,
61    /// The task's activity, one line per tool call, result or status change.
62    pub activity_log: &'a str,
63    /// The project the task's work belongs to, with where its notes are
64    /// kept: know-how that holds only in it is kept there (see
65    /// [`crate::project`]). `None` learns exactly as before.
66    pub project: Option<(
67        &'a crate::project::ProjectNotes,
68        &'a aidaemon_core::ProjectRef,
69    )>,
70}
71
72/// What one task taught, and how much of it was stored.
73#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
74pub struct TaskLearningReport {
75    pub procedures: usize,
76    pub error_solutions: usize,
77    pub stored: usize,
78    /// Of `stored`, how many went to the project's notes.
79    pub project_notes: usize,
80}
81
82/// Extracts durable knowledge from finished tasks with a model.
83#[derive(Clone)]
84pub struct TaskLearner {
85    provider: Arc<dyn Provider>,
86    model: String,
87}
88
89impl TaskLearner {
90    pub fn new(provider: Arc<dyn Provider>, model: impl Into<String>) -> Self {
91        Self {
92            provider,
93            model: model.into(),
94        }
95    }
96
97    /// Ask the model what `task` taught and store it in `store`. Extracted
98    /// error solutions start with no credit: they earn it only when reused.
99    pub async fn learn<S>(
100        &self,
101        store: &S,
102        task: &FinishedTask<'_>,
103    ) -> anyhow::Result<TaskLearningReport>
104    where
105        S: LearningStore + ?Sized,
106    {
107        let system_prompt = "You are a knowledge extraction system. Given a completed task and its activity log, \
108        extract reusable know-how. Output ONLY a JSON object:\n\
109        {\n  \"procedures\": [{\"name\": \"...\", \"trigger_pattern\": \"...\", \"steps\": [\"...\"]}],\n  \
110        \"error_solutions\": [{\"error_pattern\": \"...\", \"solution_summary\": \"...\", \"domain\": \"...\"}]\n}\n\
111        Only extract knowledge that would be useful for FUTURE tasks. If nothing worth remembering, return empty arrays.";
112        let system_prompt = match task.project {
113            Some((_, project)) => format!(
114                "{system_prompt}\n\nThe task worked in the project \"{}\". Give every procedure and error \
115                 solution a \"scope\": \"project\" when it holds only in this project (its commands, paths, \
116                 configuration, conventions), \"general\" when it would help in other projects too.",
117                project
118                    .name
119                    .split_whitespace()
120                    .collect::<Vec<_>>()
121                    .join(" ")
122            ),
123            None => system_prompt.to_string(),
124        };
125
126        let user_prompt = format!(
127            "## Task\n{}\n\n## Result\n{}\n\n## Activity Log\n{}",
128            task.description,
129            task.result.unwrap_or("(no result)"),
130            task.activity_log
131        );
132        let request = ModelRequest {
133            model: self.model.clone(),
134            messages: vec![Message::system(system_prompt), Message::user(user_prompt)],
135            ..Default::default()
136        };
137        let response = self.provider.complete(&request).await?;
138        if response.text.trim().is_empty() {
139            anyhow::bail!("Empty extraction response");
140        }
141        let extraction = parse_extraction_response(&response.text)?;
142
143        let mut stored = 0usize;
144        let mut project_notes = 0usize;
145        // What holds only in the task's project becomes its notes.
146        let in_project = |scope: &Option<String>| {
147            task.project.filter(|_| {
148                scope
149                    .as_deref()
150                    .is_some_and(|scope| scope.trim().eq_ignore_ascii_case("project"))
151            })
152        };
153        for proc in &extraction.procedures {
154            if proc.name.is_empty() || proc.steps.is_empty() {
155                continue;
156            }
157            if let Some((notes, project)) = in_project(&proc.scope) {
158                let mut body = String::new();
159                if !proc.trigger_pattern.trim().is_empty() {
160                    body.push_str(&format!("When: {}\n\n", proc.trigger_pattern.trim()));
161                }
162                for (i, step) in proc.steps.iter().enumerate() {
163                    body.push_str(&format!("{}. {}\n", i + 1, step.trim()));
164                }
165                let note = crate::project::NoteWrite {
166                    kind: crate::project::NoteKind::Procedure,
167                    key: proc.name.clone(),
168                    category: None,
169                    description: Some(if proc.trigger_pattern.trim().is_empty() {
170                        proc.name.clone()
171                    } else {
172                        proc.trigger_pattern.clone()
173                    }),
174                    body,
175                    source: crate::project::NoteSource::Learned,
176                };
177                match notes.write(project, &note) {
178                    Ok(_) => {
179                        stored += 1;
180                        project_notes += 1;
181                    }
182                    Err(e) => warn!(error = %e, "Failed to store project procedure note"),
183                }
184                continue;
185            }
186            let now = chrono::Utc::now();
187            let procedure = Procedure {
188                id: 0,
189                name: procedure_keyed_name(&proc.name, &proc.steps),
190                trigger_pattern: proc.trigger_pattern.clone(),
191                steps: proc.steps.clone(),
192                success_count: 1,
193                failure_count: 0,
194                avg_duration_secs: None,
195                last_used_at: Some(now),
196                created_at: now,
197                updated_at: now,
198            };
199            match store.upsert_procedure(&procedure).await {
200                Ok(_) => stored += 1,
201                Err(e) => warn!(error = %e, "Failed to store extracted procedure"),
202            }
203        }
204
205        for es in &extraction.error_solutions {
206            if es.error_pattern.is_empty() || es.solution_summary.is_empty() {
207                continue;
208            }
209            if let Some((notes, project)) = in_project(&es.scope) {
210                let note = crate::project::NoteWrite {
211                    kind: crate::project::NoteKind::Pitfall,
212                    key: es.error_pattern.clone(),
213                    category: None,
214                    description: Some(es.error_pattern.clone()),
215                    body: format!(
216                        "Problem: {}\n\nWhat works: {}",
217                        es.error_pattern.trim(),
218                        es.solution_summary.trim()
219                    ),
220                    source: crate::project::NoteSource::Learned,
221                };
222                match notes.write(project, &note) {
223                    Ok(_) => {
224                        stored += 1;
225                        project_notes += 1;
226                    }
227                    Err(e) => warn!(error = %e, "Failed to store project pitfall note"),
228                }
229                continue;
230            }
231            let now = chrono::Utc::now();
232            let solution = ErrorSolution {
233                id: 0,
234                error_pattern: es.error_pattern.clone(),
235                domain: (!es.domain.is_empty()).then(|| es.domain.clone()),
236                solution_summary: es.solution_summary.clone(),
237                solution_steps: None,
238                success_count: 0,
239                failure_count: 0,
240                last_used_at: Some(now),
241                created_at: now,
242            };
243            match store.insert_error_solution(&solution).await {
244                Ok(_) => stored += 1,
245                Err(e) => warn!(error = %e, "Failed to store extracted error solution"),
246            }
247        }
248
249        let report = TaskLearningReport {
250            procedures: extraction.procedures.len(),
251            error_solutions: extraction.error_solutions.len(),
252            stored,
253            project_notes,
254        };
255        info!(?report, "Task knowledge extraction complete");
256        Ok(report)
257    }
258}
259
260/// Parsed extraction response from the LLM.
261#[derive(Debug, Deserialize)]
262struct ExtractionResponse {
263    #[serde(default)]
264    procedures: Vec<ExtractedProcedure>,
265    #[serde(default)]
266    error_solutions: Vec<ExtractedErrorSolution>,
267}
268
269#[derive(Debug, Deserialize)]
270struct ExtractedProcedure {
271    #[serde(default)]
272    name: String,
273    #[serde(default)]
274    trigger_pattern: String,
275    #[serde(default)]
276    steps: Vec<String>,
277    #[serde(default)]
278    scope: Option<String>,
279}
280
281#[derive(Debug, Deserialize)]
282struct ExtractedErrorSolution {
283    #[serde(default)]
284    error_pattern: String,
285    #[serde(default)]
286    solution_summary: String,
287    #[serde(default)]
288    domain: String,
289    #[serde(default)]
290    scope: Option<String>,
291}
292
293/// Parse the LLM extraction response, handling markdown fences and partial JSON.
294fn parse_extraction_response(text: &str) -> anyhow::Result<ExtractionResponse> {
295    // Try to extract JSON from markdown code fences first
296    let json_str = if let Some(start) = text.find("```json") {
297        let after = &text[start + 7..];
298        if let Some(end) = after.find("```") {
299            after[..end].trim()
300        } else {
301            text.trim()
302        }
303    } else if let Some(start) = text.find("```") {
304        let after = &text[start + 3..];
305        if let Some(end) = after.find("```") {
306            after[..end].trim()
307        } else {
308            text.trim()
309        }
310    } else {
311        text.trim()
312    };
313
314    // Try to find a JSON object in the text
315    let json_str = if let Some(start) = json_str.find('{') {
316        if let Some(end) = json_str.rfind('}') {
317            &json_str[start..=end]
318        } else {
319            json_str
320        }
321    } else {
322        json_str
323    };
324
325    serde_json::from_str(json_str).map_err(|e| {
326        anyhow::anyhow!(
327            "Failed to parse extraction response: {} (text: {})",
328            e,
329            &text[..text.len().min(200)]
330        )
331    })
332}
333
334#[cfg(test)]
335mod tests {
336    use super::*;
337
338    #[test]
339    fn test_parse_extraction_response_full() {
340        let response = r#"{"facts": [{"category": "technical", "key": "database", "value": "Uses PostgreSQL 15"}], "procedures": [{"name": "deploy", "trigger_pattern": "deploy to prod", "steps": ["build", "test", "deploy"]}], "error_solutions": [{"error_pattern": "connection refused", "solution_summary": "Check if DB is running", "domain": "database"}]}"#;
341
342        let result = parse_extraction_response(response).unwrap();
343        assert_eq!(result.procedures.len(), 1);
344        assert_eq!(result.procedures[0].name, "deploy");
345        assert_eq!(result.procedures[0].steps.len(), 3);
346        assert_eq!(result.error_solutions.len(), 1);
347        assert_eq!(
348            result.error_solutions[0].error_pattern,
349            "connection refused"
350        );
351    }
352
353    #[test]
354    fn test_parse_extraction_response_empty_arrays() {
355        let response = r#"{"facts": [], "procedures": [], "error_solutions": []}"#;
356        let result = parse_extraction_response(response).unwrap();
357        assert!(result.procedures.is_empty());
358        assert!(result.error_solutions.is_empty());
359    }
360
361    #[test]
362    fn test_parse_extraction_response_with_markdown_fences() {
363        let response = "Here is the extraction:\n```json\n{\"facts\": [{\"category\": \"project\", \"key\": \"lang\", \"value\": \"Rust\"}], \"procedures\": [{\"name\": \"build\", \"steps\": [\"cargo build\"]}], \"error_solutions\": []}\n```";
364        let result = parse_extraction_response(response).unwrap();
365        assert_eq!(result.procedures[0].name, "build");
366    }
367
368    #[test]
369    fn test_parse_extraction_response_partial_fields() {
370        // Missing some fields — defaults should apply
371        let response = r#"{"procedures": [{"name": "deploy"}]}"#;
372        let result = parse_extraction_response(response).unwrap();
373        assert!(result.procedures[0].steps.is_empty()); // default empty
374        assert!(result.error_solutions.is_empty()); // missing → default empty
375    }
376
377    #[test]
378    fn test_parse_extraction_response_invalid_json() {
379        let response = "This is not JSON at all";
380        assert!(parse_extraction_response(response).is_err());
381    }
382}
383
384#[cfg(test)]
385mod learner_tests {
386    use std::sync::Mutex;
387
388    use aidaemon_core::testing::{ScriptedProvider, text};
389    use async_trait::async_trait;
390
391    use super::*;
392    /// Records what the learner stores.
393    #[derive(Default)]
394    struct Recorder {
395        procedures: Mutex<Vec<Procedure>>,
396        solutions: Mutex<Vec<ErrorSolution>>,
397    }
398
399    #[async_trait]
400    impl LearningStore for Recorder {
401        async fn upsert_procedure(&self, procedure: &Procedure) -> crate::Result<i64> {
402            self.procedures.lock().unwrap().push(procedure.clone());
403            Ok(1)
404        }
405
406        async fn insert_error_solution(&self, solution: &ErrorSolution) -> crate::Result<i64> {
407            self.solutions.lock().unwrap().push(solution.clone());
408            Ok(1)
409        }
410    }
411
412    const REPLY: &str = r#"{"facts": [
413        {"category": "project", "key": "stack", "value": "Rust"},
414        {"category": "project", "key": "last_run", "value": "ok", "lifetime": "transient"}
415      ],
416      "procedures": [{"name": "deploy", "trigger_pattern": "deploy", "steps": ["build", "ship"]}],
417      "error_solutions": [{"error_pattern": "connection refused", "solution_summary": "start the db"}]}"#;
418
419    fn task() -> FinishedTask<'static> {
420        FinishedTask {
421            project: None,
422            description: "Ship the release",
423            result: Some("shipped"),
424            activity_log: "TOOL_CALL: terminal args={}\n",
425        }
426    }
427
428    #[tokio::test]
429    async fn procedures_and_solutions_are_stored_and_facts_never_are() {
430        let store = Recorder::default();
431        let learner = TaskLearner::new(Arc::new(ScriptedProvider::new([text(REPLY)])), "mock");
432        let report = learner.learn(&store, &task()).await.unwrap();
433
434        assert_eq!((report.procedures, report.error_solutions), (1, 1));
435        assert_eq!(report.stored, 2, "the reply's facts are ignored");
436        let procedures = store.procedures.lock().unwrap();
437        assert!(procedures[0].name.starts_with("deploy-"));
438        let solutions = store.solutions.lock().unwrap();
439        assert_eq!(solutions[0].success_count, 0, "extracted, not yet observed");
440    }
441
442    #[tokio::test]
443    async fn project_only_know_how_becomes_the_projects_notes() {
444        let reply = r#"{"procedures": [
445            {"name": "deploy", "trigger_pattern": "deploy the site", "steps": ["make build", "make ship"], "scope": "project"},
446            {"name": "bisect", "trigger_pattern": "find a regression", "steps": ["git bisect"], "scope": "general"}],
447          "error_solutions": [
448            {"error_pattern": "port 5433 in use", "solution_summary": "stop the old dev db", "scope": "project"},
449            {"error_pattern": "connection refused", "solution_summary": "start the db"}]}"#;
450        let dir = tempfile::tempdir().unwrap();
451        let notes = crate::project::ProjectNotes::new(dir.path());
452        let project = aidaemon_core::ProjectRef::new("project-a", "Acme Site", None).unwrap();
453        let provider = Arc::new(ScriptedProvider::new([text(reply)]));
454        let store = Recorder::default();
455        let report = TaskLearner::new(provider.clone(), "mock")
456            .learn(
457                &store,
458                &FinishedTask {
459                    project: Some((&notes, &project)),
460                    ..task()
461                },
462            )
463            .await
464            .unwrap();
465        assert_eq!((report.stored, report.project_notes), (4, 2));
466        assert_eq!(store.procedures.lock().unwrap().len(), 1);
467        assert_eq!(store.solutions.lock().unwrap().len(), 1);
468        let entries = notes.entries(&project);
469        let kinds: Vec<_> = entries.iter().map(|e| (e.kind, e.name.clone())).collect();
470        assert_eq!(
471            kinds,
472            [
473                (
474                    Some(crate::project::NoteKind::Procedure),
475                    "deploy".to_string()
476                ),
477                (
478                    Some(crate::project::NoteKind::Pitfall),
479                    "port_5433_in_use".to_string()
480                ),
481            ]
482        );
483        let deploy = notes
484            .read(&project, crate::project::NoteKind::Procedure, "deploy")
485            .unwrap();
486        assert!(deploy.contains("1. make build\n2. make ship"), "{deploy}");
487        assert!(
488            provider.requests()[0].messages[0]
489                .content
490                .contains("\"scope\"")
491        );
492        // Without a project, scopes are ignored and the prompt is unchanged.
493        let provider = Arc::new(ScriptedProvider::new([text(reply)]));
494        let store = Recorder::default();
495        TaskLearner::new(provider.clone(), "mock")
496            .learn(&store, &task())
497            .await
498            .unwrap();
499        assert_eq!(store.procedures.lock().unwrap().len(), 2);
500        assert!(!provider.requests()[0].messages[0].content.contains("scope"));
501    }
502}