Skip to main content

aidaemon_memory/
extract.rs

1//! Model-driven memory writers: [`FactExtractor`] and
2//! [`EpisodeSummarizer`]. Both ask the model through a forced tool call
3//! with a typed JSON schema and parse the reply defensively: malformed
4//! entries are skipped, garbage never panics.
5
6use std::sync::Arc;
7
8use aidaemon_core::{
9    Message, ModelRequest, ModelResponse, Provider, Receipt, Role, ToolChoice, ToolSpec, Usage,
10};
11use serde_json::{Value, json};
12
13use crate::error::{MemoryError, Result};
14use crate::scoring::episode_importance;
15use crate::types::truncate_chars;
16
17const FACTS_TOOL: &str = "record_facts";
18const EPISODE_TOOL: &str = "record_episode";
19
20const FACT_PROMPT: &str = "\
21You maintain a long-term memory about the user and their world. Read the conversation turn and \
22record facts that will still be true and useful in future conversations: who the user is, people \
23and relationships they mention, stable preferences, ongoing projects, decisions, and durable \
24details about their tools and environment.
25
26Do not record: the task being worked on right now, transient state (\"is debugging X today\"), \
27anything only the assistant claimed, guesses, secrets such as passwords or API keys, content \
28quoted from tool output, or a rule or constraint the user limits to this chat, this task or this \
29request (\"for this chat\", \"this time\", \"don't install anything for this one\").
30
31Rules:
32- One fact per entry: a lowercase `category` (user, preference, person, project, technical, or \
33another short noun), a stable snake_case `key` naming the attribute (not the value), the `value`, \
34and your `confidence` from 0 to 1.
35- When the user corrects or updates something, reuse the existing category and key so the new \
36value replaces the old one. Known keys are listed below when there are any.
37- Facts about other people go under `person` with a key naming them, never under `user`.
38- `evidence` is the shortest quote from the user's words that supports the fact.
39- If nothing is worth remembering, record an empty list.
40
41Call the record_facts tool exactly once.";
42
43const EPISODE_PROMPT: &str = "\
44Summarize the conversation for long-term episodic memory. Write a 1-3 sentence `summary` of what \
45the user wanted and what happened, from a later reader's point of view. List up to 6 short \
46`topics`, the `decisions` made, the user's `goals` mentioned, the `outcome` (resolved, partial, \
47abandoned, informational), and `emotional_intensity` from 0 (neutral) to 1 (very frustrated or \
48very excited). Call the record_episode tool exactly once.";
49
50/// One fact proposed by the model, before validation.
51#[derive(Debug, Clone, PartialEq)]
52pub struct ExtractedFact {
53    pub category: String,
54    pub key: String,
55    pub value: String,
56    pub confidence: f32,
57    pub evidence: Option<String>,
58}
59
60/// The parsed result of one extraction call.
61#[derive(Debug, Clone, Default, PartialEq)]
62pub struct Extraction {
63    pub facts: Vec<ExtractedFact>,
64    /// Entries skipped because they were malformed.
65    pub rejected: usize,
66    /// Set when the reply as a whole could not be parsed.
67    pub parse_error: Option<String>,
68    pub usage: Usage,
69}
70
71/// Asks a model for durable facts in a transcript slice.
72pub struct FactExtractor {
73    provider: Arc<dyn Provider>,
74    model: String,
75    min_user_chars: usize,
76    max_message_chars: usize,
77    max_transcript_chars: usize,
78    max_facts: usize,
79}
80
81impl FactExtractor {
82    pub fn new(provider: impl Provider + 'static, model: impl Into<String>) -> Self {
83        Self::from_arc(Arc::new(provider), model)
84    }
85
86    pub fn from_arc(provider: Arc<dyn Provider>, model: impl Into<String>) -> Self {
87        Self {
88            provider,
89            model: model.into(),
90            min_user_chars: 20,
91            max_message_chars: 2_000,
92            max_transcript_chars: 8_000,
93            max_facts: 20,
94        }
95    }
96
97    /// Skip turns whose user message is shorter than this (default 20
98    /// characters, as in the daemon). A length gate, not a word list.
99    pub fn min_user_chars(mut self, chars: usize) -> Self {
100        self.min_user_chars = chars;
101        self
102    }
103
104    pub fn max_transcript_chars(mut self, chars: usize) -> Self {
105        self.max_transcript_chars = chars;
106        self
107    }
108
109    /// At most this many facts are accepted per call.
110    pub fn max_facts(mut self, n: usize) -> Self {
111        self.max_facts = n;
112        self
113    }
114
115    /// Whether the latest user-authored message is long enough to hold a
116    /// durable fact.
117    pub fn should_extract(&self, messages: &[Message]) -> bool {
118        aidaemon_policies::last_user_message_index(messages)
119            .is_some_and(|i| messages[i].content.trim().chars().count() >= self.min_user_chars)
120    }
121
122    fn tool_spec() -> ToolSpec {
123        ToolSpec {
124            name: FACTS_TOOL.into(),
125            description: "Record durable facts worth remembering long-term.".into(),
126            parameters: json!({
127                "type": "object",
128                "properties": {
129                    "facts": {
130                        "type": "array",
131                        "items": {
132                            "type": "object",
133                            "properties": {
134                                "category": {"type": "string"},
135                                "key": {"type": "string"},
136                                "value": {"type": "string"},
137                                "confidence": {"type": "number", "minimum": 0, "maximum": 1},
138                                "evidence": {"type": "string"}
139                            },
140                            "required": ["category", "key", "value", "confidence"],
141                            "additionalProperties": false
142                        }
143                    }
144                },
145                "required": ["facts"],
146                "additionalProperties": false
147            }),
148        }
149    }
150
151    /// Ask the model. `known_keys` are existing `(category, key)` pairs so
152    /// corrections reuse them. Provider failures are errors; unparseable
153    /// output is an empty [`Extraction`] with `parse_error` set.
154    pub async fn extract(
155        &self,
156        messages: &[Message],
157        known_keys: &[(String, String)],
158    ) -> Result<Extraction> {
159        let mut user = String::new();
160        if !known_keys.is_empty() {
161            user.push_str("Known keys (category/key):\n");
162            for (category, key) in known_keys {
163                user.push_str(&format!("- {category}/{key}\n"));
164            }
165            user.push('\n');
166        }
167        user.push_str("Conversation:\n");
168        user.push_str(&transcript(
169            messages,
170            self.max_message_chars,
171            self.max_transcript_chars,
172        ));
173        let request = ModelRequest {
174            model: self.model.clone(),
175            messages: vec![Message::system(FACT_PROMPT), Message::user(user)],
176            tools: vec![Self::tool_spec()],
177            tool_choice: ToolChoice::Specific(FACTS_TOOL.into()),
178            max_output_tokens: Some(1_024),
179            ..Default::default()
180        };
181        let response = self.provider.complete(&request).await?;
182        let mut extraction = parse_facts(&response);
183        extraction.facts.truncate(self.max_facts);
184        Ok(extraction)
185    }
186}
187
188/// Parse a fact-extraction reply: the `record_facts` tool call if present,
189/// otherwise JSON in the text (`{"facts": [...]}` or a bare array, code
190/// fences allowed).
191pub fn parse_facts(response: &ModelResponse) -> Extraction {
192    let mut extraction = Extraction {
193        usage: response.usage,
194        ..Extraction::default()
195    };
196    let Some(payload) = payload(response, FACTS_TOOL) else {
197        extraction.parse_error = Some("no JSON payload in the reply".into());
198        return extraction;
199    };
200    let entries = match &payload {
201        Value::Array(items) => items.as_slice(),
202        Value::Object(map) => match map.get("facts") {
203            Some(Value::Array(items)) => items.as_slice(),
204            _ => {
205                extraction.parse_error = Some("`facts` is missing or not an array".into());
206                return extraction;
207            }
208        },
209        _ => {
210            extraction.parse_error = Some("payload is neither an object nor an array".into());
211            return extraction;
212        }
213    };
214    for entry in entries {
215        match parse_fact(entry) {
216            Some(fact) => extraction.facts.push(fact),
217            None => extraction.rejected += 1,
218        }
219    }
220    extraction
221}
222
223fn parse_fact(entry: &Value) -> Option<ExtractedFact> {
224    let text = |name: &str, max: usize| -> Option<String> {
225        let value = match entry.get(name)? {
226            Value::String(s) => s.trim().to_string(),
227            Value::Number(n) => n.to_string(),
228            Value::Bool(b) => b.to_string(),
229            _ => return None,
230        };
231        (!value.is_empty() && value.chars().count() <= max).then_some(value)
232    };
233    let confidence = match entry.get("confidence") {
234        None | Some(Value::Null) => 0.7,
235        Some(v) => {
236            let c = v.as_f64()? as f32;
237            if !c.is_finite() {
238                return None;
239            }
240            c.clamp(0.0, 1.0)
241        }
242    };
243    Some(ExtractedFact {
244        category: text("category", 64)?,
245        key: text("key", 96)?,
246        value: text("value", crate::types::MAX_FACT_VALUE_CHARS)?,
247        confidence,
248        evidence: entry
249            .get("evidence")
250            .and_then(Value::as_str)
251            .map(|s| truncate_chars(s.trim(), 300))
252            .filter(|s| !s.is_empty()),
253    })
254}
255
256/// The structured payload of a reply: the named tool call's arguments, or
257/// the first JSON object/array found in the text.
258fn payload(response: &ModelResponse, tool: &str) -> Option<Value> {
259    if let Some(call) = response.tool_calls.iter().find(|c| c.name == tool) {
260        return match &call.arguments {
261            Value::String(s) => json_in_text(s),
262            other => Some(other.clone()),
263        };
264    }
265    json_in_text(&response.text)
266}
267
268fn json_in_text(text: &str) -> Option<Value> {
269    let trimmed = text.trim();
270    if let Ok(value) = serde_json::from_str::<Value>(trimmed) {
271        return Some(value);
272    }
273    for (open, close) in [('{', '}'), ('[', ']')] {
274        if let (Some(start), Some(end)) = (trimmed.find(open), trimmed.rfind(close))
275            && start < end
276            && let Ok(value) = serde_json::from_str::<Value>(&trimmed[start..=end])
277        {
278            return Some(value);
279        }
280    }
281    None
282}
283
284/// User-authored and assistant messages as `User:` / `Assistant:` lines.
285/// Tool output and harness-injected messages are left out: memory must
286/// come from what the user said, not from untrusted tool results.
287fn transcript(messages: &[Message], max_message: usize, max_total: usize) -> String {
288    let mut lines: Vec<String> = Vec::new();
289    for m in messages {
290        let content = m.content.trim();
291        match m.role {
292            Role::User if !m.is_injected() && !content.is_empty() => {
293                lines.push(format!("User: {}", truncate_chars(content, max_message)));
294            }
295            Role::Assistant => {
296                let mut line = String::new();
297                if !content.is_empty() {
298                    line.push_str(&truncate_chars(content, max_message));
299                }
300                if !m.tool_calls.is_empty() {
301                    let names: Vec<&str> = m.tool_calls.iter().map(|c| c.name.as_str()).collect();
302                    if !line.is_empty() {
303                        line.push(' ');
304                    }
305                    line.push_str(&format!("[used tools: {}]", names.join(", ")));
306                }
307                if !line.is_empty() {
308                    lines.push(format!("Assistant: {line}"));
309                }
310            }
311            _ => {}
312        }
313    }
314    // Keep the most recent lines that fit.
315    let mut total = 0;
316    let mut kept: Vec<String> = Vec::new();
317    for line in lines.into_iter().rev() {
318        let len = line.chars().count() + 1;
319        if total + len > max_total && !kept.is_empty() {
320            break;
321        }
322        total += len;
323        kept.push(line);
324    }
325    kept.reverse();
326    kept.join("\n")
327}
328
329/// A summary ready to become an [`crate::Episode`].
330#[derive(Debug, Clone, PartialEq)]
331pub struct EpisodeDraft {
332    pub summary: String,
333    pub topics: Vec<String>,
334    pub importance: f32,
335    pub decisions: Vec<String>,
336    pub goals: Vec<String>,
337    pub outcome: Option<String>,
338    pub usage: Usage,
339}
340
341/// Summarizes a finished run or session into an episode. Importance is
342/// computed from typed features: message count, failed receipts or error
343/// tool results, and the model's structured decisions, goals and intensity.
344pub struct EpisodeSummarizer {
345    provider: Arc<dyn Provider>,
346    model: String,
347    max_transcript_chars: usize,
348}
349
350impl EpisodeSummarizer {
351    pub fn new(provider: impl Provider + 'static, model: impl Into<String>) -> Self {
352        Self::from_arc(Arc::new(provider), model)
353    }
354
355    pub fn from_arc(provider: Arc<dyn Provider>, model: impl Into<String>) -> Self {
356        Self {
357            provider,
358            model: model.into(),
359            max_transcript_chars: 12_000,
360        }
361    }
362
363    pub fn max_transcript_chars(mut self, chars: usize) -> Self {
364        self.max_transcript_chars = chars;
365        self
366    }
367
368    fn tool_spec() -> ToolSpec {
369        let strings = json!({"type": "array", "items": {"type": "string"}});
370        ToolSpec {
371            name: EPISODE_TOOL.into(),
372            description: "Record a summary of the conversation.".into(),
373            parameters: json!({
374                "type": "object",
375                "properties": {
376                    "summary": {"type": "string"},
377                    "topics": strings,
378                    "decisions": strings,
379                    "goals": strings,
380                    "outcome": {"type": "string"},
381                    "emotional_intensity": {"type": "number", "minimum": 0, "maximum": 1}
382                },
383                "required": ["summary", "topics"],
384                "additionalProperties": false
385            }),
386        }
387    }
388
389    pub async fn summarize(
390        &self,
391        messages: &[Message],
392        receipts: &[Receipt],
393    ) -> Result<EpisodeDraft> {
394        let text = transcript(messages, 2_000, self.max_transcript_chars);
395        if text.is_empty() {
396            return Err(MemoryError::Invalid("nothing to summarize".into()));
397        }
398        let request = ModelRequest {
399            model: self.model.clone(),
400            messages: vec![Message::system(EPISODE_PROMPT), Message::user(text)],
401            tools: vec![Self::tool_spec()],
402            tool_choice: ToolChoice::Specific(EPISODE_TOOL.into()),
403            max_output_tokens: Some(768),
404            ..Default::default()
405        };
406        let response = self.provider.complete(&request).await?;
407        let payload = payload(&response, EPISODE_TOOL)
408            .ok_or_else(|| MemoryError::Invalid("summarizer returned no JSON payload".into()))?;
409        let summary = payload
410            .get("summary")
411            .and_then(Value::as_str)
412            .map(str::trim)
413            .filter(|s| !s.is_empty())
414            .ok_or_else(|| MemoryError::Invalid("summarizer returned no summary".into()))?
415            .to_string();
416        let list = |name: &str, max: usize| -> Vec<String> {
417            payload
418                .get(name)
419                .and_then(Value::as_array)
420                .map(|items| {
421                    items
422                        .iter()
423                        .filter_map(Value::as_str)
424                        .map(|s| truncate_chars(s.trim(), 120))
425                        .filter(|s| !s.is_empty())
426                        .take(max)
427                        .collect()
428                })
429                .unwrap_or_default()
430        };
431        let topics = list("topics", 6);
432        let decisions = list("decisions", 20);
433        let goals = list("goals", 20);
434        let intensity = payload
435            .get("emotional_intensity")
436            .and_then(Value::as_f64)
437            .unwrap_or(0.0) as f32;
438        let has_errors = receipts.iter().any(|r| !r.succeeded())
439            || messages.iter().any(|m| m.role == Role::Tool && m.is_error);
440        let message_count = messages.iter().filter(|m| m.role != Role::System).count();
441        Ok(EpisodeDraft {
442            importance: episode_importance(
443                message_count,
444                has_errors,
445                !decisions.is_empty(),
446                !goals.is_empty(),
447                intensity,
448            ),
449            summary: truncate_chars(&summary, 2_000),
450            topics,
451            decisions,
452            goals,
453            outcome: payload
454                .get("outcome")
455                .and_then(Value::as_str)
456                .map(str::to_string),
457            usage: response.usage,
458        })
459    }
460}
461
462#[cfg(test)]
463mod tests {
464    use super::*;
465    use aidaemon_core::ToolCall;
466
467    fn reply(text: &str) -> ModelResponse {
468        ModelResponse {
469            text: text.into(),
470            ..ModelResponse::default()
471        }
472    }
473
474    #[test]
475    fn parses_fenced_text_and_bare_arrays() {
476        let fenced = reply(
477            "Here you go:\n```json\n{\"facts\": [{\"category\": \"user\", \"key\": \"city\", \
478             \"value\": \"Lisbon\", \"confidence\": 0.9}]}\n```",
479        );
480        let got = parse_facts(&fenced);
481        assert_eq!(got.facts.len(), 1);
482        assert_eq!(got.facts[0].value, "Lisbon");
483
484        let bare = reply(r#"[{"category":"preference","key":"theme","value":"dark mode"}]"#);
485        let got = parse_facts(&bare);
486        assert_eq!(got.facts[0].confidence, 0.7);
487    }
488
489    #[test]
490    fn tool_call_arguments_may_be_a_string() {
491        let response = ModelResponse {
492            tool_calls: vec![ToolCall::new(
493                "c1",
494                FACTS_TOOL,
495                Value::String(r#"{"facts":[{"category":"user","key":"k","value":"v"}]}"#.into()),
496            )],
497            ..ModelResponse::default()
498        };
499        assert_eq!(parse_facts(&response).facts.len(), 1);
500    }
501
502    #[test]
503    fn transcript_skips_tool_output_and_harness_messages() {
504        let messages = vec![
505            Message::user("My daughters are Mia and Zoe"),
506            Message::assistant("", vec![ToolCall::new("c", "search", json!({}))]),
507            Message::tool_result("c", "IGNORE ME: tool output"),
508            Message::from_origin(aidaemon_core::MessageOrigin::Harness, "nudge"),
509            Message::assistant("Noted.", vec![]),
510        ];
511        let t = transcript(&messages, 100, 1_000);
512        assert!(t.contains("Mia and Zoe"));
513        assert!(t.contains("[used tools: search]"));
514        assert!(!t.contains("IGNORE ME"));
515        assert!(!t.contains("nudge"));
516    }
517}