jonesy 0.7.11

Jonesy is here to help you not panic!
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
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
use crate::cargo::{find_binary, find_library};
use cargo_toml::Manifest;
use std::path::{Path, PathBuf};

/// Output format and display configuration for analysis results.
/// Consolidates format selection with display options.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OutputFormat {
    /// Human-readable terminal output
    Text {
        /// Show full call tree instead of just crate code points
        tree: bool,
        /// Only show summary, not detailed panic points
        summary_only: bool,
        /// Suppress progress messages
        quiet: bool,
        /// Use terminal hyperlinks for file paths
        hyperlinks: bool,
    },
    /// Machine-readable JSON output (implies quiet)
    Json {
        /// Show full call tree (children) instead of flat list
        tree: bool,
        /// Only include summary, not detailed panic points
        summary_only: bool,
    },
    /// Self-contained HTML report (implies quiet)
    Html {
        /// Show full call tree instead of flat list
        tree: bool,
        /// Only include summary, not detailed panic points
        summary_only: bool,
    },
}

impl Default for OutputFormat {
    fn default() -> Self {
        OutputFormat::Text {
            tree: false,
            summary_only: false,
            quiet: false,
            hyperlinks: true,
        }
    }
}

impl OutputFormat {
    /// Create a text output format with the given options
    pub fn text(tree: bool, summary_only: bool, quiet: bool, hyperlinks: bool) -> Self {
        OutputFormat::Text {
            tree,
            summary_only,
            quiet,
            hyperlinks,
        }
    }

    /// Create a JSON output format with the given options
    pub fn json(tree: bool, summary_only: bool) -> Self {
        OutputFormat::Json { tree, summary_only }
    }

    /// Create an HTML output format with the given options
    pub fn html(tree: bool, summary_only: bool) -> Self {
        OutputFormat::Html { tree, summary_only }
    }

    /// Create a quiet text output format (for LSP/programmatic use)
    pub fn quiet() -> Self {
        OutputFormat::Text {
            tree: false,
            summary_only: false,
            quiet: true,
            hyperlinks: false,
        }
    }

    /// Returns true if this is JSON output
    pub fn is_json(&self) -> bool {
        matches!(self, OutputFormat::Json { .. })
    }

    /// Returns true if this is HTML output
    pub fn is_html(&self) -> bool {
        matches!(self, OutputFormat::Html { .. })
    }

    /// Returns true if this is text output
    pub fn is_text(&self) -> bool {
        matches!(self, OutputFormat::Text { .. })
    }

    /// Returns true if progress messages should be shown
    pub fn show_progress(&self) -> bool {
        match self {
            OutputFormat::Text {
                quiet,
                summary_only,
                ..
            } => !quiet && !summary_only,
            OutputFormat::Json { .. } | OutputFormat::Html { .. } => false,
        }
    }

    /// Returns true if only the summary should be shown (no panic point details)
    pub fn is_summary_only(&self) -> bool {
        match self {
            OutputFormat::Text { summary_only, .. }
            | OutputFormat::Json { summary_only, .. }
            | OutputFormat::Html { summary_only, .. } => *summary_only,
        }
    }

    /// Returns true if the full call tree should be shown
    pub fn show_tree(&self) -> bool {
        match self {
            OutputFormat::Text { tree, .. }
            | OutputFormat::Json { tree, .. }
            | OutputFormat::Html { tree, .. } => *tree,
        }
    }

    /// Returns true if hyperlinks should be used in output
    pub fn use_hyperlinks(&self) -> bool {
        match self {
            OutputFormat::Text { hyperlinks, .. } => *hyperlinks,
            OutputFormat::Json { .. } | OutputFormat::Html { .. } => false,
        }
    }
}

/// Represents a workspace member crate with its binaries
#[derive(Debug)]
pub struct WorkspaceMember {
    /// Name of the member crate
    pub name: String,
    /// Path to the member crate directory
    pub path: PathBuf,
    /// Paths to binaries for this member
    pub binaries: Vec<PathBuf>,
}

/// Parsed command line arguments
pub struct Args {
    /// Paths to binaries to analyze (for non-workspace mode)
    pub binaries: Vec<PathBuf>,
    /// Workspace members to analyze (for workspace mode)
    pub workspace_members: Option<Vec<WorkspaceMember>>,
    /// Whether to show timing information (--show-timings flag)
    pub show_timings: bool,
    /// Maximum number of threads to use for parallel analysis
    pub max_threads: usize,
    /// Optional path to config file (--config flag)
    pub config_path: Option<PathBuf>,
    /// Output format and display options
    pub output: OutputFormat,
    /// Run in LSP server mode
    pub lsp_mode: bool,
}

/// The version of jonesy, read from Cargo.toml at compile time.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Parse command line arguments.
///
/// Modes:
/// 1) No arguments (run from crate root)
///    Parse Cargo.toml to find package name and binary targets,
///    then look for binaries in target/debug/
/// 2) --bin <path>
///    Analyze the specified binary file
/// 3) --lib <path>
///    Analyze the specified library object file
///
/// Optional flags:
/// --tree           Show the full call tree instead of just crate code points
/// --summary-only   Only show summary output, not detailed panic points
/// --max-threads N  Maximum threads for parallel analysis (default: number of CPUs)
/// --config <path>  Path to a TOML config file for allow/deny rules
/// --version        Print version and exit
pub fn parse_args(args: &[String]) -> Result<Args, String> {
    // Handle --version flag early
    if args.iter().any(|a| a == "--version" || a == "-V") {
        println!("jonesy {}", VERSION);
        std::process::exit(0);
    }

    // Check for lsp subcommand
    if args.get(1).is_some_and(|a| a == "lsp") {
        return Ok(Args {
            binaries: Vec::new(),
            workspace_members: None,
            show_timings: false,
            max_threads: 1,
            config_path: None,
            output: OutputFormat::default(),
            lsp_mode: true,
        });
    }

    // Check for flags
    let show_tree = args.iter().any(|a| a == "--tree");
    let summary_only = args.iter().any(|a| a == "--summary-only");
    let show_timings = args.iter().any(|a| a == "--show-timings");
    let quiet = args.iter().any(|a| a == "--quiet");
    let no_hyperlinks = args.iter().any(|a| a == "--no-hyperlinks");

    // Parse --format option with validation
    let output = parse_output_format(args, show_tree, summary_only, quiet, no_hyperlinks)?;

    // Parse --max-threads option
    let max_threads = parse_max_threads(args)?;

    // Parse --config option
    let config_path = parse_config_path(args)?;

    // Filter out standalone flags from args for path parsing
    // Keep --bin and --lib with their arguments for separate processing
    let filtered_args: Vec<&String> = args
        .iter()
        .enumerate()
        .filter(|(i, a)| {
            *a != "--tree"
                && *a != "--summary-only"
                && *a != "--show-timings"
                && *a != "--quiet"
                && *a != "--no-hyperlinks"
                && *a != "--max-threads"
                && *a != "--config"
                && *a != "--format"
                && !(*i > 0 && args.get(i - 1).is_some_and(|prev| prev == "--max-threads"))
                && !(*i > 0 && args.get(i - 1).is_some_and(|prev| prev == "--config"))
                && !(*i > 0 && args.get(i - 1).is_some_and(|prev| prev == "--format"))
        })
        .map(|(_, a)| a)
        .collect();

    // Check for --bin or --lib flags
    let has_bin_flag = filtered_args.iter().any(|a| *a == "--bin");
    let has_lib_flag = filtered_args.iter().any(|a| *a == "--lib");

    if has_bin_flag && has_lib_flag {
        return Err("--bin and --lib are mutually exclusive".to_string());
    }

    // Check if running from a workspace root first
    let at_workspace_root = is_workspace_root();

    // Reject --bin and --lib at workspace level
    if at_workspace_root && (has_bin_flag || has_lib_flag) {
        return Err("--bin and --lib are not supported at workspace level. \
             cd into a member crate directory for target-specific analysis."
            .to_string());
    }

    let (binaries, workspace_members) = if has_bin_flag {
        (parse_bin_args(&filtered_args)?, None)
    } else if has_lib_flag {
        (parse_lib_args(&filtered_args)?, None)
    } else if filtered_args.len() == 1 {
        // No arguments besides program name - try to find binaries from Cargo.toml
        // Check if this is a workspace root first
        if let Some(members) = find_workspace_members()? {
            (vec![], Some(members))
        } else {
            (find_crate_binaries()?, None)
        }
    } else {
        return Err(usage());
    };

    Ok(Args {
        binaries,
        workspace_members,
        show_timings,
        max_threads,
        config_path,
        output,
        lsp_mode: false,
    })
}

/// Parse --max-threads option, defaulting to number of available CPUs
fn parse_max_threads(args: &[String]) -> Result<usize, String> {
    for (i, arg) in args.iter().enumerate() {
        if arg == "--max-threads" {
            let value = args
                .get(i + 1)
                .ok_or("--max-threads requires a number argument")?;
            let n: usize = value
                .parse()
                .map_err(|_| format!("Invalid --max-threads value: {}", value))?;
            if n == 0 {
                return Err("--max-threads must be at least 1".to_string());
            }
            return Ok(n);
        }
    }
    // Default to number of available CPUs
    Ok(std::thread::available_parallelism()
        .map(|n| n.get())
        .unwrap_or(1))
}

/// Parse --config option for custom config file path
fn parse_config_path(args: &[String]) -> Result<Option<PathBuf>, String> {
    for (i, arg) in args.iter().enumerate() {
        if arg == "--config" {
            let value = args.get(i + 1).ok_or("--config requires a path argument")?;
            let path = PathBuf::from(value);
            if !path.exists() {
                return Err(format!("Config file not found: {}", path.display()));
            }
            return Ok(Some(path));
        }
    }
    Ok(None)
}

/// Parse --format option and build OutputFormat with proper validation
fn parse_output_format(
    args: &[String],
    show_tree: bool,
    summary_only: bool,
    quiet: bool,
    no_hyperlinks: bool,
) -> Result<OutputFormat, String> {
    for (i, arg) in args.iter().enumerate() {
        if arg == "--format" {
            let value = args
                .get(i + 1)
                .ok_or("--format requires an argument (text, json, or html)")?;
            return match value.to_lowercase().as_str() {
                "text" => Ok(OutputFormat::text(
                    show_tree,
                    summary_only,
                    quiet,
                    !no_hyperlinks,
                )),
                "json" => Ok(OutputFormat::json(show_tree, summary_only)),
                "html" => Ok(OutputFormat::html(show_tree, summary_only)),
                _ => Err(format!(
                    "Invalid format '{}'. Valid options: text, json, html",
                    value
                )),
            };
        }
    }
    // No --format flag, default to text
    Ok(OutputFormat::text(
        show_tree,
        summary_only,
        quiet,
        !no_hyperlinks,
    ))
}

fn usage() -> String {
    format!(
        "jonesy {} - Find panic points in Rust binaries\n\n\
         Usage:\n  \
         jonesy [OPTIONS]\n  \
         jonesy [OPTIONS] --bin <name_or_path>\n  \
         jonesy [OPTIONS] --lib [path_to_lib_object]\n  \
         jonesy lsp\n\n\
         When run without --bin or --lib, jonesy looks for Cargo.toml in the current\n\
         directory and analyzes all binary targets found in target/debug/.\n\n\
         Subcommands:\n  \
         lsp                Start LSP server for IDE integration\n\n\
         Options:\n  \
         --bin <name>       Analyze only the specified binary (by name or path)\n  \
         --lib              Analyze only the library target\n  \
         --tree             Show full call tree instead of just crate code points\n  \
         --summary-only     Only show summary, not detailed panic points\n  \
         --quiet            Suppress progress messages (keeps panic points and summary)\n  \
         --show-timings     Show timing information for each analysis step\n  \
         --max-threads N    Maximum threads for parallel analysis (default: CPU count)\n  \
         --config <path>    Path to TOML config file for allow/deny rules\n  \
         --no-hyperlinks    Disable terminal hyperlinks (use plain absolute paths)\n  \
         --format <fmt>     Output format: text (default), json, html\n  \
         --version, -V      Print version and exit",
        VERSION
    )
}

/// Find target/debug directory, checking current directory and walking up to workspace root
fn find_target_dir() -> Result<PathBuf, String> {
    let mut current =
        std::env::current_dir().map_err(|e| format!("Cannot get current dir: {}", e))?;

    loop {
        let target_dir = current.join("target/debug");
        if target_dir.exists() {
            return Ok(target_dir);
        }

        // Check if this is a workspace root (has [workspace] in Cargo.toml)
        let cargo_toml = current.join("Cargo.toml");
        if cargo_toml.exists()
            && let Ok(content) = std::fs::read_to_string(&cargo_toml)
            && content.contains("[workspace]")
        {
            // This is workspace root but no target/debug
            return Err("target/debug/ directory not found. Run 'cargo build' first.".to_string());
        }

        // Move up one directory
        if let Some(parent) = current.parent() {
            current = parent.to_path_buf();
        } else {
            break;
        }
    }

    Err("target/debug/ directory not found. Run 'cargo build' first.".to_string())
}

/// Check if the current directory is a workspace root (virtual or non-virtual).
/// Virtual workspace: has [workspace] but no [package]
/// Non-virtual workspace: has both [workspace] and [package]
/// Uses from_slice to avoid workspace inheritance resolution issues.
fn is_workspace_root() -> bool {
    let cargo_toml_path = PathBuf::from("Cargo.toml");
    if !cargo_toml_path.exists() {
        return false;
    }

    let Ok(content) = std::fs::read_to_string(&cargo_toml_path) else {
        return false;
    };

    // Use from_slice to avoid workspace inheritance resolution
    let Ok(manifest) = Manifest::from_slice(content.as_bytes()) else {
        return false;
    };

    manifest.workspace.is_some()
}

/// Check if running from a workspace root and return workspace members.
/// Handles both virtual workspaces (no [package]) and non-virtual workspaces
/// (has both [workspace] and [package]).
fn find_workspace_members() -> Result<Option<Vec<WorkspaceMember>>, String> {
    let cargo_toml_path = PathBuf::from("Cargo.toml");
    if !cargo_toml_path.exists() {
        return Ok(None);
    }

    let cargo_toml_content = std::fs::read_to_string(&cargo_toml_path)
        .map_err(|e| format!("Failed to read Cargo.toml: {}", e))?;

    // Use from_slice to avoid workspace inheritance resolution issues
    let manifest = Manifest::from_slice(cargo_toml_content.as_bytes())
        .map_err(|e| format!("Failed to parse Cargo.toml: {}", e))?;

    // Only proceed if this is a workspace root
    if manifest.workspace.is_none() {
        return Ok(None);
    }

    let workspace = manifest.workspace.as_ref().unwrap();
    let target_dir = PathBuf::from("target/debug");
    if !target_dir.exists() {
        return Err("target/debug/ directory not found. Run 'cargo build' first.".to_string());
    }

    let mut members = Vec::new();

    // For non-virtual workspaces, include the root package as a member
    if let Some(pkg) = &manifest.package {
        let pkg_name = pkg.name.clone();
        // Complete the manifest to discover implicit targets
        let mut root_manifest = manifest.clone();
        let _ = root_manifest.complete_from_path_and_workspace::<toml::Value>(
            &cargo_toml_path,
            None::<(&Manifest<toml::Value>, &std::path::Path)>, // No parent workspace for the root
        );
        let binaries = collect_binaries_from_manifest(&root_manifest, &pkg_name, &target_dir);
        if !binaries.is_empty() {
            members.push(WorkspaceMember {
                name: pkg_name,
                path: PathBuf::from("."),
                binaries,
            });
        }
    }

    // Iterate through workspace members
    for member_pattern in &workspace.members {
        // Handle glob patterns (e.g., "examples/*")
        let member_paths = if member_pattern.contains('*') {
            let base = member_pattern.trim_end_matches("/*").trim_end_matches("/*");
            let base_path = PathBuf::from(base);
            if base_path.is_dir() {
                std::fs::read_dir(&base_path)
                    .map(|entries| {
                        entries
                            .filter_map(|e| e.ok())
                            .filter(|e| e.path().is_dir())
                            .map(|e| e.path())
                            .collect::<Vec<_>>()
                    })
                    .unwrap_or_default()
            } else {
                vec![]
            }
        } else {
            vec![PathBuf::from(member_pattern)]
        };

        for member_path in member_paths {
            let member_cargo_toml = member_path.join("Cargo.toml");
            if !member_cargo_toml.exists() {
                continue;
            }

            // Parse manifest and complete it with workspace context for implicit target discovery
            if let Ok(content) = std::fs::read_to_string(&member_cargo_toml)
                && let Ok(mut member_manifest) = Manifest::from_slice(content.as_bytes())
                && let Some(pkg) = &member_manifest.package
            {
                let pkg_name = pkg.name.clone();

                // Complete the manifest to discover implicit targets (src/main.rs, src/lib.rs, etc.)
                // Pass the workspace manifest to avoid resolution errors
                let _ = member_manifest.complete_from_path_and_workspace(
                    &member_cargo_toml,
                    Some((&manifest, &cargo_toml_path)),
                );

                let binaries =
                    collect_binaries_from_manifest(&member_manifest, &pkg_name, &target_dir);

                // Only add member if it has binaries
                if !binaries.is_empty() {
                    members.push(WorkspaceMember {
                        name: pkg_name,
                        path: member_path,
                        binaries,
                    });
                }
            }
        }
    }

    if members.is_empty() {
        return Err("No binary targets found in workspace. Run 'cargo build' first.".to_string());
    }

    Ok(Some(members))
}

/// Collect binaries from a parsed manifest
fn collect_binaries_from_manifest(
    manifest: &Manifest,
    pkg_name: &str,
    target_dir: &Path,
) -> Vec<PathBuf> {
    let mut binaries = Vec::new();

    // Check for [[bin]] targets (populated by complete_from_path_and_workspace)
    // No fallback probe needed - complete_from_path_and_workspace populates bin if there's a binary
    for bin in &manifest.bin {
        let bin_name = bin.name.as_deref().unwrap_or(pkg_name);
        if let Some(bin_path) = find_binary(target_dir, bin_name) {
            binaries.push(bin_path);
        }
    }

    // Check for library target
    if manifest.lib.is_some() {
        let lib_name = manifest
            .lib
            .as_ref()
            .and_then(|l| l.name.clone())
            .unwrap_or_else(|| pkg_name.replace('-', "_"));

        if let Some(lib_path) = find_library(target_dir, &lib_name) {
            binaries.push(lib_path);
        }
    }

    binaries
}

/// Find binaries for all workspace members
fn find_workspace_binaries(manifest: &Manifest) -> Result<Vec<PathBuf>, String> {
    let workspace = manifest
        .workspace
        .as_ref()
        .ok_or("No workspace section found")?;

    let target_dir = PathBuf::from("target/debug");
    if !target_dir.exists() {
        return Err("target/debug/ directory not found. Run 'cargo build' first.".to_string());
    }

    let mut binaries = Vec::new();

    // Iterate through workspace members
    for member_pattern in &workspace.members {
        // Handle glob patterns (e.g., "examples/*")
        let member_paths = if member_pattern.contains('*') {
            // Simple glob expansion for common patterns like "examples/*"
            let base = member_pattern.trim_end_matches("/*").trim_end_matches("/*");
            let base_path = PathBuf::from(base);
            if base_path.is_dir() {
                std::fs::read_dir(&base_path)
                    .map(|entries| {
                        entries
                            .filter_map(|e| e.ok())
                            .filter(|e| e.path().is_dir())
                            .map(|e| e.path())
                            .collect::<Vec<_>>()
                    })
                    .unwrap_or_default()
            } else {
                vec![]
            }
        } else {
            vec![PathBuf::from(member_pattern)]
        };

        for member_path in member_paths {
            let member_cargo_toml = member_path.join("Cargo.toml");
            if !member_cargo_toml.exists() {
                continue;
            }

            if let Ok(content) = std::fs::read_to_string(&member_cargo_toml)
                && let Ok(member_manifest) = Manifest::from_slice(content.as_bytes())
                && let Some(pkg) = &member_manifest.package
            {
                let pkg_name = &pkg.name;

                // Check for explicit [[bin]] targets
                for bin in &member_manifest.bin {
                    let bin_name = bin.name.as_ref().unwrap_or(pkg_name);
                    let bin_path = target_dir.join(bin_name);
                    if bin_path.exists() {
                        binaries.push(bin_path);
                    }
                }

                // Check for default binary
                if member_manifest.bin.is_empty() {
                    let default_bin = target_dir.join(pkg_name);
                    if default_bin.exists() {
                        binaries.push(default_bin);
                    }
                }
            }
        }
    }

    if binaries.is_empty() {
        return Err("No binary targets found in workspace. Run 'cargo build' first.".to_string());
    }

    Ok(binaries)
}

/// Find binary targets by parsing Cargo.toml in the current directory
fn find_crate_binaries() -> Result<Vec<PathBuf>, String> {
    let cargo_toml_path = PathBuf::from("Cargo.toml");
    if !cargo_toml_path.exists() {
        return Err("No Cargo.toml found in current directory. \
                    Run jonesy from a crate root or use --bin <path>."
            .to_string());
    }

    // Read and parse without resolving workspace dependencies
    let cargo_toml_content = std::fs::read_to_string(&cargo_toml_path)
        .map_err(|e| format!("Failed to read Cargo.toml: {}", e))?;

    let manifest = Manifest::from_slice(cargo_toml_content.as_bytes())
        .map_err(|e| format!("Failed to parse Cargo.toml: {}", e))?;

    // Check if this is a workspace root
    if manifest.workspace.is_some() && manifest.package.is_none() {
        return find_workspace_binaries(&manifest);
    }

    let package = manifest
        .package
        .as_ref()
        .ok_or("Cargo.toml has no [package] section")?;

    let package_name = &package.name;

    // Look for target/debug in current directory or walk up to find workspace root
    let target_dir = find_target_dir()?;

    let mut binaries = Vec::new();

    // Check for explicit [[bin]] targets
    for bin in &manifest.bin {
        let bin_name = bin.name.as_ref().unwrap_or(package_name);
        let bin_path = target_dir.join(bin_name);
        if bin_path.exists() {
            binaries.push(bin_path);
        }
    }

    // If no explicit [[bin]] targets, check for default binary (same name as package)
    // This happens when there's a src/main.rs
    if manifest.bin.is_empty() {
        let default_bin = target_dir.join(package_name);
        if default_bin.exists() {
            binaries.push(default_bin);
        }
    }

    // Check for library target
    if manifest.lib.is_some() {
        // Library name defaults to package name with hyphens replaced by underscores
        let lib_name = manifest
            .lib
            .as_ref()
            .and_then(|l| l.name.clone())
            .unwrap_or_else(|| package_name.replace('-', "_"));

        // On macOS, look for .dylib or .rlib
        let dylib_path = target_dir.join(format!("lib{}.dylib", lib_name));
        let rlib_path = target_dir.join(format!("lib{}.rlib", lib_name));

        if dylib_path.exists() {
            binaries.push(dylib_path);
        } else if rlib_path.exists() {
            binaries.push(rlib_path);
        }
    }

    if binaries.is_empty() {
        return Err(format!(
            "No binary targets found in target/debug/ for package '{}'. \
             Run 'cargo build' first.",
            package_name
        ));
    }

    Ok(binaries)
}

/// Extract the binary name/path argument from --bin flag.
///
/// Returns the argument value after --bin, or an error if:
/// - --bin flag is not found
/// - No value follows --bin
/// - There are unexpected trailing positional arguments
///
/// This is a pure function that only examines the args slice.
fn extract_bin_arg<'a>(args: &[&'a String]) -> Result<&'a str, String> {
    let bin_arg_idx = args
        .iter()
        .position(|a| *a == "--bin")
        .ok_or("--bin flag not found")?;

    let bin_name = args
        .get(bin_arg_idx + 1)
        .ok_or("--bin requires a binary name or path")?;

    // Reject unexpected trailing positional args
    if let Some(extra) = args.get(bin_arg_idx + 2) {
        if !extra.starts_with("--") {
            return Err(format!(
                "Unexpected extra argument '{}' after --bin <name_or_path>",
                extra
            ));
        }
    }

    Ok(bin_name.as_str())
}

/// Find a binary by name in a manifest's [[bin]] targets.
///
/// Returns the binary path if found, None otherwise.
/// Handles hyphen/underscore normalization (e.g., "my-bin" matches "my_bin").
fn find_bin_in_manifest(bin_name: &str, manifest: &Manifest, target_dir: &Path) -> Option<PathBuf> {
    // Check [[bin]] targets
    for bin in &manifest.bin {
        let manifest_bin_name = bin
            .name
            .as_ref()
            .or(manifest.package.as_ref().map(|p| &p.name));
        if let Some(name) = manifest_bin_name {
            if name == bin_name || name.replace('-', "_") == bin_name {
                let bin_path = target_dir.join(name);
                if bin_path.exists() {
                    return Some(bin_path);
                }
            }
        }
    }

    // Check package name (default binary)
    if let Some(pkg) = &manifest.package {
        if pkg.name == bin_name || pkg.name.replace('-', "_") == bin_name {
            let bin_path = target_dir.join(&pkg.name);
            if bin_path.exists() {
                return Some(bin_path);
            }
        }
    }

    None
}

/// Parse --bin name_or_path
/// Can be either a path to a binary or a binary name to look up in Cargo.toml
fn parse_bin_args(args: &[&String]) -> Result<Vec<PathBuf>, String> {
    let bin_name = extract_bin_arg(args)?;
    let binary_path = PathBuf::from(bin_name);

    // First check if it's a path that exists
    if binary_path.exists() {
        std::fs::File::open(&binary_path)
            .map_err(|e| format!("Cannot read binary at {:?}: {}", binary_path, e))?;
        return Ok(vec![binary_path]);
    }

    // Otherwise, treat it as a binary name and look it up in Cargo.toml
    let cargo_toml_path = PathBuf::from("Cargo.toml");
    if !cargo_toml_path.exists() {
        return Err(format!(
            "Binary '{}' not found and no Cargo.toml in current directory",
            bin_name
        ));
    }

    let cargo_toml_content = std::fs::read_to_string(&cargo_toml_path)
        .map_err(|e| format!("Failed to read Cargo.toml: {}", e))?;

    let manifest = Manifest::from_slice(cargo_toml_content.as_bytes())
        .map_err(|e| format!("Failed to parse Cargo.toml: {}", e))?;

    // Look for target/debug directory
    let target_dir = find_target_dir()?;

    // Check if this binary name matches any [[bin]] target or package name
    if let Some(bin_path) = find_bin_in_manifest(bin_name, &manifest, &target_dir) {
        return Ok(vec![bin_path]);
    }

    // If this is a workspace, search workspace members
    if manifest.workspace.is_some() {
        if let Ok(workspace_binaries) = find_workspace_binaries(&manifest) {
            for bin_path in workspace_binaries {
                if let Some(name) = bin_path.file_name().and_then(|n| n.to_str()) {
                    if name == bin_name || name.replace('-', "_") == bin_name {
                        return Ok(vec![bin_path]);
                    }
                }
            }
        }
    }

    Err(format!(
        "Binary '{}' not found in Cargo.toml or target/debug/",
        bin_name
    ))
}

/// Extract the optional library path argument from --lib flag.
///
/// Returns Ok(Some(path)) if --lib has a path argument
/// Returns Ok(None) if --lib is used without a path (use Cargo.toml lookup)
/// Returns Err if --lib flag not found or there are unexpected trailing args
///
/// This is a pure function that only examines the args slice.
fn extract_lib_arg<'a>(args: &[&'a String]) -> Result<Option<&'a str>, String> {
    let lib_arg_idx = args
        .iter()
        .position(|a| *a == "--lib")
        .ok_or("--lib flag not found")?;

    // Check if there's an argument after --lib that isn't another flag
    let lib_path_arg = args.get(lib_arg_idx + 1).filter(|a| !a.starts_with("--"));

    // Reject unexpected trailing positional args
    if lib_path_arg.is_some() {
        if let Some(extra) = args.get(lib_arg_idx + 2) {
            if !extra.starts_with("--") {
                return Err(format!(
                    "Unexpected extra argument '{}' after --lib [path_to_lib_object]",
                    extra
                ));
            }
        }
    }

    Ok(lib_path_arg.map(|s| s.as_str()))
}

/// Determine the library name from a manifest.
///
/// Returns the library name from [lib] section if present,
/// otherwise derives it from package name (replacing hyphens with underscores).
fn get_lib_name(manifest: &Manifest) -> Option<String> {
    manifest
        .lib
        .as_ref()
        .and_then(|l| l.name.clone())
        .or_else(|| manifest.package.as_ref().map(|p| p.name.replace('-', "_")))
}

/// Find a library file by name in the target directory.
///
/// Checks for .dylib, .rlib, and .a files in order.
/// Returns the first existing library path, or None if not found.
fn find_lib_in_target(lib_name: &str, target_dir: &Path) -> Option<PathBuf> {
    let dylib_path = target_dir.join(format!("lib{}.dylib", lib_name));
    let rlib_path = target_dir.join(format!("lib{}.rlib", lib_name));
    let staticlib_path = target_dir.join(format!("lib{}.a", lib_name));

    if dylib_path.exists() {
        Some(dylib_path)
    } else if rlib_path.exists() {
        Some(rlib_path)
    } else if staticlib_path.exists() {
        Some(staticlib_path)
    } else {
        None
    }
}

/// Parse --lib [path_to_library_object]
/// If a path is provided, use it directly.
/// Otherwise, find the library target from Cargo.toml
fn parse_lib_args(args: &[&String]) -> Result<Vec<PathBuf>, String> {
    let lib_path_arg = extract_lib_arg(args)?;

    if let Some(path_str) = lib_path_arg {
        let binary_path = PathBuf::from(path_str);
        if !binary_path.exists() {
            return Err(format!(
                "Library shared object not found at {:?}",
                binary_path
            ));
        }
        std::fs::File::open(&binary_path).map_err(|e| {
            format!(
                "Cannot read Library shared object at {:?}: {}",
                binary_path, e
            )
        })?;
        return Ok(vec![binary_path]);
    }

    // No path provided - find the library from Cargo.toml
    let cargo_toml_path = PathBuf::from("Cargo.toml");
    if !cargo_toml_path.exists() {
        return Err("No Cargo.toml found. Use --lib <path> to specify library path.".to_string());
    }

    let cargo_toml_content = std::fs::read_to_string(&cargo_toml_path)
        .map_err(|e| format!("Failed to read Cargo.toml: {}", e))?;

    let manifest = Manifest::from_slice(cargo_toml_content.as_bytes())
        .map_err(|e| format!("Failed to parse Cargo.toml: {}", e))?;

    // Check for explicit [lib] or implicit library (src/lib.rs)
    let has_implicit_lib = PathBuf::from("src/lib.rs").exists();
    if manifest.lib.is_none() && !has_implicit_lib {
        return Err("No library target found in Cargo.toml or src/lib.rs".to_string());
    }

    let target_dir = find_target_dir()?;

    let lib_name = get_lib_name(&manifest).ok_or("Cannot determine library name")?;

    find_lib_in_target(&lib_name, &target_dir)
        .map(|p| vec![p])
        .ok_or_else(|| {
            format!(
                "Library 'lib{}' not found in target/debug/. Run 'cargo build' first.",
                lib_name
            )
        })
}

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

    // ========================================================================
    // OutputFormat tests
    // ========================================================================

    #[test]
    fn test_output_format_default() {
        let format = OutputFormat::default();
        assert!(format.is_text());
        assert!(!format.is_json());
        assert!(!format.is_html());
        assert!(format.show_progress());
        assert!(!format.is_summary_only());
        assert!(!format.show_tree());
        assert!(format.use_hyperlinks());
    }

    #[test]
    fn test_output_format_text_constructor() {
        let format = OutputFormat::text(true, true, true, false);
        assert!(format.is_text());
        assert!(format.show_tree());
        assert!(format.is_summary_only());
        assert!(!format.show_progress()); // quiet=true means no progress
        assert!(!format.use_hyperlinks());
    }

    #[test]
    fn test_output_format_json_constructor() {
        let format = OutputFormat::json(true, false);
        assert!(format.is_json());
        assert!(!format.is_text());
        assert!(!format.is_html());
        assert!(format.show_tree());
        assert!(!format.is_summary_only());
        assert!(!format.show_progress()); // JSON never shows progress
        assert!(!format.use_hyperlinks()); // JSON never uses hyperlinks
    }

    #[test]
    fn test_output_format_html_constructor() {
        let format = OutputFormat::html(false, true);
        assert!(format.is_html());
        assert!(!format.is_text());
        assert!(!format.is_json());
        assert!(!format.show_tree());
        assert!(format.is_summary_only());
        assert!(!format.show_progress()); // HTML never shows progress
        assert!(!format.use_hyperlinks()); // HTML never uses hyperlinks
    }

    #[test]
    fn test_output_format_quiet() {
        let format = OutputFormat::quiet();
        assert!(format.is_text());
        assert!(!format.show_progress());
        assert!(!format.use_hyperlinks());
    }

    #[test]
    fn test_output_format_show_progress_logic() {
        // Progress shown when text, not quiet, not summary_only
        let format = OutputFormat::text(false, false, false, true);
        assert!(format.show_progress());

        // No progress when quiet
        let format = OutputFormat::text(false, false, true, true);
        assert!(!format.show_progress());

        // No progress when summary_only
        let format = OutputFormat::text(false, true, false, true);
        assert!(!format.show_progress());

        // No progress when both
        let format = OutputFormat::text(false, true, true, true);
        assert!(!format.show_progress());
    }

    // ========================================================================
    // parse_max_threads tests
    // ========================================================================

    #[test]
    fn test_parse_max_threads_default() {
        let args = vec!["jonesy".to_string()];
        let result = parse_max_threads(&args).unwrap();
        // Default should be at least 1
        assert!(result >= 1);
    }

    #[test]
    fn test_parse_max_threads_explicit() {
        let args = vec![
            "jonesy".to_string(),
            "--max-threads".to_string(),
            "4".to_string(),
        ];
        let result = parse_max_threads(&args).unwrap();
        assert_eq!(result, 4);
    }

    #[test]
    fn test_parse_max_threads_one() {
        let args = vec![
            "jonesy".to_string(),
            "--max-threads".to_string(),
            "1".to_string(),
        ];
        let result = parse_max_threads(&args).unwrap();
        assert_eq!(result, 1);
    }

    #[test]
    fn test_parse_max_threads_zero_error() {
        let args = vec![
            "jonesy".to_string(),
            "--max-threads".to_string(),
            "0".to_string(),
        ];
        let result = parse_max_threads(&args);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("at least 1"));
    }

    #[test]
    fn test_parse_max_threads_missing_value() {
        let args = vec!["jonesy".to_string(), "--max-threads".to_string()];
        let result = parse_max_threads(&args);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("requires a number"));
    }

    #[test]
    fn test_parse_max_threads_invalid_value() {
        let args = vec![
            "jonesy".to_string(),
            "--max-threads".to_string(),
            "abc".to_string(),
        ];
        let result = parse_max_threads(&args);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Invalid"));
    }

    // ========================================================================
    // parse_output_format tests
    // ========================================================================

    #[test]
    fn test_parse_output_format_default() {
        let args = vec!["jonesy".to_string()];
        let result = parse_output_format(&args, false, false, false, false).unwrap();
        assert!(result.is_text());
        assert!(result.use_hyperlinks());
    }

    #[test]
    fn test_parse_output_format_text_explicit() {
        let args = vec![
            "jonesy".to_string(),
            "--format".to_string(),
            "text".to_string(),
        ];
        let result = parse_output_format(&args, false, false, false, false).unwrap();
        assert!(result.is_text());
    }

    #[test]
    fn test_parse_output_format_json() {
        let args = vec![
            "jonesy".to_string(),
            "--format".to_string(),
            "json".to_string(),
        ];
        let result = parse_output_format(&args, true, false, false, false).unwrap();
        assert!(result.is_json());
        assert!(result.show_tree());
    }

    #[test]
    fn test_parse_output_format_html() {
        let args = vec![
            "jonesy".to_string(),
            "--format".to_string(),
            "html".to_string(),
        ];
        let result = parse_output_format(&args, false, true, false, false).unwrap();
        assert!(result.is_html());
        assert!(result.is_summary_only());
    }

    #[test]
    fn test_parse_output_format_case_insensitive() {
        let args = vec![
            "jonesy".to_string(),
            "--format".to_string(),
            "JSON".to_string(),
        ];
        let result = parse_output_format(&args, false, false, false, false).unwrap();
        assert!(result.is_json());
    }

    #[test]
    fn test_parse_output_format_invalid() {
        let args = vec![
            "jonesy".to_string(),
            "--format".to_string(),
            "xml".to_string(),
        ];
        let result = parse_output_format(&args, false, false, false, false);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Invalid format"));
    }

    #[test]
    fn test_parse_output_format_missing_value() {
        let args = vec!["jonesy".to_string(), "--format".to_string()];
        let result = parse_output_format(&args, false, false, false, false);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("requires an argument"));
    }

    #[test]
    fn test_parse_output_format_no_hyperlinks() {
        let args = vec!["jonesy".to_string()];
        let result = parse_output_format(&args, false, false, false, true).unwrap();
        assert!(result.is_text());
        assert!(!result.use_hyperlinks());
    }

    #[test]
    fn test_parse_output_format_with_flags() {
        let args = vec!["jonesy".to_string()];
        let result = parse_output_format(&args, true, true, true, true).unwrap();
        assert!(result.is_text());
        assert!(result.show_tree());
        assert!(result.is_summary_only());
        assert!(!result.show_progress()); // quiet + summary_only
        assert!(!result.use_hyperlinks());
    }

    // ========================================================================
    // usage tests
    // ========================================================================

    #[test]
    fn test_usage_contains_version() {
        let help = usage();
        assert!(help.contains(VERSION));
    }

    #[test]
    fn test_usage_contains_key_options() {
        let help = usage();
        assert!(help.contains("--bin"));
        assert!(help.contains("--lib"));
        assert!(help.contains("--tree"));
        assert!(help.contains("--quiet"));
        assert!(help.contains("--format"));
        assert!(help.contains("--config"));
        assert!(help.contains("--max-threads"));
        assert!(help.contains("lsp"));
    }

    #[test]
    fn test_usage_contains_format_options() {
        let help = usage();
        assert!(help.contains("text"));
        assert!(help.contains("json"));
        assert!(help.contains("html"));
    }

    // ========================================================================
    // extract_bin_arg tests
    // ========================================================================

    #[test]
    fn test_extract_bin_arg_valid() {
        let args = [
            "jonesy".to_string(),
            "--bin".to_string(),
            "my-binary".to_string(),
        ];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_bin_arg(&refs).unwrap();
        assert_eq!(result, "my-binary");
    }

    #[test]
    fn test_extract_bin_arg_with_path() {
        let args = [
            "jonesy".to_string(),
            "--bin".to_string(),
            "/path/to/binary".to_string(),
        ];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_bin_arg(&refs).unwrap();
        assert_eq!(result, "/path/to/binary");
    }

    #[test]
    fn test_extract_bin_arg_missing_value() {
        let args = ["jonesy".to_string(), "--bin".to_string()];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_bin_arg(&refs);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("requires a binary name"));
    }

    #[test]
    fn test_extract_bin_arg_no_flag() {
        let args = ["jonesy".to_string()];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_bin_arg(&refs);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("flag not found"));
    }

    #[test]
    fn test_extract_bin_arg_extra_positional() {
        let args = [
            "jonesy".to_string(),
            "--bin".to_string(),
            "my-binary".to_string(),
            "extra-arg".to_string(),
        ];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_bin_arg(&refs);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Unexpected extra argument"));
    }

    #[test]
    fn test_extract_bin_arg_allows_trailing_flags() {
        let args = [
            "jonesy".to_string(),
            "--bin".to_string(),
            "my-binary".to_string(),
            "--quiet".to_string(),
        ];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_bin_arg(&refs).unwrap();
        assert_eq!(result, "my-binary");
    }

    // ========================================================================
    // extract_lib_arg tests
    // ========================================================================

    #[test]
    fn test_extract_lib_arg_with_path() {
        let args = [
            "jonesy".to_string(),
            "--lib".to_string(),
            "/path/to/lib.rlib".to_string(),
        ];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_lib_arg(&refs).unwrap();
        assert_eq!(result, Some("/path/to/lib.rlib"));
    }

    #[test]
    fn test_extract_lib_arg_without_path() {
        let args = ["jonesy".to_string(), "--lib".to_string()];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_lib_arg(&refs).unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn test_extract_lib_arg_followed_by_flag() {
        let args = [
            "jonesy".to_string(),
            "--lib".to_string(),
            "--quiet".to_string(),
        ];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_lib_arg(&refs).unwrap();
        assert_eq!(result, None); // --quiet is not a path
    }

    #[test]
    fn test_extract_lib_arg_no_flag() {
        let args = ["jonesy".to_string()];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_lib_arg(&refs);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("flag not found"));
    }

    #[test]
    fn test_extract_lib_arg_extra_positional() {
        let args = [
            "jonesy".to_string(),
            "--lib".to_string(),
            "/path/to/lib.rlib".to_string(),
            "extra-arg".to_string(),
        ];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_lib_arg(&refs);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Unexpected extra argument"));
    }

    // ========================================================================
    // get_lib_name tests
    // ========================================================================

    #[test]
    fn test_get_lib_name_from_lib_section() {
        let content = r#"
            [package]
            name = "my-package"
            version = "0.1.0"

            [lib]
            name = "custom_lib_name"
        "#;
        let manifest = Manifest::from_slice(content.as_bytes()).unwrap();
        let result = get_lib_name(&manifest);
        assert_eq!(result, Some("custom_lib_name".to_string()));
    }

    #[test]
    fn test_get_lib_name_from_package() {
        let content = r#"
            [package]
            name = "my-package"
            version = "0.1.0"
        "#;
        let manifest = Manifest::from_slice(content.as_bytes()).unwrap();
        let result = get_lib_name(&manifest);
        assert_eq!(result, Some("my_package".to_string())); // hyphen -> underscore
    }

    #[test]
    fn test_get_lib_name_no_package() {
        let content = r#"
            [workspace]
            members = ["crate_a"]
        "#;
        let manifest = Manifest::from_slice(content.as_bytes()).unwrap();
        let result = get_lib_name(&manifest);
        assert_eq!(result, None);
    }

    // ========================================================================
    // find_lib_in_target tests
    // ========================================================================

    #[test]
    fn test_find_lib_in_target_nonexistent() {
        let result = find_lib_in_target("nonexistent", Path::new("/tmp"));
        assert!(result.is_none());
    }

    // ========================================================================
    // find_bin_in_manifest tests
    // ========================================================================

    #[test]
    fn test_find_bin_in_manifest_no_bins() {
        let content = r#"
            [package]
            name = "my-package"
            version = "0.1.0"
        "#;
        let manifest = Manifest::from_slice(content.as_bytes()).unwrap();
        let result = find_bin_in_manifest("nonexistent", &manifest, Path::new("/tmp"));
        assert!(result.is_none());
    }

    // ========================================================================
    // parse_config_path tests
    // ========================================================================

    #[test]
    fn test_parse_config_path_none() {
        let args = vec!["jonesy".to_string()];
        let result = parse_config_path(&args).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn test_parse_config_path_missing_value() {
        let args = vec!["jonesy".to_string(), "--config".to_string()];
        let result = parse_config_path(&args);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("requires a path"));
    }

    #[test]
    fn test_parse_config_path_file_not_found() {
        let args = vec![
            "jonesy".to_string(),
            "--config".to_string(),
            "/nonexistent/path/config.toml".to_string(),
        ];
        let result = parse_config_path(&args);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not found"));
    }

    #[test]
    fn test_parse_config_path_valid_file() {
        // Use Cargo.toml as a config file that exists
        let args = vec![
            "jonesy".to_string(),
            "--config".to_string(),
            "Cargo.toml".to_string(),
        ];

        // This test depends on running from the jonesy directory
        if PathBuf::from("Cargo.toml").exists() {
            let result = parse_config_path(&args).unwrap();
            assert!(result.is_some());
            assert!(result.unwrap().ends_with("Cargo.toml"));
        }
    }

    // ========================================================================
    // Additional OutputFormat tests
    // ========================================================================

    #[test]
    fn test_output_format_text_with_all_options() {
        let format = OutputFormat::text(true, true, true, true);
        assert!(format.is_text());
        assert!(format.show_tree());
        assert!(format.is_summary_only());
        assert!(!format.show_progress()); // quiet=true
        assert!(format.use_hyperlinks());
    }

    #[test]
    fn test_output_format_json_no_hyperlinks() {
        // JSON format should never use hyperlinks
        let format = OutputFormat::json(false, false);
        assert!(!format.use_hyperlinks());
    }

    #[test]
    fn test_output_format_html_no_hyperlinks() {
        // HTML format should never use hyperlinks (they're embedded differently)
        let format = OutputFormat::html(false, false);
        assert!(!format.use_hyperlinks());
    }

    #[test]
    fn test_output_format_json_no_progress() {
        // JSON format should never show progress
        let format = OutputFormat::json(false, false);
        assert!(!format.show_progress());
    }

    #[test]
    fn test_output_format_html_no_progress() {
        // HTML format should never show progress
        let format = OutputFormat::html(false, false);
        assert!(!format.show_progress());
    }

    // ========================================================================
    // Additional parse_output_format tests
    // ========================================================================

    #[test]
    fn test_parse_output_format_html_case_insensitive() {
        let args = vec![
            "jonesy".to_string(),
            "--format".to_string(),
            "HTML".to_string(),
        ];
        let result = parse_output_format(&args, false, false, false, false).unwrap();
        assert!(result.is_html());
    }

    #[test]
    fn test_parse_output_format_text_case_insensitive() {
        let args = vec![
            "jonesy".to_string(),
            "--format".to_string(),
            "TEXT".to_string(),
        ];
        let result = parse_output_format(&args, false, false, false, false).unwrap();
        assert!(result.is_text());
    }

    // ========================================================================
    // collect_binaries_from_manifest tests (with temp dir)
    // ========================================================================

    #[test]
    fn test_collect_binaries_no_bins() {
        // Create manifest with package but no [[bin]] or [lib] sections
        let content = r#"
            [package]
            name = "my-package"
            version = "0.1.0"
        "#;
        let manifest = Manifest::from_slice(content.as_bytes()).unwrap();
        let target_dir = PathBuf::from("/tmp");

        let binaries = collect_binaries_from_manifest(&manifest, "my-package", &target_dir);

        // No binaries exist in /tmp, so should be empty
        assert!(binaries.is_empty());
    }

    // ========================================================================
    // WorkspaceMember struct tests
    // ========================================================================

    #[test]
    fn test_workspace_member_debug() {
        let member = WorkspaceMember {
            name: "test-crate".to_string(),
            path: PathBuf::from("crates/test-crate"),
            binaries: vec![PathBuf::from("target/debug/test-crate")],
        };

        // Test Debug trait
        let debug_str = format!("{:?}", member);
        assert!(debug_str.contains("test-crate"));
        assert!(debug_str.contains("crates/test-crate"));
    }

    // ========================================================================
    // Args struct tests
    // ========================================================================

    #[test]
    fn test_args_default_values() {
        // Test that we can construct Args with expected default-like values
        let args = Args {
            binaries: vec![],
            workspace_members: None,
            show_timings: false,
            max_threads: 1,
            config_path: None,
            output: OutputFormat::default(),
            lsp_mode: false,
        };

        assert!(args.binaries.is_empty());
        assert!(args.workspace_members.is_none());
        assert!(!args.show_timings);
        assert!(!args.lsp_mode);
        assert!(args.output.is_text());
    }

    // ========================================================================
    // VERSION constant test
    // ========================================================================

    #[test]
    fn test_version_not_empty() {
        assert!(!VERSION.is_empty());
        // Version should be a valid semver-ish string
        assert!(
            VERSION.contains('.'),
            "Version should contain dots: {}",
            VERSION
        );
    }

    // ========================================================================
    // Additional extract_bin_arg edge cases
    // ========================================================================

    #[test]
    fn test_extract_bin_arg_at_end() {
        let args = [
            "jonesy".to_string(),
            "--quiet".to_string(),
            "--bin".to_string(),
            "my-binary".to_string(),
        ];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_bin_arg(&refs).unwrap();
        assert_eq!(result, "my-binary");
    }

    #[test]
    fn test_extract_bin_arg_with_multiple_flags_after() {
        let args = [
            "jonesy".to_string(),
            "--bin".to_string(),
            "my-binary".to_string(),
            "--quiet".to_string(),
            "--tree".to_string(),
        ];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_bin_arg(&refs).unwrap();
        assert_eq!(result, "my-binary");
    }

    // ========================================================================
    // Additional extract_lib_arg edge cases
    // ========================================================================

    #[test]
    fn test_extract_lib_arg_at_end_no_path() {
        let args = [
            "jonesy".to_string(),
            "--quiet".to_string(),
            "--lib".to_string(),
        ];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_lib_arg(&refs).unwrap();
        assert_eq!(result, None);
    }

    #[test]
    fn test_extract_lib_arg_with_path_and_trailing_flags() {
        let args = [
            "jonesy".to_string(),
            "--lib".to_string(),
            "/path/to/lib.rlib".to_string(),
            "--quiet".to_string(),
        ];
        let refs: Vec<&String> = args.iter().collect();
        let result = extract_lib_arg(&refs).unwrap();
        assert_eq!(result, Some("/path/to/lib.rlib"));
    }

    // ========================================================================
    // find_lib_in_target with temp directory
    // ========================================================================

    #[test]
    fn test_find_lib_in_target_dylib() {
        let temp_dir = std::env::temp_dir().join("jonesy_test_lib_dylib");
        let _ = std::fs::create_dir_all(&temp_dir);

        // Create a fake dylib
        let dylib_path = temp_dir.join("libtest.dylib");
        std::fs::write(&dylib_path, "fake dylib").unwrap();

        let result = find_lib_in_target("test", &temp_dir);
        assert!(result.is_some());
        assert!(result.unwrap().ends_with("libtest.dylib"));

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_find_lib_in_target_rlib() {
        let temp_dir = std::env::temp_dir().join("jonesy_test_lib_rlib");
        let _ = std::fs::create_dir_all(&temp_dir);

        // Create a fake rlib (no dylib)
        let rlib_path = temp_dir.join("libtest.rlib");
        std::fs::write(&rlib_path, "fake rlib").unwrap();

        let result = find_lib_in_target("test", &temp_dir);
        assert!(result.is_some());
        assert!(result.unwrap().ends_with("libtest.rlib"));

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_find_lib_in_target_staticlib() {
        let temp_dir = std::env::temp_dir().join("jonesy_test_lib_static");
        let _ = std::fs::create_dir_all(&temp_dir);

        // Create a fake staticlib (no dylib or rlib)
        let static_path = temp_dir.join("libtest.a");
        std::fs::write(&static_path, "fake staticlib").unwrap();

        let result = find_lib_in_target("test", &temp_dir);
        assert!(result.is_some());
        assert!(result.unwrap().ends_with("libtest.a"));

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_find_lib_in_target_prefers_dylib() {
        let temp_dir = std::env::temp_dir().join("jonesy_test_lib_prefer");
        let _ = std::fs::create_dir_all(&temp_dir);

        // Create all three types
        std::fs::write(temp_dir.join("libtest.dylib"), "dylib").unwrap();
        std::fs::write(temp_dir.join("libtest.rlib"), "rlib").unwrap();
        std::fs::write(temp_dir.join("libtest.a"), "staticlib").unwrap();

        let result = find_lib_in_target("test", &temp_dir);
        assert!(result.is_some());
        // Should prefer dylib
        assert!(result.unwrap().ends_with("libtest.dylib"));

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    // ========================================================================
    // get_lib_name edge cases
    // ========================================================================

    #[test]
    fn test_get_lib_name_lib_section_no_name() {
        let content = r#"
            [package]
            name = "my-package"
            version = "0.1.0"

            [lib]
            path = "src/lib.rs"
        "#;
        let manifest = Manifest::from_slice(content.as_bytes()).unwrap();
        let result = get_lib_name(&manifest);
        // Falls back to package name with hyphen replacement
        assert_eq!(result, Some("my_package".to_string()));
    }

    #[test]
    fn test_get_lib_name_underscore_preserved() {
        let content = r#"
            [package]
            name = "my_package"
            version = "0.1.0"
        "#;
        let manifest = Manifest::from_slice(content.as_bytes()).unwrap();
        let result = get_lib_name(&manifest);
        // Underscores should be preserved
        assert_eq!(result, Some("my_package".to_string()));
    }
}