agpm-cli 0.4.3

AGent Package Manager - A Git-based package manager for Claude agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
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
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
//! List installed Claude Code resources from the lockfile.
//!
//! This module provides the `list` command which displays information about
//! currently installed dependencies as recorded in the lockfile (`agpm.lock`).
//! The command offers various output formats and filtering options to help
//! users understand their project's dependencies.
//!
//! # Features
//!
//! - **Multiple Output Formats**: JSON, table, or tree view
//! - **Filtering Options**: Show only agents, snippets, or specific dependencies
//! - **Detailed Information**: Source URLs, versions, installation paths, checksums
//! - **Dependency Analysis**: Shows unused dependencies and source statistics
//! - **Path Information**: Displays where resources are installed
//!
//! # Examples
//!
//! List all installed resources:
//! ```bash
//! agpm list
//! ```
//!
//! List only agents:
//! ```bash
//! agpm list --agents
//! ```
//!
//! List with detailed information:
//! ```bash
//! agpm list --details
//! ```
//!
//! Output in JSON format:
//! ```bash
//! agpm list --format json
//! ```
//!
//! Show dependency tree:
//! ```bash
//! agpm list --format tree
//! ```
//!
//! List specific dependencies:
//! ```bash
//! agpm list my-agent utils-snippet
//! ```
//!
//! # Output Formats
//!
//! ## Table Format (Default)
//! ```text
//! NAME          TYPE     SOURCE      VERSION   PATH
//! code-reviewer agent    official    v1.0.0    agents/code-reviewer.md
//! utils         snippet  community   v2.1.0    snippets/utils.md
//! ```
//!
//! ## JSON Format
//! ```json
//! {
//!   "agents": [...],
//!   "snippets": [...],
//!   "sources": [...]
//! }
//! ```
//!
//! ## Tree Format
//! ```text
//! Sources:
//! ├── official (https://github.com/org/official.git)
//! │   └── agents/code-reviewer.md@v1.0.0
//! └── community (https://github.com/org/community.git)
//!     └── snippets/utils.md@v2.1.0
//! ```
//!
//! # Data Sources
//!
//! The command primarily reads from:
//! - **Primary**: `agpm.lock` - Contains installed resource information
//! - **Secondary**: `agpm.toml` - Used for manifest comparison and validation
//!
//! # Error Conditions
//!
//! - No lockfile found (no dependencies installed)
//! - Lockfile is corrupted or has invalid format
//! - Requested dependency names not found in lockfile
//! - File system access issues

use anyhow::{Context, Result};
use clap::Args;
use colored::Colorize;
use std::collections::HashMap;
use std::path::PathBuf;

use crate::lockfile::LockFile;
use crate::manifest::{Manifest, find_manifest_with_optional};

/// Internal representation for list items used in various output formats.
///
/// This struct normalizes resource information from both agents and snippets
/// in the lockfile to provide a consistent view for display purposes.
#[derive(Debug, Clone)]
struct ListItem {
    /// The name/key of the resource as defined in the manifest
    name: String,
    /// The source repository name (if from a Git source)
    source: Option<String>,
    /// The version/tag/branch of the resource
    version: Option<String>,
    /// The path within the source repository
    path: Option<String>,
    /// The type of resource ("agent" or "snippet")
    resource_type: String,
    /// The local installation path where the resource file is located
    installed_at: Option<String>,
    /// The SHA-256 checksum of the installed resource file
    checksum: Option<String>,
    /// The resolved Git commit hash
    resolved_commit: Option<String>,
    /// The tool ("claude-code", "opencode", "agpm", or custom)
    tool: String,
}

/// Command to list installed Claude Code resources.
///
/// This command displays information about dependencies currently installed
/// in the project based on the lockfile. It supports various output formats,
/// filtering options, and detail levels to help users understand their
/// project's resource dependencies.
///
/// # Examples
///
/// ```rust,ignore
/// use agpm_cli::cli::list::ListCommand;
///
/// // List all resources in default table format
/// let cmd = ListCommand {
///     agents: false,
///     snippets: false,
///     format: "table".to_string(),
///     manifest: false,
///     r#type: None,
///     source: None,
///     search: None,
///     detailed: false,
///     files: false,
///     verbose: false,
///     sort: None,
/// };
///
/// // List only agents with detailed information
/// let cmd = ListCommand {
///     agents: true,
///     snippets: false,
///     format: "table".to_string(),
///     manifest: false,
///     r#type: None,
///     source: None,
///     search: None,
///     detailed: true,
///     files: true,
///     verbose: false,
///     sort: Some("name".to_string()),
/// };
/// ```
#[derive(Args)]
pub struct ListCommand {
    /// Show only agents
    ///
    /// When specified, filters the output to show only agent resources,
    /// excluding snippets. Mutually exclusive with `--snippets`.
    #[arg(long)]
    agents: bool,

    /// Show only snippets
    ///
    /// When specified, filters the output to show only snippet resources,
    /// excluding agents and commands. Mutually exclusive with `--agents` and `--commands`.
    #[arg(long)]
    snippets: bool,

    /// Show only commands
    ///
    /// When specified, filters the output to show only command resources,
    /// excluding agents and snippets. Mutually exclusive with `--agents` and `--snippets`.
    #[arg(long)]
    commands: bool,

    /// Output format (table, json, yaml, compact, simple)
    ///
    /// Controls how the resource information is displayed:
    /// - `table`: Formatted table with columns (default)
    /// - `json`: JSON object with structured data
    /// - `yaml`: YAML format for structured data
    /// - `compact`: Minimal single-line format
    /// - `simple`: Plain text list format
    #[arg(short = 'f', long, default_value = "table")]
    format: String,

    /// Show from manifest instead of lockfile
    ///
    /// When enabled, shows dependencies defined in the manifest (`agpm.toml`)
    /// rather than installed dependencies from the lockfile (`agpm.lock`).
    /// This is useful for comparing intended vs. actual installations.
    #[arg(long)]
    manifest: bool,

    /// Filter by resource type
    ///
    /// Filters resources by their type (agent, snippet). This is an
    /// alternative to using the `--agents` or `--snippets` flags.
    #[arg(long, value_name = "TYPE")]
    r#type: Option<String>,

    /// Filter by source name
    ///
    /// Shows only resources from the specified source repository.
    /// The source name should match one defined in the manifest.
    #[arg(long, value_name = "SOURCE")]
    source: Option<String>,

    /// Search by name pattern
    ///
    /// Filters resources whose names match the given pattern.
    /// Supports substring matching (case-insensitive).
    #[arg(long, value_name = "PATTERN")]
    search: Option<String>,

    /// Show detailed information
    ///
    /// Includes additional columns in the output such as checksums,
    /// resolved commits, and full source URLs. This provides more
    /// comprehensive information about each resource.
    #[arg(long)]
    detailed: bool,

    /// Show installed file paths
    ///
    /// Includes the local file system paths where resources are installed.
    /// Useful for understanding the project layout and locating resource files.
    #[arg(long)]
    files: bool,

    /// Verbose output (show all sections)
    ///
    /// Enables verbose mode which shows additional information including
    /// source statistics, dependency summaries, and extended metadata.
    #[arg(short = 'v', long)]
    verbose: bool,

    /// Sort by field (name, version, source, type)
    ///
    /// Controls the sorting order of the resource list. Supported fields:
    /// - `name`: Sort alphabetically by resource name
    /// - `version`: Sort by version (semantic versioning aware)
    /// - `source`: Sort by source repository name
    /// - `type`: Sort by resource type (agents first, then snippets)
    #[arg(long, value_name = "FIELD")]
    sort: Option<String>,
}

impl ListCommand {
    /// Execute the list command to display installed resources.
    ///
    /// This method orchestrates the process of loading resource data, applying
    /// filters, and formatting the output according to the specified options.
    ///
    /// # Behavior
    ///
    /// 1. **Data Loading**: Loads resource data from lockfile or manifest
    /// 2. **Filtering**: Applies type, source, and search filters
    /// 3. **Sorting**: Orders results according to the specified sort field
    /// 4. **Formatting**: Outputs data in the requested format
    ///
    /// # Data Sources
    ///
    /// - **Default**: Uses lockfile (`agpm.lock`) to show installed resources
    /// - **Manifest Mode**: Uses manifest (`agpm.toml`) to show defined dependencies
    ///
    /// # Filtering Logic
    ///
    /// Filters are applied in this order:
    /// 1. Type filter (agents/snippets)
    /// 2. Source filter (specific repository)
    /// 3. Search pattern (name matching)
    ///
    /// # Returns
    ///
    /// - `Ok(())` if the list was displayed successfully
    /// - `Err(anyhow::Error)` if:
    ///   - No lockfile found (and not using manifest mode)
    ///   - Lockfile format is invalid
    /// - Unable to load manifest (in manifest mode)
    ///   - Output formatting fails
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use agpm_cli::cli::list::ListCommand;
    ///
    /// # tokio_test::block_on(async {
    /// let cmd = ListCommand {
    ///     agents: false,
    ///     snippets: false,
    ///     format: "json".to_string(),
    ///     manifest: false,
    ///     r#type: None,
    ///     source: None,
    ///     search: None,
    ///     detailed: true,
    ///     files: false,
    ///     verbose: false,
    ///     sort: Some("name".to_string()),
    /// };
    /// // cmd.execute_with_manifest_path(None).await?;
    /// # Ok::<(), anyhow::Error>(())
    /// # }));
    /// ```
    /// Execute the list command with an optional manifest path
    pub async fn execute_with_manifest_path(self, manifest_path: Option<PathBuf>) -> Result<()> {
        // Validate arguments
        self.validate_arguments()?;

        // Find manifest file
        let manifest_path = find_manifest_with_optional(manifest_path)
            .context("No agpm.toml found. Please create one to define your dependencies.")?;

        self.execute_from_path(manifest_path).await
    }

    pub async fn execute_from_path(self, manifest_path: PathBuf) -> Result<()> {
        // Validate arguments
        self.validate_arguments()?;

        // For consistency with execute(), require the manifest to exist
        if !manifest_path.exists() {
            return Err(anyhow::anyhow!("Manifest file {} not found", manifest_path.display()));
        }

        let project_dir = manifest_path.parent().unwrap();

        if self.manifest {
            // List from manifest
            self.list_from_manifest(&manifest_path)?;
        } else {
            // List from lockfile
            self.list_from_lockfile(project_dir)?;
        }

        Ok(())
    }

    fn validate_arguments(&self) -> Result<()> {
        // Validate format
        match self.format.as_str() {
            "table" | "json" | "yaml" | "compact" | "simple" => {}
            _ => {
                return Err(anyhow::anyhow!(
                    "Invalid format '{}'. Valid formats are: table, json, yaml, compact, simple",
                    self.format
                ));
            }
        }

        // Validate type filter
        if let Some(ref t) = self.r#type {
            match t.as_str() {
                "agents" | "snippets" => {}
                _ => {
                    return Err(anyhow::anyhow!(
                        "Invalid type '{t}'. Valid types are: agents, snippets"
                    ));
                }
            }
        }

        // Validate sort field
        if let Some(ref field) = self.sort {
            match field.as_str() {
                "name" | "version" | "source" | "type" => {}
                _ => {
                    return Err(anyhow::anyhow!(
                        "Invalid sort field '{field}'. Valid fields are: name, version, source, type"
                    ));
                }
            }
        }

        Ok(())
    }

    fn list_from_manifest(&self, manifest_path: &std::path::Path) -> Result<()> {
        let manifest = Manifest::load(manifest_path)?;

        // Collect and filter dependencies
        let mut items = Vec::new();

        // Iterate through all resource types using the central definition
        for resource_type in crate::core::ResourceType::all() {
            // Check if we should show this resource type
            if !self.should_show_resource_type(*resource_type) {
                continue;
            }

            let type_str = resource_type.to_string();

            // Note: MCP servers are handled separately as they use a different dependency type
            if *resource_type == crate::core::ResourceType::McpServer {
                // Skip MCP servers in this generic iteration - they need special handling
                continue;
            }

            // Get dependencies for this resource type from the manifest
            if let Some(deps) = manifest.get_dependencies(*resource_type) {
                for (name, dep) in deps {
                    if self.matches_filters(name, Some(dep), &type_str) {
                        items.push(ListItem {
                            name: name.clone(),
                            source: dep.get_source().map(std::string::ToString::to_string),
                            version: dep.get_version().map(std::string::ToString::to_string),
                            path: Some(dep.get_path().to_string()),
                            resource_type: type_str.clone(),
                            installed_at: None,
                            checksum: None,
                            resolved_commit: None,
                            tool: dep.get_tool().to_string(),
                        });
                    }
                }
            }
        }

        // Handle MCP servers (now using standard ResourceDependency)
        if self.should_show_resource_type(crate::core::ResourceType::McpServer) {
            for (name, mcp_dep) in &manifest.mcp_servers {
                // MCP servers now use standard ResourceDependency
                if self.matches_filters(name, Some(mcp_dep), "mcp-server") {
                    items.push(ListItem {
                        name: name.clone(),
                        source: mcp_dep.get_source().map(std::string::ToString::to_string),
                        version: mcp_dep.get_version().map(std::string::ToString::to_string),
                        path: Some(mcp_dep.get_path().to_string()),
                        resource_type: "mcp-server".to_string(),
                        installed_at: None,
                        checksum: None,
                        resolved_commit: None,
                        tool: mcp_dep.get_tool().to_string(),
                    });
                }
            }
        }

        // Sort items
        self.sort_items(&mut items);

        // Output results
        self.output_items(&items, "Dependencies from agpm.toml:")?;

        Ok(())
    }

    fn list_from_lockfile(&self, project_dir: &std::path::Path) -> Result<()> {
        let lockfile_path = project_dir.join("agpm.lock");

        if !lockfile_path.exists() {
            if self.format == "json" {
                println!("{{}}");
            } else {
                println!("No installed resources found.");
                println!("⚠️  agpm.lock not found. Run 'agpm install' first.");
            }
            return Ok(());
        }

        let lockfile = LockFile::load(&lockfile_path)?;

        // Collect and filter entries
        let mut items = Vec::new();

        // Iterate through all resource types using the central definition
        for resource_type in crate::core::ResourceType::all() {
            // Check if we should show this resource type
            if !self.should_show_resource_type(*resource_type) {
                continue;
            }

            let type_str = resource_type.to_string();

            // Get resources for this type from the lockfile
            for entry in lockfile.get_resources(*resource_type) {
                if self.matches_lockfile_filters(&entry.name, entry, &type_str) {
                    items.push(self.lockentry_to_listitem(entry, &type_str));
                }
            }
        }

        // Sort items
        self.sort_items(&mut items);

        // Handle special flags

        // Output results
        self.output_items(&items, "Installed resources from agpm.lock:")?;

        Ok(())
    }

    /// Determine if a resource type should be shown based on filters
    fn should_show_resource_type(&self, resource_type: crate::core::ResourceType) -> bool {
        use crate::core::ResourceType;

        // Check if there's a type filter
        if let Some(ref t) = self.r#type {
            let type_str = resource_type.to_string();
            return t == &type_str || t == &format!("{type_str}s");
        }

        // Check individual flags
        match resource_type {
            ResourceType::Agent => !self.snippets && !self.commands,
            ResourceType::Snippet => !self.agents && !self.commands,
            ResourceType::Command => !self.agents && !self.snippets,
            ResourceType::Script => !self.agents && !self.snippets && !self.commands,
            ResourceType::Hook => !self.agents && !self.snippets && !self.commands,
            ResourceType::McpServer => !self.agents && !self.snippets && !self.commands,
        }
    }

    /// Check if an item matches all filters
    fn matches_filters(
        &self,
        name: &str,
        dep: Option<&crate::manifest::ResourceDependency>,
        _resource_type: &str,
    ) -> bool {
        // Source filter
        if let Some(ref source_filter) = self.source
            && let Some(dep) = dep
        {
            if let Some(source) = dep.get_source() {
                if source != source_filter {
                    return false;
                }
            } else {
                return false; // No source but filter specified
            }
        }

        // Search filter
        if let Some(ref search) = self.search
            && !name.contains(search)
        {
            return false;
        }

        true
    }

    /// Sort items based on sort criteria
    fn sort_items(&self, items: &mut [ListItem]) {
        if let Some(ref sort_field) = self.sort {
            match sort_field.as_str() {
                "name" => items.sort_by(|a, b| a.name.cmp(&b.name)),
                "version" => items.sort_by(|a, b| {
                    a.version.as_deref().unwrap_or("").cmp(b.version.as_deref().unwrap_or(""))
                }),
                "source" => items.sort_by(|a, b| {
                    a.source
                        .as_deref()
                        .unwrap_or("local")
                        .cmp(b.source.as_deref().unwrap_or("local"))
                }),
                "type" => items.sort_by(|a, b| a.resource_type.cmp(&b.resource_type)),
                _ => {} // Already validated
            }
        }
    }

    /// Output items in the specified format
    fn output_items(&self, items: &[ListItem], title: &str) -> Result<()> {
        if items.is_empty() {
            if self.format == "json" {
                println!("{{}}");
            } else {
                println!("No installed resources found.");
            }
            return Ok(());
        }

        match self.format.as_str() {
            "json" => self.output_json(items)?,
            "yaml" => self.output_yaml(items)?,
            "compact" => self.output_compact(items),
            "simple" => self.output_simple(items),
            _ => self.output_table(items, title),
        }

        Ok(())
    }

    /// Output in JSON format
    fn output_json(&self, items: &[ListItem]) -> Result<()> {
        let json_items: Vec<serde_json::Value> = items
            .iter()
            .map(|item| {
                let mut obj = serde_json::json!({
                    "name": item.name,
                    "type": item.resource_type,
                    "tool": item.tool
                });

                if let Some(ref source) = item.source {
                    obj["source"] = serde_json::Value::String(source.clone());
                }
                if let Some(ref version) = item.version {
                    obj["version"] = serde_json::Value::String(version.clone());
                }
                if let Some(ref path) = item.path {
                    obj["path"] = serde_json::Value::String(path.clone());
                }
                if let Some(ref installed_at) = item.installed_at {
                    obj["installed_at"] = serde_json::Value::String(installed_at.clone());
                }
                if let Some(ref checksum) = item.checksum {
                    obj["checksum"] = serde_json::Value::String(checksum.clone());
                }

                obj
            })
            .collect();

        println!("{}", serde_json::to_string_pretty(&json_items)?);
        Ok(())
    }

    /// Output in YAML format
    fn output_yaml(&self, items: &[ListItem]) -> Result<()> {
        let yaml_items: Vec<HashMap<String, serde_yaml::Value>> = items
            .iter()
            .map(|item| {
                let mut obj = HashMap::new();
                obj.insert("name".to_string(), serde_yaml::Value::String(item.name.clone()));
                obj.insert(
                    "type".to_string(),
                    serde_yaml::Value::String(item.resource_type.clone()),
                );
                obj.insert("tool".to_string(), serde_yaml::Value::String(item.tool.clone()));

                if let Some(ref source) = item.source {
                    obj.insert("source".to_string(), serde_yaml::Value::String(source.clone()));
                }
                if let Some(ref version) = item.version {
                    obj.insert("version".to_string(), serde_yaml::Value::String(version.clone()));
                }
                if let Some(ref path) = item.path {
                    obj.insert("path".to_string(), serde_yaml::Value::String(path.clone()));
                }
                if let Some(ref installed_at) = item.installed_at {
                    obj.insert(
                        "installed_at".to_string(),
                        serde_yaml::Value::String(installed_at.clone()),
                    );
                }

                obj
            })
            .collect();

        println!("{}", serde_yaml::to_string(&yaml_items)?);
        Ok(())
    }

    /// Output in compact format
    fn output_compact(&self, items: &[ListItem]) {
        for item in items {
            let source = item.source.as_deref().unwrap_or("local");
            let version = item.version.as_deref().unwrap_or("latest");
            println!("{} {} {}", item.name, version, source);
        }
    }

    /// Output in simple format
    fn output_simple(&self, items: &[ListItem]) {
        for item in items {
            println!("{} ({}))", item.name, item.resource_type);
        }
    }

    /// Output in table format
    fn output_table(&self, items: &[ListItem], title: &str) {
        println!("{}", title.bold());
        println!();

        // Show headers for table format (but not verbose mode)
        if !items.is_empty() && self.format == "table" && !self.verbose {
            println!(
                "{:<20} {:<15} {:<15} {:<12} {:<15}",
                "Name".cyan().bold(),
                "Version".cyan().bold(),
                "Source".cyan().bold(),
                "Type".cyan().bold(),
                "Artifact".cyan().bold()
            );
            println!("{}", "-".repeat(80).bright_black());
        }

        if self.format == "table" && !self.files && !self.detailed && !self.verbose {
            // Print items directly in table format
            for item in items {
                self.print_item(item);
            }
        } else {
            // Simple listing
            let show_agents = self.should_show_resource_type(crate::core::ResourceType::Agent);
            let show_snippets = self.should_show_resource_type(crate::core::ResourceType::Snippet);

            if show_agents {
                let agents: Vec<_> = items.iter().filter(|i| i.resource_type == "agent").collect();
                if !agents.is_empty() {
                    println!("{}:", "Agents".cyan().bold());
                    for item in agents {
                        self.print_item(item);
                    }
                    println!();
                }
            }

            if show_snippets {
                let snippets: Vec<_> =
                    items.iter().filter(|i| i.resource_type == "snippet").collect();
                if !snippets.is_empty() {
                    println!("{}:", "Snippets".cyan().bold());
                    for item in snippets {
                        self.print_item(item);
                    }
                }
            }
        }

        println!("{}: {} resources", "Total".green().bold(), items.len());
    }

    /// Print a single item
    fn print_item(&self, item: &ListItem) {
        let source = item.source.as_deref().unwrap_or("local");
        let version = item.version.as_deref().unwrap_or("latest");

        if self.format == "table" && !self.files && !self.detailed {
            // Table format with columns
            println!(
                "{:<20} {:<15} {:<15} {:<12} {:<15}",
                item.name.bright_white(),
                version.yellow(),
                source.bright_black(),
                item.resource_type.bright_white(),
                item.tool.bright_black()
            );
        } else if self.files {
            if let Some(ref installed_at) = item.installed_at {
                println!("    {}", installed_at.bright_black());
            } else if let Some(ref path) = item.path {
                println!("    {}", path.bright_black());
            }
        } else if self.detailed {
            println!("    {}", item.name.bright_white());
            println!("      Source: {}", source.bright_black());
            println!("      Version: {}", version.yellow());
            if let Some(ref path) = item.path {
                println!("      Path: {}", path.bright_black());
            }
            if let Some(ref installed_at) = item.installed_at {
                println!("      Installed at: {}", installed_at.bright_black());
            }
            if let Some(ref checksum) = item.checksum {
                println!("      Checksum: {}", checksum.bright_black());
            }
            println!();
        } else {
            let commit_info = if let Some(ref commit) = item.resolved_commit {
                format!("@{}", &commit[..7.min(commit.len())])
            } else {
                String::new()
            };

            println!(
                "    {} {} {} {}",
                item.name.bright_white(),
                format!("({source}))").bright_black(),
                version.yellow(),
                commit_info.bright_black()
            );

            if let Some(ref installed_at) = item.installed_at {
                println!("{}", installed_at.bright_black());
            }
        }
    }

    /// Check if a lockfile entry matches all filters
    fn matches_lockfile_filters(
        &self,
        name: &str,
        entry: &crate::lockfile::LockedResource,
        _resource_type: &str,
    ) -> bool {
        // Source filter
        if let Some(ref source_filter) = self.source {
            if let Some(ref source) = entry.source {
                if source != source_filter {
                    return false;
                }
            } else {
                return false; // No source but filter specified
            }
        }

        // Search filter
        if let Some(ref search) = self.search
            && !name.contains(search)
        {
            return false;
        }

        true
    }

    /// Convert a lockfile entry to a `ListItem`
    fn lockentry_to_listitem(
        &self,
        entry: &crate::lockfile::LockedResource,
        resource_type: &str,
    ) -> ListItem {
        ListItem {
            name: entry.name.clone(),
            source: entry.source.clone(),
            version: entry.version.clone(),
            path: Some(entry.path.clone()),
            resource_type: resource_type.to_string(),
            installed_at: Some(entry.installed_at.clone()),
            checksum: Some(entry.checksum.clone()),
            resolved_commit: entry.resolved_commit.clone(),
            tool: entry.tool.clone(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lockfile::{LockedResource, LockedSource};
    use crate::manifest::{DetailedDependency, ResourceDependency};
    use tempfile::TempDir;

    fn create_default_command() -> ListCommand {
        ListCommand {
            agents: false,
            snippets: false,
            commands: false,
            format: "table".to_string(),
            manifest: false,
            r#type: None,
            source: None,
            search: None,
            detailed: false,
            files: false,
            verbose: false,
            sort: None,
        }
    }

    fn create_test_manifest() -> crate::manifest::Manifest {
        let mut manifest = crate::manifest::Manifest::new();

        // Add sources
        manifest
            .sources
            .insert("official".to_string(), "https://github.com/example/official.git".to_string());
        manifest.sources.insert(
            "community".to_string(),
            "https://github.com/example/community.git".to_string(),
        );

        // Add agents
        manifest.agents.insert(
            "code-reviewer".to_string(),
            ResourceDependency::Detailed(Box::new(DetailedDependency {
                source: Some("official".to_string()),
                path: "agents/reviewer.md".to_string(),
                version: Some("v1.0.0".to_string()),
                command: None,
                branch: None,
                rev: None,
                args: None,
                target: None,
                filename: None,
                dependencies: None,
                tool: "claude-code".to_string(),
            })),
        );

        manifest.agents.insert(
            "local-helper".to_string(),
            ResourceDependency::Simple("../local/helper.md".to_string()),
        );

        // Add snippets
        manifest.snippets.insert(
            "utils".to_string(),
            ResourceDependency::Detailed(Box::new(DetailedDependency {
                source: Some("community".to_string()),
                path: "snippets/utils.md".to_string(),
                version: Some("v1.2.0".to_string()),
                command: None,
                branch: None,
                rev: None,
                args: None,
                target: None,
                filename: None,
                dependencies: None,
                tool: "claude-code".to_string(),
            })),
        );

        manifest.snippets.insert(
            "local-snippet".to_string(),
            ResourceDependency::Simple("./snippets/local.md".to_string()),
        );

        manifest
    }

    fn create_test_lockfile() -> crate::lockfile::LockFile {
        let mut lockfile = crate::lockfile::LockFile::new();

        // Add sources
        lockfile.sources.push(LockedSource {
            name: "official".to_string(),
            url: "https://github.com/example/official.git".to_string(),
            fetched_at: "2024-01-01T00:00:00Z".to_string(),
        });

        lockfile.sources.push(LockedSource {
            name: "community".to_string(),
            url: "https://github.com/example/community.git".to_string(),
            fetched_at: "2024-01-01T00:00:00Z".to_string(),
        });

        // Add agents
        lockfile.agents.push(LockedResource {
            name: "code-reviewer".to_string(),
            source: Some("official".to_string()),
            url: Some("https://github.com/example/official.git".to_string()),
            path: "agents/reviewer.md".to_string(),
            version: Some("v1.0.0".to_string()),
            resolved_commit: Some("abc123def456".to_string()),
            checksum: "sha256:abc123".to_string(),
            installed_at: "agents/code-reviewer.md".to_string(),
            dependencies: vec![],
            resource_type: crate::core::ResourceType::Agent,

            tool: "claude-code".to_string(),
        });

        lockfile.agents.push(LockedResource {
            name: "local-helper".to_string(),
            source: None,
            url: None,
            path: "../local/helper.md".to_string(),
            version: None,
            resolved_commit: None,
            checksum: "sha256:def456".to_string(),
            installed_at: "agents/local-helper.md".to_string(),
            dependencies: vec![],
            resource_type: crate::core::ResourceType::Agent,

            tool: "claude-code".to_string(),
        });

        // Add snippets
        lockfile.snippets.push(LockedResource {
            name: "utils".to_string(),
            source: Some("community".to_string()),
            url: Some("https://github.com/example/community.git".to_string()),
            path: "snippets/utils.md".to_string(),
            version: Some("v1.2.0".to_string()),
            resolved_commit: Some("def456ghi789".to_string()),
            checksum: "sha256:ghi789".to_string(),
            installed_at: "snippets/utils.md".to_string(),
            dependencies: vec![],
            resource_type: crate::core::ResourceType::Snippet,

            tool: "claude-code".to_string(),
        });

        lockfile
    }

    #[tokio::test]
    async fn test_list_no_manifest() {
        let temp = TempDir::new().unwrap();
        // Don't create agpm.toml
        let manifest_path = temp.path().join("agpm.toml");

        let cmd = create_default_command();

        // This should fail because there's no manifest
        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_list_empty_manifest() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create empty manifest
        let manifest = crate::manifest::Manifest::new();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_from_manifest_with_resources() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest with resources
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_from_lockfile_no_lockfile() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest but no lockfile
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = create_default_command(); // manifest = false by default

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_from_lockfile_with_resources() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");
        let lockfile_path = temp.path().join("agpm.lock");

        // Create both manifest and lockfile
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let lockfile = create_test_lockfile();
        lockfile.save(&lockfile_path).unwrap();

        let cmd = create_default_command(); // manifest = false by default

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_arguments_valid_format() {
        let valid_formats = ["table", "json", "yaml", "compact", "simple"];

        for format in valid_formats {
            let cmd = ListCommand {
                format: format.to_string(),
                ..create_default_command()
            };
            assert!(cmd.validate_arguments().is_ok());
        }
    }

    #[test]
    fn test_validate_arguments_invalid_format() {
        let cmd = ListCommand {
            format: "invalid".to_string(),
            ..create_default_command()
        };

        let result = cmd.validate_arguments();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid format"));
    }

    #[test]
    fn test_validate_arguments_valid_type() {
        let valid_types = ["agents", "snippets"];

        for type_name in valid_types {
            let cmd = ListCommand {
                r#type: Some(type_name.to_string()),
                ..create_default_command()
            };
            assert!(cmd.validate_arguments().is_ok());
        }
    }

    #[test]
    fn test_validate_arguments_invalid_type() {
        let cmd = ListCommand {
            r#type: Some("invalid".to_string()),
            ..create_default_command()
        };

        let result = cmd.validate_arguments();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid type"));
    }

    #[test]
    fn test_validate_arguments_valid_sort() {
        let valid_sorts = ["name", "version", "source", "type"];

        for sort in valid_sorts {
            let cmd = ListCommand {
                sort: Some(sort.to_string()),
                ..create_default_command()
            };
            assert!(cmd.validate_arguments().is_ok());
        }
    }

    #[test]
    fn test_validate_arguments_invalid_sort() {
        let cmd = ListCommand {
            sort: Some("invalid".to_string()),
            ..create_default_command()
        };

        let result = cmd.validate_arguments();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid sort field"));
    }

    #[test]
    fn test_should_show_agents() {
        // Show agents when no specific type filter
        let cmd = create_default_command();
        assert!(cmd.should_show_resource_type(crate::core::ResourceType::Agent));

        // Show only agents when agents flag is set
        let cmd = ListCommand {
            agents: true,
            ..create_default_command()
        };
        assert!(cmd.should_show_resource_type(crate::core::ResourceType::Agent));

        // Don't show agents when snippets flag is set
        let cmd = ListCommand {
            snippets: true,
            ..create_default_command()
        };
        assert!(!cmd.should_show_resource_type(crate::core::ResourceType::Agent));

        // Show agents when type is "agents"
        let cmd = ListCommand {
            r#type: Some("agents".to_string()),
            ..create_default_command()
        };
        assert!(cmd.should_show_resource_type(crate::core::ResourceType::Agent));

        // Don't show agents when type is "snippets"
        let cmd = ListCommand {
            r#type: Some("snippets".to_string()),
            ..create_default_command()
        };
        assert!(!cmd.should_show_resource_type(crate::core::ResourceType::Agent));
    }

    #[test]
    fn test_should_show_snippets() {
        // Show snippets when no specific type filter
        let cmd = create_default_command();
        assert!(cmd.should_show_resource_type(crate::core::ResourceType::Snippet));

        // Don't show snippets when agents flag is set
        let cmd = ListCommand {
            agents: true,
            ..create_default_command()
        };
        assert!(!cmd.should_show_resource_type(crate::core::ResourceType::Snippet));

        // Show only snippets when snippets flag is set
        let cmd = ListCommand {
            snippets: true,
            ..create_default_command()
        };
        assert!(cmd.should_show_resource_type(crate::core::ResourceType::Snippet));

        // Don't show snippets when type is "agents"
        let cmd = ListCommand {
            r#type: Some("agents".to_string()),
            ..create_default_command()
        };
        assert!(!cmd.should_show_resource_type(crate::core::ResourceType::Snippet));

        // Show snippets when type is "snippets"
        let cmd = ListCommand {
            r#type: Some("snippets".to_string()),
            ..create_default_command()
        };
        assert!(cmd.should_show_resource_type(crate::core::ResourceType::Snippet));
    }

    #[test]
    fn test_should_show_commands() {
        // Show commands when no specific type filter
        let cmd = create_default_command();
        assert!(cmd.should_show_resource_type(crate::core::ResourceType::Command));

        // Don't show commands when agents flag is set
        let cmd = ListCommand {
            agents: true,
            ..create_default_command()
        };
        assert!(!cmd.should_show_resource_type(crate::core::ResourceType::Command));

        // Don't show commands when snippets flag is set
        let cmd = ListCommand {
            snippets: true,
            ..create_default_command()
        };
        assert!(!cmd.should_show_resource_type(crate::core::ResourceType::Command));

        // Show only commands when commands flag is set
        let cmd = ListCommand {
            commands: true,
            ..create_default_command()
        };
        assert!(cmd.should_show_resource_type(crate::core::ResourceType::Command));

        // Don't show other types when commands flag is set
        assert!(!cmd.should_show_resource_type(crate::core::ResourceType::Agent));
        assert!(!cmd.should_show_resource_type(crate::core::ResourceType::Snippet));

        // Show commands when type is "commands" or "command"
        let cmd = ListCommand {
            r#type: Some("commands".to_string()),
            ..create_default_command()
        };
        assert!(cmd.should_show_resource_type(crate::core::ResourceType::Command));

        let cmd = ListCommand {
            r#type: Some("command".to_string()),
            ..create_default_command()
        };
        assert!(cmd.should_show_resource_type(crate::core::ResourceType::Command));
    }

    #[test]
    fn test_mutually_exclusive_type_filters() {
        // Test that only one type shows when flags are set individually
        let cmd = ListCommand {
            agents: true,
            ..create_default_command()
        };
        assert!(cmd.should_show_resource_type(crate::core::ResourceType::Agent));
        assert!(!cmd.should_show_resource_type(crate::core::ResourceType::Snippet));
        assert!(!cmd.should_show_resource_type(crate::core::ResourceType::Command));

        let cmd = ListCommand {
            snippets: true,
            ..create_default_command()
        };
        assert!(!cmd.should_show_resource_type(crate::core::ResourceType::Agent));
        assert!(cmd.should_show_resource_type(crate::core::ResourceType::Snippet));
        assert!(!cmd.should_show_resource_type(crate::core::ResourceType::Command));

        let cmd = ListCommand {
            commands: true,
            ..create_default_command()
        };
        assert!(!cmd.should_show_resource_type(crate::core::ResourceType::Agent));
        assert!(!cmd.should_show_resource_type(crate::core::ResourceType::Snippet));
        assert!(cmd.should_show_resource_type(crate::core::ResourceType::Command));
    }

    #[test]
    fn test_matches_filters_source() {
        let cmd = ListCommand {
            source: Some("official".to_string()),
            ..create_default_command()
        };

        let dep_with_source = ResourceDependency::Detailed(Box::new(DetailedDependency {
            source: Some("official".to_string()),
            path: "agents/test.md".to_string(),
            version: Some("v1.0.0".to_string()),
            command: None,
            branch: None,
            rev: None,
            args: None,
            target: None,
            filename: None,
            dependencies: None,
            tool: "claude-code".to_string(),
        }));

        let dep_with_different_source =
            ResourceDependency::Detailed(Box::new(DetailedDependency {
                source: Some("community".to_string()),
                path: "agents/test.md".to_string(),
                version: Some("v1.0.0".to_string()),
                command: None,
                branch: None,
                rev: None,
                args: None,
                target: None,
                filename: None,
                dependencies: None,
                tool: "claude-code".to_string(),
            }));

        let dep_without_source = ResourceDependency::Simple("local/file.md".to_string());

        assert!(cmd.matches_filters("test", Some(&dep_with_source), "agent"));
        assert!(!cmd.matches_filters("test", Some(&dep_with_different_source), "agent"));
        assert!(!cmd.matches_filters("test", Some(&dep_without_source), "agent"));
    }

    #[test]
    fn test_matches_filters_search() {
        let cmd = ListCommand {
            search: Some("code".to_string()),
            ..create_default_command()
        };

        assert!(cmd.matches_filters("code-reviewer", None, "agent"));
        assert!(cmd.matches_filters("my-code-helper", None, "agent"));
        assert!(!cmd.matches_filters("utils", None, "agent"));
    }

    #[test]
    fn test_matches_lockfile_filters_source() {
        let cmd = ListCommand {
            source: Some("official".to_string()),
            ..create_default_command()
        };

        let entry_with_source = LockedResource {
            name: "test".to_string(),
            source: Some("official".to_string()),
            url: None,
            path: "test.md".to_string(),
            version: None,
            resolved_commit: None,
            checksum: "abc123".to_string(),
            installed_at: "test.md".to_string(),
            dependencies: vec![],
            resource_type: crate::core::ResourceType::Agent,

            tool: "claude-code".to_string(),
        };

        let entry_with_different_source = LockedResource {
            name: "test".to_string(),
            source: Some("community".to_string()),
            url: None,
            path: "test.md".to_string(),
            version: None,
            resolved_commit: None,
            checksum: "abc123".to_string(),
            installed_at: "test.md".to_string(),
            dependencies: vec![],
            resource_type: crate::core::ResourceType::Agent,

            tool: "claude-code".to_string(),
        };

        let entry_without_source = LockedResource {
            name: "test".to_string(),
            source: None,
            url: None,
            path: "test.md".to_string(),
            version: None,
            resolved_commit: None,
            checksum: "abc123".to_string(),
            installed_at: "test.md".to_string(),
            dependencies: vec![],
            resource_type: crate::core::ResourceType::Agent,

            tool: "claude-code".to_string(),
        };

        assert!(cmd.matches_lockfile_filters("test", &entry_with_source, "agent"));
        assert!(!cmd.matches_lockfile_filters("test", &entry_with_different_source, "agent"));
        assert!(!cmd.matches_lockfile_filters("test", &entry_without_source, "agent"));
    }

    #[test]
    fn test_matches_lockfile_filters_search() {
        let cmd = ListCommand {
            search: Some("code".to_string()),
            ..create_default_command()
        };

        let entry = LockedResource {
            name: "test".to_string(),
            source: None,
            url: None,
            path: "test.md".to_string(),
            version: None,
            resolved_commit: None,
            checksum: "abc123".to_string(),
            installed_at: "test.md".to_string(),
            dependencies: vec![],
            resource_type: crate::core::ResourceType::Agent,

            tool: "claude-code".to_string(),
        };

        assert!(cmd.matches_lockfile_filters("code-reviewer", &entry, "agent"));
        assert!(cmd.matches_lockfile_filters("my-code-helper", &entry, "agent"));
        assert!(!cmd.matches_lockfile_filters("utils", &entry, "agent"));
    }

    #[test]
    fn test_sort_items() {
        let cmd = ListCommand {
            sort: Some("name".to_string()),
            ..create_default_command()
        };

        let mut items = vec![
            ListItem {
                name: "zebra".to_string(),
                source: None,
                version: None,
                path: None,
                resource_type: "agent".to_string(),
                installed_at: None,
                checksum: None,
                resolved_commit: None,
                tool: "claude-code".to_string(),
            },
            ListItem {
                name: "alpha".to_string(),
                source: None,
                version: None,
                path: None,
                resource_type: "agent".to_string(),
                installed_at: None,
                checksum: None,
                resolved_commit: None,
                tool: "claude-code".to_string(),
            },
        ];

        cmd.sort_items(&mut items);
        assert_eq!(items[0].name, "alpha");
        assert_eq!(items[1].name, "zebra");
    }

    #[test]
    fn test_sort_items_by_version() {
        let cmd = ListCommand {
            sort: Some("version".to_string()),
            ..create_default_command()
        };

        let mut items = vec![
            ListItem {
                name: "test1".to_string(),
                source: None,
                version: Some("v2.0.0".to_string()),
                path: None,
                resource_type: "agent".to_string(),
                installed_at: None,
                checksum: None,
                resolved_commit: None,
                tool: "claude-code".to_string(),
            },
            ListItem {
                name: "test2".to_string(),
                source: None,
                version: Some("v1.0.0".to_string()),
                path: None,
                resource_type: "agent".to_string(),
                installed_at: None,
                checksum: None,
                resolved_commit: None,
                tool: "claude-code".to_string(),
            },
        ];

        cmd.sort_items(&mut items);
        assert_eq!(items[0].version, Some("v1.0.0".to_string()));
        assert_eq!(items[1].version, Some("v2.0.0".to_string()));
    }

    #[test]
    fn test_sort_items_by_source() {
        let cmd = ListCommand {
            sort: Some("source".to_string()),
            ..create_default_command()
        };

        let mut items = vec![
            ListItem {
                name: "test1".to_string(),
                source: Some("zebra".to_string()),
                version: None,
                path: None,
                resource_type: "agent".to_string(),
                installed_at: None,
                checksum: None,
                resolved_commit: None,
                tool: "claude-code".to_string(),
            },
            ListItem {
                name: "test2".to_string(),
                source: Some("alpha".to_string()),
                version: None,
                path: None,
                resource_type: "agent".to_string(),
                installed_at: None,
                checksum: None,
                resolved_commit: None,
                tool: "claude-code".to_string(),
            },
            ListItem {
                name: "test3".to_string(),
                source: None, // Should be treated as "local"
                version: None,
                path: None,
                resource_type: "agent".to_string(),
                installed_at: None,
                checksum: None,
                resolved_commit: None,
                tool: "claude-code".to_string(),
            },
        ];

        cmd.sort_items(&mut items);
        assert_eq!(items[0].source, Some("alpha".to_string()));
        assert_eq!(items[1].source, None); // "local" comes before "zebra"
        assert_eq!(items[2].source, Some("zebra".to_string()));
    }

    #[test]
    fn test_sort_items_by_type() {
        let cmd = ListCommand {
            sort: Some("type".to_string()),
            ..create_default_command()
        };

        let mut items = vec![
            ListItem {
                name: "test1".to_string(),
                source: None,
                version: None,
                path: None,
                resource_type: "snippet".to_string(),
                installed_at: None,
                checksum: None,
                resolved_commit: None,
                tool: "agpm".to_string(),
            },
            ListItem {
                name: "test2".to_string(),
                source: None,
                version: None,
                path: None,
                resource_type: "agent".to_string(),
                installed_at: None,
                checksum: None,
                resolved_commit: None,
                tool: "claude-code".to_string(),
            },
        ];

        cmd.sort_items(&mut items);
        assert_eq!(items[0].resource_type, "agent");
        assert_eq!(items[1].resource_type, "snippet");
    }

    #[test]
    fn test_lockentry_to_listitem() {
        let cmd = create_default_command();

        let lock_entry = LockedResource {
            name: "test-agent".to_string(),
            source: Some("official".to_string()),
            url: Some("https://example.com/repo.git".to_string()),
            path: "agents/test.md".to_string(),
            version: Some("v1.0.0".to_string()),
            resolved_commit: Some("abc123".to_string()),
            checksum: "sha256:def456".to_string(),
            installed_at: "agents/test-agent.md".to_string(),
            dependencies: vec![],
            resource_type: crate::core::ResourceType::Agent,

            tool: "claude-code".to_string(),
        };

        let list_item = cmd.lockentry_to_listitem(&lock_entry, "agent");

        assert_eq!(list_item.name, "test-agent");
        assert_eq!(list_item.source, Some("official".to_string()));
        assert_eq!(list_item.version, Some("v1.0.0".to_string()));
        assert_eq!(list_item.path, Some("agents/test.md".to_string()));
        assert_eq!(list_item.resource_type, "agent");
        assert_eq!(list_item.installed_at, Some("agents/test-agent.md".to_string()));
        assert_eq!(list_item.checksum, Some("sha256:def456".to_string()));
        assert_eq!(list_item.resolved_commit, Some("abc123".to_string()));
    }

    #[tokio::test]
    async fn test_list_with_json_format() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest with resources
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            format: "json".to_string(),
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_with_yaml_format() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest with resources
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            format: "yaml".to_string(),
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_with_compact_format() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest with resources
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            format: "compact".to_string(),
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_with_simple_format() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest with resources
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            format: "simple".to_string(),
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_filter_by_agents_only() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest with both agents and snippets
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            agents: true,
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_filter_by_snippets_only() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest with both agents and snippets
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            snippets: true,
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_filter_by_type() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest with both agents and snippets
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        // Test filtering by agents
        let cmd = ListCommand {
            r#type: Some("agents".to_string()),
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path.clone()).await;
        assert!(result.is_ok());

        // Test filtering by snippets
        let cmd = ListCommand {
            r#type: Some("snippets".to_string()),
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_filter_by_source() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest with resources from different sources
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            source: Some("official".to_string()),
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_search_by_pattern() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest with resources
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            search: Some("code".to_string()),
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_with_detailed_flag() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest with resources
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            detailed: true,
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_with_files_flag() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest with resources
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            files: true,
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_with_verbose_flag() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest with resources
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            verbose: true,
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_with_sort() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest with resources
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            sort: Some("name".to_string()),
            manifest: true,
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_list_empty_lockfile_json_output() {
        let temp = TempDir::new().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        // Create manifest but no lockfile
        let manifest = create_test_manifest();
        manifest.save(&manifest_path).unwrap();

        let cmd = ListCommand {
            format: "json".to_string(),
            manifest: false, // Use lockfile mode
            ..create_default_command()
        };

        let result = cmd.execute_from_path(manifest_path).await;
        assert!(result.is_ok());
    }
}