vibe_coding_tracker 1.6.0

Vibe Coding Tracker - AI coding assistant telemetry/usage parser, aggregate JSONL events into CodeAnalysis results
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
//! Parser for OpenAI Codex rollout logs (`~/.codex/sessions/**/*.jsonl`).
//!
//! Codex records carry a `type` discriminator (`session_meta`,
//! `turn_context`, `event_msg`, `response_item`). File operations are not
//! first-class: Codex performs them through shell `function_call` records,
//! so this parser pairs each `function_call` with its `function_call_output`
//! by `call_id`, then reverse-engineers the intent from the command text —
//! `apply_patch` scripts become write/edit details, `sed`/`cat` invocations
//! become reads, and everything else is recorded as a run command. Both the
//! legacy `shell` and current `exec_command` function shapes are supported.
use crate::constants::FastHashMap;
use crate::models::*;
use crate::session::state::{ParseMode, SessionParseState};
use crate::utils::{get_git_remote_url, parse_iso_timestamp, process_codex_usage};
use anyhow::Result;
use regex::Regex;
use serde_json::Value;

/// Parse Codex session records from a slice of pre-typed logs.
///
/// Walks the records in order, threading shell `function_call`s to their
/// outputs and folding token usage from `token_count` events. Returns a
/// single-record [`CodeAnalysis`] with the runtime metadata fields blank
/// (the caller's `finalize` step fills them).
///
/// # Errors
///
/// Returns `anyhow::Result` for parity with the other provider parsers, but
/// has no fallible step: malformed arguments and outputs are tolerated
/// (skipped or substituted), so it returns `Ok` for any slice.
pub fn parse_codex_logs(logs: &[CodexLog], mode: ParseMode) -> Result<CodeAnalysis> {
    let mut state = SessionParseState::with_mode(mode);
    let mut conversation_usage: FastHashMap<String, Value> = FastHashMap::with_capacity(5);
    let mut current_model = String::new();
    let mut shell_calls: FastHashMap<String, CodexShellCall> = FastHashMap::with_capacity(50);

    for entry in logs {
        let ts = parse_iso_timestamp(&entry.timestamp);
        if ts > state.last_ts {
            state.last_ts = ts;
        }

        match entry.log_type.as_str() {
            "session_meta" => {
                if state.folder_path.is_empty()
                    && let Some(cwd) = &entry.payload.cwd
                {
                    state.folder_path.clone_from(cwd); // More efficient than clone()
                }
                if state.task_id.is_empty()
                    && let Some(id) = &entry.payload.id
                {
                    state.task_id.clone_from(id);
                }
                if state.git_remote.is_empty()
                    && let Some(git) = &entry.payload.git
                    && let Some(url) = &git.repository_url
                {
                    state.git_remote.clone_from(url);
                }
            }
            "turn_context" => {
                if state.folder_path.is_empty()
                    && let Some(cwd) = &entry.payload.cwd
                {
                    state.folder_path.clone_from(cwd);
                }
                if let Some(model) = &entry.payload.model {
                    current_model.clone_from(model); // Reuse existing allocation
                }
            }
            "event_msg" => {
                if let Some(payload_type) = &entry.payload.payload_type
                    && payload_type == "token_count"
                    && !current_model.is_empty()
                    && let Some(info) = &entry.payload.info
                {
                    process_codex_usage(&mut conversation_usage, &current_model, info);
                }
            }
            "response_item" => {
                if let Some(payload_type) = &entry.payload.payload_type {
                    match payload_type.as_str() {
                        "function_call" => {
                            if let (Some(name), Some(args_str), Some(call_id)) = (
                                entry.payload.name.as_deref(),
                                entry.payload.arguments.as_deref(),
                                entry.payload.call_id.as_deref(),
                            ) && let Some(call) = parse_function_call(name, args_str, ts)
                            {
                                shell_calls.insert(call_id.to_string(), call);
                            }
                        }
                        "function_call_output" => {
                            if let Some(call_id) = &entry.payload.call_id
                                && let Some(call) = shell_calls.remove(call_id)
                            {
                                let output = if let Some(output_str) = &entry.payload.output {
                                    serde_json::from_str::<CodexShellOutput>(output_str)
                                        .unwrap_or_else(|_| CodexShellOutput {
                                            output: output_str.clone(),
                                            metadata: None,
                                        })
                                } else {
                                    CodexShellOutput {
                                        output: String::new(),
                                        metadata: None,
                                    }
                                };
                                state.handle_shell_call(call, output);
                            }
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }

    if state.git_remote.is_empty() {
        state.git_remote = get_git_remote_url(&state.folder_path);
    }

    let record = state.into_record(conversation_usage);

    Ok(CodeAnalysis {
        user: String::new(),
        extension_name: String::new(),
        insights_version: String::new(),
        machine_id: String::new(),
        records: vec![record],
    })
}

/// Strip the metadata header that current Codex (`exec_command`) prepends
/// to every shell output. Format observed in the wild:
///
/// ```text
/// Chunk ID: <hex>
/// Wall time: <num> seconds
/// Process exited with code <num>
/// Original token count: <num>
/// Output:
/// <actual stdout>
/// ```
///
/// Without stripping, sed/cat read-detail extraction over-counts the file
/// by 5 lines (the prefix). Legacy `shell` outputs do not include the
/// header, so the search returns the original slice unchanged when no
/// `\nOutput:\n` marker is found.
fn strip_exec_command_metadata_prefix(output: &str) -> &str {
    const MARKER: &str = "\nOutput:\n";
    if let Some(idx) = output.find(MARKER) {
        &output[idx + MARKER.len()..]
    } else if let Some(rest) = output.strip_prefix("Output:\n") {
        rest
    } else {
        output
    }
}

/// Build a `CodexShellCall` from either the legacy `shell` function or the
/// current `exec_command` function.
///
/// Returns `None` when the function name is unrelated (e.g. `update_plan`,
/// MCP tool calls) or when the arguments fail to deserialize. Both shapes
/// collapse to the same downstream representation so the patch / sed / cat
/// dispatch in `handle_shell_call` does not need to branch on the source
/// function name.
fn parse_function_call(name: &str, args_str: &str, ts: i64) -> Option<CodexShellCall> {
    match name {
        "shell" => {
            let args = serde_json::from_str::<CodexShellArguments>(args_str).ok()?;
            let script = args.command.last().cloned().unwrap_or_default();
            Some(CodexShellCall {
                timestamp: ts,
                script,
                full_command: args.command,
            })
        }
        "exec_command" => {
            let args = serde_json::from_str::<CodexExecCommandArguments>(args_str).ok()?;
            let cmd = args.cmd;
            Some(CodexShellCall {
                timestamp: ts,
                script: cmd.clone(),
                full_command: vec![cmd],
            })
        }
        _ => None,
    }
}

/// Codex-specific dispatch helpers grafted onto [`SessionParseState`].
///
/// Kept as a private extension trait so the generic state type stays free of
/// Codex's `apply_patch`/`sed`/`cat` heuristics.
trait CodexAnalysisExt {
    /// Routes a completed shell call to the read / patch / run-command tally
    /// based on what its `script` did.
    fn handle_shell_call(&mut self, call: CodexShellCall, output: CodexShellOutput);
    /// Applies one parsed `apply_patch` hunk as a write, delete, or edit.
    fn handle_patch(&mut self, patch: CodexPatch, ts: i64);
    /// Records a shell call that was not a file operation as a run command.
    fn record_run_command(&mut self, call: CodexShellCall);
}

impl CodexAnalysisExt for SessionParseState {
    fn handle_shell_call(&mut self, call: CodexShellCall, output: CodexShellOutput) {
        // Check for applypatch script
        if call.script.contains("applypatch") {
            let patches = parse_apply_patch_script(&call.script);
            for patch in patches {
                self.handle_patch(patch, call.timestamp);
            }
            return;
        }

        // The legacy `shell` function returned just the raw command output
        // in `output`. The current `exec_command` function wraps that
        // output with a metadata header — strip it so line counting sees
        // only what the model actually saw as the file body.
        let output_body = strip_exec_command_metadata_prefix(&output.output);

        // Check for sed command
        if let Some(path) = extract_sed_file_path(&call.script) {
            self.add_read_detail(&path, output_body, call.timestamp);
            return;
        }

        // Check for cat command
        if let Some((path, content)) = extract_cat_read(&call.script, output_body) {
            self.add_read_detail(&path, &content, call.timestamp);
            return;
        }

        // Record as run command
        self.record_run_command(call);
    }

    fn handle_patch(&mut self, patch: CodexPatch, ts: i64) {
        if patch.file_path.is_empty() {
            return;
        }

        let resolved = self.normalize_path(&patch.file_path);
        if resolved.is_empty() {
            return;
        }

        let (old_str, new_str) = extract_patch_strings(&patch.lines);

        match patch.action.as_str() {
            "add" => {
                self.add_write_detail(&resolved, &new_str, ts);
            }
            "delete" => {
                let content = old_str.trim_end_matches('\n');
                if !content.is_empty() {
                    self.add_edit_detail(&resolved, content, "", ts);
                }
            }
            _ => {
                self.add_edit_detail(&resolved, &old_str, &new_str, ts);
            }
        }
    }

    fn record_run_command(&mut self, call: CodexShellCall) {
        let command_str = if call.full_command.is_empty() {
            call.script.trim()
        } else {
            &call.full_command.join(" ")
        };

        self.add_run_command(command_str, "", call.timestamp);
    }
}

/// A Codex shell invocation awaiting its output, normalized across the
/// legacy `shell` and current `exec_command` function shapes.
struct CodexShellCall {
    /// Event timestamp in epoch milliseconds.
    timestamp: i64,
    /// The command line actually executed (used for `sed`/`cat`/patch sniffing).
    script: String,
    /// The full argv as written by the model, for verbatim run-command display.
    full_command: Vec<String>,
}

/// One file hunk extracted from an `apply_patch` script.
struct CodexPatch {
    /// `"add"`, `"delete"`, or `"update"`.
    action: String,
    /// Target file path as written in the patch header.
    file_path: String,
    /// Raw diff body lines (with their leading `+`/`-`/context markers).
    lines: Vec<String>,
}

/// Parses an `apply_patch` script into its constituent per-file hunks.
///
/// Returns an empty `Vec` when no `*** Begin Patch` marker is present.
fn parse_apply_patch_script(script: &str) -> Vec<CodexPatch> {
    let start = match script.find("*** Begin Patch") {
        Some(idx) => idx,
        None => return Vec::new(),
    };

    let segment = &script[start..];
    let lines: Vec<&str> = segment.lines().collect();
    // Pre-allocate capacity based on typical patch count (1-5 patches)
    let mut patches = Vec::with_capacity(3);
    let mut current: Option<CodexPatch> = None;

    for line in lines {
        let line = line.trim_end_matches('\r');

        if line.starts_with("*** End Patch") {
            if let Some(patch) = current.take() {
                patches.push(patch);
            }
            break;
        } else if line.starts_with("*** Begin Patch") {
            continue;
        } else if line.starts_with("*** Update File:") {
            if let Some(patch) = current.take() {
                patches.push(patch);
            }
            let file_path = line
                .trim_start_matches("*** Update File:")
                .trim()
                .to_string();
            current = Some(CodexPatch {
                action: "update".to_string(),
                file_path,
                lines: Vec::with_capacity(20), // typical: 10-30 lines per patch
            });
        } else if line.starts_with("*** Add File:") {
            if let Some(patch) = current.take() {
                patches.push(patch);
            }
            let file_path = line.trim_start_matches("*** Add File:").trim().to_string();
            current = Some(CodexPatch {
                action: "add".to_string(),
                file_path,
                lines: Vec::with_capacity(20),
            });
        } else if line.starts_with("*** Delete File:") {
            if let Some(patch) = current.take() {
                patches.push(patch);
            }
            let file_path = line
                .trim_start_matches("*** Delete File:")
                .trim()
                .to_string();
            current = Some(CodexPatch {
                action: "delete".to_string(),
                file_path,
                lines: Vec::with_capacity(20),
            });
        } else if let Some(ref mut patch) = current {
            patch.lines.push(line.to_string());
        }
    }

    if let Some(patch) = current {
        patches.push(patch);
    }

    patches
}

/// Splits diff `lines` into the joined `(old, new)` text.
///
/// `+`-prefixed lines build the new content, `-`-prefixed lines the old;
/// `@@` hunk headers and `\` no-newline markers are skipped. Both results
/// have their trailing newline trimmed.
fn extract_patch_strings(lines: &[String]) -> (String, String) {
    // Pre-allocate with estimated capacity
    let estimated_size = lines.iter().map(|l| l.len()).sum::<usize>();
    let mut old_str = String::with_capacity(estimated_size / 2);
    let mut new_str = String::with_capacity(estimated_size / 2);

    for line in lines {
        if line.is_empty() {
            continue;
        }

        if line.len() > 1 && line.starts_with("@@") {
            continue;
        }

        let Some(first_char) = line.chars().next() else {
            continue;
        };
        match first_char {
            '+' => {
                new_str.push_str(&line[1..]);
                new_str.push('\n');
            }
            '-' => {
                old_str.push_str(&line[1..]);
                old_str.push('\n');
            }
            '\\' => continue,
            _ => {}
        }
    }

    // Trim in-place instead of allocating new strings
    let old_len = old_str.trim_end_matches('\n').len();
    old_str.truncate(old_len);
    let new_len = new_str.trim_end_matches('\n').len();
    new_str.truncate(new_len);

    (old_str, new_str)
}

/// Extracts the file path read by a `sed -n '<range>' <path>` command.
///
/// Returns `None` when the script is not a recognised `sed -n` read.
fn extract_sed_file_path(script: &str) -> Option<String> {
    use std::sync::OnceLock;
    static RE: OnceLock<Regex> = OnceLock::new();
    let re = RE.get_or_init(|| Regex::new(r"sed\s+-n\s+'[^']*'\s+([^\s]+)").unwrap());
    let caps = re.captures(script)?;
    Some(
        caps.get(1)?
            .as_str()
            .trim_matches(|c| c == '"' || c == '\'')
            .to_string(),
    )
}

/// Extracts the `(path, content)` read by a `cat <path>` command.
///
/// `output` is the captured stdout (already metadata-stripped); content after
/// a `\n---` separator is dropped. Returns `None` when no `cat` line is found.
fn extract_cat_read(script: &str, output: &str) -> Option<(String, String)> {
    for line in script.lines() {
        let trimmed = line.trim();
        if !trimmed.starts_with("cat ") {
            continue;
        }

        let fields: Vec<&str> = trimmed.split_whitespace().collect();
        if fields.len() < 2 {
            continue;
        }

        let path = fields[1].trim_matches(|c| c == '"' || c == '\'');

        // Optimize: avoid multiple allocations
        let clean_output = if let Some(idx) = output.find("\n---") {
            output[..idx].trim_end_matches('\n').to_string()
        } else {
            output.trim_end_matches('\n').to_string()
        };

        return Some((path.to_string(), clean_output));
    }

    None
}

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

    #[test]
    fn legacy_shell_function_parses_into_call() {
        // Old schema: arguments = {"command": ["bash", "-lc", "<script>"]}
        let args = r#"{"command":["bash","-lc","ls -la"]}"#;
        let call = parse_function_call("shell", args, 42).expect("shell call should parse");
        assert_eq!(call.timestamp, 42);
        assert_eq!(call.script, "ls -la");
        assert_eq!(call.full_command, vec!["bash", "-lc", "ls -la"]);
    }

    #[test]
    fn current_exec_command_function_parses_into_call() {
        // Current schema: arguments = {"cmd":"...","workdir":"...","yield_time_ms":...}
        let args =
            r#"{"cmd":"sed -n '1,260p' src/main.rs","workdir":"/repo","yield_time_ms":1000}"#;
        let call =
            parse_function_call("exec_command", args, 99).expect("exec_command should parse");
        assert_eq!(call.timestamp, 99);
        assert_eq!(call.script, "sed -n '1,260p' src/main.rs");
        // `full_command` collapses to the single cmd string so
        // `record_run_command`'s `join(" ")` produces the verbatim command.
        assert_eq!(call.full_command, vec!["sed -n '1,260p' src/main.rs"]);
    }

    #[test]
    fn unrelated_function_names_are_ignored() {
        // MCP tool calls, `update_plan`, etc. must not be treated as shell.
        assert!(parse_function_call("update_plan", "{}", 0).is_none());
        assert!(parse_function_call("_fetch_pr", "{}", 0).is_none());
    }

    #[test]
    fn malformed_arguments_yield_none_instead_of_panicking() {
        assert!(parse_function_call("shell", "not json", 0).is_none());
        assert!(parse_function_call("exec_command", "not json", 0).is_none());
    }

    #[test]
    fn exec_command_metadata_prefix_is_stripped() {
        // Real-world Codex `exec_command` output wraps actual stdout with
        // a 5-line header; without stripping, the analyzer over-counts
        // file reads by 5 lines per sed/cat invocation.
        let raw = "Chunk ID: deadbeef\n\
                   Wall time: 0.0000 seconds\n\
                   Process exited with code 0\n\
                   Original token count: 100\n\
                   Output:\n\
                   line one\n\
                   line two\n";
        assert_eq!(
            strip_exec_command_metadata_prefix(raw),
            "line one\nline two\n"
        );
    }

    #[test]
    fn legacy_shell_output_passes_through_unchanged() {
        // Legacy `shell` function output has no metadata header; the
        // helper must leave non-prefixed strings exactly as-is so the
        // existing fixture-based tests keep matching.
        let raw = "line one\nline two\n";
        assert_eq!(strip_exec_command_metadata_prefix(raw), raw);
    }

    #[test]
    fn output_starting_with_marker_handles_no_leading_newline() {
        // Defensive: if a future Codex variant drops the leading newline
        // before the `Output:` marker, still strip it cleanly.
        let raw = "Output:\nthe content";
        assert_eq!(strip_exec_command_metadata_prefix(raw), "the content");
    }
}