1use std::sync::Arc;
5
6use aidaemon_core::{Message, ModelRequest, Provider};
7use chrono::{DateTime, Utc};
8use serde::Deserialize;
9use tracing::info;
10
11use crate::history::TurnRole;
12use crate::scoring::episode_importance;
13use crate::stores::EpisodeStore;
14
15#[derive(Debug, Clone, PartialEq)]
17pub struct TranscriptEntry {
18 pub role: TurnRole,
19 pub content: Option<String>,
20 pub tool_calls: Vec<String>,
22 pub tool_name: Option<String>,
24}
25
26pub fn clean_transcript(entries: &[TranscriptEntry]) -> String {
30 let mut transcript = String::new();
31 for entry in entries {
32 match entry.role {
33 TurnRole::User => {
34 if let Some(content) = &entry.content {
35 transcript.push_str(&format!("User: {content}\n\n"));
36 }
37 }
38 TurnRole::Assistant => {
39 for name in &entry.tool_calls {
40 transcript.push_str(&format!("[Action: {name}]\n"));
41 }
42 if let Some(content) = entry.content.as_deref().filter(|c| !c.trim().is_empty()) {
43 let shortened = crate::text::truncate_chars(content, 500);
44 transcript.push_str(&format!("Assistant: {shortened}\n\n"));
45 }
46 }
47 TurnRole::Tool => {
48 if let (Some(content), Some(name)) = (&entry.content, &entry.tool_name) {
49 let summary = if content.len() > 200 {
50 format!("[{name} output: {} chars]", content.len())
51 } else {
52 format!(
53 "[{name}: {}]",
54 content.chars().take(100).collect::<String>()
55 )
56 };
57 transcript.push_str(&format!("{summary}\n"));
58 }
59 }
60 }
61 }
62 transcript
63}
64
65const ANALYSIS_PROMPT: &str = r#"You are a memory system analyzing a conversation. Extract:
661. A brief summary (1-2 sentences)
672. Main topics discussed (list of keywords)
683. Emotional tone (one of: neutral, productive, frustrated, exploratory, celebratory)
694. Outcome (one of: resolved, ongoing, abandoned, learning)
705. Possible enduring personal goals the user explicitly stated for themselves
716. Whether the session ran into errors (had_errors) and whether the user made decisions or commitments (made_decisions)
72
73For goals_mentioned, return an empty list for ordinary one-off requests, implementation
74steps, delegated work, quoted examples, prohibitions, review checklists, or specialist/system
75instructions. Only include a goal when the user's own words describe an intention that should
76remain relevant beyond this conversation.
77
78Respond with ONLY valid JSON:
79{
80 "summary": "...",
81 "topics": ["topic1", "topic2"],
82 "emotional_tone": "...",
83 "outcome": "...",
84 "goals_mentioned": ["goal1", "goal2"],
85 "emotional_intensity": 0.5,
86 "had_errors": false,
87 "made_decisions": false
88}
89
90emotional_intensity is 0.0-1.0 scale (0=calm, 1=highly emotional)"#;
91
92#[derive(Clone)]
94pub struct SessionAnalyst {
95 provider: Arc<dyn Provider>,
96 model: String,
97}
98
99#[derive(Debug, Clone, PartialEq)]
101pub struct SessionEpisode {
102 pub session_id: String,
103 pub summary: String,
104 pub topics: Vec<String>,
105 pub emotional_tone: String,
106 pub outcome: String,
107 pub importance: f32,
108 pub message_count: usize,
109 pub start_time: DateTime<Utc>,
110 pub end_time: DateTime<Utc>,
111 pub channel_id: Option<String>,
112}
113
114impl SessionAnalyst {
115 pub fn new(provider: Arc<dyn Provider>, model: impl Into<String>) -> Self {
116 Self {
117 provider,
118 model: model.into(),
119 }
120 }
121
122 pub async fn analyze(&self, transcript: &str) -> anyhow::Result<SessionAnalysis> {
125 let request = ModelRequest {
126 model: self.model.clone(),
127 messages: vec![
128 Message::system(ANALYSIS_PROMPT),
129 Message::user(format!("Analyze this conversation:\n\n{transcript}")),
130 ],
131 ..Default::default()
132 };
133 let response = self.provider.complete(&request).await?;
134 if response.text.trim().is_empty() {
135 anyhow::bail!("Empty response from LLM");
136 }
137 Ok(parse_session_analysis(&response.text))
138 }
139
140 #[allow(clippy::too_many_arguments)]
145 pub async fn record_episode<S>(
146 &self,
147 store: &S,
148 session_id: &str,
149 entries: &[TranscriptEntry],
150 message_count: usize,
151 start_time: DateTime<Utc>,
152 end_time: DateTime<Utc>,
153 channel_id: Option<String>,
154 ) -> anyhow::Result<(i64, SessionAnalysis)>
155 where
156 S: EpisodeStore + ?Sized,
157 {
158 anyhow::ensure!(message_count > 0, "No messages to create episode from");
159 let analysis = self.analyze(&clean_transcript(entries)).await?;
160 let importance = episode_importance(
161 message_count,
162 analysis.had_errors,
163 analysis.made_decisions,
164 !analysis.goals_mentioned.is_empty(),
165 analysis.emotional_intensity,
166 );
167 let episode = SessionEpisode {
168 session_id: session_id.to_string(),
169 summary: analysis.summary.clone(),
170 topics: analysis.topics.clone(),
171 emotional_tone: analysis.emotional_tone.clone(),
172 outcome: analysis.outcome.clone(),
173 importance,
174 message_count,
175 start_time,
176 end_time,
177 channel_id,
178 };
179 let episode_id = store.record_session_episode(&episode).await?;
180 info!(
181 session_id,
182 episode_id,
183 topics = ?analysis.topics,
184 emotional_tone = ?analysis.emotional_tone,
185 outcome = ?analysis.outcome,
186 goals = analysis.goals_mentioned.len(),
187 "Created episode"
188 );
189 Ok((episode_id, analysis))
190 }
191}
192
193pub fn parse_session_analysis(text: &str) -> SessionAnalysis {
196 let trimmed = text.trim();
197 let json = match (trimmed.find('{'), trimmed.rfind('}')) {
198 (Some(start), Some(end)) if end >= start => &trimmed[start..=end],
199 _ => trimmed,
200 };
201 serde_json::from_str(json).unwrap_or_else(|_| SessionAnalysis {
202 summary: "Session with various tasks".to_string(),
203 topics: vec!["general".to_string()],
204 emotional_tone: "neutral".to_string(),
205 outcome: "ongoing".to_string(),
206 goals_mentioned: vec![],
207 emotional_intensity: 0.3,
208 had_errors: false,
209 made_decisions: false,
210 })
211}
212
213#[derive(Debug, Clone, Deserialize)]
215pub struct SessionAnalysis {
216 #[serde(
217 default = "default_session_summary",
218 deserialize_with = "deserialize_session_summary"
219 )]
220 pub summary: String,
221 #[serde(default, deserialize_with = "deserialize_lossy_string_vec")]
222 pub topics: Vec<String>,
223 #[serde(
224 default = "default_emotional_tone",
225 deserialize_with = "deserialize_emotional_tone"
226 )]
227 pub emotional_tone: String,
228 #[serde(
229 default = "default_session_outcome",
230 deserialize_with = "deserialize_session_outcome"
231 )]
232 pub outcome: String,
233 #[serde(default, deserialize_with = "deserialize_lossy_string_vec")]
234 pub goals_mentioned: Vec<String>,
235 #[serde(
236 default = "default_emotional_intensity",
237 deserialize_with = "deserialize_emotional_intensity"
238 )]
239 pub emotional_intensity: f32,
240 #[serde(default, deserialize_with = "deserialize_lossy_bool")]
242 pub had_errors: bool,
243 #[serde(default, deserialize_with = "deserialize_lossy_bool")]
245 pub made_decisions: bool,
246}
247
248fn deserialize_lossy_bool<'de, D>(deserializer: D) -> Result<bool, D::Error>
249where
250 D: serde::Deserializer<'de>,
251{
252 let value = serde_json::Value::deserialize(deserializer)?;
253 Ok(match value {
254 serde_json::Value::Bool(flag) => flag,
255 serde_json::Value::String(text) => text.trim().eq_ignore_ascii_case("true"),
256 _ => false,
257 })
258}
259
260fn default_session_summary() -> String {
261 "Session with various tasks".to_string()
262}
263
264fn default_emotional_tone() -> String {
265 "neutral".to_string()
266}
267
268fn default_session_outcome() -> String {
269 "ongoing".to_string()
270}
271
272fn default_emotional_intensity() -> f32 {
273 0.3
274}
275
276fn deserialize_string_value<'de, D>(deserializer: D, fallback: &str) -> Result<String, D::Error>
277where
278 D: serde::Deserializer<'de>,
279{
280 let value = serde_json::Value::deserialize(deserializer)?;
281 Ok(value
282 .as_str()
283 .map(str::trim)
284 .filter(|value| !value.is_empty())
285 .unwrap_or(fallback)
286 .to_string())
287}
288
289fn deserialize_session_summary<'de, D>(deserializer: D) -> Result<String, D::Error>
290where
291 D: serde::Deserializer<'de>,
292{
293 deserialize_string_value(deserializer, "Session with various tasks")
294}
295
296fn deserialize_emotional_tone<'de, D>(deserializer: D) -> Result<String, D::Error>
297where
298 D: serde::Deserializer<'de>,
299{
300 deserialize_string_value(deserializer, "neutral")
301}
302
303fn deserialize_session_outcome<'de, D>(deserializer: D) -> Result<String, D::Error>
304where
305 D: serde::Deserializer<'de>,
306{
307 deserialize_string_value(deserializer, "ongoing")
308}
309
310fn deserialize_lossy_string_vec<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
311where
312 D: serde::Deserializer<'de>,
313{
314 let value = serde_json::Value::deserialize(deserializer)?;
315 let values = match value {
316 serde_json::Value::Array(values) => values,
317 serde_json::Value::String(value) => vec![serde_json::Value::String(value)],
318 _ => return Ok(Vec::new()),
319 };
320 Ok(values
321 .into_iter()
322 .filter_map(|value| value.as_str().map(str::trim).map(str::to_string))
323 .filter(|value| !value.is_empty())
324 .collect())
325}
326
327fn deserialize_emotional_intensity<'de, D>(deserializer: D) -> Result<f32, D::Error>
328where
329 D: serde::Deserializer<'de>,
330{
331 let value = serde_json::Value::deserialize(deserializer)?;
332 let intensity = value
333 .as_f64()
334 .map(|value| value as f32)
335 .or_else(|| value.as_str().and_then(|value| value.parse::<f32>().ok()))
336 .unwrap_or_else(default_emotional_intensity);
337 Ok(intensity.clamp(0.0, 1.0))
338}
339
340#[cfg(test)]
341mod tests {
342 use std::sync::Mutex;
343
344 use aidaemon_core::testing::{ScriptedProvider, text};
345 use async_trait::async_trait;
346
347 use super::*;
348
349 #[test]
350 fn analysis_keeps_valid_fields_when_siblings_are_null_or_malformed() {
351 let analysis: SessionAnalysis = serde_json::from_str(
352 r#"{
353 "summary": {"unexpected":"object"},
354 "topics": ["deployments", null, {"bad":true}, "reliability"],
355 "emotional_tone": null,
356 "outcome": "",
357 "goals_mentioned": "Improve release reliability",
358 "emotional_intensity": "1.7",
359 "had_errors": "true"
360 }"#,
361 )
362 .unwrap();
363 assert_eq!(analysis.summary, "Session with various tasks");
364 assert_eq!(analysis.topics, ["deployments", "reliability"]);
365 assert_eq!(analysis.emotional_tone, "neutral");
366 assert_eq!(analysis.outcome, "ongoing");
367 assert_eq!(analysis.goals_mentioned, ["Improve release reliability"]);
368 assert_eq!(analysis.emotional_intensity, 1.0);
369 assert!(analysis.had_errors && !analysis.made_decisions);
370 assert_eq!(
371 parse_session_analysis("not json").summary,
372 "Session with various tasks"
373 );
374 }
375
376 #[test]
377 fn transcripts_keep_the_users_words_and_compress_the_rest() {
378 let entries = [
379 TranscriptEntry {
380 role: TurnRole::User,
381 content: Some("Deploy the site".into()),
382 tool_calls: vec![],
383 tool_name: None,
384 },
385 TranscriptEntry {
386 role: TurnRole::Assistant,
387 content: Some("Deploying now.".into()),
388 tool_calls: vec!["terminal".into()],
389 tool_name: None,
390 },
391 TranscriptEntry {
392 role: TurnRole::Tool,
393 content: Some("x".repeat(500)),
394 tool_calls: vec![],
395 tool_name: Some("terminal".into()),
396 },
397 ];
398 let transcript = clean_transcript(&entries);
399 assert!(transcript.contains("User: Deploy the site"));
400 assert!(transcript.contains("[Action: terminal]"));
401 assert!(transcript.contains("Assistant: Deploying now."));
402 assert!(transcript.contains("[terminal output: 500 chars]"));
403 }
404
405 #[derive(Default)]
406 struct Episodes(Mutex<Vec<SessionEpisode>>);
407
408 #[async_trait]
409 impl EpisodeStore for Episodes {
410 async fn record_session_episode(&self, episode: &SessionEpisode) -> anyhow::Result<i64> {
411 self.0.lock().unwrap().push(episode.clone());
412 Ok(7)
413 }
414 }
415
416 #[tokio::test]
417 async fn importance_comes_from_typed_signals() {
418 let reply = r#"{"summary":"Fixed the release pipeline","topics":["ci"],"emotional_tone":"productive",
419 "outcome":"resolved","goals_mentioned":[],"emotional_intensity":0.0,"had_errors":true,"made_decisions":true}"#;
420 let analyst = SessionAnalyst::new(Arc::new(ScriptedProvider::new([text(reply)])), "mock");
421 let store = Episodes::default();
422 let now = Utc::now();
423 let entry = TranscriptEntry {
424 role: TurnRole::User,
425 content: Some("The build is broken again".into()),
426 tool_calls: vec![],
427 tool_name: None,
428 };
429 let (id, analysis) = analyst
430 .record_episode(
431 &store,
432 "telegram:synthetic-chat",
433 &[entry],
434 4,
435 now,
436 now,
437 None,
438 )
439 .await
440 .unwrap();
441 assert_eq!(id, 7);
442 assert_eq!(analysis.outcome, "resolved");
443 let episode = &store.0.lock().unwrap()[0];
444 assert_eq!(episode.summary, "Fixed the release pipeline");
445 assert!(
447 (episode.importance - 0.75).abs() < 1e-6,
448 "{}",
449 episode.importance
450 );
451 }
452}