cargo-copter 0.3.0

Test dependents against multiple versions of your crate (or your local WIP before publishing). Inspired by the cargo-crusader
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
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
use crate::error_extract::{Diagnostic, extract_crates_needing_patch, has_multiple_version_conflict, parse_cargo_json};
use crate::metadata;
use fs2::FileExt;
use lazy_static::lazy_static;
use log::{debug, warn};
use std::env;
use std::fs::{self, OpenOptions};
use std::io::{BufWriter, Read, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;
use std::time::{Duration, Instant};

// Constants for formatting and limits
const LOG_SEPARATOR_LENGTH: usize = 100;
const MAX_METADATA_LOG_LINES: usize = 100;

// Failure log file path
lazy_static! {
    static ref FAILURE_LOG: Mutex<Option<PathBuf>> = Mutex::new(None);
    static ref BUILD_FAILURE_LOG: Mutex<Option<PathBuf>> = Mutex::new(None);
    // Track last error signature for deduplication
    static ref LAST_ERROR_SIGNATURE: Mutex<Option<String>> = Mutex::new(None);
}

/// Initialize the failure log file
pub fn init_failure_log(log_path: PathBuf) {
    let mut log = FAILURE_LOG.lock().unwrap();
    *log = Some(log_path.clone());

    // Also initialize build-only log
    let build_log_path = log_path.with_file_name("copter-build-failures.log");
    let mut build_log = BUILD_FAILURE_LOG.lock().unwrap();
    *build_log = Some(build_log_path);

    // Clear the error signature when initializing
    let mut sig = LAST_ERROR_SIGNATURE.lock().unwrap();
    *sig = None;
}

/// Log a compilation failure to the failure log file with proper locking
#[allow(clippy::too_many_arguments)]
pub fn log_failure(
    dependent: &str,
    dependent_version: &str,
    base_crate: &str,
    test_label: &str, // "baseline", "WIP", or version number
    command: &str,
    exit_code: Option<i32>,
    stdout: &str,
    stderr: &str,
) {
    log_failure_with_diagnostics(
        dependent,
        dependent_version,
        base_crate,
        test_label,
        command,
        exit_code,
        stdout,
        stderr,
        &[],
    );
}

/// Log a compilation failure with parsed diagnostics for better readability
#[allow(clippy::too_many_arguments)]
pub fn log_failure_with_diagnostics(
    dependent: &str,
    dependent_version: &str,
    base_crate: &str,
    test_label: &str, // "baseline", "WIP", or version number
    command: &str,
    exit_code: Option<i32>,
    stdout: &str,
    stderr: &str,
    diagnostics: &[Diagnostic],
) {
    let (log_path, build_log_path) = {
        let log = FAILURE_LOG.lock().unwrap();
        let build_log = BUILD_FAILURE_LOG.lock().unwrap();
        match (&*log, &*build_log) {
            (Some(path), Some(build_path)) => (path.clone(), Some(build_path.clone())),
            (Some(path), None) => (path.clone(), None),
            _ => return, // Logging not initialized
        }
    };

    // Generate error signature for deduplication
    let current_signature = if !diagnostics.is_empty() {
        let error_text = diagnostics.iter().map(|d| d.rendered.as_str()).collect::<Vec<_>>().join("\n");
        crate::report::error_signature(&error_text)
    } else {
        crate::report::error_signature(stderr)
    };

    // Check if this error matches the previous one
    let is_duplicate = {
        let mut last_sig = LAST_ERROR_SIGNATURE.lock().unwrap();
        let duplicate = last_sig.as_ref().map(|s| s == &current_signature).unwrap_or(false);
        *last_sig = Some(current_signature);
        duplicate
    };

    // Write to main debug log
    write_failure_to_log(
        &log_path,
        "FAILURE",
        dependent,
        dependent_version,
        base_crate,
        test_label,
        command,
        exit_code,
        stderr,
        diagnostics,
        is_duplicate,
    );

    // If this is a build/check failure, also write to build-specific log
    let is_build_failure = command.contains("cargo fetch") || command.contains("cargo check");
    if is_build_failure && let Some(build_path) = build_log_path {
        write_failure_to_log(
            &build_path,
            "BUILD FAILURE",
            dependent,
            dependent_version,
            base_crate,
            test_label,
            command,
            exit_code,
            stderr,
            diagnostics,
            is_duplicate,
        );
    }
}

/// Helper function to write a failure entry to a specific log file
#[allow(clippy::too_many_arguments)]
fn write_failure_to_log(
    log_path: &Path,
    log_type: &str, // "FAILURE" or "BUILD FAILURE"
    dependent: &str,
    dependent_version: &str,
    base_crate: &str,
    test_label: &str,
    command: &str,
    exit_code: Option<i32>,
    stderr: &str,
    diagnostics: &[Diagnostic],
    is_duplicate: bool,
) {
    // Open file with append mode
    let file = match OpenOptions::new().create(true).append(true).open(log_path) {
        Ok(f) => f,
        Err(e) => {
            eprintln!("Failed to open {} log: {}", log_type, e);
            return;
        }
    };

    // Lock the file for exclusive write access
    if let Err(e) = file.lock_exclusive() {
        eprintln!("Failed to lock {} log: {}", log_type, e);
        return;
    }

    let mut writer = BufWriter::new(&file);
    let timestamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S");
    let exit_str = exit_code.map(|c| c.to_string()).unwrap_or_else(|| "N/A".to_string());

    let _ = writeln!(writer, "\n{}", "=".repeat(LOG_SEPARATOR_LENGTH));
    let _ = writeln!(
        writer,
        "[{}] {}: {} {} testing {} {}",
        timestamp, log_type, dependent, dependent_version, base_crate, test_label
    );
    let _ = writeln!(writer, "{}", "=".repeat(LOG_SEPARATOR_LENGTH));
    let _ = writeln!(writer, "Command: {}", command);
    let _ = writeln!(writer, "Exit code: {}", exit_str);

    if is_duplicate {
        let _ = writeln!(writer, "\n--- SAME FAILURE AS PREVIOUS ---");
    } else if !diagnostics.is_empty() {
        let _ = writeln!(writer, "\n--- ERRORS ---");
        for (idx, diag) in diagnostics.iter().enumerate() {
            let level_str = match diag.level {
                crate::error_extract::DiagnosticLevel::Error => "error",
                crate::error_extract::DiagnosticLevel::Warning => "warning",
                crate::error_extract::DiagnosticLevel::Help => "help",
                crate::error_extract::DiagnosticLevel::Note => "note",
                crate::error_extract::DiagnosticLevel::Other(ref s) => s.as_str(),
            };
            let _ = writeln!(writer, "\n{}. [{}] {}", idx + 1, level_str, diag.message);

            if !diag.rendered.is_empty() {
                let _ = writeln!(writer, "{}", diag.rendered);
            }
        }
    } else {
        let _ = writeln!(writer, "\n--- STDERR (no structured errors) ---");
        for line in stderr.lines() {
            if !line.trim_start().starts_with('{') {
                let _ = writeln!(writer, "{}", line);
            }
        }
    }

    let _ = writeln!(writer, "\n{}", "=".repeat(LOG_SEPARATOR_LENGTH));
    let _ = writer.flush();
    // Unlock is automatic when file goes out of scope
}

/// Restore Cargo.toml from the original backup before testing
/// This prevents contamination between test runs in the cached staging directory
///
/// CRITICAL: This is idempotent and Ctrl+C safe. If a backup exists from a previous
/// (possibly interrupted) run, we restore from it rather than overwriting it.
pub fn restore_cargo_toml(staging_path: &Path) -> Result<(), String> {
    let cargo_toml = staging_path.join("Cargo.toml");
    let original = staging_path.join("Cargo.toml.original.txt");

    // CRITICAL: Never overwrite existing .original - it might be from an interrupted run
    if !original.exists() {
        if cargo_toml.exists() {
            fs::copy(&cargo_toml, &original).map_err(|e| format!("Failed to save original Cargo.toml: {}", e))?;
            debug!("Saved original Cargo.toml to {:?}", original);
        }
    } else {
        // Restore from existing original (might be from interrupted run)
        fs::copy(&original, &cargo_toml).map_err(|e| format!("Failed to restore Cargo.toml from original: {}", e))?;
        debug!("Restored Cargo.toml from existing original backup in {:?}", staging_path);
    }
    Ok(())
}

/// The type of compilation step being performed
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum CompileStep {
    /// cargo fetch - download dependencies
    Fetch,
    /// cargo check - fast compilation check without code generation
    Check,
    /// cargo test - full test suite execution
    Test,
}

impl CompileStep {
    pub fn as_str(&self) -> &'static str {
        match self {
            CompileStep::Fetch => "fetch",
            CompileStep::Check => "check",
            CompileStep::Test => "test",
        }
    }

    pub fn cargo_subcommand(&self) -> &'static str {
        match self {
            CompileStep::Fetch => "fetch",
            CompileStep::Check => "check",
            CompileStep::Test => "test",
        }
    }
}

/// Result of a compilation step
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CompileResult {
    pub step: CompileStep,
    pub success: bool,
    pub stdout: String,
    pub stderr: String,
    pub duration: Duration,
    pub diagnostics: Vec<Diagnostic>,
}

impl CompileResult {
    pub fn failed(&self) -> bool {
        !self.success
    }
}

/// Verify that the correct version of a dependency is being used
/// Returns the actual version found, or None if not found
fn verify_dependency_version(crate_path: &Path, dep_name: &str) -> Option<String> {
    debug!("Verifying {} version in {:?}", dep_name, crate_path);

    // Try using cargo metadata which works better with path dependencies
    // Don't use --no-deps because we need to see resolved dependencies
    let output =
        Command::new("cargo").args(["metadata", "--format-version=1"]).current_dir(crate_path).output().ok()?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        debug!("cargo metadata failed: {}", stderr.trim());
        return None;
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let metadata = match serde_json::from_str::<serde_json::Value>(&stdout) {
        Ok(m) => m,
        Err(e) => {
            debug!("Failed to parse metadata JSON: {}", e);
            return None;
        }
    };

    // First try resolve.nodes to find the actually-used version (handles multiple versions correctly)
    if let Some(resolve) = metadata.get("resolve")
        && let Some(nodes) = resolve.get("nodes").and_then(|n| n.as_array())
    {
        for node in nodes {
            if let Some(deps) = node.get("deps").and_then(|d| d.as_array()) {
                for dep in deps {
                    if let Some(name) = dep.get("name").and_then(|n| n.as_str())
                        && name == dep_name
                        && let Some(pkg) = dep.get("pkg").and_then(|p| p.as_str())
                    {
                        // pkg format: "registry+https://...#crate-name@version" or "path+file://...#crate-name@version"
                        // Extract version by splitting on "#" then "@"
                        if let Some(after_hash) = pkg.split('#').nth(1)
                            && let Some(version) = after_hash.split('@').nth(1)
                        {
                            debug!("✓ Verified {} version: {}", dep_name, version);
                            return Some(version.to_string());
                        }
                    }
                }
            }
        }
    }

    // Fallback: Check packages array for the dependency (may pick wrong version if multiple exist)
    let packages = match metadata.get("packages").and_then(|p| p.as_array()) {
        Some(p) => p,
        None => {
            debug!("No 'packages' in metadata");
            return None;
        }
    };

    // Find the package with matching name
    for pkg in packages {
        if let Some(name) = pkg.get("name").and_then(|n| n.as_str())
            && name == dep_name
            && let Some(version) = pkg.get("version").and_then(|v| v.as_str())
        {
            debug!("✓ Verified {} version: {}", dep_name, version);
            return Some(version.to_string());
        }
    }

    debug!("Could not find {} in dependency graph", dep_name);
    None
}

/// Extract the version requirement spec for a dependency using cargo metadata
/// Returns None if the dependency is not found
fn extract_dependency_spec(crate_path: &Path, dep_name: &str) -> Result<Option<String>, String> {
    debug!("Extracting spec for '{}' from {:?}", dep_name, crate_path);

    // Run cargo metadata to get dependency specs
    let output = Command::new("cargo")
        .args(["metadata", "--format-version=1"])
        .current_dir(crate_path)
        .output()
        .map_err(|e| format!("Failed to run cargo metadata: {}", e))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(format!("cargo metadata failed: {}", stderr.trim()));
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed = metadata::parse_metadata(&stdout)?;

    // Get the root package (the dependent being tested)
    let root_package_id =
        if let Some(resolve) = &parsed.resolve { resolve.get("root").and_then(|r| r.as_str()) } else { None };

    if let Some(root_id) = root_package_id {
        // Use the metadata module to get the spec
        match metadata::get_version_spec(&parsed, root_id, dep_name) {
            Ok(spec) if spec != "?" => {
                debug!("  Extracted spec: {}", spec);
                return Ok(Some(spec));
            }
            Ok(_) => debug!("  Spec is '?', dependency not found in root package"),
            Err(e) => debug!("  Failed to get spec: {}", e),
        }
    }

    Ok(None)
}

/// Extract spec from Cargo.toml directly (fallback when cargo metadata fails)
/// Used for broken packages where fetch fails
fn extract_spec_from_toml(crate_path: &Path, dep_name: &str) -> Result<Option<String>, String> {
    use std::fs;
    use toml_edit::DocumentMut;

    debug!("Extracting spec from Cargo.toml for '{}' in {:?}", dep_name, crate_path);

    let toml_path = crate_path.join("Cargo.toml");
    let content = fs::read_to_string(&toml_path).map_err(|e| format!("Failed to read Cargo.toml: {}", e))?;

    let doc: DocumentMut = content.parse().map_err(|e| format!("Failed to parse Cargo.toml: {}", e))?;

    // Check [dependencies] section
    if let Some(deps) = doc.get("dependencies").and_then(|s| s.as_table_like())
        && let Some(dep_value) = deps.get(dep_name)
    {
        // Handle different formats:
        // 1. String: rgb = "0.8.27"
        if let Some(version_str) = dep_value.as_str() {
            return Ok(Some(version_str.to_string()));
        }

        // 2. Table: [dependencies.rgb] or inline table
        if let Some(table) = dep_value.as_table_like()
            && let Some(version_value) = table.get("version")
            && let Some(version_str) = version_value.as_str()
        {
            return Ok(Some(version_str.to_string()));
        }
    }

    // Not found
    Ok(None)
}

/// How to apply a dependency override
#[derive(Debug, Clone, Copy)]
enum DependencyOverrideMode {
    /// Replace dependency spec directly - bypasses semver requirements
    Force,
}

/// Apply a dependency override to Cargo.toml - Force mode only
fn apply_dependency_override(
    crate_path: &Path,
    dep_name: &str,
    override_path: &Path,
    mode: DependencyOverrideMode,
) -> Result<(), String> {
    use std::io::{Read, Write};

    // Convert to absolute path
    let override_path = if override_path.is_absolute() {
        override_path.to_path_buf()
    } else {
        env::current_dir().map_err(|e| format!("Failed to get current dir: {}", e))?.join(override_path)
    };

    let cargo_toml_path = crate_path.join("Cargo.toml");
    let mut content = String::new();

    // Read original Cargo.toml
    let mut file = fs::File::open(&cargo_toml_path).map_err(|e| format!("Failed to open Cargo.toml: {}", e))?;
    file.read_to_string(&mut content).map_err(|e| format!("Failed to read Cargo.toml: {}", e))?;
    drop(file);

    // Parse as TOML
    let mut doc: toml_edit::DocumentMut = content.parse().map_err(|e| format!("Failed to parse Cargo.toml: {}", e))?;

    match mode {
        DependencyOverrideMode::Force => {
            // Update dependency in all sections (force mode - replaces the spec entirely)
            let sections = vec!["dependencies", "dev-dependencies", "build-dependencies"];

            for section in sections {
                if let Some(deps) = doc.get_mut(section).and_then(|s| s.as_table_mut())
                    && let Some(dep) = deps.get_mut(dep_name)
                {
                    debug!("Force-replacing {} in [{}] with path {:?}", dep_name, section, override_path);

                    // Preserve existing fields (optional, default-features, features, etc.)
                    let mut new_dep = toml_edit::InlineTable::new();
                    new_dep.insert("path", override_path.display().to_string().into());

                    // Copy fields from original dependency if it's a table
                    if let Some(old_table) = dep.as_inline_table() {
                        // Preserve important fields
                        for key in ["optional", "default-features", "features", "package"] {
                            if let Some(value) = old_table.get(key) {
                                new_dep.insert(key, value.clone());
                                debug!("Preserving field '{}' = {:?}", key, value);
                            }
                        }
                    } else if let Some(old_table) = dep.as_table_like() {
                        // Handle table-like dependencies
                        for key in ["optional", "default-features", "features", "package"] {
                            if let Some(value) = old_table.get(key)
                                && let Some(v) = value.as_value()
                            {
                                new_dep.insert(key, v.clone());
                                debug!("Preserving field '{}' = {:?}", key, v);
                            }
                        }
                    }

                    *dep = toml_edit::Item::Value(toml_edit::Value::InlineTable(new_dep));
                }
            }

            debug!("Force-replaced {} dependency spec with path: {}", dep_name, override_path.display());
        }
    }

    // Write back
    let mut file = fs::File::create(&cargo_toml_path).map_err(|e| format!("Failed to create Cargo.toml: {}", e))?;
    file.write_all(doc.to_string().as_bytes()).map_err(|e| format!("Failed to write Cargo.toml: {}", e))?;

    Ok(())
}

/// Apply a [patch.crates-io] section to Cargo.toml to patch ALL transitive dependencies
///
/// This adds or updates the [patch.crates-io] section in the dependent's Cargo.toml,
/// which causes cargo to unify ALL versions of the specified crate across the entire
/// dependency tree (including transitive dependencies).
fn apply_patch_crates_io(crate_path: &Path, crate_name: &str, override_path: &Path) -> Result<(), String> {
    use std::io::{Read, Write};

    // Convert to absolute path
    let override_path = if override_path.is_absolute() {
        override_path.to_path_buf()
    } else {
        env::current_dir().map_err(|e| format!("Failed to get current dir: {}", e))?.join(override_path)
    };

    let cargo_toml_path = crate_path.join("Cargo.toml");
    let mut content = String::new();

    // Read original Cargo.toml
    let mut file = fs::File::open(&cargo_toml_path).map_err(|e| format!("Failed to open Cargo.toml: {}", e))?;
    file.read_to_string(&mut content).map_err(|e| format!("Failed to read Cargo.toml: {}", e))?;
    drop(file);

    // Parse as TOML
    let mut doc: toml_edit::DocumentMut = content.parse().map_err(|e| format!("Failed to parse Cargo.toml: {}", e))?;

    // Get or create [patch.crates-io] section
    if doc.get("patch").is_none() {
        doc["patch"] = toml_edit::Item::Table(toml_edit::Table::new());
    }
    let patch = doc["patch"].as_table_mut().ok_or("Failed to get patch table")?;

    if patch.get("crates-io").is_none() {
        patch["crates-io"] = toml_edit::Item::Table(toml_edit::Table::new());
    }
    let crates_io = patch["crates-io"].as_table_mut().ok_or("Failed to get crates-io table")?;

    // Add the patch entry
    let mut patch_entry = toml_edit::InlineTable::new();
    patch_entry.insert("path", override_path.display().to_string().into());
    crates_io[crate_name] = toml_edit::Item::Value(toml_edit::Value::InlineTable(patch_entry));

    debug!("Applied [patch.crates-io].{} = {{ path = \"{}\" }}", crate_name, override_path.display());

    // Write back
    let mut file = fs::File::create(&cargo_toml_path).map_err(|e| format!("Failed to create Cargo.toml: {}", e))?;
    file.write_all(doc.to_string().as_bytes()).map_err(|e| format!("Failed to write Cargo.toml: {}", e))?;

    Ok(())
}

pub fn compile_crate(
    crate_path: &Path,
    step: CompileStep,
    override_spec: Option<(&str, &Path)>,
) -> Result<CompileResult, String> {
    debug!("compiling {:?} with step {:?}", crate_path, step);

    // Run the cargo command with JSON output for better error extraction
    let start = Instant::now();
    let mut cmd = Command::new("cargo");
    cmd.arg(step.cargo_subcommand());

    // Add --message-format=json for check and test (not fetch)
    if step != CompileStep::Fetch {
        cmd.arg("--message-format=json");
    }

    // If override is provided, use --config flag instead of creating .cargo/config file
    if let Some((crate_name, override_path)) = override_spec {
        // Convert to absolute path if needed
        let override_path = if override_path.is_absolute() {
            override_path.to_path_buf()
        } else {
            env::current_dir().map_err(|e| format!("Failed to get current dir: {}", e))?.join(override_path)
        };

        let config_str = format!("patch.crates-io.{}.path=\"{}\"", crate_name, override_path.display());
        cmd.arg("--config").arg(&config_str);
        debug!("using --config: {}", config_str);
    }

    cmd.current_dir(crate_path);

    debug!("running cargo: {:?}", cmd);
    let output = cmd.output().map_err(|e| format!("Failed to execute cargo: {}", e))?;

    let duration = start.elapsed();
    let success = output.status.success();

    debug!("result: {:?}, duration: {:?}", success, duration);

    // Parse stdout for JSON messages (cargo writes JSON to stdout)
    let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
    let stderr = String::from_utf8_lossy(&output.stderr).into_owned();

    // Parse diagnostics from JSON output (only for check/test, not fetch)
    let diagnostics = if step != CompileStep::Fetch { parse_cargo_json(&stdout) } else { Vec::new() };

    debug!("parsed {} diagnostics", diagnostics.len());

    Ok(CompileResult { step, success, stdout, stderr, duration, diagnostics })
}

/// Source of a version being tested
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VersionSource {
    /// Published version from crates.io
    Published { version: String, forced: bool },
    /// Local work-in-progress version ("this")
    Local { path: PathBuf, forced: bool },
}

impl VersionSource {
    pub fn label(&self) -> String {
        match self {
            VersionSource::Published { version, .. } => version.clone(),
            VersionSource::Local { .. } => "this".to_string(),
        }
    }

    pub fn is_local(&self) -> bool {
        matches!(self, VersionSource::Local { .. })
    }

    pub fn is_forced(&self) -> bool {
        match self {
            VersionSource::Published { forced, .. } => *forced,
            VersionSource::Local { forced, .. } => *forced,
        }
    }

    pub fn version_string(&self) -> Option<String> {
        match self {
            VersionSource::Published { version, .. } => Some(version.clone()),
            VersionSource::Local { .. } => None,
        }
    }

    pub fn path(&self) -> Option<&PathBuf> {
        match self {
            VersionSource::Published { .. } => None,
            VersionSource::Local { path, .. } => Some(path),
        }
    }
}

/// Depth of patching applied to resolve version conflicts
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, serde::Deserialize)]
pub enum PatchDepth {
    /// No patching - natural resolution or simple force mode
    #[default]
    None,
    /// Force mode only - direct dependency spec replaced (!)
    Force,
    /// Patch retry - [patch.crates-io] added after multi-version error (!!)
    Patch,
    /// Deep patch - recursive transitive patching after Patch still failed (!!!)
    DeepPatch,
}

impl PatchDepth {
    /// Get marker suffix for display
    pub fn marker(&self) -> &'static str {
        match self {
            PatchDepth::None => "",
            PatchDepth::Force => "!",
            PatchDepth::Patch => "!!",
            PatchDepth::DeepPatch => "!!!",
        }
    }

    /// Check if any patching was applied
    pub fn is_patched(&self) -> bool {
        !matches!(self, PatchDepth::None)
    }
}

/// Three-step ICT (Install/Check/Test) result for a single version
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ThreeStepResult {
    /// Install step (cargo fetch) - always runs
    pub fetch: CompileResult,
    /// Check step (cargo check) - only if fetch succeeds
    pub check: Option<CompileResult>,
    /// Test step (cargo test) - only if check succeeds
    pub test: Option<CompileResult>,
    /// Actual version resolved (from cargo tree), if verification succeeded
    pub actual_version: Option<String>,
    /// Expected version being tested
    pub expected_version: Option<String>,
    /// Whether this version was forced (bypassed semver requirements)
    pub forced_version: bool,
    /// Original requirement from dependent (e.g., "^0.8.52"), if known
    pub original_requirement: Option<String>,
    /// All versions of the tested crate found in the dependency tree (for multi-version scenarios)
    pub all_crate_versions: Vec<(String, String, String)>, // (spec, resolved_version, dependent_name)
    /// Depth of patching applied to resolve version conflicts
    pub patch_depth: PatchDepth,
}

impl ThreeStepResult {
    /// Determine if all executed steps succeeded
    pub fn is_success(&self) -> bool {
        if !self.fetch.success {
            return false;
        }
        if let Some(ref check) = self.check
            && !check.success
        {
            return false;
        }
        if let Some(ref test) = self.test
            && !test.success
        {
            return false;
        }
        true
    }

    /// Validate internal consistency of the result (debug builds only).
    ///
    /// Panics if fetch failed but check/test is Some, or check failed but test is Some.
    #[inline]
    pub fn debug_assert_consistent(&self) {
        debug_assert!(
            self.fetch.success || (self.check.is_none() && self.test.is_none()),
            "Invariant violated: fetch failed but check/test is Some. \
             fetch.success={}, check.is_some={}, test.is_some={}",
            self.fetch.success,
            self.check.is_some(),
            self.test.is_some()
        );
        if let Some(ref check) = self.check {
            debug_assert!(
                check.success || self.test.is_none(),
                "Invariant violated: check failed but test is Some. \
                 check.success={}, test.is_some={}",
                check.success,
                self.test.is_some()
            );
        }
    }

    /// Get the first failed step, if any
    pub fn first_failure(&self) -> Option<&CompileResult> {
        if !self.fetch.success {
            return Some(&self.fetch);
        }
        if let Some(ref check) = self.check
            && !check.success
        {
            return Some(check);
        }
        if let Some(ref test) = self.test
            && !test.success
        {
            return Some(test);
        }
        None
    }

    /// Format ICT marks for display (e.g., "✓✓✓", "✓✗-", "✗--")
    /// Shows cumulative failure: after first failure, show dashes
    pub fn format_ict_marks(&self) -> String {
        let fetch_mark = if self.fetch.success { "" } else { "" };

        if !self.fetch.success {
            return format!("{}--", fetch_mark);
        }

        let check_mark = match &self.check {
            Some(c) if c.success => "",
            Some(_) => "",
            None => "-",
        };

        if matches!(&self.check, Some(c) if !c.success) {
            return format!("{}{}-", fetch_mark, check_mark);
        }

        let test_mark = match &self.test {
            Some(t) if t.success => "",
            Some(_) => "",
            None => "-",
        };

        format!("{}{}{}", fetch_mark, check_mark, test_mark)
    }
}

/// Information about the dependent crate for logging
#[derive(Debug, Clone)]
pub struct DependentInfo<'a> {
    pub name: &'a str,
    pub version: &'a str,
}

/// Configuration for three-step ICT testing
#[derive(Debug, Clone)]
pub struct TestConfig<'a> {
    /// Path to the dependent crate being tested
    pub crate_path: &'a Path,
    /// Name of the base crate being overridden (e.g., "rgb")
    pub base_crate_name: &'a str,
    /// Optional path to override the dependency with
    pub override_path: Option<&'a Path>,
    /// Skip cargo check step
    pub skip_check: bool,
    /// Skip cargo test step
    pub skip_test: bool,
    /// Expected version to verify after fetch
    pub expected_version: Option<String>,
    /// Force version (bypass semver requirements)
    pub force_versions: bool,
    /// Original requirement from dependent's Cargo.toml
    pub original_requirement: Option<String>,
    /// Information about the dependent for logging
    pub dependent_info: Option<DependentInfo<'a>>,
    /// Test label for logging ("baseline", "WIP", or version)
    pub test_label: Option<&'a str>,
    /// Use [patch.crates-io] to patch all transitive dependencies
    pub patch_transitive: bool,
}

impl<'a> TestConfig<'a> {
    /// Create a new test configuration
    pub fn new(crate_path: &'a Path, base_crate_name: &'a str) -> Self {
        Self {
            crate_path,
            base_crate_name,
            override_path: None,
            skip_check: false,
            skip_test: false,
            expected_version: None,
            force_versions: false,
            original_requirement: None,
            dependent_info: None,
            test_label: None,
            patch_transitive: false,
        }
    }

    /// Set patch_transitive flag (builder pattern)
    pub fn with_patch_transitive(mut self, patch_transitive: bool) -> Self {
        self.patch_transitive = patch_transitive;
        self
    }

    /// Set the override path (builder pattern)
    pub fn with_override_path(mut self, path: &'a Path) -> Self {
        self.override_path = Some(path);
        self
    }

    /// Set skip flags (builder pattern)
    pub fn with_skip_flags(mut self, skip_check: bool, skip_test: bool) -> Self {
        self.skip_check = skip_check;
        self.skip_test = skip_test;
        self
    }

    /// Set version information (builder pattern)
    pub fn with_version_info(
        mut self,
        expected_version: Option<String>,
        force_versions: bool,
        original_requirement: Option<String>,
    ) -> Self {
        self.expected_version = expected_version;
        self.force_versions = force_versions;
        self.original_requirement = original_requirement;
        self
    }

    /// Set logging information (builder pattern)
    pub fn with_logging_info(mut self, dependent_info: Option<DependentInfo<'a>>, test_label: Option<&'a str>) -> Self {
        self.dependent_info = dependent_info;
        self.test_label = test_label;
        self
    }
}

/// Run three-step ICT (Install/Check/Test) test with early stopping
///
/// # Returns
/// ThreeStepResult with cumulative early stopping:
/// - Fetch always runs
/// - Check only runs if fetch succeeds (and !skip_check)
/// - Test only runs if check succeeds (and !skip_test)
pub fn run_three_step_ict(config: TestConfig) -> Result<ThreeStepResult, String> {
    let TestConfig {
        crate_path,
        base_crate_name,
        override_path,
        skip_check,
        skip_test,
        expected_version,
        force_versions,
        original_requirement,
        dependent_info,
        test_label,
        patch_transitive,
    } = config;
    debug!(
        "running three-step ICT for {:?} (force={}, expected_version={:?}, patch_transitive={}, has_override_path={})",
        crate_path,
        force_versions,
        expected_version,
        patch_transitive,
        override_path.is_some()
    );

    // Sanity check: baseline should NOT have an override_path
    if override_path.is_some() && !force_versions {
        debug!("PATCH MODE: will use --config for patching (override_path={:?})", override_path);
    } else if override_path.is_none() {
        debug!("BASELINE MODE: no override, testing natural resolution");
    }

    // Always restore Cargo.toml from original backup to prevent contamination
    restore_cargo_toml(crate_path)?;

    // Always delete Cargo.lock to force fresh dependency resolution
    let lock_file = crate_path.join("Cargo.lock");
    if lock_file.exists() {
        debug!("Deleting Cargo.lock to force dependency resolution");
        fs::remove_file(&lock_file).map_err(|e| format!("Failed to remove Cargo.lock: {}", e))?;
    }

    // Setup: Choose patching strategy based on mode
    // For FORCE mode: Modify Cargo.toml to bypass semver (direct dependency)
    //   - If patch_transitive is also enabled, add [patch.crates-io] for transitive deps
    // For PATCH mode (non-force): Use --config flag (clean, no file modifications)
    // For BASELINE: No override at all
    //
    // IMPORTANT: patch_transitive ONLY applies with force mode, because:
    // 1. Baseline should never be modified
    // 2. Non-forced versions use --config which doesn't modify files
    let override_path_buf = if let Some(override_path) = override_path {
        if force_versions {
            // FORCE MODE: Must modify Cargo.toml to bypass semver
            // No backup needed - restore_cargo_toml already has .original saved

            // Replace dependency spec directly (bypasses semver)
            apply_dependency_override(crate_path, base_crate_name, override_path, DependencyOverrideMode::Force)?;

            // If patch_transitive is also enabled, add [patch.crates-io] for transitive deps
            if patch_transitive {
                apply_patch_crates_io(crate_path, base_crate_name, override_path)?;
                debug!("Applied BOTH force override AND [patch.crates-io] for transitive patching");
            }

            None // Don't use --config when we modified Cargo.toml
        } else {
            // PATCH MODE: Use --config flag (clean, no file modifications)
            let abs_path = if override_path.is_absolute() {
                override_path.to_path_buf()
            } else {
                env::current_dir().map_err(|e| format!("Failed to get current directory: {}", e))?.join(override_path)
            };

            debug!("Using --config for patch mode with override_path={:?}, abs_path={:?}", override_path, abs_path);
            Some(abs_path) // Use --config, no file modifications
        }
    } else {
        None // No override (baseline test)
    };

    // Build override_spec for compile_crate calls (only used in regular patch mode)
    let override_spec = override_path_buf.as_ref().map(|path| (base_crate_name, path.as_path()));

    // Step 1: Fetch (always runs)
    let fetch = compile_crate(crate_path, CompileStep::Fetch, override_spec)?;

    // Verify the actual version after fetch
    let actual_version = if fetch.success { verify_dependency_version(crate_path, base_crate_name) } else { None };

    // Extract original requirement spec from metadata if not provided
    let original_requirement = if original_requirement.is_none() {
        if fetch.success {
            // Fetch succeeded - extract from metadata
            let extracted = extract_dependency_spec(crate_path, base_crate_name).ok().flatten();
            debug!("Extracted spec (fetch succeeded): {:?} (force={})", extracted, force_versions);
            if extracted.is_none() && !force_versions {
                panic!(
                    "Failed to extract dependency spec for '{}' from {:?}. \
                    This should never happen if fetch succeeded in non-force mode. \
                    The dependency must exist in the manifest.",
                    base_crate_name, crate_path
                );
            }
            extracted
        } else {
            // Fetch failed - try to extract from Cargo.toml directly (fallback for broken dependents)
            let extracted = extract_spec_from_toml(crate_path, base_crate_name).ok().flatten();
            debug!("Extracted spec (fetch failed, from Cargo.toml): {:?}", extracted);
            extracted
        }
    } else {
        original_requirement.clone()
    };

    if fetch.failed() {
        // Log failure with diagnostics
        if let (Some(dep_info), Some(label)) = (dependent_info.as_ref(), test_label) {
            log_failure_with_diagnostics(
                dep_info.name,
                dep_info.version,
                base_crate_name,
                label,
                "cargo fetch",
                None,
                &fetch.stdout,
                &fetch.stderr,
                &fetch.diagnostics,
            );
        }

        // Fetch failed - stop here with dashes for remaining steps
        return Ok(ThreeStepResult {
            fetch,
            check: None,
            test: None,
            actual_version,
            expected_version,
            forced_version: force_versions,
            original_requirement,
            all_crate_versions: vec![],
            patch_depth: if force_versions { PatchDepth::Force } else { PatchDepth::None },
        });
    }

    // Step 2: Check (only if fetch succeeded and not skipped)
    let check = if !skip_check {
        let result = compile_crate(crate_path, CompileStep::Check, override_spec)?;
        if result.failed() {
            // Log failure with diagnostics
            if let (Some(dep_info), Some(label)) = (dependent_info.as_ref(), test_label) {
                log_failure_with_diagnostics(
                    dep_info.name,
                    dep_info.version,
                    base_crate_name,
                    label,
                    "cargo check",
                    None,
                    &result.stdout,
                    &result.stderr,
                    &result.diagnostics,
                );
            }

            // Check failed - try auto-retry with [patch.crates-io] if it's a multi-version conflict
            let combined_output = format!("{}\n{}", result.stdout, result.stderr);
            if force_versions
                && (has_multiple_version_conflict(&combined_output)
                    || has_multiple_resolved_versions(crate_path, base_crate_name))
            {
                debug!("Multi-version conflict detected, attempting auto-retry with [patch.crates-io]");

                // Restore Cargo.toml and apply both force AND patch.crates-io
                restore_cargo_toml(crate_path)?;

                // Delete Cargo.lock again for fresh resolution
                let lock_file = crate_path.join("Cargo.lock");
                if lock_file.exists() {
                    let _ = fs::remove_file(&lock_file);
                }

                // Apply force override
                if let Some(override_path) = override_path {
                    apply_dependency_override(
                        crate_path,
                        base_crate_name,
                        override_path,
                        DependencyOverrideMode::Force,
                    )?;
                    // Also apply [patch.crates-io] for transitive deps
                    apply_patch_crates_io(crate_path, base_crate_name, override_path)?;
                    debug!("Applied FORCE + [patch.crates-io] for auto-retry");
                }

                // Retry fetch and check
                let retry_fetch = compile_crate(crate_path, CompileStep::Fetch, None)?;
                if retry_fetch.success {
                    let retry_check = compile_crate(crate_path, CompileStep::Check, None)?;
                    if retry_check.success {
                        // Auto-retry succeeded! Continue with test step
                        debug!("Auto-retry with [patch.crates-io] succeeded!");

                        // Run test if not skipped
                        let test =
                            if !skip_test { Some(compile_crate(crate_path, CompileStep::Test, None)?) } else { None };

                        // Log test failure if needed
                        if let Some(ref test_result) = test
                            && test_result.failed()
                            && let (Some(dep_info), Some(label)) = (dependent_info.as_ref(), test_label)
                        {
                            log_failure_with_diagnostics(
                                dep_info.name,
                                dep_info.version,
                                base_crate_name,
                                label,
                                "cargo test",
                                None,
                                &test_result.stdout,
                                &test_result.stderr,
                                &test_result.diagnostics,
                            );
                        }

                        // Cleanup and return success with Patch depth
                        restore_cargo_toml(crate_path).ok();
                        let all_crate_versions = extract_all_crate_versions(crate_path, base_crate_name);

                        return Ok(ThreeStepResult {
                            fetch: retry_fetch,
                            check: Some(retry_check),
                            test,
                            actual_version: verify_dependency_version(crate_path, base_crate_name),
                            expected_version: expected_version.clone(),
                            forced_version: true,
                            original_requirement: original_requirement.clone(),
                            all_crate_versions,
                            patch_depth: PatchDepth::Patch, // !! marker
                        });
                    }
                    // Retry check also failed - check if still multi-version conflict
                    let retry_output = format!("{}\n{}", retry_check.stdout, retry_check.stderr);
                    let still_multi_version = has_multiple_version_conflict(&retry_output);

                    // Extract blocking crates for !!! case
                    let blocking_crates = if still_multi_version {
                        let crates = extract_crates_needing_patch(&retry_output, base_crate_name);
                        debug!("Auto-retry still has multi-version conflict - blocking crates: {:?}", crates);
                        // Convert to all_crate_versions format: (spec, version, crate_name)
                        crates.into_iter().map(|c| ("blocking".to_string(), "?".to_string(), c)).collect()
                    } else {
                        debug!("Auto-retry check failed with different error");
                        vec![]
                    };

                    restore_cargo_toml(crate_path).ok();
                    return Ok(ThreeStepResult {
                        fetch: retry_fetch,
                        check: Some(retry_check),
                        test: None,
                        actual_version: actual_version.clone(),
                        expected_version: expected_version.clone(),
                        forced_version: true,
                        original_requirement: original_requirement.clone(),
                        all_crate_versions: blocking_crates,
                        // !!! if still multi-version (deep transitive issue), !! otherwise
                        patch_depth: if still_multi_version { PatchDepth::DeepPatch } else { PatchDepth::Patch },
                    });
                }
                // Retry fetch failed - return original failure
                debug!("Auto-retry fetch failed");
                restore_cargo_toml(crate_path).ok();
            }

            // Check failed - stop here with dash for test
            return Ok(ThreeStepResult {
                fetch,
                check: Some(result),
                test: None,
                actual_version: actual_version.clone(),
                expected_version: expected_version.clone(),
                forced_version: force_versions,
                original_requirement: original_requirement.clone(),
                all_crate_versions: vec![],
                patch_depth: if force_versions { PatchDepth::Force } else { PatchDepth::None },
            });
        }
        Some(result)
    } else {
        None
    };

    // Step 3: Test (only if check succeeded or was skipped, and not skip_test)
    // If test fails with force_versions, check for multi-version conflicts in the dep tree
    // and retry with [patch.crates-io] (mirrors the check-step auto-retry logic).
    // This catches cases where dev-dependencies (only compiled during tests) bring in
    // a second version of the base crate, causing trait mismatches that the compiler
    // doesn't always annotate with "multiple different versions of crate".
    let (test, _test_patch_depth): (Option<CompileResult>, Option<PatchDepth>) = if !skip_test {
        let should_run = match &check {
            Some(c) => c.success,
            None => true, // check was skipped, proceed
        };

        if should_run {
            let result = compile_crate(crate_path, CompileStep::Test, override_spec)?;
            if result.failed() && force_versions {
                // Check if there are multiple resolved versions in the dep tree
                let multi_version_in_tree = has_multiple_resolved_versions(crate_path, base_crate_name);
                let combined_output = format!("{}\n{}", result.stdout, result.stderr);
                let multi_version_in_output = has_multiple_version_conflict(&combined_output);

                if multi_version_in_tree || multi_version_in_output {
                    debug!(
                        "Test failed with multi-version conflict (tree={}, output={}), attempting auto-retry with [patch.crates-io]",
                        multi_version_in_tree, multi_version_in_output
                    );

                    // Restore Cargo.toml and apply both force AND patch.crates-io
                    restore_cargo_toml(crate_path)?;
                    let lock_file = crate_path.join("Cargo.lock");
                    if lock_file.exists() {
                        let _ = fs::remove_file(&lock_file);
                    }

                    if let Some(op) = override_path {
                        apply_dependency_override(crate_path, base_crate_name, op, DependencyOverrideMode::Force)?;
                        apply_patch_crates_io(crate_path, base_crate_name, op)?;
                        debug!("Applied FORCE + [patch.crates-io] for test auto-retry");
                    }

                    // Retry fetch + check + test
                    let retry_fetch = compile_crate(crate_path, CompileStep::Fetch, None)?;
                    if retry_fetch.success {
                        let retry_check = compile_crate(crate_path, CompileStep::Check, None)?;
                        if retry_check.success {
                            let retry_test = compile_crate(crate_path, CompileStep::Test, None)?;

                            if let (Some(dep_info), Some(label)) = (dependent_info.as_ref(), test_label) {
                                if retry_test.failed() {
                                    log_failure_with_diagnostics(
                                        dep_info.name,
                                        dep_info.version,
                                        base_crate_name,
                                        label,
                                        "cargo test",
                                        None,
                                        &retry_test.stdout,
                                        &retry_test.stderr,
                                        &retry_test.diagnostics,
                                    );
                                }
                            }

                            restore_cargo_toml(crate_path).ok();
                            let all_crate_versions = extract_all_crate_versions(crate_path, base_crate_name);

                            return Ok(ThreeStepResult {
                                fetch: retry_fetch,
                                check: Some(retry_check),
                                test: Some(retry_test),
                                actual_version: verify_dependency_version(crate_path, base_crate_name),
                                expected_version: expected_version.clone(),
                                forced_version: true,
                                original_requirement: original_requirement.clone(),
                                all_crate_versions,
                                patch_depth: PatchDepth::Patch, // !! marker
                            });
                        }
                    }

                    // Retry failed, restore and fall through with original result
                    debug!("Test auto-retry with [patch.crates-io] failed");
                    restore_cargo_toml(crate_path).ok();
                }

                // Log original failure
                if let (Some(dep_info), Some(label)) = (dependent_info.as_ref(), test_label) {
                    log_failure_with_diagnostics(
                        dep_info.name,
                        dep_info.version,
                        base_crate_name,
                        label,
                        "cargo test",
                        None,
                        &result.stdout,
                        &result.stderr,
                        &result.diagnostics,
                    );
                }
                (Some(result), None)
            } else {
                if result.failed() {
                    if let (Some(dep_info), Some(label)) = (dependent_info.as_ref(), test_label) {
                        log_failure_with_diagnostics(
                            dep_info.name,
                            dep_info.version,
                            base_crate_name,
                            label,
                            "cargo test",
                            None,
                            &result.stdout,
                            &result.stderr,
                            &result.diagnostics,
                        );
                    }
                }
                (Some(result), None)
            }
        } else {
            (None, None)
        }
    } else {
        (None, None)
    };

    // Cleanup: Always restore Cargo.toml to original state
    // This handles both FORCE mode (where we modified it) and ensures clean state
    restore_cargo_toml(crate_path).ok(); // Ignore errors on cleanup
    debug!("Restored Cargo.toml to original state");

    // Extract all versions of the base crate from the dependency tree (if fetch succeeded)
    let all_crate_versions =
        if fetch.success { extract_all_crate_versions(crate_path, base_crate_name) } else { vec![] };

    // Determine patch depth based on mode
    let patch_depth = if force_versions && patch_transitive {
        PatchDepth::Patch // Force + explicit patch_transitive = !!
    } else if force_versions {
        PatchDepth::Force // Force only = !
    } else {
        PatchDepth::None // Natural resolution
    };

    Ok(ThreeStepResult {
        fetch,
        check,
        test,
        actual_version,
        expected_version,
        forced_version: force_versions,
        original_requirement,
        all_crate_versions,
        patch_depth,
    })
}

/// Check if the dependency tree has multiple distinct resolved versions of a crate.
/// This detects multi-version conflicts even when the compiler error message
/// doesn't explicitly mention "multiple different versions of crate".
fn has_multiple_resolved_versions(crate_dir: &Path, crate_name: &str) -> bool {
    let all_versions = extract_all_crate_versions(crate_dir, crate_name);
    let unique_versions: std::collections::HashSet<&String> =
        all_versions.iter().map(|(_, resolved, _)| resolved).collect();
    let result = unique_versions.len() > 1;
    if result {
        debug!(
            "Detected {} distinct resolved versions of '{}': {:?}",
            unique_versions.len(),
            crate_name,
            unique_versions
        );
    }
    result
}

/// Extract ALL versions of a crate from cargo metadata (for multi-version scenarios)
/// Returns Vec<(spec, resolved_version, dependent_name)>
fn extract_all_crate_versions(crate_dir: &Path, crate_name: &str) -> Vec<(String, String, String)> {
    let mut all_versions = Vec::new();

    debug!("extracting all versions of '{}' from cargo metadata", crate_name);

    // Run cargo metadata to get resolved dependencies
    let output = match Command::new("cargo").args(["metadata", "--format-version=1"]).current_dir(crate_dir).output() {
        Ok(o) => o,
        Err(e) => {
            debug!("failed to run cargo metadata: {}", e);
            return all_versions;
        }
    };

    if !output.status.success() {
        debug!("cargo metadata exited with error status");
        return all_versions;
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let parsed = match metadata::parse_metadata(&stdout) {
        Ok(p) => p,
        Err(e) => {
            debug!("failed to parse cargo metadata JSON: {}", e);
            return all_versions;
        }
    };

    // Find all versions of the target crate using the metadata module
    let version_infos = metadata::find_all_versions(&parsed, crate_name);
    debug!("processing {} version entries from cargo metadata", version_infos.len());

    for (idx, version_info) in version_infos.iter().enumerate() {
        // Extract the dependent name from the node_id
        let dependent_name = if let Some((name, _ver)) = metadata::parse_node_id(&version_info.node_id) {
            name
        } else {
            version_info.node_id.clone()
        };

        debug!(
            "  [{}]: spec='{}' resolved='{}' dependent='{}'",
            idx, version_info.spec, version_info.version, dependent_name
        );

        all_versions.push((version_info.spec.clone(), version_info.version.clone(), dependent_name));
    }

    debug!("extracted {} total version entries for '{}'", all_versions.len(), crate_name);

    // Check for multiple different resolved versions (version mismatch scenario)
    let unique_versions: std::collections::HashSet<&String> =
        all_versions.iter().map(|(_, resolved, _)| resolved).collect();

    if unique_versions.len() > 1 {
        // Multiple versions detected - log them with metadata context
        warn!("⚠️  Multiple versions of '{}' detected in dependency tree:", crate_name);

        // Log the raw metadata JSON for debugging (just the resolve section to keep it manageable)
        if let Some(resolve) = &parsed.resolve {
            debug!("Metadata resolve section (for debugging multi-version scenario):");
            if let Ok(pretty_json) = serde_json::to_string_pretty(resolve) {
                // Log first MAX_METADATA_LOG_LINES to avoid overwhelming logs
                for (idx, line) in pretty_json.lines().enumerate() {
                    if idx >= MAX_METADATA_LOG_LINES {
                        debug!("  ... ({} more lines truncated)", pretty_json.lines().count() - MAX_METADATA_LOG_LINES);
                        break;
                    }
                    debug!("  {}", line);
                }
            }
        }
        for (spec, resolved, dependent) in &all_versions {
            warn!("  {} requires {} → resolved to {} (via {})", dependent, spec, resolved, crate_name);
        }

        // Log to failure log file if initialized
        if let Some(ref log_path) = *FAILURE_LOG.lock().unwrap()
            && let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(log_path)
        {
            let _ = writeln!(file, "\n=== Multi-version detection for '{}' ===", crate_name);
            for (spec, resolved, dependent) in &all_versions {
                let _ = writeln!(file, "  {} requires {} → resolved to {}", dependent, spec, resolved);
            }
        }
    }

    all_versions
}

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

    #[test]
    fn test_compile_step_as_str() {
        assert_eq!(CompileStep::Check.as_str(), "check");
        assert_eq!(CompileStep::Test.as_str(), "test");
    }

    #[test]
    fn test_compile_step_cargo_subcommand() {
        assert_eq!(CompileStep::Check.cargo_subcommand(), "check");
        assert_eq!(CompileStep::Test.cargo_subcommand(), "test");
    }

    #[test]
    fn test_compile_result_failed() {
        let result = CompileResult {
            step: CompileStep::Check,
            success: false,
            stdout: String::new(),
            stderr: String::new(),
            duration: Duration::from_secs(1),
            diagnostics: Vec::new(),
        };
        assert!(result.failed());

        let result = CompileResult {
            step: CompileStep::Check,
            success: true,
            stdout: String::new(),
            stderr: String::new(),
            duration: Duration::from_secs(1),
            diagnostics: Vec::new(),
        };
        assert!(!result.failed());
    }

    #[test]
    fn test_apply_patch_crates_io() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let crate_path = temp_dir.path();

        // Create a basic Cargo.toml
        let cargo_toml = crate_path.join("Cargo.toml");
        fs::write(
            &cargo_toml,
            r#"[package]
name = "test-crate"
version = "0.1.0"

[dependencies]
rgb = "0.8.50"
"#,
        )
        .unwrap();

        // Apply the patch
        let override_path = PathBuf::from("/some/local/path");
        apply_patch_crates_io(crate_path, "rgb", &override_path).unwrap();

        // Verify the result
        let content = fs::read_to_string(&cargo_toml).unwrap();
        assert!(content.contains("[patch.crates-io]"), "Should have [patch.crates-io] section");
        assert!(content.contains("rgb"), "Should have rgb entry");
        assert!(content.contains("/some/local/path"), "Should have the override path");
    }

    #[test]
    fn test_apply_patch_crates_io_preserves_existing_content() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let crate_path = temp_dir.path();

        // Create a Cargo.toml with existing patch section
        let cargo_toml = crate_path.join("Cargo.toml");
        fs::write(
            &cargo_toml,
            r#"[package]
name = "test-crate"
version = "0.1.0"

[dependencies]
rgb = "0.8.50"
serde = "1.0"

[patch.crates-io]
other-crate = { path = "/other/path" }
"#,
        )
        .unwrap();

        // Apply the patch
        let override_path = PathBuf::from("/rgb/path");
        apply_patch_crates_io(crate_path, "rgb", &override_path).unwrap();

        // Verify the result
        let content = fs::read_to_string(&cargo_toml).unwrap();
        assert!(content.contains("other-crate"), "Should preserve existing patches");
        assert!(content.contains("/other/path"), "Should preserve existing patch path");
        assert!(content.contains("/rgb/path"), "Should have new rgb path");
    }
}