Skip to main content

vibe_coding_tracker/session/
state.rs

1//! Mutable accumulator shared by every per-provider session parser.
2//!
3//! Each provider parser ([`crate::session::claude`], [`crate::session::codex`],
4//! …) walks its own JSONL shape but funnels the file-operation facts it
5//! extracts through a single [`SessionParseState`], which tallies line /
6//! character counts and (in [`ParseMode::Full`]) accumulates the per-op detail
7//! records. Once the file is consumed the state is converted into one
8//! [`CodeAnalysisRecord`] via [`SessionParseState::into_record`].
9use crate::constants::FastHashMap;
10use crate::models::*;
11use crate::utils::count_lines;
12use serde_json::Value;
13use std::collections::HashSet;
14
15/// Controls how much per-operation detail the session parser retains.
16///
17/// `Full` keeps everything that ends up in the public JSON output
18/// (file contents on `Write`, old/new strings on `Edit`, command text on
19/// `Bash`). `UsageOnly` skips those allocations — counts and totals are
20/// still accurate, but the per-detail `Vec`s stay empty. Callers that only
21/// consume `conversation_usage` / `tool_call_counts` / `total_*_lines`
22/// (the `usage` command, the aggregated `analysis` path) should pick
23/// `UsageOnly` to avoid pulling entire file bodies into memory on every
24/// session parse.
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum ParseMode {
27    /// Retain everything that ends up in the JSON output, including file
28    /// bodies and old/new edit strings.
29    Full,
30    /// Skip per-detail allocations; keep only counts and totals.
31    UsageOnly,
32}
33
34/// Common parse state shared by all per-provider session parsers.
35///
36/// Construct with [`SessionParseState::new`] (full detail) or
37/// [`SessionParseState::with_mode`], populate the metadata fields
38/// (`folder_path`, `git_remote`, `task_id`) directly as the provider header
39/// is read, feed file operations through the `add_*` helpers, then call
40/// [`SessionParseState::into_record`] to produce the final
41/// [`CodeAnalysisRecord`]. Not thread-safe; one instance parses one file on
42/// one thread.
43pub struct SessionParseState {
44    /// Detail-retention level chosen at construction.
45    pub mode: ParseMode,
46    /// Per-`Write` detail records (empty in [`ParseMode::UsageOnly`]).
47    pub write_details: Vec<CodeAnalysisWriteDetail>,
48    /// Per-`Read` detail records (empty in [`ParseMode::UsageOnly`]).
49    pub read_details: Vec<CodeAnalysisReadDetail>,
50    /// Per-`Edit`/diff detail records (empty in [`ParseMode::UsageOnly`]).
51    pub edit_details: Vec<CodeAnalysisApplyDiffDetail>,
52    /// Per-`Bash`/run-command detail records (empty in [`ParseMode::UsageOnly`]).
53    pub run_details: Vec<CodeAnalysisRunCommandDetail>,
54    /// Running per-tool call counts (always tallied, both modes).
55    pub tool_counts: CodeAnalysisToolCalls,
56    /// Distinct normalized file paths touched (only populated in [`ParseMode::Full`]).
57    pub unique_files: HashSet<String>,
58    /// Sum of lines written across all `Write` operations.
59    pub total_write_lines: usize,
60    /// Sum of lines read across all `Read` operations.
61    pub total_read_lines: usize,
62    /// Sum of new-content lines across all `Edit` operations.
63    pub total_edit_lines: usize,
64    /// Sum of characters written across all `Write` operations.
65    pub total_write_characters: usize,
66    /// Sum of characters read across all `Read` operations.
67    pub total_read_characters: usize,
68    /// Sum of new-content characters across all `Edit` operations.
69    pub total_edit_characters: usize,
70    /// Session working directory; used to resolve relative paths to absolute.
71    pub folder_path: String,
72    /// Git remote URL for the session's repository, when known.
73    pub git_remote: String,
74    /// Provider-specific session identifier.
75    pub task_id: String,
76    /// Latest event timestamp seen, in epoch milliseconds.
77    pub last_ts: i64,
78}
79
80impl SessionParseState {
81    /// Creates an empty parse state in [`ParseMode::Full`].
82    ///
83    /// # Examples
84    ///
85    /// ```
86    /// use vibe_coding_tracker::session::state::SessionParseState;
87    ///
88    /// let mut state = SessionParseState::new();
89    /// state.folder_path = "/repo".to_string();
90    /// state.add_read_detail("src/main.rs", "fn main() {}\n", 0);
91    /// assert_eq!(state.total_read_lines, 1);
92    /// assert_eq!(state.tool_counts.read, 1);
93    /// ```
94    pub fn new() -> Self {
95        Self::with_mode(ParseMode::Full)
96    }
97
98    /// Creates an empty parse state with the given detail-retention `mode`.
99    ///
100    /// In [`ParseMode::Full`] the detail `Vec`s and `unique_files` set are
101    /// pre-sized to typical session sizes; in [`ParseMode::UsageOnly`] they
102    /// start empty since they stay empty for the whole parse.
103    pub fn with_mode(mode: ParseMode) -> Self {
104        // Pre-allocate Vecs with reasonable capacity estimates based on
105        // typical session sizes. In `UsageOnly` mode we skip the
106        // pre-allocation because the vecs stay empty.
107        let pre = matches!(mode, ParseMode::Full);
108        Self {
109            mode,
110            write_details: if pre {
111                Vec::with_capacity(10)
112            } else {
113                Vec::new()
114            },
115            read_details: if pre {
116                Vec::with_capacity(20)
117            } else {
118                Vec::new()
119            },
120            edit_details: if pre {
121                Vec::with_capacity(15)
122            } else {
123                Vec::new()
124            },
125            run_details: if pre {
126                Vec::with_capacity(10)
127            } else {
128                Vec::new()
129            },
130            tool_counts: CodeAnalysisToolCalls::default(),
131            unique_files: HashSet::with_capacity(if pre { 20 } else { 0 }),
132            total_write_lines: 0,
133            total_read_lines: 0,
134            total_edit_lines: 0,
135            total_write_characters: 0,
136            total_read_characters: 0,
137            total_edit_characters: 0,
138            folder_path: String::new(),
139            git_remote: String::new(),
140            task_id: String::new(),
141            last_ts: 0,
142        }
143    }
144
145    /// Records a `Read` operation against `path` with the read `content`.
146    ///
147    /// Trailing newlines are stripped before counting. No-op (and no count
148    /// bump) when the trimmed content is empty or when `path` normalizes to
149    /// an empty string. The detail record and `unique_files` entry are only
150    /// stored in [`ParseMode::Full`]; counts accrue in both modes.
151    pub fn add_read_detail(&mut self, path: &str, content: &str, ts: i64) {
152        let trimmed = content.trim_end_matches('\n');
153        let line_count = count_lines(trimmed);
154
155        if line_count == 0 {
156            return;
157        }
158
159        let char_count = trimmed.chars().count();
160        let resolved = self.normalize_path(path);
161
162        if resolved.is_empty() {
163            return;
164        }
165
166        if matches!(self.mode, ParseMode::Full) {
167            self.read_details.push(CodeAnalysisReadDetail {
168                base: CodeAnalysisDetailBase {
169                    file_path: resolved.clone(),
170                    line_count,
171                    character_count: char_count,
172                    timestamp: ts,
173                },
174            });
175            self.unique_files.insert(resolved);
176        }
177
178        self.total_read_lines += line_count;
179        self.total_read_characters += char_count;
180        self.tool_counts.read += 1;
181    }
182
183    /// Records a `Write` operation against `path` with the written `content`.
184    ///
185    /// Trailing newlines are stripped before counting. No-op when `path`
186    /// normalizes to an empty string (an empty body is still counted as a
187    /// zero-line write). The full detail (including `content`) and
188    /// `unique_files` entry are stored only in [`ParseMode::Full`].
189    pub fn add_write_detail(&mut self, path: &str, content: &str, ts: i64) {
190        let trimmed = content.trim_end_matches('\n');
191        let line_count = count_lines(trimmed);
192        let char_count = trimmed.chars().count();
193        let resolved = self.normalize_path(path);
194
195        if resolved.is_empty() {
196            return;
197        }
198
199        if matches!(self.mode, ParseMode::Full) {
200            self.write_details.push(CodeAnalysisWriteDetail {
201                base: CodeAnalysisDetailBase {
202                    file_path: resolved.clone(),
203                    line_count,
204                    character_count: char_count,
205                    timestamp: ts,
206                },
207                content: trimmed.to_string(),
208            });
209            self.unique_files.insert(resolved);
210        }
211
212        self.total_write_lines += line_count;
213        self.total_write_characters += char_count;
214        self.tool_counts.write += 1;
215    }
216
217    /// Records an `Edit` operation against `path`, replacing `old` with `new`.
218    ///
219    /// When `old` is empty but `new` is not, the edit is reclassified as a
220    /// `Write` (a new-file creation expressed as a diff) and forwarded to
221    /// [`SessionParseState::add_write_detail`]. Otherwise delegates to
222    /// [`SessionParseState::add_edit_detail_raw`].
223    pub fn add_edit_detail(&mut self, path: &str, old: &str, new: &str, ts: i64) {
224        // If old is empty and new has content, treat as write
225        if old.trim_end_matches('\n').is_empty() && !new.trim_end_matches('\n').is_empty() {
226            self.add_write_detail(path, new, ts);
227            return;
228        }
229
230        self.add_edit_detail_raw(path, old, new, ts);
231    }
232
233    /// Records an `Edit` operation against `path` without the new-file
234    /// reclassification in [`SessionParseState::add_edit_detail`].
235    ///
236    /// Used for patch hunks that update an existing file, where an empty `old`
237    /// just means an insert-only hunk. The line/character tally is taken from
238    /// the trimmed `new` content. No-op when `path` normalizes to an empty
239    /// string; full detail stored only in [`ParseMode::Full`].
240    pub fn add_edit_detail_raw(&mut self, path: &str, old: &str, new: &str, ts: i64) {
241        let trimmed_new = new.trim_end_matches('\n');
242        let trimmed_old = old.trim_end_matches('\n');
243
244        let line_count = count_lines(trimmed_new);
245        let char_count = trimmed_new.chars().count();
246        let resolved = self.normalize_path(path);
247
248        if resolved.is_empty() {
249            return;
250        }
251
252        if matches!(self.mode, ParseMode::Full) {
253            self.edit_details.push(CodeAnalysisApplyDiffDetail {
254                base: CodeAnalysisDetailBase {
255                    file_path: resolved.clone(),
256                    line_count,
257                    character_count: char_count,
258                    timestamp: ts,
259                },
260                old_string: trimmed_old.to_string(),
261                new_string: trimmed_new.to_string(),
262            });
263            self.unique_files.insert(resolved);
264        }
265
266        self.total_edit_lines += line_count;
267        self.total_edit_characters += char_count;
268        self.tool_counts.edit += 1;
269    }
270
271    /// Records a `Bash`/run-command invocation with its `command` text.
272    ///
273    /// No-op (and no count bump) when `command` is empty after trimming. The
274    /// detail record (attributed to `folder_path`) is stored only in
275    /// [`ParseMode::Full`]; the `bash` count accrues in both modes.
276    pub fn add_run_command(&mut self, command: &str, description: &str, ts: i64) {
277        let command = command.trim();
278        if command.is_empty() {
279            return;
280        }
281
282        let command_chars = command.chars().count();
283
284        if matches!(self.mode, ParseMode::Full) {
285            self.run_details.push(CodeAnalysisRunCommandDetail {
286                base: CodeAnalysisDetailBase {
287                    file_path: self.folder_path.clone(),
288                    line_count: 0,
289                    character_count: command_chars,
290                    timestamp: ts,
291                },
292                command: command.to_string(),
293                description: description.to_string(),
294            });
295        }
296
297        self.tool_counts.bash += 1;
298    }
299
300    /// Resolves `path` to an absolute path, joining it onto `folder_path`.
301    ///
302    /// Returns the input unchanged when it is already absolute, when it is
303    /// empty, or when `folder_path` is empty (nothing to join against).
304    pub fn normalize_path(&self, path: &str) -> String {
305        if path.is_empty() {
306            return String::new();
307        }
308
309        let path_buf = std::path::PathBuf::from(path);
310        if path_buf.is_absolute() {
311            return path.to_string();
312        }
313
314        if self.folder_path.is_empty() {
315            return path.to_string();
316        }
317
318        std::path::PathBuf::from(&self.folder_path)
319            .join(path)
320            .to_string_lossy()
321            .to_string()
322    }
323
324    /// Consumes the state into a finished [`CodeAnalysisRecord`].
325    ///
326    /// `conversation_usage` is the per-model token map the provider parser
327    /// accumulated separately; it is folded into the record verbatim.
328    pub fn into_record(self, conversation_usage: FastHashMap<String, Value>) -> CodeAnalysisRecord {
329        CodeAnalysisRecord {
330            total_unique_files: self.unique_files.len(),
331            total_write_lines: self.total_write_lines,
332            total_read_lines: self.total_read_lines,
333            total_edit_lines: self.total_edit_lines,
334            total_write_characters: self.total_write_characters,
335            total_read_characters: self.total_read_characters,
336            total_edit_characters: self.total_edit_characters,
337            write_file_details: self.write_details,
338            read_file_details: self.read_details,
339            edit_file_details: self.edit_details,
340            run_command_details: self.run_details,
341            tool_call_counts: self.tool_counts,
342            conversation_usage,
343            advisor_usage: FastHashMap::default(),
344            task_id: self.task_id,
345            timestamp: self.last_ts,
346            folder_path: self.folder_path,
347            git_remote_url: self.git_remote,
348        }
349    }
350}
351
352impl Default for SessionParseState {
353    /// Equivalent to [`SessionParseState::new`] ([`ParseMode::Full`]).
354    fn default() -> Self {
355        Self::new()
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362
363    #[test]
364    fn test_session_parse_state_new() {
365        // Test creating a new SessionParseState
366        let state = SessionParseState::new();
367
368        assert_eq!(state.total_write_lines, 0);
369        assert_eq!(state.total_read_lines, 0);
370        assert_eq!(state.total_edit_lines, 0);
371        assert_eq!(state.write_details.len(), 0);
372        assert_eq!(state.read_details.len(), 0);
373        assert_eq!(state.edit_details.len(), 0);
374        assert_eq!(state.unique_files.len(), 0);
375        assert!(state.folder_path.is_empty());
376    }
377
378    #[test]
379    fn test_add_read_detail() {
380        // Test adding a read operation
381        let mut state = SessionParseState::new();
382        state.folder_path = "/test/folder".to_string();
383
384        state.add_read_detail("test.rs", "line1\nline2\nline3", 1234567890);
385
386        assert_eq!(state.read_details.len(), 1);
387        assert_eq!(state.total_read_lines, 3);
388        assert_eq!(state.tool_counts.read, 1);
389        assert!(state.unique_files.contains("/test/folder/test.rs"));
390    }
391
392    #[test]
393    fn test_add_read_detail_ignores_empty() {
394        // Test that empty content is ignored
395        let mut state = SessionParseState::new();
396
397        state.add_read_detail("test.rs", "", 1234567890);
398
399        assert_eq!(state.read_details.len(), 0);
400        assert_eq!(state.total_read_lines, 0);
401        assert_eq!(state.tool_counts.read, 0);
402    }
403
404    #[test]
405    fn test_add_write_detail() {
406        // Test adding a write operation
407        let mut state = SessionParseState::new();
408        state.folder_path = "/test/folder".to_string();
409
410        state.add_write_detail("output.txt", "content line 1\ncontent line 2", 1234567890);
411
412        assert_eq!(state.write_details.len(), 1);
413        assert_eq!(state.total_write_lines, 2);
414        assert_eq!(state.tool_counts.write, 1);
415        assert!(state.unique_files.contains("/test/folder/output.txt"));
416    }
417
418    #[test]
419    fn test_add_edit_detail() {
420        // Test adding an edit operation
421        let mut state = SessionParseState::new();
422        state.folder_path = "/test".to_string();
423
424        state.add_edit_detail(
425            "file.rs",
426            "old content\nold line 2",
427            "new content\nnew line 2\nnew line 3",
428            1234567890,
429        );
430
431        assert_eq!(state.edit_details.len(), 1);
432        assert_eq!(state.total_edit_lines, 3);
433        assert_eq!(state.tool_counts.edit, 1);
434        assert!(state.unique_files.contains("/test/file.rs"));
435    }
436
437    #[test]
438    fn test_add_edit_detail_empty_old_becomes_write() {
439        // Test that edit with empty old content becomes a write
440        let mut state = SessionParseState::new();
441        state.folder_path = "/test".to_string();
442
443        state.add_edit_detail("new_file.rs", "", "new content", 1234567890);
444
445        // Should be recorded as write, not edit
446        assert_eq!(state.write_details.len(), 1);
447        assert_eq!(state.edit_details.len(), 0);
448        assert_eq!(state.tool_counts.write, 1);
449        assert_eq!(state.tool_counts.edit, 0);
450    }
451
452    #[test]
453    fn test_add_run_command() {
454        // Test adding a run command
455        let mut state = SessionParseState::new();
456        state.folder_path = "/workspace".to_string();
457
458        state.add_run_command("cargo test", "Running tests", 1234567890);
459
460        assert_eq!(state.run_details.len(), 1);
461        assert_eq!(state.tool_counts.bash, 1);
462        assert_eq!(state.run_details[0].command, "cargo test");
463    }
464
465    #[test]
466    fn test_add_run_command_ignores_empty() {
467        // Test that empty commands are ignored
468        let mut state = SessionParseState::new();
469
470        state.add_run_command("", "description", 1234567890);
471        state.add_run_command("   ", "description", 1234567890);
472
473        assert_eq!(state.run_details.len(), 0);
474        assert_eq!(state.tool_counts.bash, 0);
475    }
476
477    #[test]
478    fn test_normalize_path_absolute() {
479        // Test normalizing absolute paths
480        let mut state = SessionParseState::new();
481        state.folder_path = "/workspace".to_string();
482
483        let result = state.normalize_path("/absolute/path/file.rs");
484        assert_eq!(result, "/absolute/path/file.rs");
485    }
486
487    #[test]
488    fn test_normalize_path_relative() {
489        // Test normalizing relative paths
490        let mut state = SessionParseState::new();
491        state.folder_path = "/workspace".to_string();
492
493        let result = state.normalize_path("relative/file.rs");
494        assert_eq!(result, "/workspace/relative/file.rs");
495    }
496
497    #[test]
498    fn test_normalize_path_empty_folder() {
499        // Test normalizing when folder_path is empty
500        let state = SessionParseState::new();
501
502        let result = state.normalize_path("file.rs");
503        assert_eq!(result, "file.rs");
504    }
505
506    #[test]
507    fn test_normalize_path_empty_input() {
508        // Test normalizing empty path
509        let mut state = SessionParseState::new();
510        state.folder_path = "/workspace".to_string();
511
512        let result = state.normalize_path("");
513        assert_eq!(result, "");
514    }
515
516    #[test]
517    fn test_unique_files_tracking() {
518        // Test that unique files are tracked correctly
519        let mut state = SessionParseState::new();
520        state.folder_path = "/project".to_string();
521
522        // Add operations on same file
523        state.add_read_detail("file1.rs", "content", 1);
524        state.add_write_detail("file1.rs", "content", 2);
525        state.add_edit_detail("file1.rs", "old", "new", 3);
526
527        // Add operations on different file
528        state.add_read_detail("file2.rs", "content", 4);
529
530        assert_eq!(state.unique_files.len(), 2);
531        assert!(state.unique_files.contains("/project/file1.rs"));
532        assert!(state.unique_files.contains("/project/file2.rs"));
533    }
534
535    #[test]
536    fn test_character_counting() {
537        // Test that character counts are correct
538        let mut state = SessionParseState::new();
539
540        state.add_read_detail("file.txt", "hello", 1);
541        assert_eq!(state.total_read_characters, 5);
542
543        state.add_write_detail("file2.txt", "world!", 2);
544        assert_eq!(state.total_write_characters, 6);
545
546        state.add_edit_detail("file3.txt", "old", "new content", 3);
547        assert_eq!(state.total_edit_characters, 11);
548    }
549
550    #[test]
551    fn test_into_record() {
552        // Test converting state into a record
553        let mut state = SessionParseState::new();
554        state.folder_path = "/test".to_string();
555        state.git_remote = "https://github.com/test/repo".to_string();
556        state.task_id = "task-123".to_string();
557        state.last_ts = 9999999999;
558
559        state.add_read_detail("file.rs", "line1\nline2", 1);
560        state.add_write_detail("output.rs", "content", 2);
561
562        let usage = FastHashMap::default();
563        let record = state.into_record(usage);
564
565        assert_eq!(record.total_unique_files, 2);
566        assert_eq!(record.total_read_lines, 2);
567        assert_eq!(record.total_write_lines, 1);
568        assert_eq!(record.folder_path, "/test");
569        assert_eq!(record.git_remote_url, "https://github.com/test/repo");
570        assert_eq!(record.task_id, "task-123");
571        assert_eq!(record.timestamp, 9999999999);
572    }
573
574    #[test]
575    fn test_default_trait() {
576        // Test Default trait implementation
577        let state = SessionParseState::default();
578
579        assert_eq!(state.total_write_lines, 0);
580        assert_eq!(state.total_read_lines, 0);
581        assert_eq!(state.total_edit_lines, 0);
582    }
583
584    #[test]
585    fn test_multiple_operations() {
586        // Test handling multiple operations
587        let mut state = SessionParseState::new();
588        state.folder_path = "/workspace".to_string();
589
590        // Multiple reads
591        state.add_read_detail("a.rs", "line1", 1);
592        state.add_read_detail("b.rs", "line1\nline2", 2);
593        state.add_read_detail("c.rs", "line1\nline2\nline3", 3);
594
595        // Multiple writes
596        state.add_write_detail("out1.txt", "content1", 4);
597        state.add_write_detail("out2.txt", "content2", 5);
598
599        // Multiple edits
600        state.add_edit_detail("edit1.rs", "old", "new", 6);
601
602        // Multiple commands
603        state.add_run_command("ls", "list files", 7);
604        state.add_run_command("pwd", "print dir", 8);
605
606        assert_eq!(state.read_details.len(), 3);
607        assert_eq!(state.write_details.len(), 2);
608        assert_eq!(state.edit_details.len(), 1);
609        assert_eq!(state.run_details.len(), 2);
610        assert_eq!(state.total_read_lines, 6); // 1 + 2 + 3
611        assert_eq!(state.tool_counts.read, 3);
612        assert_eq!(state.tool_counts.write, 2);
613        assert_eq!(state.tool_counts.edit, 1);
614        assert_eq!(state.tool_counts.bash, 2);
615    }
616}