vibe_coding_tracker 2.1.0

Vibe Coding Tracker - AI coding assistant telemetry/usage parser, aggregate local session data 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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
//! 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 records them as legacy `function_call` pairs or current
//! `custom_tool_call` pairs. This parser joins each call to its output by
//! `call_id`. Legacy shell calls retain command-level analysis. A top-level
//! custom `exec` is counted as one run command because its JavaScript source
//! does not prove which nested tools actually ran. Direct custom patches are
//! applied only when their paired output explicitly reports success.
use crate::constants::FastHashMap;
use crate::models::*;
use crate::session::diagnostics::{ParseDiagnostics, ParsedAnalysis};
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;
use std::borrow::Borrow;

/// Parse Codex session records from a slice of pre-typed logs.
///
/// Walks the records in order, threading function and custom-tool calls 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> {
    parse_codex_log_iter(logs, mode)
}

/// Streaming Codex parser used by JSONL readers that already own an iterator.
pub(crate) fn parse_codex_log_iter<I>(logs: I, mode: ParseMode) -> Result<CodeAnalysis>
where
    I: IntoIterator,
    I::Item: Borrow<CodexLog>,
{
    Ok(parse_codex_log_iter_with_diagnostics(logs, mode)?.analysis)
}

/// Streaming Codex parser with parser-only schema diagnostics.
pub(crate) fn parse_codex_log_iter_with_diagnostics<I>(
    logs: I,
    mode: ParseMode,
) -> Result<ParsedAnalysis>
where
    I: IntoIterator,
    I::Item: Borrow<CodexLog>,
{
    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 replay_baseline = None;
    let mut shell_calls: FastHashMap<String, PendingCodexShellCall> =
        FastHashMap::with_capacity(50);
    let mut custom_calls: FastHashMap<String, CodexCustomCall> = FastHashMap::with_capacity(32);
    let mut diagnostics = ParseDiagnostics::default();

    for entry in logs {
        let entry = entry.borrow();
        let recognized = matches!(
            entry.log_type.as_str(),
            "session_meta"
                | "turn_context"
                | "event_msg"
                | "response_item"
                | "inter_agent_communication_metadata"
                | "world_state"
                | "compacted"
        );
        if recognized {
            diagnostics.record_recognized_source();
        } else {
            diagnostics.record_unrecognized();
        }
        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
                    .as_ref()
                    .filter(|model| !model.is_empty())
                {
                    current_model.clone_from(model); // Reuse existing allocation
                }
            }
            "event_msg" => {
                if let Some(payload_type) = &entry.payload.payload_type
                    && payload_type == "token_count"
                    && let Some(info) = entry.payload.info.as_ref().filter(|info| !info.is_null())
                {
                    if !is_supported_codex_usage(info) {
                        diagnostics.record_relevant(false);
                    } else if current_model.is_empty() {
                        diagnostics.record_relevant(true);
                        if let Some(total) = info.get("total_token_usage") {
                            replay_baseline = Some(total.clone());
                        }
                    } else {
                        diagnostics.record_relevant(true);
                        if let Some(baseline) = &replay_baseline {
                            let adjusted = subtract_codex_replay_baseline(info, baseline);
                            process_codex_usage(&mut conversation_usage, &current_model, &adjusted);
                        } else {
                            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) = entry.payload.name.as_deref()
                                && matches!(name, "shell" | "exec_command")
                            {
                                let call = entry
                                    .payload
                                    .arguments
                                    .as_deref()
                                    .and_then(|args| parse_function_call(name, args, ts));
                                if let Some(call_id) = entry.payload.call_id.as_deref() {
                                    if let Some(call) = call {
                                        diagnostics.record_relevant(true);
                                        shell_calls.insert(
                                            call_id.to_string(),
                                            PendingCodexShellCall::Parsed(call),
                                        );
                                    } else {
                                        // Defer the schema verdict until the paired output. Codex
                                        // persists model-generated argument errors as ordinary
                                        // lifecycle records even though no command ran.
                                        shell_calls.insert(
                                            call_id.to_string(),
                                            PendingCodexShellCall::InvalidArguments,
                                        );
                                    }
                                } else {
                                    diagnostics.record_relevant(false);
                                }
                            }
                        }
                        "function_call_output" => {
                            if let Some(call_id) = &entry.payload.call_id
                                && let Some(call) = shell_calls.remove(call_id)
                            {
                                match call {
                                    PendingCodexShellCall::Parsed(call) => {
                                        diagnostics.record_relevant(true);
                                        let output = shell_output(entry.payload.output.as_deref());
                                        state.handle_shell_call(call, output);
                                    }
                                    PendingCodexShellCall::InvalidArguments => {
                                        diagnostics.record_relevant(output_reports_argument_error(
                                            entry.payload.output.as_deref(),
                                        ));
                                    }
                                }
                            }
                        }
                        "custom_tool_call" => {
                            if let Some(name) = entry.payload.name.as_deref()
                                && matches!(name, "exec" | "apply_patch")
                            {
                                let call = entry
                                    .payload
                                    .arguments
                                    .as_deref()
                                    .and_then(|input| parse_custom_call(name, input, ts, mode));
                                let normalized = call.is_some() && entry.payload.call_id.is_some();
                                diagnostics.record_relevant(normalized);
                                if let (Some(call), Some(call_id)) =
                                    (call, entry.payload.call_id.as_deref())
                                {
                                    custom_calls.insert(call_id.to_string(), call);
                                }
                            }
                        }
                        "custom_tool_call_output" => {
                            if let Some(call_id) = entry.payload.call_id.as_deref()
                                && let Some(call) = custom_calls.remove(call_id)
                            {
                                let normalized = dispatch_custom_call(
                                    &mut state,
                                    call,
                                    entry.payload.output.as_deref(),
                                );
                                diagnostics.record_relevant(normalized);
                            }
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }

    for call in shell_calls.into_values() {
        if matches!(call, PendingCodexShellCall::InvalidArguments) {
            diagnostics.record_relevant(false);
        }
    }
    if state.git_remote.is_empty() {
        state.git_remote = get_git_remote_url(&state.folder_path);
    }

    let record = state.into_record(conversation_usage);

    let analysis = CodeAnalysis {
        user: String::new(),
        extension_name: String::new(),
        insights_version: String::new(),
        machine_id: String::new(),
        records: vec![record],
    };
    Ok(ParsedAnalysis::new(analysis, diagnostics))
}

fn is_supported_codex_usage(info: &Value) -> bool {
    let Some(info) = info.as_object() else {
        return false;
    };
    let mut recognized = false;
    for key in ["total_token_usage", "last_token_usage"] {
        let Some(usage) = info.get(key) else {
            continue;
        };
        if !is_supported_codex_token_usage(usage) {
            return false;
        }
        recognized = true;
    }
    if let Some(context_window) = info.get("model_context_window") {
        if context_window.is_null() {
            // Older Codex records retain the field with a null value while
            // still carrying valid token objects.
        } else if context_window.as_i64().is_none() {
            return false;
        } else {
            recognized = true;
        }
    }
    recognized
}

fn subtract_codex_replay_baseline(info: &Value, baseline: &Value) -> Value {
    let mut adjusted = info.clone();
    let (Some(total), Some(baseline)) = (
        adjusted
            .get_mut("total_token_usage")
            .and_then(Value::as_object_mut),
        baseline.as_object(),
    ) else {
        return adjusted;
    };
    for key in [
        "input_tokens",
        "cached_input_tokens",
        "output_tokens",
        "reasoning_output_tokens",
        "total_tokens",
    ] {
        if let (Some(current), Some(replayed)) = (
            total.get(key).and_then(Value::as_i64),
            baseline.get(key).and_then(Value::as_i64),
        ) {
            total.insert(
                key.to_string(),
                Value::from(current.saturating_sub(replayed).max(0)),
            );
        }
    }
    adjusted
}

fn is_supported_codex_token_usage(usage: &Value) -> bool {
    let Some(usage) = usage.as_object() else {
        return false;
    };
    if usage.is_empty() {
        return true;
    }

    let mut recognized = false;
    for key in [
        "input_tokens",
        "cached_input_tokens",
        "output_tokens",
        "reasoning_output_tokens",
        "total_tokens",
    ] {
        if let Some(value) = usage.get(key) {
            if value.as_i64().is_none() {
                return false;
            }
            recognized = true;
        }
    }
    recognized
}

enum PendingCodexShellCall {
    Parsed(CodexShellCall),
    InvalidArguments,
}

fn output_reports_argument_error(output: Option<&str>) -> bool {
    let output = shell_output(output).output;
    let output = strip_exec_command_metadata_prefix(&output)
        .trim_start()
        .to_ascii_lowercase();
    (output.starts_with("error") || output.starts_with("failed"))
        && (output.contains("failed to parse")
            || output.contains("missing field")
            || output.contains("missing required")
            || output.contains("invalid argument"))
}

/// 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
    }
}

/// Normalizes legacy strings and structured outputs serialized at the model boundary.
fn shell_output(output: Option<&str>) -> CodexShellOutput {
    let Some(output) = output else {
        return CodexShellOutput {
            output: String::new(),
            metadata: None,
        };
    };

    serde_json::from_str::<CodexShellOutput>(output).unwrap_or_else(|_| CodexShellOutput {
        output: serde_json::from_str::<Value>(output)
            .ok()
            .and_then(|value| value.get("output")?.as_str().map(str::to_string))
            .unwrap_or_else(|| output.to_string()),
        metadata: None,
    })
}

/// 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,
    }
}

enum CodexCustomCall {
    Exec {
        source: Option<String>,
        timestamp: i64,
    },
    ApplyPatch {
        patches: Vec<CodexPatch>,
        timestamp: i64,
    },
}

fn parse_custom_call(
    name: &str,
    input: &str,
    timestamp: i64,
    mode: ParseMode,
) -> Option<CodexCustomCall> {
    match name {
        "exec" if !input.trim().is_empty() => Some(CodexCustomCall::Exec {
            source: matches!(mode, ParseMode::Full).then(|| input.to_string()),
            timestamp,
        }),
        "apply_patch" => {
            let patches: Vec<_> = parse_apply_patch_script(input)
                .into_iter()
                .filter(|patch| !patch.file_path.is_empty())
                .collect();
            (!patches.is_empty()).then_some(CodexCustomCall::ApplyPatch { patches, timestamp })
        }
        _ => None,
    }
}

fn dispatch_custom_call(
    state: &mut SessionParseState,
    call: CodexCustomCall,
    output: Option<&str>,
) -> bool {
    match call {
        CodexCustomCall::Exec { source, timestamp } => {
            // The JavaScript wrapper can contain branches, loops, retries, or
            // tool calls whose execution cannot be proven from source text.
            // Treat the completed cell itself as the only observable action.
            if let Some(source) = source {
                state.add_run_command(&source, "", timestamp);
            } else {
                state.tool_counts.bash += 1;
            }
            true
        }
        CodexCustomCall::ApplyPatch { patches, timestamp } => {
            match custom_apply_patch_result(output) {
                CustomApplyPatchResult::Success => {
                    for patch in patches {
                        state.handle_patch(patch, timestamp);
                    }
                    true
                }
                CustomApplyPatchResult::Failure => true,
                CustomApplyPatchResult::Unknown => false,
            }
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CustomApplyPatchResult {
    Success,
    Failure,
    Unknown,
}

fn custom_apply_patch_result(output: Option<&str>) -> CustomApplyPatchResult {
    let output = normalize_custom_output(output);
    let output = output.trim();
    if output == "Done!" || output.starts_with("Success. Updated the following files:") {
        CustomApplyPatchResult::Success
    } else if output.starts_with("Failed")
        || output.starts_with("Error")
        || output.starts_with("apply_patch verification failed:")
        || output.starts_with("Invalid patch")
        || output.starts_with("apply_patch handler received")
        || output.starts_with("apply_patch is unavailable")
    {
        CustomApplyPatchResult::Failure
    } else {
        CustomApplyPatchResult::Unknown
    }
}

/// Decodes a custom tool's normalized string or `JSON.stringify` result.
fn normalize_custom_output(output: Option<&str>) -> String {
    let body = strip_exec_command_metadata_prefix(output.unwrap_or_default()).trim();
    match serde_json::from_str::<Value>(body) {
        Ok(Value::Object(object)) => object
            .get("output")
            .and_then(Value::as_str)
            .unwrap_or(body)
            .to_string(),
        Ok(Value::String(text)) => text,
        _ => body.to_string(),
    }
}

/// 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) {
        // Patch payloads carry a stable envelope regardless of the launcher name.
        if call.script.contains("*** Begin Patch") {
            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::*;

    fn response_item(payload: Value) -> CodexLog {
        serde_json::from_value(serde_json::json!({
            "timestamp": "2026-07-12T00:00:00Z",
            "type": "response_item",
            "payload": payload
        }))
        .unwrap()
    }

    fn custom_output(call_id: &str, blocks: Value) -> CodexLog {
        response_item(serde_json::json!({
            "type": "custom_tool_call_output",
            "call_id": call_id,
            "output": blocks
        }))
    }

    #[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 structured_function_arguments_are_normalized_end_to_end() {
        let logs = vec![
            response_item(serde_json::json!({
                "type": "function_call",
                "name": "exec_command",
                "arguments": { "cmd": "pwd", "workdir": "/repo" },
                "call_id": "exec-object"
            })),
            response_item(serde_json::json!({
                "type": "function_call_output",
                "call_id": "exec-object",
                "output": "done"
            })),
        ];

        let analysis = parse_codex_logs(&logs, ParseMode::Full).unwrap();
        let record = &analysis.records[0];
        assert_eq!(record.tool_call_counts.bash, 1);
        assert_eq!(record.run_command_details[0].command, "pwd");
    }

    #[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 paired_exec_argument_errors_are_supported_metric_free_lifecycles() {
        for arguments in ["{not json", r#"{"command_as_key":""}"#] {
            let logs = vec![
                response_item(serde_json::json!({
                    "type": "function_call",
                    "name": "exec_command",
                    "arguments": arguments,
                    "call_id": "bad-exec"
                })),
                response_item(serde_json::json!({
                    "type": "function_call_output",
                    "call_id": "bad-exec",
                    "output": "Error: failed to parse function arguments"
                })),
            ];

            let parsed = parse_codex_log_iter_with_diagnostics(&logs, ParseMode::Full).unwrap();
            assert_eq!(parsed.diagnostics.partial_failure_count(), 0);
            assert!(!parsed.diagnostics.is_complete_failure());
            assert_eq!(parsed.analysis.records[0].tool_call_counts.bash, 0);
            assert!(parsed.analysis.records[0].run_command_details.is_empty());
        }
    }

    #[test]
    fn invalid_exec_arguments_without_an_explicit_error_remain_drift() {
        let logs = vec![
            response_item(serde_json::json!({
                "type": "function_call",
                "name": "exec_command",
                "arguments": { "future_command": "pwd" },
                "call_id": "future-exec"
            })),
            response_item(serde_json::json!({
                "type": "function_call_output",
                "call_id": "future-exec",
                "output": "completed"
            })),
        ];

        let parsed = parse_codex_log_iter_with_diagnostics(&logs, ParseMode::Full).unwrap();
        assert!(parsed.diagnostics.is_complete_failure());
        assert_eq!(parsed.analysis.records[0].tool_call_counts.bash, 0);
    }

    #[test]
    fn valid_token_count_without_model_context_is_not_schema_failure() {
        let logs: Vec<CodexLog> = [
            serde_json::json!({
                "timestamp": "2026-07-12T00:00:00Z",
                "type": "session_meta",
                "payload": { "id": "compacted-session", "model_provider": "openai" }
            }),
            serde_json::json!({
                "timestamp": "2026-07-12T00:00:01Z",
                "type": "event_msg",
                "payload": {
                    "type": "token_count",
                    "info": {
                        "total_token_usage": { "input_tokens": 1, "output_tokens": 1 },
                        "last_token_usage": { "input_tokens": 1, "output_tokens": 1 },
                        "model_context_window": 200000
                    }
                }
            }),
        ]
        .into_iter()
        .map(|value| serde_json::from_value(value).unwrap())
        .collect();

        let parsed = parse_codex_log_iter_with_diagnostics(&logs, ParseMode::Full).unwrap();
        assert!(!parsed.diagnostics.is_complete_failure());
        assert_eq!(parsed.diagnostics.partial_failure_count(), 0);
        assert_eq!(parsed.diagnostics.relevant_records, 1);
        assert_eq!(parsed.diagnostics.normalized_records, 1);
        assert_eq!(parsed.diagnostics.failed_relevant_records, 0);
        assert!(parsed.analysis.records[0].conversation_usage.is_empty());
    }

    #[test]
    fn resumed_usage_subtracts_the_pre_context_replay_baseline() {
        let logs: Vec<CodexLog> = [
            serde_json::json!({
                "timestamp": "2026-07-12T00:00:00Z",
                "type": "session_meta",
                "payload": { "id": "resumed-session", "model_provider": "openai" }
            }),
            serde_json::json!({
                "timestamp": "2026-07-12T00:00:01Z",
                "type": "event_msg",
                "payload": {
                    "type": "token_count",
                    "info": {
                        "total_token_usage": {
                            "input_tokens": 100,
                            "cached_input_tokens": 20,
                            "output_tokens": 30,
                            "reasoning_output_tokens": 10,
                            "total_tokens": 130
                        },
                        "model_context_window": 200000
                    }
                }
            }),
            serde_json::json!({
                "timestamp": "2026-07-12T00:00:02Z",
                "type": "turn_context",
                "payload": { "model": "gpt-5.3-codex" }
            }),
            serde_json::json!({
                "timestamp": "2026-07-12T00:00:03Z",
                "type": "event_msg",
                "payload": {
                    "type": "token_count",
                    "info": {
                        "total_token_usage": {
                            "input_tokens": 160,
                            "cached_input_tokens": 25,
                            "output_tokens": 50,
                            "reasoning_output_tokens": 15,
                            "total_tokens": 210
                        },
                        "last_token_usage": { "input_tokens": 60, "output_tokens": 20 },
                        "model_context_window": 200000
                    }
                }
            }),
            serde_json::json!({
                "timestamp": "2026-07-12T00:00:04Z",
                "type": "event_msg",
                "payload": {
                    "type": "token_count",
                    "info": {
                        "total_token_usage": {
                            "input_tokens": 190,
                            "cached_input_tokens": 30,
                            "output_tokens": 60,
                            "reasoning_output_tokens": 20,
                            "total_tokens": 250
                        },
                        "last_token_usage": { "input_tokens": 30, "output_tokens": 10 },
                        "model_context_window": 200000
                    }
                }
            }),
        ]
        .into_iter()
        .map(|value| serde_json::from_value(value).unwrap())
        .collect();

        let parsed = parse_codex_log_iter_with_diagnostics(&logs, ParseMode::Full).unwrap();
        assert!(!parsed.diagnostics.is_complete_failure());
        assert_eq!(parsed.diagnostics.partial_failure_count(), 0);

        let usage = &parsed.analysis.records[0].conversation_usage["gpt-5.3-codex"];
        assert_eq!(usage["total_token_usage"]["input_tokens"], 90);
        assert_eq!(usage["total_token_usage"]["cached_input_tokens"], 10);
        assert_eq!(usage["total_token_usage"]["output_tokens"], 30);
        assert_eq!(usage["total_token_usage"]["reasoning_output_tokens"], 10);
        assert_eq!(usage["total_token_usage"]["total_tokens"], 120);
        assert_eq!(usage["last_token_usage"]["output_tokens"], 10);
        assert_eq!(usage["model_context_window"], 200000);
    }

    #[test]
    fn pre_context_usage_is_not_guessed_from_a_later_model() {
        let logs: Vec<CodexLog> = [
            serde_json::json!({
                "timestamp": "2026-07-12T00:00:00Z",
                "type": "event_msg",
                "payload": {
                    "type": "token_count",
                    "info": { "total_token_usage": { "input_tokens": 10 } }
                }
            }),
            serde_json::json!({
                "timestamp": "2026-07-12T00:00:01Z",
                "type": "turn_context",
                "payload": { "model": "gpt-5.3-codex" }
            }),
        ]
        .into_iter()
        .map(|value| serde_json::from_value(value).unwrap())
        .collect();

        let parsed = parse_codex_log_iter_with_diagnostics(&logs, ParseMode::Full).unwrap();
        assert_eq!(parsed.diagnostics.partial_failure_count(), 0);
        assert!(parsed.analysis.records[0].conversation_usage.is_empty());
    }

    #[test]
    fn malformed_pre_context_usage_remains_schema_failure() {
        let logs: Vec<CodexLog> = [serde_json::json!({
            "timestamp": "2026-07-12T00:00:00Z",
            "type": "event_msg",
            "payload": {
                "type": "token_count",
                "info": { "total_token_usage": { "input_tokens": "10" } }
            }
        })]
        .into_iter()
        .map(|value| serde_json::from_value(value).unwrap())
        .collect();

        let parsed = parse_codex_log_iter_with_diagnostics(&logs, ParseMode::Full).unwrap();
        assert!(parsed.diagnostics.is_complete_failure());
        assert!(parsed.analysis.records[0].conversation_usage.is_empty());
    }

    #[test]
    fn usage_validation_rejects_unknown_only_and_wrong_typed_token_payloads() {
        assert!(is_supported_codex_usage(&serde_json::json!({
            "total_token_usage": {}
        })));
        assert!(is_supported_codex_usage(&serde_json::json!({
            "last_token_usage": { "input_tokens": 0, "future_metric": 5 }
        })));
        assert!(is_supported_codex_usage(&serde_json::json!({
            "total_token_usage": { "output_tokens": 0 },
            "model_context_window": null
        })));
        assert!(is_supported_codex_usage(&serde_json::json!({
            "model_context_window": 200000
        })));

        assert!(!is_supported_codex_usage(&serde_json::json!({
            "total_token_usage": { "prompt_tokens": 3 }
        })));
        assert!(!is_supported_codex_usage(&serde_json::json!({
            "last_token_usage": { "output_tokens": "3" }
        })));
        assert!(!is_supported_codex_usage(&serde_json::json!({
            "total_token_usage": { "input_tokens": 3 },
            "last_token_usage": { "completion_tokens": 1 }
        })));
        assert!(!is_supported_codex_usage(&serde_json::json!({
            "model_context_window": "200000"
        })));
    }

    #[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");
    }

    #[test]
    fn custom_apply_patch_requires_supported_nonempty_file_headers() {
        let drifted = "*** Begin Patch\n*** Future File: src/lib.rs\n+new\n*** End Patch";
        assert!(
            parse_custom_call("apply_patch", drifted, 1, ParseMode::Full).is_none(),
            "an unknown file header must not normalize as a successful patch"
        );

        for patch in [
            "*** Begin Patch\n*** Add File: empty.txt\n*** End Patch",
            "*** Begin Patch\n*** Delete File: empty.txt\n*** End Patch",
        ] {
            let Some(CodexCustomCall::ApplyPatch { patches, .. }) =
                parse_custom_call("apply_patch", patch, 1, ParseMode::Full)
            else {
                panic!("supported empty-body patch was rejected");
            };
            assert_eq!(patches.len(), 1);
            assert_eq!(patches[0].file_path, "empty.txt");
        }

        let empty_path = "*** Begin Patch\n*** Add File:\n+new\n*** End Patch";
        assert!(parse_custom_call("apply_patch", empty_path, 1, ParseMode::Full).is_none());
    }

    #[test]
    fn direct_custom_apply_patch_success_is_paired_and_parsed() {
        let patch = "*** Begin Patch\n*** Update File: src/lib.rs\n@@\n-old\n+new\n*** End Patch";
        let wire_result = serde_json::json!({
            "output": "Success. Updated the following files:\nM src/lib.rs",
            "metadata": { "exit_code": 0, "duration_seconds": 0.01 }
        })
        .to_string();
        let logs = vec![
            response_item(serde_json::json!({
                "type": "custom_tool_call",
                "name": "apply_patch",
                "input": patch,
                "call_id": "patch-1"
            })),
            custom_output("patch-1", Value::String(wire_result)),
        ];

        let analysis = parse_codex_logs(&logs, ParseMode::Full).unwrap();
        let record = &analysis.records[0];
        assert_eq!(record.tool_call_counts.edit, 1);
        assert_eq!(record.edit_file_details.len(), 1);
        assert_eq!(record.edit_file_details[0].base.file_path, "src/lib.rs");
    }

    #[test]
    fn direct_object_custom_apply_patch_output_is_paired_and_parsed() {
        let patch = "*** Begin Patch\n*** Update File: src/lib.rs\n@@\n-old\n+new\n*** End Patch";
        let logs = vec![
            response_item(serde_json::json!({
                "type": "custom_tool_call",
                "name": "apply_patch",
                "input": patch,
                "call_id": "patch-object"
            })),
            custom_output(
                "patch-object",
                serde_json::json!({
                    "output": "Success. Updated the following files:\nM src/lib.rs",
                    "metadata": { "exit_code": 0, "duration_seconds": 0.01 }
                }),
            ),
        ];

        let analysis = parse_codex_logs(&logs, ParseMode::Full).unwrap();
        let record = &analysis.records[0];
        assert_eq!(record.tool_call_counts.edit, 1);
        assert_eq!(record.edit_file_details.len(), 1);
    }

    #[test]
    fn failed_direct_custom_apply_patch_is_skipped() {
        let patch = "*** Begin Patch\n*** Update File: src/lib.rs\n@@\n-old\n+new\n*** End Patch";
        let wire_result = serde_json::json!({
            "output": "Failed to find expected lines in src/lib.rs",
            "metadata": { "exit_code": 1, "duration_seconds": 0.01 }
        })
        .to_string();
        let logs = vec![
            response_item(serde_json::json!({
                "type": "custom_tool_call",
                "name": "apply_patch",
                "input": patch,
                "call_id": "patch-failed"
            })),
            custom_output("patch-failed", Value::String(wire_result)),
        ];

        let parsed = parse_codex_log_iter_with_diagnostics(&logs, ParseMode::Full).unwrap();
        let record = &parsed.analysis.records[0];
        assert_eq!(record.tool_call_counts.edit, 0);
        assert!(record.edit_file_details.is_empty());
        assert_eq!(parsed.diagnostics.partial_failure_count(), 0);
    }

    #[test]
    fn unknown_direct_custom_apply_patch_result_is_skipped() {
        let patch = "*** Begin Patch\n*** Update File: src/lib.rs\n@@\n-old\n+new\n*** End Patch";
        for output in [
            Value::Null,
            serde_json::json!("Patch command finished"),
            serde_json::json!({
                "success": true,
                "updated_files": ["src/lib.rs"]
            }),
        ] {
            let logs = vec![
                response_item(serde_json::json!({
                    "type": "custom_tool_call",
                    "name": "apply_patch",
                    "input": patch,
                    "call_id": "patch-unknown"
                })),
                custom_output("patch-unknown", output),
            ];

            let parsed = parse_codex_log_iter_with_diagnostics(&logs, ParseMode::Full).unwrap();
            let record = &parsed.analysis.records[0];
            assert_eq!(record.tool_call_counts.edit, 0);
            assert!(record.edit_file_details.is_empty());
            assert_eq!(parsed.diagnostics.relevant_records, 2);
            assert_eq!(parsed.diagnostics.normalized_records, 1);
            assert_eq!(parsed.diagnostics.failed_relevant_records, 1);
            assert_eq!(parsed.diagnostics.partial_failure_count(), 1);
            assert!(!parsed.diagnostics.is_complete_failure());
        }
    }

    #[test]
    fn custom_output_envelope_is_stripped_before_json_result() {
        let result = serde_json::json!({
            "output": "Success. Updated the following files:\nM src/lib.rs",
            "metadata": { "exit_code": 0, "duration_seconds": 0.01 }
        })
        .to_string();
        let output = custom_output(
            "patch-array",
            serde_json::json!([
                { "type": "input_text", "text": "Script completed\nWall time: 0.1 seconds\nOutput:\n" },
                { "type": "input_text", "text": result }
            ]),
        )
        .payload
        .output;

        assert_eq!(
            normalize_custom_output(output.as_deref()),
            "Success. Updated the following files:\nM src/lib.rs"
        );
        assert_eq!(
            custom_apply_patch_result(output.as_deref()),
            CustomApplyPatchResult::Success
        );
    }

    #[test]
    fn custom_exec_is_one_bash_cell_not_nested_operations() {
        let input = "const results = await Promise.all([tools.exec_command({cmd: \"sed -n '1,2p' src/lib.rs\"}), tools.apply_patch(`*** Begin Patch\n*** Add File: notes.txt\n+hello\n*** End Patch`)]); text(JSON.stringify(results));";
        let logs = vec![
            response_item(serde_json::json!({
                "type": "custom_tool_call",
                "name": "exec",
                "input": input,
                "call_id": "exec-1"
            })),
            custom_output("exec-1", serde_json::json!("Script completed")),
        ];

        let analysis = parse_codex_logs(&logs, ParseMode::Full).unwrap();
        let record = &analysis.records[0];
        assert_eq!(record.tool_call_counts.bash, 1);
        assert_eq!(record.tool_call_counts.read, 0);
        assert_eq!(record.tool_call_counts.write, 0);
        assert_eq!(record.tool_call_counts.edit, 0);
        assert_eq!(record.run_command_details.len(), 1);
        assert_eq!(record.run_command_details[0].command, input);
    }

    #[test]
    fn custom_exec_usage_only_keeps_count_without_source_detail() {
        let logs = vec![
            response_item(serde_json::json!({
                "type": "custom_tool_call",
                "name": "exec",
                "input": "await tools.exec_command({cmd: dynamicCommand});",
                "call_id": "exec-dynamic"
            })),
            custom_output("exec-dynamic", serde_json::json!("Script completed")),
        ];

        let analysis = parse_codex_log_iter(logs, ParseMode::UsageOnly).unwrap();
        let record = &analysis.records[0];
        assert_eq!(record.tool_call_counts.bash, 1);
        assert!(record.run_command_details.is_empty());
    }

    #[test]
    fn current_exec_command_apply_patch_marker_is_parsed() {
        let args = serde_json::json!({
            "cmd": "apply_patch <<'PATCH'\n*** Begin Patch\n*** Update File: src/lib.rs\n@@\n-old\n+new\n*** End Patch\nPATCH"
        })
        .to_string();
        let call = parse_function_call("exec_command", &args, 1).unwrap();
        let mut state = SessionParseState::new();
        state.handle_shell_call(
            call,
            CodexShellOutput {
                output: String::new(),
                metadata: None,
            },
        );
        assert_eq!(state.tool_counts.edit, 1);
        assert_eq!(state.edit_details.len(), 1);
    }
}