Skip to main content

vibe_coding_tracker/session/
gemini.rs

1//! Parser for Gemini CLI session logs
2//! (`~/.gemini/tmp/<project_hash>/chats/*.jsonl`).
3//!
4//! The first line is a session-meta record; every subsequent line is an
5//! event. The parser deduplicates repeated message ids across incremental
6//! updates and snapshots, while retaining messages later hidden by a rewind
7//! because their usage was billed and their tools already ran. It then processes
8//! only `type == "gemini"` messages, which carry usage and tool calls.
9use crate::constants::FastHashMap;
10use crate::models::*;
11use crate::session::diagnostics::{ParseDiagnostics, ParsedAnalysis};
12use crate::session::state::{ParseMode, SessionParseState};
13use crate::utils::{get_git_remote_url, parse_iso_timestamp, process_gemini_usage};
14use anyhow::Result;
15use serde::Deserialize;
16use serde_json::Value;
17
18/// Parse Gemini CLI session events from the JSONL event stream.
19///
20/// `session` carries the first-line meta record (`sessionId` etc.), and
21/// `events` yields one parsed JSON value per subsequent line. The parser
22/// deduplicates append-only revisions into the historical message set, then
23/// deserializes each `type == "gemini"` message into [`GeminiMessage`]. User
24/// and info messages remain in the set for ordering but do not contribute
25/// metrics.
26///
27/// This is the only supported Gemini entry point — legacy single-object
28/// exports (`chats/<session>.json` with an inline `messages` array) are no
29/// longer handled.
30///
31/// # Errors
32///
33/// Returns `anyhow::Result` for parity with the other provider parsers, but
34/// has no fallible step. Non-`gemini` events are skipped, and unsupported
35/// Gemini message schemas are logged before being skipped.
36pub fn parse_gemini_events<I>(
37    session: GeminiSession,
38    events: I,
39    mode: ParseMode,
40) -> Result<CodeAnalysis>
41where
42    I: IntoIterator<Item = Value>,
43{
44    Ok(parse_gemini_events_with_diagnostics(session, events, mode)?.analysis)
45}
46
47/// Streaming Gemini parser with event-payload schema diagnostics.
48pub(crate) fn parse_gemini_events_with_diagnostics<I>(
49    session: GeminiSession,
50    events: I,
51    mode: ParseMode,
52) -> Result<ParsedAnalysis>
53where
54    I: IntoIterator<Item = Value>,
55{
56    let mut state = SessionParseState::with_mode(mode);
57    let mut conversation_usage: FastHashMap<String, Value> = FastHashMap::with_capacity(3);
58    let mut diagnostics = ParseDiagnostics::default();
59    diagnostics.record_recognized_source();
60
61    let messages = deduplicate_messages(events, mode, &mut diagnostics);
62    for message in messages {
63        diagnostics.merge(message.diagnostics);
64        if let (Some(tokens), Some(model)) = (&message.tokens, &message.model) {
65            process_gemini_usage(&mut conversation_usage, model, tokens);
66        }
67        state.merge(message.state);
68    }
69
70    let analysis = finalize_record(state, conversation_usage, session.session_id);
71    Ok(ParsedAnalysis::new(analysis, diagnostics))
72}
73
74/// One compacted assistant-message revision retained for historical metrics.
75struct GeminiMessageAnalysis {
76    state: SessionParseState,
77    tokens: Option<GeminiTokens>,
78    model: Option<String>,
79    diagnostics: ParseDiagnostics,
80}
81
82/// Minimal Gemini message shape needed by analysis.
83///
84/// Deliberately omits user content and thoughts so `UsageOnly` never retains
85/// those large fields while deduplicating revisions.
86#[derive(Deserialize)]
87struct GeminiAnalysisMessage {
88    #[serde(default)]
89    timestamp: String,
90    #[serde(rename = "type", default)]
91    message_type: String,
92    tokens: Option<GeminiTokens>,
93    model: Option<String>,
94    #[serde(rename = "toolCalls", default)]
95    tool_calls: Vec<Value>,
96}
97
98/// Deduplicates Gemini's append-only chat log into its historical message set.
99///
100/// A message id may be appended repeatedly as tokens and tool results arrive,
101/// so only its latest revision is retained. `$set.messages` entries are merged
102/// by id instead of counted again. `$rewindTo` changes the CLI's visible chat,
103/// but does not undo already billed model calls or executed tools, so it does
104/// not remove historical analysis records. Each revision is compacted before
105/// storage, preserving the [`ParseMode::UsageOnly`] memory boundary.
106fn deduplicate_messages<I>(
107    events: I,
108    mode: ParseMode,
109    diagnostics: &mut ParseDiagnostics,
110) -> Vec<GeminiMessageAnalysis>
111where
112    I: IntoIterator<Item = Value>,
113{
114    let mut messages = Vec::new();
115    let mut positions: FastHashMap<String, usize> = FastHashMap::default();
116
117    for event in events {
118        if event.get("$rewindTo").is_some() {
119            diagnostics.record_recognized_source();
120            continue;
121        }
122
123        if event.get("id").and_then(Value::as_str).is_some()
124            && let Some(message_type) = event.get("type").and_then(Value::as_str)
125        {
126            if matches!(message_type, "gemini" | "user" | "info" | "error") {
127                diagnostics.record_recognized_source();
128            } else {
129                diagnostics.record_unrecognized();
130            }
131            upsert_message(&mut messages, &mut positions, event, mode, diagnostics);
132            continue;
133        }
134
135        let Some(set) = event.get("$set") else {
136            diagnostics.record_unrecognized();
137            continue;
138        };
139        diagnostics.record_recognized_source();
140        let Some(messages_value) = set.get("messages") else {
141            continue;
142        };
143        let Some(snapshot) = messages_value.as_array() else {
144            diagnostics.record_relevant(false);
145            continue;
146        };
147
148        for message in snapshot {
149            upsert_message(
150                &mut messages,
151                &mut positions,
152                message.clone(),
153                mode,
154                diagnostics,
155            );
156        }
157    }
158
159    messages
160}
161
162/// Inserts a new message or replaces the latest revision for an existing id.
163fn upsert_message(
164    messages: &mut Vec<GeminiMessageAnalysis>,
165    positions: &mut FastHashMap<String, usize>,
166    message: Value,
167    mode: ParseMode,
168    diagnostics: &mut ParseDiagnostics,
169) {
170    if message.get("type").and_then(Value::as_str) != Some("gemini") {
171        return;
172    }
173    let Some(id) = message
174        .get("id")
175        .and_then(Value::as_str)
176        .filter(|id| !id.is_empty())
177        .map(str::to_string)
178    else {
179        diagnostics.record_relevant(false);
180        return;
181    };
182    let raw_tokens = message
183        .get("tokens")
184        .filter(|tokens| !tokens.is_null())
185        .cloned();
186    let analysis = match serde_json::from_value::<GeminiAnalysisMessage>(message) {
187        Ok(mut message) => {
188            let mut message_diagnostics = ParseDiagnostics::default();
189            if let Some(raw_tokens) = raw_tokens.as_ref() {
190                let normalized = message
191                    .model
192                    .as_deref()
193                    .is_some_and(|model| !model.is_empty())
194                    && gemini_tokens_supported(raw_tokens);
195                message_diagnostics.record_relevant(normalized);
196                if !normalized {
197                    message.tokens = None;
198                }
199            }
200            record_message_diagnostics(&message, &mut message_diagnostics);
201            let mut state = SessionParseState::with_mode(mode);
202            process_gemini_message(&mut state, &message);
203            GeminiMessageAnalysis {
204                state,
205                tokens: message.tokens,
206                model: message.model,
207                diagnostics: message_diagnostics,
208            }
209        }
210        Err(_) => {
211            let mut message_diagnostics = ParseDiagnostics::default();
212            message_diagnostics.record_relevant(false);
213            GeminiMessageAnalysis {
214                state: SessionParseState::with_mode(mode),
215                tokens: None,
216                model: None,
217                diagnostics: message_diagnostics,
218            }
219        }
220    };
221
222    if let Some(&index) = positions.get(&id) {
223        messages[index] = analysis;
224    } else {
225        positions.insert(id, messages.len());
226        messages.push(analysis);
227    }
228}
229
230fn gemini_tokens_supported(tokens: &Value) -> bool {
231    const TOKEN_FIELDS: &[&str] = &["input", "output", "cached", "thoughts", "tool", "total"];
232    let Some(tokens) = tokens.as_object() else {
233        return false;
234    };
235    if tokens.is_empty() {
236        return true;
237    }
238
239    let mut recognized = false;
240    for field in TOKEN_FIELDS {
241        if let Some(value) = tokens.get(*field) {
242            recognized = true;
243            if value.as_i64().is_none() {
244                return false;
245            }
246        }
247    }
248    recognized
249}
250
251#[derive(Clone, Copy, PartialEq, Eq)]
252enum GeminiToolStatus {
253    Success,
254    Failed,
255    Pending,
256    Unsupported,
257}
258
259fn gemini_tool_status(tool_call: &Value) -> GeminiToolStatus {
260    match tool_call.get("status").and_then(Value::as_str) {
261        Some("success") => GeminiToolStatus::Success,
262        Some("error" | "failed") => GeminiToolStatus::Failed,
263        Some("pending" | "running") => GeminiToolStatus::Pending,
264        None if tool_call.get("result").is_none_or(|result| {
265            result.is_null() || result.as_array().is_some_and(Vec::is_empty)
266        }) =>
267        {
268            GeminiToolStatus::Pending
269        }
270        _ => GeminiToolStatus::Unsupported,
271    }
272}
273
274fn tracked_tool_schema_supported(name: &str, tool_call: &Value) -> bool {
275    let args = tool_call.get("args");
276    match name {
277        "read_file" => {
278            args.and_then(|args| args.get("file_path"))
279                .and_then(Value::as_str)
280                .is_some_and(|path| !path.is_empty())
281                && tool_result_output(tool_call).is_some()
282        }
283        "write_file" | "create_file" => {
284            args.and_then(|args| args.get("file_path"))
285                .and_then(Value::as_str)
286                .is_some_and(|path| !path.is_empty())
287                && args
288                    .and_then(|args| args.get("content"))
289                    .is_some_and(Value::is_string)
290        }
291        "edit_file" | "replace_in_file" | "replace" => {
292            args.and_then(|args| args.get("file_path"))
293                .and_then(Value::as_str)
294                .is_some_and(|path| !path.is_empty())
295                && args
296                    .and_then(|args| args.get("old_string").or_else(|| args.get("old_text")))
297                    .is_some_and(Value::is_string)
298                && args
299                    .and_then(|args| args.get("new_string").or_else(|| args.get("new_text")))
300                    .is_some_and(Value::is_string)
301        }
302        "run_command" | "run_shell_command" | "execute_command" | "shell" => args
303            .and_then(|args| args.get("command").or_else(|| args.get("cmd")))
304            .and_then(Value::as_str)
305            .is_some_and(|command| !command.trim().is_empty()),
306        "write_todos" | "read_many_files" => true,
307        _ => false,
308    }
309}
310
311fn record_message_diagnostics(message: &GeminiAnalysisMessage, diagnostics: &mut ParseDiagnostics) {
312    for tool_call in &message.tool_calls {
313        let Some(name) = tool_call.get("name").and_then(Value::as_str) else {
314            continue;
315        };
316        if !matches!(
317            name,
318            "read_file"
319                | "write_file"
320                | "create_file"
321                | "edit_file"
322                | "replace_in_file"
323                | "replace"
324                | "run_command"
325                | "run_shell_command"
326                | "execute_command"
327                | "shell"
328                | "write_todos"
329                | "read_many_files"
330        ) {
331            continue;
332        }
333        let normalized = match gemini_tool_status(tool_call) {
334            GeminiToolStatus::Success => tracked_tool_schema_supported(name, tool_call),
335            GeminiToolStatus::Failed => true,
336            GeminiToolStatus::Pending | GeminiToolStatus::Unsupported => false,
337        };
338        diagnostics.record_relevant(normalized);
339    }
340}
341
342/// Converts the accumulated state into a single-record [`CodeAnalysis`],
343/// stamping the `task_id` from the session meta and resolving the git remote
344/// from the process working directory when none was captured.
345fn finalize_record(
346    mut state: SessionParseState,
347    conversation_usage: FastHashMap<String, Value>,
348    session_id: String,
349) -> CodeAnalysis {
350    // Gemini CLI does not record the invoking `cwd` in its log format today;
351    // fall back to querying git from the process's current dir so the usage
352    // report still stamps a remote URL when running inside a repo.
353    if state.git_remote.is_empty() {
354        state.git_remote = get_git_remote_url(&state.folder_path);
355    }
356
357    let last_ts = state.last_ts;
358    let mut record = state.into_record(conversation_usage);
359    record.task_id = session_id;
360    record.timestamp = last_ts;
361
362    CodeAnalysis {
363        user: String::new(),
364        extension_name: String::new(),
365        insights_version: String::new(),
366        machine_id: String::new(),
367        records: vec![record],
368    }
369}
370
371/// Folds one assistant message's timestamp and tools into a compact state.
372fn process_gemini_message(state: &mut SessionParseState, message: &GeminiAnalysisMessage) {
373    let ts = parse_iso_timestamp(&message.timestamp);
374    if ts > state.last_ts {
375        state.last_ts = ts;
376    }
377
378    if message.message_type != "gemini" {
379        return;
380    }
381
382    for tool_call in &message.tool_calls {
383        let Some(name) = tool_call.get("name").and_then(|n| n.as_str()) else {
384            continue;
385        };
386        let status = gemini_tool_status(tool_call);
387        if status == GeminiToolStatus::Unsupported {
388            continue;
389        }
390        if status != GeminiToolStatus::Success {
391            record_tool_invocation(state, name);
392            continue;
393        }
394        if !tracked_tool_schema_supported(name, tool_call) {
395            record_tool_invocation(state, name);
396            continue;
397        }
398
399        let args = tool_call.get("args");
400
401        match name {
402            "read_file" => {
403                state.tool_counts.read += 1;
404                let file_path = args
405                    .and_then(|a| a.get("file_path"))
406                    .and_then(|p| p.as_str())
407                    .unwrap_or("");
408
409                // Content sits at result[0].functionResponse.response.output
410                if let Some(content) = tool_result_output(tool_call) {
411                    attach_read_detail(state, file_path, content, ts);
412                }
413            }
414            "write_file" | "create_file" => {
415                let file_path = args
416                    .and_then(|a| a.get("file_path"))
417                    .and_then(|p| p.as_str())
418                    .unwrap_or("");
419                let content = args
420                    .and_then(|a| a.get("content"))
421                    .and_then(|c| c.as_str())
422                    .unwrap_or("");
423
424                state.add_write_detail(file_path, content, ts);
425            }
426            // Current Gemini CLI emits `replace`; `edit_file` /
427            // `replace_in_file` were the historical names and are kept
428            // here as best-effort aliases in case older sessions are
429            // still being replayed through `vct analysis <file>`.
430            "edit_file" | "replace_in_file" | "replace" => {
431                let file_path = args
432                    .and_then(|a| a.get("file_path"))
433                    .and_then(|p| p.as_str())
434                    .unwrap_or("");
435                let old_string = args
436                    .and_then(|a| a.get("old_string").or_else(|| a.get("old_text")))
437                    .and_then(|s| s.as_str())
438                    .unwrap_or("");
439                let new_string = args
440                    .and_then(|a| a.get("new_string").or_else(|| a.get("new_text")))
441                    .and_then(|s| s.as_str())
442                    .unwrap_or("");
443
444                state.add_edit_detail_raw(file_path, old_string, new_string, ts);
445            }
446            "run_command" | "run_shell_command" | "execute_command" | "shell" => {
447                let command = args
448                    .and_then(|a| a.get("command").or_else(|| a.get("cmd")))
449                    .and_then(|c| c.as_str())
450                    .unwrap_or("");
451                let description = args
452                    .and_then(|a| a.get("description"))
453                    .and_then(|d| d.as_str())
454                    .unwrap_or("");
455
456                state.add_run_command(command, description, ts);
457            }
458            "write_todos" => state.tool_counts.todo_write += 1,
459            "read_many_files" => state.tool_counts.read += 1,
460            // Meta tools like `update_topic` / `task_complete` carry no
461            // file-operation data; ignore them silently.
462            _ => {}
463        }
464    }
465}
466
467fn record_tool_invocation(state: &mut SessionParseState, name: &str) {
468    match name {
469        "read_file" | "read_many_files" => state.tool_counts.read += 1,
470        "write_file" | "create_file" => state.tool_counts.write += 1,
471        "edit_file" | "replace_in_file" | "replace" => state.tool_counts.edit += 1,
472        "run_command" | "run_shell_command" | "execute_command" | "shell" => {
473            state.tool_counts.bash += 1;
474        }
475        "write_todos" => state.tool_counts.todo_write += 1,
476        _ => {}
477    }
478}
479
480fn attach_read_detail(state: &mut SessionParseState, path: &str, content: &str, ts: i64) {
481    let invocation_count = state.tool_counts.read;
482    state.add_read_detail(path, content, ts);
483    state.tool_counts.read = invocation_count;
484}
485
486/// Returns the output string from a Gemini tool call result.
487fn tool_result_output(tool_call: &Value) -> Option<&str> {
488    tool_call
489        .get("result")
490        .and_then(|r| r.as_array())
491        .and_then(|arr| arr.first())
492        .and_then(|item| item.get("functionResponse"))
493        .and_then(|fr| fr.get("response"))
494        .and_then(|resp| resp.get("output"))
495        .and_then(|o| o.as_str())
496}
497
498#[cfg(test)]
499mod tests {
500    use super::*;
501    use serde_json::json;
502
503    fn session() -> GeminiSession {
504        GeminiSession {
505            session_id: "session-1".to_string(),
506            project_hash: "project-1".to_string(),
507            start_time: String::new(),
508            last_updated: String::new(),
509            kind: Some("main".to_string()),
510        }
511    }
512
513    fn assistant(id: &str, model: &str, input_tokens: i64, mut tool_calls: Value) -> Value {
514        if let Some(tool_calls) = tool_calls.as_array_mut() {
515            for tool_call in tool_calls {
516                if let Some(tool_call) = tool_call.as_object_mut() {
517                    tool_call
518                        .entry("status")
519                        .or_insert_with(|| Value::String("success".to_string()));
520                }
521            }
522        }
523        json!({
524            "id": id,
525            "timestamp": "2026-07-12T00:00:00Z",
526            "type": "gemini",
527            "model": model,
528            "tokens": {
529                "input": input_tokens,
530                "output": 1,
531                "cached": 0,
532                "thoughts": 0,
533                "tool": 0,
534                "total": input_tokens + 1
535            },
536            "toolCalls": tool_calls
537        })
538    }
539
540    #[test]
541    fn repeated_message_id_uses_only_latest_revision() {
542        let first = assistant(
543            "message-1",
544            "gemini-test",
545            10,
546            json!([{ "name": "write_file", "args": {
547                "file_path": "/tmp/a.txt", "content": "old"
548            }}]),
549        );
550        let latest = assistant(
551            "message-1",
552            "gemini-test",
553            20,
554            json!([{ "name": "write_file", "args": {
555                "file_path": "/tmp/a.txt", "content": "new"
556            }}]),
557        );
558
559        let analysis =
560            parse_gemini_events(session(), vec![first, latest], ParseMode::Full).unwrap();
561        let record = &analysis.records[0];
562        assert_eq!(record.conversation_usage["gemini-test"]["input_tokens"], 20);
563        assert_eq!(record.tool_call_counts.write, 1);
564        assert_eq!(record.write_file_details.len(), 1);
565        assert_eq!(record.write_file_details[0].content, "new");
566    }
567
568    #[test]
569    fn messages_snapshot_merges_without_recounting_ids() {
570        let prior = assistant("prior", "gemini-prior", 10, json!([]));
571        let current = assistant("current", "gemini-current", 30, json!([]));
572        let snapshot = json!({ "$set": { "messages": [current] } });
573
574        let analysis =
575            parse_gemini_events(session(), vec![prior, snapshot], ParseMode::Full).unwrap();
576        let usage = &analysis.records[0].conversation_usage;
577        assert_eq!(usage["gemini-prior"]["input_tokens"], 10);
578        assert_eq!(usage["gemini-current"]["input_tokens"], 30);
579    }
580
581    #[test]
582    fn rewind_keeps_already_billed_messages() {
583        let first = assistant("first", "gemini-first", 10, json!([]));
584        let second = assistant("second", "gemini-second", 20, json!([]));
585        let third = assistant("third", "gemini-third", 30, json!([]));
586        let rewind = json!({ "$rewindTo": "second" });
587
588        let analysis = parse_gemini_events(
589            session(),
590            vec![first, second, third, rewind],
591            ParseMode::Full,
592        )
593        .unwrap();
594        let usage = &analysis.records[0].conversation_usage;
595        assert_eq!(usage.len(), 3);
596        assert!(usage.contains_key("gemini-first"));
597        assert!(usage.contains_key("gemini-second"));
598        assert!(usage.contains_key("gemini-third"));
599    }
600
601    #[test]
602    fn current_tool_names_map_to_existing_metrics() {
603        let message = assistant(
604            "message-1",
605            "gemini-test",
606            10,
607            json!([
608                { "name": "run_shell_command", "args": { "command": "true" } },
609                { "name": "write_todos", "args": { "todos": [] } },
610                { "name": "read_many_files", "args": { "include": ["src/**"] } }
611            ]),
612        );
613
614        let analysis = parse_gemini_events(session(), vec![message], ParseMode::Full).unwrap();
615        let counts = &analysis.records[0].tool_call_counts;
616        assert_eq!(counts.bash, 1);
617        assert_eq!(counts.todo_write, 1);
618        assert_eq!(counts.read, 1);
619    }
620
621    #[test]
622    fn read_result_validation_distinguishes_empty_files_from_schema_drift() {
623        let drifted = assistant(
624            "drifted",
625            "gemini-test",
626            10,
627            json!([{
628                "name": "read_file",
629                "args": { "file_path": "/tmp/a.txt" },
630                "result": [{
631                    "functionResponse": { "response": { "futureOutput": "" } }
632                }]
633            }]),
634        );
635        let drifted =
636            parse_gemini_events_with_diagnostics(session(), vec![drifted], ParseMode::Full)
637                .unwrap();
638        assert_eq!(drifted.diagnostics.partial_failure_count(), 1);
639        assert_eq!(drifted.analysis.records[0].tool_call_counts.read, 1);
640        assert_eq!(drifted.analysis.records[0].total_read_lines, 0);
641
642        let empty = assistant(
643            "empty",
644            "gemini-test",
645            10,
646            json!([{
647                "name": "read_file",
648                "args": { "file_path": "/tmp/a.txt" },
649                "result": [{
650                    "functionResponse": { "response": { "output": "" } }
651                }]
652            }]),
653        );
654        let empty =
655            parse_gemini_events_with_diagnostics(session(), vec![empty], ParseMode::Full).unwrap();
656        assert_eq!(empty.diagnostics.partial_failure_count(), 0);
657        assert_eq!(empty.analysis.records[0].tool_call_counts.read, 1);
658        assert_eq!(empty.analysis.records[0].total_read_lines, 0);
659    }
660
661    #[test]
662    fn unknown_only_token_keys_do_not_become_zero_usage() {
663        let mut message = assistant("drifted", "gemini-test", 10, json!([]));
664        message["tokens"] = json!({ "prompt": 123, "completion": 45 });
665
666        let parsed =
667            parse_gemini_events_with_diagnostics(session(), vec![message], ParseMode::Full)
668                .unwrap();
669        assert!(parsed.diagnostics.is_complete_failure());
670        assert!(
671            parsed.analysis.records[0].conversation_usage.is_empty(),
672            "unknown token keys must not become a successful all-zero usage row"
673        );
674
675        let mut current = assistant("current", "gemini-test", 10, json!([]));
676        current["tokens"] = json!({ "input": 0 });
677        let parsed =
678            parse_gemini_events_with_diagnostics(session(), vec![current], ParseMode::Full)
679                .unwrap();
680        assert!(!parsed.diagnostics.is_complete_failure());
681        assert_eq!(
682            parsed.analysis.records[0].conversation_usage["gemini-test"]["input_tokens"],
683            0
684        );
685    }
686
687    #[test]
688    fn edit_requires_both_old_and_new_text_without_falling_back_to_write() {
689        let message = assistant(
690            "drifted-edit",
691            "gemini-test",
692            10,
693            json!([{
694                "name": "replace",
695                "args": {
696                    "file_path": "/tmp/a.txt",
697                    "future_old": "old",
698                    "new_string": "new"
699                }
700            }]),
701        );
702
703        let parsed =
704            parse_gemini_events_with_diagnostics(session(), vec![message], ParseMode::Full)
705                .unwrap();
706        let record = &parsed.analysis.records[0];
707        assert_eq!(parsed.diagnostics.partial_failure_count(), 1);
708        assert_eq!(record.tool_call_counts.edit, 1);
709        assert_eq!(record.tool_call_counts.write, 0);
710        assert_eq!(record.total_edit_lines, 0);
711        assert_eq!(record.total_write_lines, 0);
712    }
713
714    #[test]
715    fn failed_write_counts_the_invocation_without_claiming_file_changes() {
716        let message = assistant(
717            "failed-write",
718            "gemini-test",
719            10,
720            json!([{
721                "name": "write_file",
722                "status": "error",
723                "args": {
724                    "file_path": "/tmp/a.txt",
725                    "content": "one\ntwo"
726                },
727                "result": [{ "functionResponse": { "response": { "error": "denied" } } }]
728            }]),
729        );
730
731        let parsed =
732            parse_gemini_events_with_diagnostics(session(), vec![message], ParseMode::Full)
733                .unwrap();
734        let record = &parsed.analysis.records[0];
735        assert_eq!(parsed.diagnostics.partial_failure_count(), 0);
736        assert_eq!(record.tool_call_counts.write, 1);
737        assert_eq!(record.total_write_lines, 0);
738        assert!(record.write_file_details.is_empty());
739    }
740
741    #[test]
742    fn superseded_pending_revision_does_not_leave_a_false_warning() {
743        let pending = assistant(
744            "message-1",
745            "gemini-test",
746            10,
747            json!([{
748                "name": "read_file",
749                "status": "pending",
750                "args": { "file_path": "/tmp/a.txt" }
751            }]),
752        );
753        let complete = assistant(
754            "message-1",
755            "gemini-test",
756            20,
757            json!([{
758                "name": "read_file",
759                "status": "success",
760                "args": { "file_path": "/tmp/a.txt" },
761                "result": [{
762                    "functionResponse": { "response": { "output": "one\ntwo" } }
763                }]
764            }]),
765        );
766
767        let parsed = parse_gemini_events_with_diagnostics(
768            session(),
769            vec![pending, complete],
770            ParseMode::Full,
771        )
772        .unwrap();
773        assert_eq!(parsed.diagnostics.partial_failure_count(), 0);
774        assert_eq!(parsed.analysis.records[0].tool_call_counts.read, 1);
775        assert_eq!(parsed.analysis.records[0].total_read_lines, 2);
776    }
777}