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