Skip to main content

vibe_coding_tracker/session/
copilot.rs

1//! Parser for GitHub Copilot CLI session events
2//! (`~/.copilot/session-state/<sessionId>/events.jsonl`).
3//!
4//! One [`CopilotEvent`] per line, dispatched on `event_type`. Token usage is
5//! taken from the authoritative `session.shutdown` record when present, with
6//! streamed `assistant.message.outputTokens` as a partial fallback for
7//! sessions that never shut down cleanly. File operations are paired across
8//! `tool.execution_start` / `tool.execution_complete` by `toolCallId` and
9//! only counted on success. See the table below for the full event map.
10use crate::constants::{FastHashMap, capacity};
11use crate::models::*;
12use crate::session::diagnostics::{ParseDiagnostics, ParsedAnalysis};
13use crate::session::state::{ParseMode, SessionParseState};
14use crate::utils::{get_git_remote_url, parse_iso_timestamp};
15use anyhow::Result;
16use serde_json::{Value, json};
17
18// =============================================================================
19// Copilot CLI `events.jsonl` streaming parser
20// =============================================================================
21//
22// Copilot CLI stores every session as
23// `~/.copilot/session-state/<sessionId>/events.jsonl`. Each line is a single
24// `CopilotEvent` whose `event_type` decides how to interpret `data`:
25//
26//   session.start            → session-scoped context (sessionId, cwd, …)
27//   session.model_change     → tracks the currently active model
28//   session.task_complete    → task summary, informational only
29//   session.shutdown         → authoritative per-model token usage
30//   system.message           → system prompt; ignored
31//   user.message             → user-turn content; ignored
32//   assistant.message        → streaming output; only outputTokens is reliable
33//   assistant.turn_start/end → turn bookkeeping; ignored
34//   tool.execution_start     → paired with the matching complete event
35//   tool.execution_complete  → fires the analyzer's file-op handlers
36//
37// Legacy single-object dumps under `~/.copilot/history-session-state/` are
38// not supported — users with old dumps will see them fall through to the
39// Codex default in `detect_extension_type` and fail cleanly rather than
40// being mis-parsed.
41
42/// Parse Copilot CLI session events from the JSONL event stream.
43///
44/// Returns a single-record [`CodeAnalysis`] stamped with the
45/// `"Copilot-CLI"` extension name. When the stream lacks a
46/// `session.shutdown` record, the per-model usage map is grafted from the
47/// streamed output-token fallback and will report `input_tokens: 0` so
48/// callers can detect the partial accounting.
49///
50/// # Errors
51///
52/// Returns `anyhow::Result` for parity with the other provider parsers, but
53/// has no fallible step — events that fail to deserialise into their typed
54/// payload are skipped — so it returns `Ok` for any iterator.
55pub fn parse_copilot_events<I>(events: I, mode: ParseMode) -> Result<CodeAnalysis>
56where
57    I: IntoIterator<Item = CopilotEvent>,
58{
59    Ok(parse_copilot_events_with_diagnostics(events, mode)?.analysis)
60}
61
62/// Streaming Copilot parser with event-payload schema diagnostics.
63pub(crate) fn parse_copilot_events_with_diagnostics<I>(
64    events: I,
65    mode: ParseMode,
66) -> Result<ParsedAnalysis>
67where
68    I: IntoIterator<Item = CopilotEvent>,
69{
70    let mut state = SessionParseState::with_mode(mode);
71    let mut conversation_usage: FastHashMap<String, Value> =
72        FastHashMap::with_capacity(capacity::MODELS_PER_SESSION);
73    // Pending tool calls indexed by `toolCallId` — each `tool.execution_start`
74    // stashes its arguments here until the matching `tool.execution_complete`
75    // arrives with the result payload.
76    let mut pending_tools: FastHashMap<String, PendingTool> = FastHashMap::with_capacity(32);
77
78    // Fallback accounting used when the session does not reach
79    // `session.shutdown` (e.g. crash, SIGKILL, ongoing session). We still
80    // want to attribute `assistant.message.outputTokens` to *some* model,
81    // so we track the active model switches.
82    let mut current_model = String::new();
83    // Set to `true` once we consume a `session.shutdown` event. If so, the
84    // shutdown record is authoritative and we discard the fallback output
85    // tallies built from streamed `assistant.message` events — those would
86    // otherwise double-count.
87    let mut shutdown_seen = false;
88    let mut pending_output_tokens: FastHashMap<String, i64> = FastHashMap::with_capacity(3);
89    let mut diagnostics = ParseDiagnostics::default();
90
91    for event in events {
92        let recognized = matches!(
93            event.event_type.as_str(),
94            "session.start"
95                | "session.model_change"
96                | "session.task_complete"
97                | "session.shutdown"
98                | "session.info"
99                | "session.mode_changed"
100                | "system.message"
101                | "user.message"
102                | "assistant.message"
103                | "assistant.turn_start"
104                | "assistant.turn_end"
105                | "tool.execution_start"
106                | "tool.execution_complete"
107                | "hook.start"
108                | "hook.end"
109                | "abort"
110                | "subagent.started"
111                | "subagent.completed"
112                | "system.notification"
113                | "session.resume"
114        );
115        if recognized {
116            diagnostics.record_recognized_source();
117        } else {
118            diagnostics.record_unrecognized();
119        }
120        let ts = parse_iso_timestamp(&event.timestamp);
121        if ts > state.last_ts {
122            state.last_ts = ts;
123        }
124
125        match event.event_type.as_str() {
126            "session.start" => {
127                if let Ok(data) =
128                    serde_json::from_value::<CopilotSessionStartData>(event.data.clone())
129                {
130                    if state.task_id.is_empty() && !data.session_id.is_empty() {
131                        state.task_id = data.session_id;
132                    }
133                    if let Some(ctx) = data.context {
134                        if state.folder_path.is_empty() {
135                            if !ctx.cwd.is_empty() {
136                                state.folder_path = ctx.cwd;
137                            } else if !ctx.git_root.is_empty() {
138                                state.folder_path = ctx.git_root;
139                            }
140                        }
141                        if state.git_remote.is_empty() {
142                            state.git_remote =
143                                build_remote_url(&ctx.repository_host, &ctx.repository);
144                        }
145                    }
146                }
147            }
148            "session.model_change" => {
149                let new_model = event
150                    .data
151                    .get("newModel")
152                    .and_then(|v| v.as_str())
153                    .filter(|s| !s.is_empty());
154                if let Some(new_model) = new_model {
155                    current_model = canonicalize_model_name(new_model);
156                }
157            }
158            "session.shutdown" => {
159                let payload_supported = shutdown_payload_supported(&event.data);
160                if payload_supported
161                    && let Ok(data) =
162                        serde_json::from_value::<CopilotShutdownData>(event.data.clone())
163                {
164                    diagnostics.record_relevant(true);
165                    for (model, metric) in data.model_metrics {
166                        if model.is_empty() {
167                            continue;
168                        }
169                        let Some(usage) = metric.usage else {
170                            continue;
171                        };
172                        // Copilot's `reasoningTokens` is the model's
173                        // thinking budget emitted before the visible
174                        // response. Surface it as its own field so
175                        // `calculate_cost` can charge it against the
176                        // model's published reasoning rate (when present)
177                        // via `output_cost_per_reasoning_token`, instead
178                        // of folding it into `output_tokens` and billing
179                        // every thinking token at the flat output rate.
180                        let usage_json = json!({
181                            "input_tokens": usage.input_tokens,
182                            "output_tokens": usage.output_tokens,
183                            "reasoning_output_tokens": usage.reasoning_tokens,
184                            "cache_read_input_tokens": usage.cache_read_tokens,
185                            "cache_creation_input_tokens": usage.cache_write_tokens,
186                        });
187                        conversation_usage.insert(canonicalize_model_name(&model), usage_json);
188                    }
189                    shutdown_seen = true;
190                } else {
191                    diagnostics.record_relevant(false);
192                }
193            }
194            "assistant.message" => {
195                // Only used as a fallback when no `session.shutdown` arrives.
196                if let Some(output_tokens) = event.data.get("outputTokens") {
197                    let output_tokens = output_tokens.as_i64();
198                    diagnostics
199                        .record_relevant(output_tokens.is_some() && !current_model.is_empty());
200                    if let Some(output_tokens) = output_tokens.filter(|&t| t > 0)
201                        && !current_model.is_empty()
202                    {
203                        *pending_output_tokens
204                            .entry(current_model.clone())
205                            .or_insert(0) += output_tokens;
206                    }
207                }
208            }
209            "tool.execution_start" => {
210                match serde_json::from_value::<CopilotToolStartData>(event.data.clone()) {
211                    Ok(data) if !data.tool_call_id.is_empty() && !data.tool_name.is_empty() => {
212                        let tracked = is_tracked_tool(&data.tool_name);
213                        let arguments_supported =
214                            tracked_tool_arguments_supported(&data.tool_name, &data.arguments);
215                        pending_tools.insert(
216                            data.tool_call_id,
217                            PendingTool {
218                                tool_name: data.tool_name,
219                                arguments: data.arguments,
220                                timestamp: ts,
221                                tracked,
222                                arguments_supported,
223                            },
224                        );
225                    }
226                    Ok(_) | Err(_) => diagnostics.record_relevant(false),
227                }
228            }
229            "tool.execution_complete" => {
230                let Some(tool_call_id) = event
231                    .data
232                    .get("toolCallId")
233                    .and_then(Value::as_str)
234                    .filter(|id| !id.is_empty())
235                else {
236                    diagnostics.record_relevant(false);
237                    continue;
238                };
239                let Some(pending) = pending_tools.remove(tool_call_id) else {
240                    continue;
241                };
242                let Some(success) = event.data.get("success").and_then(Value::as_bool) else {
243                    if pending.tracked {
244                        diagnostics.record_relevant(false);
245                    }
246                    continue;
247                };
248                // Only dispatch successful tool calls — failures rarely
249                // produce meaningful arguments (e.g. path validation errors)
250                // and would skew line-count totals.
251                if !success {
252                    if pending.tracked {
253                        diagnostics.record_relevant(true);
254                    }
255                    continue;
256                }
257                let data =
258                    match serde_json::from_value::<CopilotToolCompleteData>(event.data.clone()) {
259                        Ok(data) => data,
260                        Err(_) => {
261                            if pending.tracked {
262                                diagnostics.record_relevant(false);
263                            }
264                            continue;
265                        }
266                    };
267                if pending.tracked {
268                    let result_supported = tracked_tool_result_supported(
269                        &pending.tool_name,
270                        &pending.arguments,
271                        &data.result,
272                    );
273                    diagnostics.record_relevant(pending.arguments_supported && result_supported);
274                    if !pending.arguments_supported {
275                        continue;
276                    }
277                }
278                dispatch_tool(&mut state, &pending, &data);
279            }
280            _ => {}
281        }
282    }
283
284    // If `session.shutdown` never arrived, graft the fallback streamed
285    // output-token counters into `conversation_usage` so the row still has
286    // a non-zero number (callers can tell it's partial by the missing
287    // `input_tokens`).
288    if !shutdown_seen {
289        for (model, output_tokens) in pending_output_tokens {
290            conversation_usage.insert(
291                model,
292                json!({
293                    "input_tokens": 0,
294                    "output_tokens": output_tokens,
295                    "cache_read_input_tokens": 0,
296                    "cache_creation_input_tokens": 0,
297                }),
298            );
299        }
300    }
301
302    // Fallback git remote lookup when `session.start.context` did not carry
303    // a repository string (e.g. running outside a git tree or pre-1.0 CLI).
304    if state.git_remote.is_empty() {
305        state.git_remote = get_git_remote_url(&state.folder_path);
306    }
307
308    let record = state.into_record(conversation_usage);
309
310    let analysis = CodeAnalysis {
311        user: String::new(),
312        extension_name: String::from("Copilot-CLI"),
313        insights_version: String::new(),
314        machine_id: String::new(),
315        records: vec![record],
316    };
317    Ok(ParsedAnalysis::new(analysis, diagnostics))
318}
319
320fn shutdown_payload_supported(data: &Value) -> bool {
321    let Some(metrics) = data.get("modelMetrics").and_then(Value::as_object) else {
322        return false;
323    };
324    metrics.values().all(|metric| {
325        let Some(metric) = metric.as_object() else {
326            return false;
327        };
328        match metric.get("usage") {
329            None | Some(Value::Null) => true,
330            Some(usage) => copilot_usage_supported(usage),
331        }
332    })
333}
334
335fn copilot_usage_supported(usage: &Value) -> bool {
336    const TOKEN_FIELDS: &[&str] = &[
337        "inputTokens",
338        "outputTokens",
339        "cacheReadTokens",
340        "cacheWriteTokens",
341        "reasoningTokens",
342    ];
343    let Some(usage) = usage.as_object() else {
344        return false;
345    };
346    if usage.is_empty() {
347        return true;
348    }
349
350    let mut recognized = false;
351    for field in TOKEN_FIELDS {
352        if let Some(value) = usage.get(*field) {
353            recognized = true;
354            if value.as_i64().is_none() {
355                return false;
356            }
357        }
358    }
359    recognized
360}
361
362fn is_tracked_tool(name: &str) -> bool {
363    matches!(
364        name,
365        "view"
366            | "show_file"
367            | "read_file"
368            | "rg"
369            | "grep"
370            | "create"
371            | "write_file"
372            | "write"
373            | "str_replace"
374            | "edit"
375            | "replace"
376            | "edit_file"
377            | "apply_patch"
378            | "bash"
379            | "shell"
380            | "execute"
381            | "write_bash"
382    )
383}
384
385fn tracked_tool_arguments_supported(name: &str, args: &Value) -> bool {
386    match name {
387        "view" | "show_file" | "read_file" => args
388            .get("path")
389            .and_then(Value::as_str)
390            .is_some_and(|path| !path.is_empty()),
391        "rg" | "grep" => true,
392        "create" | "write_file" | "write" => {
393            args.get("path")
394                .and_then(Value::as_str)
395                .is_some_and(|path| !path.is_empty())
396                && args
397                    .get("file_text")
398                    .or_else(|| args.get("content"))
399                    .is_some_and(Value::is_string)
400        }
401        "str_replace" | "edit" | "replace" | "edit_file" => {
402            args.get("path")
403                .and_then(Value::as_str)
404                .is_some_and(|path| !path.is_empty())
405                && args
406                    .get("old_string")
407                    .or_else(|| args.get("old_str"))
408                    .or_else(|| args.get("old_text"))
409                    .is_some_and(Value::is_string)
410                && args
411                    .get("new_string")
412                    .or_else(|| args.get("new_str"))
413                    .or_else(|| args.get("new_text"))
414                    .is_some_and(Value::is_string)
415        }
416        "apply_patch" => extract_apply_patch_text(args).is_some_and(|patch| {
417            parse_apply_patch_text(patch)
418                .iter()
419                .any(|patch| !patch.file_path.is_empty())
420        }),
421        "bash" | "shell" | "execute" => args
422            .get("command")
423            .or_else(|| args.get("cmd"))
424            .and_then(Value::as_str)
425            .is_some_and(|command| !command.trim().is_empty()),
426        "write_bash" => args
427            .get("input")
428            .and_then(Value::as_str)
429            .is_some_and(|command| !command.trim().is_empty()),
430        _ => false,
431    }
432}
433
434fn tracked_tool_result_supported(name: &str, args: &Value, result: &Value) -> bool {
435    match name {
436        "view" | "show_file" | "read_file" => {
437            if let Some(range) = args
438                .get("view_range")
439                .and_then(Value::as_array)
440                .filter(|range| range.len() >= 2)
441            {
442                return range.first().and_then(Value::as_i64).is_some()
443                    && range.get(1).and_then(Value::as_i64).is_some();
444            }
445            result.get("content").is_some_and(Value::is_string)
446        }
447        _ => true,
448    }
449}
450
451fn extract_apply_patch_text(args: &Value) -> Option<&str> {
452    args.as_str()
453        .or_else(|| args.get("input").and_then(Value::as_str))
454        .or_else(|| args.get("patch").and_then(Value::as_str))
455        .or_else(|| args.get("patchText").and_then(Value::as_str))
456        .or_else(|| args.get("string").and_then(Value::as_str))
457}
458
459/// A `tool.execution_start` event held until its matching
460/// `tool.execution_complete` arrives, keyed by `toolCallId`.
461struct PendingTool {
462    /// Tool name (e.g. `view`, `create`, `str_replace`, `bash`).
463    tool_name: String,
464    /// Raw tool arguments object, interpreted lazily by [`dispatch_tool`].
465    arguments: Value,
466    /// Start-event timestamp in epoch milliseconds, used for the detail record.
467    timestamp: i64,
468    /// Whether this tool contributes to the analysis projection.
469    tracked: bool,
470    /// Whether the tracked tool's arguments use a supported schema.
471    arguments_supported: bool,
472}
473
474/// Routes a completed Copilot tool call to the matching file-operation tally.
475///
476/// Branches on `pending.tool_name`; unrecognised tools (e.g. `glob`,
477/// `task_complete`) are silently ignored. Argument field names are probed
478/// with historical aliases for forward compatibility across CLI releases.
479fn dispatch_tool(
480    state: &mut SessionParseState,
481    pending: &PendingTool,
482    complete: &CopilotToolCompleteData,
483) {
484    let ts = pending.timestamp;
485    let args = &pending.arguments;
486
487    match pending.tool_name.as_str() {
488        // Current Copilot CLI exposes `view` for reads. Historical versions
489        // used `str_replace_editor` with `command == "view"`, which we no
490        // longer attempt to parse.
491        "view" | "show_file" | "read_file" => {
492            let Some(path) = args.get("path").and_then(|p| p.as_str()) else {
493                return;
494            };
495
496            state.tool_counts.read += 1;
497            let content = extract_view_content(args, &complete.result);
498            attach_read_detail(state, path, &content, ts);
499        }
500        // Search tools read repository content but do not identify one complete
501        // file body, so retain the invocation without inventing line totals.
502        "rg" | "grep" => state.tool_counts.read += 1,
503        // `create` is the primary write tool. Historical names are kept for
504        // robustness; a future release that renames the tool will still get
505        // counted if the argument shape stays similar.
506        "create" | "write_file" | "write" => {
507            let Some(path) = args.get("path").and_then(|p| p.as_str()) else {
508                return;
509            };
510            let content = args
511                .get("file_text")
512                .or_else(|| args.get("content"))
513                .and_then(|c| c.as_str())
514                .unwrap_or("");
515            state.add_write_detail(path, content, ts);
516        }
517        // Edit-style tool names the CLI is known or likely to emit. Field
518        // shape is assumed to stay `{path, old_string|old_str, new_string|new_str}`.
519        "str_replace" | "edit" | "replace" | "edit_file" => {
520            let Some(path) = args.get("path").and_then(|p| p.as_str()) else {
521                return;
522            };
523            let old_str = args
524                .get("old_string")
525                .or_else(|| args.get("old_str"))
526                .or_else(|| args.get("old_text"))
527                .and_then(|s| s.as_str())
528                .unwrap_or("");
529            let new_str = args
530                .get("new_string")
531                .or_else(|| args.get("new_str"))
532                .or_else(|| args.get("new_text"))
533                .and_then(|s| s.as_str())
534                .unwrap_or("");
535            state.add_edit_detail(path, old_str, new_str, ts);
536        }
537        "apply_patch" => {
538            let patch = extract_apply_patch_text(args).unwrap_or("");
539            apply_patch_text(state, patch, ts);
540        }
541        "bash" | "shell" | "execute" => {
542            let command = args
543                .get("command")
544                .or_else(|| args.get("cmd"))
545                .and_then(|c| c.as_str())
546                .unwrap_or("");
547            let description = args
548                .get("description")
549                .and_then(|d| d.as_str())
550                .unwrap_or("");
551            state.add_run_command(command, description, ts);
552        }
553        "write_bash" => {
554            let input = args.get("input").and_then(Value::as_str).unwrap_or("");
555            state.add_run_command(input, "", ts);
556        }
557        // `glob`, `report_intent`, `task_complete`, `update_topic`, … have
558        // no file-operation semantics we care about. Silently ignore.
559        _ => {}
560    }
561}
562
563fn attach_read_detail(state: &mut SessionParseState, path: &str, content: &str, ts: i64) {
564    let invocation_count = state.tool_counts.read;
565    state.add_read_detail(path, content, ts);
566    state.tool_counts.read = invocation_count;
567}
568
569/// Folds a successful `apply_patch` call into per-file details.
570fn apply_patch_text(state: &mut SessionParseState, patch_text: &str, ts: i64) {
571    for patch in parse_apply_patch_text(patch_text) {
572        let (old_string, new_string) = extract_patch_strings(&patch.lines);
573        match patch.action.as_str() {
574            "add" => state.add_write_detail(&patch.file_path, &new_string, ts),
575            "delete" => state.add_edit_detail_raw(&patch.file_path, &old_string, "", ts),
576            _ => state.add_edit_detail_raw(&patch.file_path, &old_string, &new_string, ts),
577        }
578    }
579}
580
581struct CopilotPatch {
582    action: String,
583    file_path: String,
584    lines: Vec<String>,
585}
586
587/// Parses the patch envelope used by the current Copilot CLI.
588fn parse_apply_patch_text(patch_text: &str) -> Vec<CopilotPatch> {
589    let Some(start) = patch_text.find("*** Begin Patch") else {
590        return Vec::new();
591    };
592
593    let mut patches = Vec::with_capacity(3);
594    let mut current: Option<CopilotPatch> = None;
595    for line in patch_text[start..].lines() {
596        let line = line.trim_end_matches('\r');
597        let header = [
598            ("*** Update File:", "update"),
599            ("*** Add File:", "add"),
600            ("*** Delete File:", "delete"),
601        ]
602        .into_iter()
603        .find_map(|(prefix, action)| line.strip_prefix(prefix).map(|path| (action, path)));
604
605        if line.starts_with("*** End Patch") {
606            if let Some(patch) = current.take() {
607                patches.push(patch);
608            }
609            break;
610        } else if line.starts_with("*** Begin Patch") {
611            continue;
612        } else if let Some((action, path)) = header {
613            if let Some(patch) = current.take() {
614                patches.push(patch);
615            }
616            current = Some(CopilotPatch {
617                action: action.to_string(),
618                file_path: path.trim().to_string(),
619                lines: Vec::with_capacity(20),
620            });
621        } else if let Some(path) = line.strip_prefix("*** Move to:") {
622            if let Some(patch) = &mut current {
623                patch.file_path = path.trim().to_string();
624            }
625        } else if let Some(patch) = &mut current {
626            patch.lines.push(line.to_string());
627        }
628    }
629
630    if let Some(patch) = current {
631        patches.push(patch);
632    }
633    patches
634}
635
636fn extract_patch_strings(lines: &[String]) -> (String, String) {
637    let mut old_string = String::new();
638    let mut new_string = String::new();
639    for line in lines {
640        if line.starts_with("@@") || line.starts_with('\\') {
641            continue;
642        }
643        if let Some(line) = line.strip_prefix('+') {
644            new_string.push_str(line);
645            new_string.push('\n');
646        } else if let Some(line) = line.strip_prefix('-') {
647            old_string.push_str(line);
648            old_string.push('\n');
649        }
650    }
651    old_string.truncate(old_string.trim_end_matches('\n').len());
652    new_string.truncate(new_string.trim_end_matches('\n').len());
653    (old_string, new_string)
654}
655
656/// Resolve the content a Copilot `view` tool saw.
657///
658/// Callers can pass us two sources:
659///
660/// 1. `arguments.view_range` — inclusive `[start, end]` line numbers. When
661///    present we synthesise a `line_count`-line placeholder using a
662///    non-newline character so `add_read_detail`'s `trim_end_matches('\n')`
663///    cannot collapse it back to zero. The actual content is not needed
664///    because we only care about the line count.
665/// 2. `complete.result.content` — the string the model actually received.
666///    Preferred when available and when no `view_range` was supplied.
667fn extract_view_content(arguments: &Value, result: &Value) -> String {
668    if let Some(range) = arguments.get("view_range").and_then(|v| v.as_array())
669        && range.len() >= 2
670    {
671        let start = range.first().and_then(|v| v.as_i64()).unwrap_or(0);
672        let end = range.get(1).and_then(|v| v.as_i64()).unwrap_or(0);
673        let line_count = (end - start + 1).max(0) as usize;
674        if line_count == 0 {
675            return String::new();
676        }
677        // A pure-newline placeholder ("\n".repeat(N - 1)) would survive
678        // `count_lines` on its own, but `add_read_detail` first trims
679        // trailing newlines and then the whole thing collapses to an
680        // empty string — so the line tally would silently come back as
681        // zero. Use single-char "lines" joined by '\n' so the trim is a
682        // no-op and `count_lines` recovers exactly `line_count`.
683        return vec!["-"; line_count].join("\n");
684    }
685
686    result
687        .get("content")
688        .and_then(|c| c.as_str())
689        .unwrap_or("")
690        .to_string()
691}
692
693/// Best-effort reconstruction of a repository's git remote URL from the
694/// `session.start.context` fields.
695///
696/// Copilot writes `{ repository: "owner/repo", repositoryHost: "github.com" }`
697/// but does *not* include the full clone URL. We prefix with `https://`
698/// because that's the canonical web-facing form; the value is only used for
699/// display in the usage report, not for actual git operations, so the
700/// SSH-vs-HTTPS distinction does not matter.
701fn build_remote_url(host: &str, repository: &str) -> String {
702    if host.is_empty() || repository.is_empty() {
703        return String::new();
704    }
705    format!("https://{}/{}", host.trim(), repository.trim())
706}
707
708/// Canonicalise a Copilot-supplied model name.
709///
710/// Copilot CLI writes Anthropic model names with **dot-separated** minor
711/// versions (e.g. `claude-sonnet-4.6`, `claude-opus-4.7`), while the
712/// LiteLLM pricing table and every other CLI in this tool (Claude Code,
713/// Codex) use the **dash-separated** form (`claude-sonnet-4-6`,
714/// `claude-opus-4-7`).
715///
716/// If we leave the Copilot names as-is, two things go wrong:
717///
718/// 1. `merge_usage_values` keeps Copilot's `claude-sonnet-4.6` separate
719///    from Claude Code's `claude-sonnet-4-6`, splitting a single model's
720///    usage across two rows.
721/// 2. The pricing matcher's substring/fuzzy tier finds no exact key for
722///    `claude-sonnet-4.6` and picks the *only* dot-named variant it has
723///    — `openrouter/anthropic/claude-sonnet-4.6` — which is an OpenRouter
724///    proxy entry with different per-token rates, not the Anthropic
725///    native rate the Copilot caller is actually being billed against.
726///
727/// We limit the rewrite to names starting with `claude-` so OpenAI /
728/// Google models whose native form legitimately contains dots (e.g.
729/// `gpt-5.1`, `gemini-1.5-pro`) are left untouched.
730fn canonicalize_model_name(name: &str) -> String {
731    if name.starts_with("claude-") {
732        name.replace('.', "-")
733    } else {
734        name.to_string()
735    }
736}
737
738#[cfg(test)]
739mod tests {
740    use super::{
741        CopilotToolCompleteData, PendingTool, canonicalize_model_name, dispatch_tool,
742        extract_view_content, parse_copilot_events_with_diagnostics,
743        tracked_tool_arguments_supported, tracked_tool_result_supported,
744    };
745    use crate::models::CopilotEvent;
746    use crate::session::state::ParseMode;
747    use crate::session::state::SessionParseState;
748    use serde_json::{Value, json};
749
750    fn event(event_type: &str, data: Value) -> CopilotEvent {
751        CopilotEvent {
752            event_type: event_type.to_string(),
753            data,
754            id: String::new(),
755            timestamp: "2026-07-12T00:00:00Z".to_string(),
756            parent_id: None,
757        }
758    }
759
760    fn count_lines_after_trim(s: &str) -> usize {
761        // Mirror src/session/state.rs count_lines + add_read_detail's
762        // trim_end_matches('\n') so the test reflects the actual line
763        // tally the analyzer would record.
764        let trimmed = s.trim_end_matches('\n');
765        if trimmed.is_empty() {
766            0
767        } else {
768            trimmed.chars().filter(|c| *c == '\n').count() + 1
769        }
770    }
771
772    #[test]
773    fn view_range_placeholder_survives_trim_end() {
774        // view_range [1, 5] → 5 logical lines. The synthesised
775        // placeholder must yield 5 from `count_lines` even after
776        // `trim_end_matches('\n')` runs in `add_read_detail`.
777        let args = json!({ "view_range": [1, 5], "path": "/tmp/foo" });
778        let result = json!({});
779        let placeholder = extract_view_content(&args, &result);
780        assert_eq!(
781            count_lines_after_trim(&placeholder),
782            5,
783            "view_range [1,5] must count as 5 lines after add_read_detail's trim"
784        );
785    }
786
787    #[test]
788    fn view_range_with_zero_span_returns_empty() {
789        // Edge case: empty range produces an empty placeholder so the
790        // upstream early-return in `add_read_detail` skips it cleanly.
791        let args = json!({ "view_range": [5, 4], "path": "/tmp/foo" });
792        let result = json!({});
793        assert_eq!(extract_view_content(&args, &result), "");
794    }
795
796    #[test]
797    fn view_without_range_uses_result_content() {
798        let args = json!({ "path": "/tmp/foo" });
799        let result = json!({ "content": "alpha\nbeta\ngamma" });
800        assert_eq!(extract_view_content(&args, &result), "alpha\nbeta\ngamma");
801    }
802
803    fn completed() -> CopilotToolCompleteData {
804        CopilotToolCompleteData {
805            tool_call_id: "call-1".to_string(),
806            success: true,
807            result: json!({ "content": "alpha\nbeta" }),
808            model: "test".to_string(),
809        }
810    }
811
812    #[test]
813    fn current_show_file_maps_to_read() {
814        let pending = PendingTool {
815            tool_name: "show_file".to_string(),
816            arguments: json!({ "path": "/tmp/a.txt", "view_range": [1, 2] }),
817            timestamp: 1,
818            tracked: true,
819            arguments_supported: true,
820        };
821        let mut state = SessionParseState::new();
822        dispatch_tool(&mut state, &pending, &completed());
823        assert_eq!(state.tool_counts.read, 1);
824        assert_eq!(state.total_read_lines, 2);
825    }
826
827    #[test]
828    fn show_file_empty_and_drifted_results_keep_the_known_invocation() {
829        let pending = PendingTool {
830            tool_name: "show_file".to_string(),
831            arguments: json!({ "path": "/tmp/empty.txt" }),
832            timestamp: 1,
833            tracked: true,
834            arguments_supported: true,
835        };
836
837        let mut empty = completed();
838        empty.result = json!({ "content": "" });
839        assert!(tracked_tool_result_supported(
840            &pending.tool_name,
841            &pending.arguments,
842            &empty.result
843        ));
844        let mut state = SessionParseState::new();
845        dispatch_tool(&mut state, &pending, &empty);
846        assert_eq!(state.tool_counts.read, 1);
847        assert_eq!(state.total_read_lines, 0);
848
849        let mut drifted = completed();
850        drifted.result = json!({ "futureContent": "" });
851        assert!(!tracked_tool_result_supported(
852            &pending.tool_name,
853            &pending.arguments,
854            &drifted.result
855        ));
856        let mut state = SessionParseState::new();
857        dispatch_tool(&mut state, &pending, &drifted);
858        assert_eq!(state.tool_counts.read, 1);
859        assert_eq!(state.total_read_lines, 0);
860    }
861
862    #[test]
863    fn current_search_tools_count_read_invocations_without_fake_lines() {
864        let mut state = SessionParseState::new();
865        for tool_name in ["rg", "grep"] {
866            let pending = PendingTool {
867                tool_name: tool_name.to_string(),
868                arguments: json!({ "pattern": "needle", "paths": ["src"] }),
869                timestamp: 1,
870                tracked: true,
871                arguments_supported: true,
872            };
873            dispatch_tool(&mut state, &pending, &completed());
874        }
875        assert_eq!(state.tool_counts.read, 2);
876        assert_eq!(state.total_read_lines, 0);
877    }
878
879    #[test]
880    fn apply_patch_arguments_require_a_supported_nonempty_file_header() {
881        let drifted = json!("*** Begin Patch\n*** Future File: src/lib.rs\n+new\n*** End Patch");
882        assert!(!tracked_tool_arguments_supported("apply_patch", &drifted));
883
884        let empty_body = json!("*** Begin Patch\n*** Add File: empty.txt\n*** End Patch");
885        assert!(tracked_tool_arguments_supported("apply_patch", &empty_body));
886
887        let empty_path = json!("*** Begin Patch\n*** Add File:\n+new\n*** End Patch");
888        assert!(!tracked_tool_arguments_supported(
889            "apply_patch",
890            &empty_path
891        ));
892    }
893
894    #[test]
895    fn current_apply_patch_string_maps_to_file_operations() {
896        let pending = PendingTool {
897            tool_name: "apply_patch".to_string(),
898            arguments: json!(
899                "*** Begin Patch\n*** Update File: src/lib.rs\n@@\n-old\n+new\n*** Add File: notes.txt\n+hello\n*** End Patch"
900            ),
901            timestamp: 1,
902            tracked: true,
903            arguments_supported: true,
904        };
905        let mut state = SessionParseState::new();
906        dispatch_tool(&mut state, &pending, &completed());
907        assert_eq!(state.tool_counts.edit, 1);
908        assert_eq!(state.tool_counts.write, 1);
909        assert_eq!(state.edit_details.len(), 1);
910        assert_eq!(state.write_details.len(), 1);
911    }
912
913    #[test]
914    fn current_apply_patch_string_field_maps_to_edit() {
915        let pending = PendingTool {
916            tool_name: "apply_patch".to_string(),
917            arguments: json!({
918                "string": "*** Begin Patch\n*** Update File: src/lib.rs\n@@\n-old\n+new\n*** End Patch"
919            }),
920            timestamp: 1,
921            tracked: true,
922            arguments_supported: true,
923        };
924        let mut state = SessionParseState::new();
925        dispatch_tool(&mut state, &pending, &completed());
926        assert_eq!(state.tool_counts.edit, 1);
927        assert_eq!(state.edit_details.len(), 1);
928    }
929
930    #[test]
931    fn current_apply_patch_input_field_maps_to_edit() {
932        let pending = PendingTool {
933            tool_name: "apply_patch".to_string(),
934            arguments: json!({
935                "input": "*** Begin Patch\n*** Update File: src/lib.rs\n@@\n-old\n+new\n*** End Patch"
936            }),
937            timestamp: 1,
938            tracked: true,
939            arguments_supported: true,
940        };
941        let mut state = SessionParseState::new();
942        dispatch_tool(&mut state, &pending, &completed());
943        assert_eq!(state.tool_counts.edit, 1);
944        assert_eq!(state.edit_details.len(), 1);
945    }
946
947    #[test]
948    fn current_write_bash_counts_nonempty_input() {
949        let pending = PendingTool {
950            tool_name: "write_bash".to_string(),
951            arguments: json!({ "input": "yes", "shellId": "shell-1" }),
952            timestamp: 1,
953            tracked: true,
954            arguments_supported: true,
955        };
956        let mut state = SessionParseState::new();
957        dispatch_tool(&mut state, &pending, &completed());
958        assert_eq!(state.tool_counts.bash, 1);
959        assert_eq!(state.run_details.len(), 1);
960    }
961
962    #[test]
963    fn shutdown_rejects_unknown_only_usage_keys_without_inventing_zero_usage() {
964        let parsed = parse_copilot_events_with_diagnostics(
965            vec![event(
966                "session.shutdown",
967                json!({
968                    "modelMetrics": {
969                        "future-model": {
970                            "usage": {
971                                "promptTokens": 123,
972                                "completionTokens": 45
973                            }
974                        }
975                    }
976                }),
977            )],
978            ParseMode::Full,
979        )
980        .unwrap();
981
982        assert!(parsed.diagnostics.is_complete_failure());
983        assert!(
984            parsed.analysis.records[0].conversation_usage.is_empty(),
985            "unknown token keys must not become a successful all-zero usage row"
986        );
987    }
988
989    #[test]
990    fn shutdown_accepts_partial_current_usage_even_when_the_value_is_zero() {
991        let parsed = parse_copilot_events_with_diagnostics(
992            vec![event(
993                "session.shutdown",
994                json!({
995                    "modelMetrics": {
996                        "current-model": {
997                            "usage": { "inputTokens": 0 }
998                        }
999                    }
1000                }),
1001            )],
1002            ParseMode::Full,
1003        )
1004        .unwrap();
1005
1006        assert!(!parsed.diagnostics.is_complete_failure());
1007        assert_eq!(
1008            parsed.analysis.records[0].conversation_usage["current-model"]["input_tokens"],
1009            0
1010        );
1011    }
1012
1013    #[test]
1014    fn missing_tool_success_is_schema_drift_but_explicit_false_is_a_known_failure() {
1015        let start = || {
1016            event(
1017                "tool.execution_start",
1018                json!({
1019                    "toolCallId": "call-1",
1020                    "toolName": "show_file",
1021                    "arguments": { "path": "/tmp/a.txt" }
1022                }),
1023            )
1024        };
1025
1026        let missing = parse_copilot_events_with_diagnostics(
1027            vec![
1028                start(),
1029                event(
1030                    "tool.execution_complete",
1031                    json!({
1032                        "toolCallId": "call-1",
1033                        "status": "success",
1034                        "result": { "content": "one\ntwo" }
1035                    }),
1036                ),
1037            ],
1038            ParseMode::Full,
1039        )
1040        .unwrap();
1041        assert!(missing.diagnostics.is_complete_failure());
1042        assert_eq!(missing.analysis.records[0].tool_call_counts.read, 0);
1043
1044        let failed = parse_copilot_events_with_diagnostics(
1045            vec![
1046                start(),
1047                event(
1048                    "tool.execution_complete",
1049                    json!({
1050                        "toolCallId": "call-1",
1051                        "success": false,
1052                        "result": { "error": "invalid path" }
1053                    }),
1054                ),
1055            ],
1056            ParseMode::Full,
1057        )
1058        .unwrap();
1059        assert!(!failed.diagnostics.is_complete_failure());
1060        assert_eq!(failed.diagnostics.partial_failure_count(), 0);
1061        assert_eq!(failed.analysis.records[0].tool_call_counts.read, 0);
1062    }
1063
1064    #[test]
1065    fn claude_dot_version_rewrites_to_dash() {
1066        assert_eq!(
1067            canonicalize_model_name("claude-sonnet-4.6"),
1068            "claude-sonnet-4-6"
1069        );
1070        assert_eq!(
1071            canonicalize_model_name("claude-opus-4.7"),
1072            "claude-opus-4-7"
1073        );
1074    }
1075
1076    #[test]
1077    fn claude_dash_version_is_unchanged() {
1078        assert_eq!(
1079            canonicalize_model_name("claude-sonnet-4-6"),
1080            "claude-sonnet-4-6"
1081        );
1082    }
1083
1084    #[test]
1085    fn non_claude_models_keep_dots() {
1086        // OpenAI / Azure model names use dots natively; do not touch them.
1087        assert_eq!(canonicalize_model_name("gpt-5.1"), "gpt-5.1");
1088        assert_eq!(canonicalize_model_name("gpt-4.1-mini"), "gpt-4.1-mini");
1089        assert_eq!(canonicalize_model_name("gemini-1.5-pro"), "gemini-1.5-pro");
1090    }
1091}