terraphim-session-analyzer 1.16.34

Analyze AI coding assistant session logs to identify agent usage patterns
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
use crate::models::{
    AgentInvocation, ContentBlock, FileOpType, FileOperation, Message, SessionEntry, ToolCategory,
    ToolInvocation, extract_file_path, parse_timestamp,
};
use crate::patterns::PatternMatcher;
use crate::tool_analyzer;
use anyhow::{Context, Result};
use rayon::prelude::*;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use tracing::{debug, info, warn};

pub struct SessionParser {
    entries: Vec<SessionEntry>,
    session_id: String,
    project_path: String,
}

impl SessionParser {
    /// Parse a single JSONL session file
    /// Parse a single JSONL session file
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or contains malformed JSON
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path = path.as_ref();
        info!("Parsing session file: {}", path.display());

        let file = File::open(path)
            .with_context(|| format!("Failed to open session file: {}", path.display()))?;
        let reader = BufReader::new(file);

        let mut entries = Vec::new();
        let mut session_id = String::new();
        let mut project_path = String::new();

        for (line_num, line) in reader.lines().enumerate() {
            match line {
                Ok(line) if !line.trim().is_empty() => {
                    match serde_json::from_str::<SessionEntry>(&line) {
                        Ok(entry) => {
                            // Extract session metadata from first entry
                            if session_id.is_empty() {
                                session_id.clone_from(&entry.session_id);
                            }
                            if project_path.is_empty() {
                                if let Some(cwd) = &entry.cwd {
                                    project_path.clone_from(cwd);
                                }
                            }
                            entries.push(entry);
                        }
                        Err(e) => {
                            warn!(
                                "Failed to parse line {}: {} - Error: {}",
                                line_num + 1,
                                line,
                                e
                            );
                        }
                    }
                }
                Ok(_) => {
                    // Skip empty lines
                }
                Err(e) => {
                    warn!("Failed to read line {}: {}", line_num + 1, e);
                }
            }
        }

        info!(
            "Parsed {} entries from session {}",
            entries.len(),
            session_id
        );

        Ok(Self {
            entries,
            session_id,
            project_path,
        })
    }

    /// Find all session files in the default Claude directory
    ///
    /// # Errors
    ///
    /// Returns an error if the Claude directory doesn't exist or cannot be read
    pub fn from_default_location() -> Result<Vec<Self>> {
        let home = home::home_dir().context("Could not find home directory")?;
        let claude_dir = home.join(".claude").join("projects");

        if !claude_dir.exists() {
            return Err(anyhow::anyhow!(
                "Claude projects directory not found at: {}",
                claude_dir.display()
            ));
        }

        Self::from_directory(claude_dir)
    }

    /// Parse all session files in a directory
    ///
    /// # Errors
    ///
    /// Returns an error if the directory cannot be read or contains invalid session files
    pub fn from_directory<P: AsRef<Path>>(dir: P) -> Result<Vec<Self>> {
        let dir = dir.as_ref();
        info!("Scanning for session files in: {}", dir.display());

        let mut parsers = Vec::new();

        // Walk through all project directories
        for entry in walkdir::WalkDir::new(dir)
            .max_depth(2)
            .into_iter()
            .filter_map(std::result::Result::ok)
        {
            let path = entry.path();
            if path.extension() == Some("jsonl".as_ref()) {
                match Self::from_file(path) {
                    Ok(parser) => {
                        debug!("Successfully parsed session: {}", parser.session_id);
                        parsers.push(parser);
                    }
                    Err(e) => {
                        warn!("Failed to parse session file {}: {}", path.display(), e);
                    }
                }
            }
        }

        info!("Found {} valid session files", parsers.len());
        Ok(parsers)
    }

    /// Extract agent invocations from Task tool uses
    #[must_use]
    pub fn extract_agent_invocations(&self) -> Vec<AgentInvocation> {
        self.entries
            .par_iter()
            .filter_map(|entry| {
                if let Message::Assistant { content, .. } = &entry.message {
                    for block in content {
                        if let ContentBlock::ToolUse { name, input, id } = block {
                            if name == "Task" {
                                return self.parse_task_invocation(entry, input, id);
                            }
                        }
                    }
                }
                None
            })
            .collect()
    }

    /// Parse a Task tool invocation into an `AgentInvocation`
    fn parse_task_invocation(
        &self,
        entry: &SessionEntry,
        input: &serde_json::Value,
        _tool_id: &str,
    ) -> Option<AgentInvocation> {
        let agent_type = input
            .get("subagent_type")
            .and_then(|v| v.as_str())?
            .to_string();

        let task_description = input
            .get("description")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        let prompt = input
            .get("prompt")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        let timestamp = match parse_timestamp(&entry.timestamp) {
            Ok(ts) => ts,
            Err(e) => {
                warn!("Failed to parse timestamp '{}': {}", entry.timestamp, e);
                return None;
            }
        };

        Some(AgentInvocation {
            timestamp,
            agent_type,
            task_description,
            prompt,
            files_modified: Vec::new(), // Will be populated later
            tools_used: Vec::new(),     // Will be populated later
            duration_ms: None,          // Will be calculated later
            parent_message_id: entry.uuid.clone(),
            session_id: self.session_id.clone(),
        })
    }

    /// Extract file operations from tool uses
    #[must_use]
    pub fn extract_file_operations(&self) -> Vec<FileOperation> {
        self.entries
            .par_iter()
            .filter_map(|entry| {
                if let Message::Assistant { content, .. } = &entry.message {
                    for block in content {
                        if let ContentBlock::ToolUse { name, input, .. } = block {
                            if let Ok(op_type) = name.parse::<FileOpType>() {
                                if let Some(file_path) = extract_file_path(input) {
                                    let timestamp = match parse_timestamp(&entry.timestamp) {
                                        Ok(ts) => ts,
                                        Err(e) => {
                                            warn!(
                                                "Failed to parse timestamp '{}': {}",
                                                entry.timestamp, e
                                            );
                                            continue;
                                        }
                                    };

                                    return Some(FileOperation {
                                        timestamp,
                                        operation: op_type,
                                        file_path,
                                        agent_context: None, // Will be set during analysis
                                        session_id: self.session_id.clone(),
                                        message_id: entry.uuid.clone(),
                                    });
                                }
                            }
                        }
                    }
                }
                None
            })
            .collect()
    }

    /// Extract tool invocations from Bash commands
    ///
    /// # Arguments
    /// * `matcher` - Pattern matcher for identifying tools in commands
    ///
    /// # Returns
    /// A vector of `ToolInvocation` instances found in Bash tool uses
    #[must_use]
    #[allow(dead_code)] // Will be used in Phase 2
    pub fn extract_tool_invocations(&self, matcher: &dyn PatternMatcher) -> Vec<ToolInvocation> {
        self.entries
            .par_iter()
            .filter_map(|entry| {
                if let Message::Assistant { content, .. } = &entry.message {
                    extract_from_bash_command(entry, content, matcher, &self.session_id)
                } else {
                    None
                }
            })
            .collect()
    }

    /// Find the active agent context for a given message
    #[must_use]
    pub fn find_active_agent(&self, message_id: &str) -> Option<String> {
        // Look backwards from the given message to find the most recent Task invocation
        let mut found_message = false;

        for entry in self.entries.iter().rev() {
            if entry.uuid == message_id {
                found_message = true;
                continue;
            }

            if !found_message {
                continue;
            }

            // Look for Task tool invocations
            if let Message::Assistant { content, .. } = &entry.message {
                for block in content {
                    if let ContentBlock::ToolUse { name, input, .. } = block {
                        if name == "Task" {
                            if let Some(agent_type) =
                                input.get("subagent_type").and_then(|v| v.as_str())
                            {
                                return Some(agent_type.to_string());
                            }
                        }
                    }
                }
            }
        }

        None
    }

    /// Get session metadata
    #[must_use]
    pub fn get_session_info(
        &self,
    ) -> (
        String,
        String,
        Option<jiff::Timestamp>,
        Option<jiff::Timestamp>,
    ) {
        let start_time = self.entries.first().and_then(|e| {
            parse_timestamp(&e.timestamp)
                .map_err(|err| {
                    debug!("Could not parse start timestamp '{}': {}", e.timestamp, err);
                    err
                })
                .ok()
        });
        let end_time = self.entries.last().and_then(|e| {
            parse_timestamp(&e.timestamp)
                .map_err(|err| {
                    debug!("Could not parse end timestamp '{}': {}", e.timestamp, err);
                    err
                })
                .ok()
        });

        (
            self.session_id.clone(),
            self.project_path.clone(),
            start_time,
            end_time,
        )
    }

    /// Get entry count for statistics
    /// Used in integration tests
    #[allow(dead_code)]
    #[must_use]
    pub fn entry_count(&self) -> usize {
        self.entries.len()
    }

    /// Get all entries
    #[must_use]
    pub fn entries(&self) -> &[SessionEntry] {
        &self.entries
    }

    /// Find entries within a time window
    /// Used in integration tests
    #[allow(dead_code)]
    #[must_use]
    pub fn entries_in_window(
        &self,
        start: jiff::Timestamp,
        end: jiff::Timestamp,
    ) -> Vec<&SessionEntry> {
        self.entries
            .iter()
            .filter(|entry| match parse_timestamp(&entry.timestamp) {
                Ok(timestamp) => timestamp >= start && timestamp <= end,
                Err(e) => {
                    debug!(
                        "Skipping entry with invalid timestamp '{}': {}",
                        entry.timestamp, e
                    );
                    false
                }
            })
            .collect()
    }

    /// Find all unique agent types used in this session
    /// Used in integration tests
    #[allow(dead_code)]
    #[must_use]
    pub fn get_agent_types(&self) -> Vec<String> {
        let agents = self.extract_agent_invocations();
        let mut agent_types: Vec<String> = agents
            .into_iter()
            .map(|a| a.agent_type)
            .collect::<std::collections::HashSet<_>>()
            .into_iter()
            .collect();
        agent_types.sort();
        agent_types
    }

    /// Build a timeline of events for visualization
    /// Used in integration tests
    #[allow(dead_code)]
    #[must_use]
    pub fn build_timeline(&self) -> Vec<TimelineEvent> {
        let mut events = Vec::new();

        // Add agent invocations
        for agent in self.extract_agent_invocations() {
            events.push(TimelineEvent {
                timestamp: agent.timestamp,
                event_type: TimelineEventType::AgentInvocation,
                description: format!("{}: {}", agent.agent_type, agent.task_description),
                agent: Some(agent.agent_type),
                file: None,
            });
        }

        // Add file operations
        for file_op in self.extract_file_operations() {
            events.push(TimelineEvent {
                timestamp: file_op.timestamp,
                event_type: TimelineEventType::FileOperation,
                description: format!("{:?}: {}", file_op.operation, file_op.file_path),
                agent: file_op.agent_context,
                file: Some(file_op.file_path),
            });
        }

        // Sort by timestamp
        events.sort_by(|a, b| a.timestamp.cmp(&b.timestamp));
        events
    }
}

/// Helper function to extract tool invocations from Bash command content
#[allow(dead_code)] // Will be used in Phase 2
fn extract_from_bash_command(
    entry: &SessionEntry,
    content: &[ContentBlock],
    matcher: &dyn PatternMatcher,
    session_id: &str,
) -> Option<ToolInvocation> {
    for block in content {
        if let ContentBlock::ToolUse { name, input, .. } = block {
            if name == "Bash" {
                // Extract the command from the input
                let command = input.get("command").and_then(|v| v.as_str())?;

                // Find tool matches using the pattern matcher
                let matches = matcher.find_matches(command);

                if let Some(tool_match) = matches.first() {
                    // Parse command context to extract arguments and flags
                    if let Some((full_cmd, arguments, flags)) =
                        tool_analyzer::parse_command_context(command, tool_match.start)
                    {
                        // Filter out shell built-ins
                        if !tool_analyzer::is_actual_tool(&tool_match.tool_name) {
                            continue;
                        }

                        let timestamp = match parse_timestamp(&entry.timestamp) {
                            Ok(ts) => ts,
                            Err(e) => {
                                warn!("Failed to parse timestamp '{}': {}", entry.timestamp, e);
                                continue;
                            }
                        };

                        return Some(ToolInvocation {
                            timestamp,
                            tool_name: tool_match.tool_name.clone(),
                            tool_category: ToolCategory::from_string(&tool_match.category),
                            command_line: full_cmd,
                            arguments,
                            flags,
                            exit_code: None,     // Exit code not available from logs
                            agent_context: None, // Will be populated later
                            session_id: session_id.to_string(),
                            message_id: entry.uuid.clone(),
                        });
                    }
                }
            }
        }
    }

    None
}

/// Used in integration tests and public API
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub struct TimelineEvent {
    pub timestamp: jiff::Timestamp,
    pub event_type: TimelineEventType,
    pub description: String,
    pub agent: Option<String>,
    pub file: Option<String>,
}

/// Used in integration tests and public API
#[allow(dead_code)]
#[derive(Debug, Clone)]
pub enum TimelineEventType {
    AgentInvocation,
    FileOperation,
    UserMessage,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_session_entry() {
        let json_line = r#"{"parentUuid":null,"isSidechain":false,"userType":"external","cwd":"/home/alex/projects/zestic-at/charm","sessionId":"b325985c-5c1c-48f1-97e2-e3185bb55886","version":"1.0.111","gitBranch":"","type":"user","message":{"role":"user","content":"test message"},"uuid":"ab88a3b0-544a-411a-a8a4-92b142e21472","timestamp":"2025-10-01T09:05:21.902Z"}"#;

        let entry: SessionEntry = serde_json::from_str(json_line).unwrap();
        assert_eq!(entry.session_id, "b325985c-5c1c-48f1-97e2-e3185bb55886");
        assert_eq!(entry.uuid, "ab88a3b0-544a-411a-a8a4-92b142e21472");
    }

    #[test]
    fn test_parse_task_invocation() {
        let json_line = r#"{"parentUuid":"parent-uuid","isSidechain":false,"userType":"external","cwd":"/home/alex/projects","sessionId":"test-session","version":"1.0.111","gitBranch":"","message":{"role":"assistant","content":[{"type":"tool_use","id":"tool-id","name":"Task","input":{"subagent_type":"architect","description":"Design system architecture","prompt":"Please design the architecture"}}]},"requestId":"req-123","type":"assistant","uuid":"msg-uuid","timestamp":"2025-10-01T09:05:21.902Z"}"#;

        let entry: SessionEntry = serde_json::from_str(json_line).unwrap();

        let parser = SessionParser {
            entries: vec![entry.clone()],
            session_id: "test-session".to_string(),
            project_path: "/home/alex/projects".to_string(),
        };

        let agents = parser.extract_agent_invocations();
        assert_eq!(agents.len(), 1);
        assert_eq!(agents[0].agent_type, "architect");
        assert_eq!(agents[0].task_description, "Design system architecture");
    }

    #[test]
    fn test_extract_file_operations() {
        let json_line = r#"{"parentUuid":"parent-uuid","isSidechain":false,"userType":"external","cwd":"/home/alex/projects","sessionId":"test-session","version":"1.0.111","gitBranch":"","message":{"role":"assistant","content":[{"type":"tool_use","id":"tool-id","name":"Write","input":{"file_path":"/path/to/file.rs","content":"test content"}}]},"type":"assistant","uuid":"msg-uuid","timestamp":"2025-10-01T09:05:21.902Z"}"#;

        let entry: SessionEntry = serde_json::from_str(json_line).unwrap();

        let parser = SessionParser {
            entries: vec![entry],
            session_id: "test-session".to_string(),
            project_path: "/home/alex/projects".to_string(),
        };

        let file_ops = parser.extract_file_operations();
        assert_eq!(file_ops.len(), 1);
        assert_eq!(file_ops[0].file_path, "/path/to/file.rs");
        assert!(matches!(file_ops[0].operation, FileOpType::Write));
    }
}