agpm-cli 0.4.14

AGent Package Manager - A Git-based package manager for coding 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
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
//! Lockfile management for reproducible installations across environments.
//!
//! This module provides comprehensive lockfile functionality for AGPM, similar to Cargo's
//! `Cargo.lock` but designed specifically for managing Claude Code resources (agents,
//! snippets, and commands) from Git repositories. The lockfile ensures that all team members and CI/CD
//! systems install identical versions of dependencies.
//!
//! # Overview
//!
//! The lockfile (`agpm.lock`) is automatically generated from the manifest (`agpm.toml`)
//! during installation and contains exact resolved versions of all dependencies. Unlike
//! the manifest which specifies version constraints, the lockfile pins exact commit hashes
//! and file checksums for reproducibility.
//!
//! ## Key Concepts
//!
//! - **Version Resolution**: Converts version constraints to exact commits
//! - **Dependency Pinning**: Locks all transitive dependencies at specific versions
//! - **Reproducibility**: Guarantees identical installations across environments
//! - **Integrity Verification**: Uses SHA-256 checksums to detect file corruption
//! - **Atomic Operations**: All lockfile updates are atomic to prevent corruption
//!
//! # Lockfile Format Specification
//!
//! The lockfile uses TOML format with the following structure:
//!
//! ```toml
//! # Auto-generated lockfile - DO NOT EDIT
//! version = 1
//!
//! # Source repositories with resolved commits
//! [[sources]]
//! name = "community"                              # Source name from manifest
//! url = "https://github.com/example/repo.git"     # Repository URL
//! commit = "a1b2c3d4e5f6..."                      # Resolved commit hash (40 chars)
//! fetched_at = "2024-01-01T00:00:00Z"             # Last fetch timestamp (RFC 3339)
//!
//! # Agent resources
//! [[agents]]
//! name = "example-agent"                          # Resource name
//! source = "community"                            # Source name (optional for local)
//! url = "https://github.com/example/repo.git"     # Source URL (optional for local)
//! path = "agents/example.md"                      # Path in source repository
//! version = "v1.0.0"                              # Requested version constraint
//! resolved_commit = "a1b2c3d4e5f6..."             # Resolved commit for this resource
//! checksum = "sha256:abcdef123456..."             # SHA-256 checksum of installed file
//! installed_at = "agents/example-agent.md"        # Installation path (relative to project)
//!
//! # Snippet resources (same structure as agents)
//! [[snippets]]
//! name = "example-snippet"
//! source = "community"
//! path = "snippets/example.md"
//! version = "^1.0"
//! resolved_commit = "a1b2c3d4e5f6..."
//! checksum = "sha256:fedcba654321..."
//! installed_at = "snippets/example-snippet.md"
//!
//! # Command resources (same structure as agents)
//! [[commands]]
//! name = "build-command"
//! source = "community"
//! path = "commands/build.md"
//! version = "v1.0.0"
//! resolved_commit = "a1b2c3d4e5f6..."
//! checksum = "sha256:123456abcdef..."
//! installed_at = ".claude/commands/build-command.md"
//! ```
//!
//! ## Field Details
//!
//! ### Version Field
//! - **Type**: Integer
//! - **Purpose**: Lockfile format version for future compatibility
//! - **Current**: 1
//!
//! ### Sources Array
//! - **name**: Unique identifier for the source repository
//! - **url**: Full Git repository URL (HTTP/HTTPS/SSH)
//! - **commit**: 40-character SHA-1 commit hash at time of resolution
//! - **`fetched_at`**: ISO 8601 timestamp of last successful fetch
//!
//! ### Resources Arrays (agents/snippets/commands)
//! - **name**: Unique resource identifier within its type
//! - **source**: Source name (omitted for local resources)
//! - **url**: Repository URL (omitted for local resources)  
//! - **path**: Relative path within source repository or filesystem
//! - **version**: Original version constraint from manifest (omitted for local)
//! - **`resolved_commit`**: Exact commit containing this resource (omitted for local)
//! - **checksum**: SHA-256 hash prefixed with "sha256:" for integrity verification
//! - **`installed_at`**: Relative path where resource is installed in project
//!
//! # Relationship to Manifest
//!
//! The lockfile is generated from the manifest (`agpm.toml`) through dependency resolution:
//!
//! ```toml
//! # agpm.toml (manifest)
//! [sources]
//! community = "https://github.com/example/repo.git"
//!
//! [agents]
//! example-agent = { source = "community", path = "agents/example.md", version = "^1.0" }
//! local-agent = { path = "../local/helper.md" }
//! ```
//!
//! During `agpm install`, this becomes:
//!
//! ```toml
//! # agpm.lock (lockfile)
//! version = 1
//!
//! [[sources]]
//! name = "community"
//! url = "https://github.com/example/repo.git"
//! commit = "a1b2c3d4e5f6..."
//! fetched_at = "2024-01-01T00:00:00Z"
//!
//! [[agents]]
//! name = "example-agent"
//! source = "community"
//! url = "https://github.com/example/repo.git"
//! path = "agents/example.md"
//! version = "^1.0"
//! resolved_commit = "a1b2c3d4e5f6..."
//! checksum = "sha256:abcdef..."
//! installed_at = "agents/example-agent.md"
//!
//! [[agents]]
//! name = "local-agent"
//! path = "../local/helper.md"
//! checksum = "sha256:123abc..."
//! installed_at = "agents/local-agent.md"
//! ```
//!
//! # Version Resolution and Pinning
//!
//! AGPM resolves version constraints to exact commits using Git tags and branches:
//!
//! ## Version Constraint Resolution
//!
//! 1. **Exact versions** (`"v1.2.3"`): Match exact Git tag
//! 2. **Semantic ranges** (`"^1.0"`, `"~1.2"`): Find latest compatible tag
//! 3. **Branch names** (`"main"`, `"develop"`): Use latest commit on branch
//! 4. **Commit hashes** (`"a1b2c3d"`): Use exact commit (must be full 40-char hash)
//!
//! ## Resolution Process
//!
//! 1. **Fetch Repository**: Clone or update source repository cache
//! 2. **Enumerate Tags**: List all Git tags matching semantic version pattern
//! 3. **Apply Constraints**: Filter tags that satisfy version constraint
//! 4. **Select Latest**: Choose highest version within constraint
//! 5. **Resolve Commit**: Map tag to commit hash
//! 6. **Verify Resource**: Ensure resource exists at that commit
//! 7. **Calculate Checksum**: Generate SHA-256 hash of resource content
//! 8. **Record Entry**: Add resolved information to lockfile
//!
//! # Install vs Update Semantics
//!
//! ## Install Behavior
//! - Uses existing lockfile if present (respects pinned versions)
//! - Only resolves dependencies not in lockfile
//! - Preserves existing pins even if newer versions available
//! - Ensures reproducible installations
//!
//! ## Update Behavior  
//! - Ignores existing lockfile constraints
//! - Re-resolves all dependencies against current manifest constraints
//! - Updates to latest compatible versions within constraints
//! - Regenerates entire lockfile
//!
//! ```bash
//! # Install exact versions from lockfile (if available)
//! agpm install
//!
//! # Update to latest within manifest constraints
//! agpm update
//!
//! # Update specific resource
//! agpm update example-agent
//! ```
//!
//! # Checksum Verification
//!
//! AGPM uses SHA-256 checksums to ensure file integrity:
//!
//! ## Checksum Format
//! - **Algorithm**: SHA-256
//! - **Encoding**: Hexadecimal
//! - **Prefix**: "sha256:"
//! - **Example**: "sha256:a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3"
//!
//! ## Verification Process
//! 1. **During Installation**: Calculate checksum of installed file
//! 2. **During Validation**: Compare stored checksum with file content
//! 3. **On Mismatch**: Report corruption and suggest re-installation
//!
//! # Best Practices
//!
//! ## Commit Lockfile to Version Control
//! The lockfile should always be committed to version control:
//!
//! ```bash
//! # Commit both manifest and lockfile together
//! git add agpm.toml agpm.lock
//! git commit -m "Add new agent dependency"
//! ```
//!
//! This ensures all team members get identical dependency versions.
//!
//! ## Don't Edit Lockfile Manually
//! The lockfile is auto-generated and should not be edited manually:
//! - Use `agpm install` to update lockfile from manifest changes
//! - Use `agpm update` to update dependency versions
//! - Delete lockfile and run `agpm install` to regenerate from scratch
//!
//! ## Lockfile Conflicts
//! During Git merges, lockfile conflicts may occur:
//!
//! ```bash
//! # Resolve by regenerating lockfile
//! rm agpm.lock
//! agpm install
//! git add agpm.lock
//! git commit -m "Resolve lockfile conflict"
//! ```
//!
//! # Migration and Upgrades
//!
//! ## Format Version Compatibility
//! AGPM checks lockfile format version and provides clear error messages:
//!
//! ```text
//! Error: Lockfile version 2 is newer than supported version 1.
//! This lockfile was created by a newer version of agpm.
//! Please update agpm to the latest version to use this lockfile.
//! ```
//!
//! ## Upgrading Lockfiles
//! Future format versions will include automatic migration:
//!
//! ```bash
//! # Future: Migrate lockfile to newer format
//! agpm install --migrate-lockfile
//! ```
//!
//! # Comparison with Cargo.lock
//!
//! AGPM's lockfile design is inspired by Cargo but adapted for Git-based resources:
//!
//! | Feature | Cargo.lock | agpm.lock |
//! |---------|------------|-----------|
//! | Format | TOML | TOML |
//! | Versioning | Semantic | Git tags/branches/commits |
//! | Integrity | Checksums | SHA-256 checksums |
//! | Sources | crates.io + git | Git repositories only |
//! | Resources | Crates | Agents + Snippets |
//! | Resolution | Dependency graph | Flat dependency list |
//!
//! # Error Handling
//!
//! The lockfile module provides detailed error messages with actionable suggestions:
//!
//! - **Parse Errors**: TOML syntax issues with fix suggestions
//! - **Version Errors**: Incompatible format versions with upgrade instructions  
//! - **IO Errors**: File system issues with permission/space guidance
//! - **Corruption**: Checksum mismatches with re-installation steps
//!
//! # Cross-Platform Considerations
//!
//! Lockfiles are fully cross-platform compatible:
//! - **Path Separators**: Always use forward slashes in lockfile paths
//! - **Line Endings**: Normalize to LF for consistent checksums
//! - **File Permissions**: Not stored in lockfile (Git handles this)
//! - **Case Sensitivity**: Preserve case from source repositories
//!
//! # Performance Characteristics
//!
//! - **Parsing**: O(n) where n is number of locked resources
//! - **Checksum Calculation**: O(m) where m is total file size
//! - **Lookups**: O(n) linear search (suitable for typical dependency counts)
//! - **Atomic Writes**: Single fsync per lockfile update
//!
//! # Thread Safety
//!
//! The [`LockFile`] struct is not thread-safe by itself, but the module provides
//! atomic operations for concurrent access:
//! - **File Locking**: Uses OS file locking during atomic writes
//! - **Process Safety**: Multiple agpm instances coordinate via lockfile
//! - **Concurrent Reads**: Safe to read lockfile from multiple threads

use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::PathBuf;

/// Reasons why a lockfile might be considered stale.
///
/// This enum describes various conditions that indicate a lockfile is
/// out-of-sync with the manifest and needs to be regenerated to prevent
/// installation errors or inconsistencies.
///
/// # Display Format
///
/// Each variant implements `Display` to provide user-friendly error messages
/// that explain the problem and suggest solutions.
///
/// # Examples
///
/// ```rust,no_run
/// use agpm_cli::lockfile::StalenessReason;
/// use agpm_cli::core::ResourceType;
///
/// let reason = StalenessReason::MissingDependency {
///     name: "my-agent".to_string(),
///     resource_type: ResourceType::Agent,
/// };
///
/// println!("{}", reason);
/// // Output: "Dependency 'my-agent' (agent) is in manifest but missing from lockfile"
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StalenessReason {
    /// A dependency is in the manifest but not in the lockfile.
    /// This indicates the lockfile is incomplete and needs regeneration.
    MissingDependency {
        /// Name of the missing dependency
        name: String,
        /// Type of resource (agent, snippet, etc.)
        resource_type: crate::core::ResourceType,
    },

    /// A dependency's version constraint has changed in the manifest.
    VersionChanged {
        /// Name of the dependency
        name: String,
        /// Type of resource (agent, snippet, etc.)
        resource_type: crate::core::ResourceType,
        /// Previous version from lockfile
        old_version: String,
        /// New version from manifest
        new_version: String,
    },

    /// A dependency's path has changed in the manifest.
    PathChanged {
        /// Name of the dependency
        name: String,
        /// Type of resource (agent, snippet, etc.)
        resource_type: crate::core::ResourceType,
        /// Previous path from lockfile
        old_path: String,
        /// New path from manifest
        new_path: String,
    },

    /// A source repository has a different URL in the manifest.
    /// This is a security concern as it could point to a different repository.
    SourceUrlChanged {
        /// Name of the source repository
        name: String,
        /// Previous URL from lockfile
        old_url: String,
        /// New URL from manifest
        new_url: String,
    },

    /// Multiple entries exist for the same dependency (lockfile corruption).
    DuplicateEntries {
        /// Name of the duplicated dependency
        name: String,
        /// Type of resource (agent, snippet, etc.)
        resource_type: crate::core::ResourceType,
        /// Number of duplicate entries found
        count: usize,
    },

    /// A dependency's tool field has changed in the manifest.
    ToolChanged {
        /// Name of the dependency
        name: String,
        /// Type of resource (agent, snippet, etc.)
        resource_type: crate::core::ResourceType,
        /// Previous tool from lockfile
        old_tool: String,
        /// New tool from manifest (with defaults applied)
        new_tool: String,
    },
}

impl std::fmt::Display for StalenessReason {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::MissingDependency {
                name,
                resource_type,
            } => {
                write!(
                    f,
                    "Dependency '{name}' ({resource_type}) is in manifest but missing from lockfile"
                )
            }
            Self::VersionChanged {
                name,
                resource_type,
                old_version,
                new_version,
            } => {
                write!(
                    f,
                    "Dependency '{name}' ({resource_type}) version changed from '{old_version}' to '{new_version}'"
                )
            }
            Self::PathChanged {
                name,
                resource_type,
                old_path,
                new_path,
            } => {
                write!(
                    f,
                    "Dependency '{name}' ({resource_type}) path changed from '{old_path}' to '{new_path}'"
                )
            }
            Self::SourceUrlChanged {
                name,
                old_url,
                new_url,
            } => {
                write!(f, "Source repository '{name}' URL changed from '{old_url}' to '{new_url}'")
            }
            Self::DuplicateEntries {
                name,
                resource_type,
                count,
            } => {
                write!(
                    f,
                    "Found {count} duplicate entries for dependency '{name}' ({resource_type})"
                )
            }
            Self::ToolChanged {
                name,
                resource_type,
                old_tool,
                new_tool,
            } => {
                write!(
                    f,
                    "Dependency '{name}' ({resource_type}) tool changed from '{old_tool}' to '{new_tool}'"
                )
            }
        }
    }
}

impl std::error::Error for StalenessReason {}

/// Unique identifier for a resource in the lockfile.
///
/// This struct ensures type-safe identification of lockfile entries by combining
/// the resource name, source, and tool. Resources are considered unique when they
/// have distinct combinations of these fields:
///
/// - Same name, different sources: Different repositories providing same-named resources
/// - Same name, different tools: Resources used by different tools (e.g., Claude Code vs OpenCode)
/// - Same name and source, different tools: Transitive dependencies inherited from different parent tools
///
/// # Examples
///
/// ```rust
/// use agpm_cli::lockfile::ResourceId;
/// use agpm_cli::core::ResourceType;
///
/// // Local resource (no source)
/// let local = ResourceId::new("my-agent", None::<String>, Some("claude-code"), ResourceType::Agent, "default".to_string());
///
/// // Git resource from a source
/// let git = ResourceId::new("shared-agent", Some("community"), Some("claude-code"), ResourceType::Agent, "default".to_string());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ResourceId {
    /// The name of the resource
    name: String,
    /// The source repository name (None for local resources)
    source: Option<String>,
    /// The tool identifier (e.g., "claude-code", "opencode", "agpm")
    tool: Option<String>,
    /// The resource type (Agent, Snippet, Command, etc.)
    resource_type: crate::core::ResourceType,
    /// SHA-256 hash of the complete merged template variable context
    ///
    /// This hash uniquely identifies the template inputs used during dependency resolution.
    /// Two resources with different variant_inputs_hash are considered distinct, even if
    /// they have the same name, source, and tool. Only the hash is needed for identity
    /// comparison; the full JSON value is stored in LockedResource for serialization.
    variant_inputs_hash: String,
}

impl ResourceId {
    /// Create a new ResourceId with pre-computed hash
    pub fn new(
        name: impl Into<String>,
        source: Option<impl Into<String>>,
        tool: Option<impl Into<String>>,
        resource_type: crate::core::ResourceType,
        variant_inputs_hash: String,
    ) -> Self {
        Self {
            name: name.into(),
            source: source.map(|s| s.into()),
            tool: tool.map(|t| t.into()),
            resource_type,
            variant_inputs_hash,
        }
    }

    /// Create a ResourceId from a LockedResource
    pub fn from_resource(resource: &LockedResource) -> Self {
        Self {
            name: resource.name.clone(),
            source: resource.source.clone(),
            tool: resource.tool.clone(),
            resource_type: resource.resource_type,
            variant_inputs_hash: resource.variant_inputs.hash().to_string(),
        }
    }

    /// Resource name accessor.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Source repository name accessor.
    #[must_use]
    pub fn source(&self) -> Option<&str> {
        self.source.as_deref()
    }

    /// Tool identifier accessor.
    #[must_use]
    pub fn tool(&self) -> Option<&str> {
        self.tool.as_deref()
    }

    /// Resource type accessor.
    #[must_use]
    pub fn resource_type(&self) -> crate::core::ResourceType {
        self.resource_type
    }

    /// Get the variant_inputs_hash for this resource ID.
    #[must_use]
    pub fn variant_inputs_hash(&self) -> &str {
        &self.variant_inputs_hash
    }
}

impl std::fmt::Display for ResourceId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name)?;
        if let Some(ref source) = self.source {
            write!(f, " (source: {})", source)?;
        }
        if let Some(ref tool) = self.tool {
            write!(f, " [{}]", tool)?;
        }
        // Show hash prefix for variant inputs (not default empty hash)
        if !self.variant_inputs_hash.is_empty()
            && self.variant_inputs_hash != crate::utils::EMPTY_VARIANT_INPUTS_HASH.as_str()
        {
            write!(f, " <hash: {}>", &self.variant_inputs_hash[..16])?;
        }
        Ok(())
    }
}

/// The main lockfile structure representing a complete `agpm.lock` file.
///
/// This structure contains all resolved dependencies, source repositories, and their
/// exact versions/commits for reproducible installations. The lockfile is automatically
/// generated from the [`crate::manifest::Manifest`] during installation and should not
/// be edited manually.
///
/// # Format Version
///
/// The lockfile includes a format version to enable future migrations and compatibility
/// checking. The current version is 1.
///
/// # Serialization
///
/// The lockfile serializes to TOML format with arrays of sources, agents, and snippets.
/// Empty arrays are omitted from serialization to keep the lockfile clean.
///
/// # Examples
///
/// Creating a new lockfile:
///
/// ```rust,no_run
/// use agpm_cli::lockfile::LockFile;
///
/// let lockfile = LockFile::new();
/// assert_eq!(lockfile.version, 1);
/// assert!(lockfile.sources.is_empty());
/// ```
///
/// Loading an existing lockfile:
///
/// ```rust,no_run
/// # use std::path::Path;
/// # use agpm_cli::lockfile::LockFile;
/// # fn example() -> anyhow::Result<()> {
/// let lockfile = LockFile::load(Path::new("agpm.lock"))?;
/// println!("Loaded {} sources, {} agents",
///          lockfile.sources.len(), lockfile.agents.len());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockFile {
    /// Version of the lockfile format.
    ///
    /// This field enables forward and backward compatibility checking. AGPM will
    /// refuse to load lockfiles with versions newer than it supports, and may
    /// provide migration paths for older versions in the future.
    pub version: u32,

    /// Locked source repositories with their resolved commit hashes.
    ///
    /// Each entry represents a Git repository that has been fetched and resolved
    /// to an exact commit. The commit hash ensures all team members get identical
    /// source content even as the upstream repository evolves.
    ///
    /// This field is omitted from TOML serialization if empty to keep the lockfile clean.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sources: Vec<LockedSource>,

    /// Locked agent resources with their exact versions and checksums.
    ///
    /// Contains all resolved agent dependencies from the manifest, with exact
    /// commit hashes, installation paths, and SHA-256 checksums for integrity
    /// verification.
    ///
    /// This field is omitted from TOML serialization if empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub agents: Vec<LockedResource>,

    /// Locked snippet resources with their exact versions and checksums.
    ///
    /// Contains all resolved snippet dependencies from the manifest, with exact
    /// commit hashes, installation paths, and SHA-256 checksums for integrity
    /// verification.
    ///
    /// This field is omitted from TOML serialization if empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub snippets: Vec<LockedResource>,

    /// Locked command resources with their exact versions and checksums.
    ///
    /// Contains all resolved command dependencies from the manifest, with exact
    /// commit hashes, installation paths, and SHA-256 checksums for integrity
    /// verification.
    ///
    /// This field is omitted from TOML serialization if empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub commands: Vec<LockedResource>,

    /// Locked MCP server resources with their exact versions and checksums.
    ///
    /// Contains all resolved MCP server dependencies from the manifest, with exact
    /// commit hashes, installation paths, and SHA-256 checksums for integrity
    /// verification. MCP servers are installed as JSON files and also configured
    /// in `.claude/settings.local.json`.
    ///
    /// This field is omitted from TOML serialization if empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty", rename = "mcp-servers")]
    pub mcp_servers: Vec<LockedResource>,

    /// Locked script resources with their exact versions and checksums.
    ///
    /// Contains all resolved script dependencies from the manifest, with exact
    /// commit hashes, installation paths, and SHA-256 checksums for integrity
    /// verification. Scripts are executable files that can be referenced by hooks.
    ///
    /// This field is omitted from TOML serialization if empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub scripts: Vec<LockedResource>,

    /// Locked hook configurations with their exact versions and checksums.
    ///
    /// Contains all resolved hook dependencies from the manifest. Hooks are
    /// JSON configuration files that define event-based automation in Claude Code.
    ///
    /// This field is omitted from TOML serialization if empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub hooks: Vec<LockedResource>,

    /// Locked skill resources with their exact versions and checksums.
    ///
    /// Skills are directory-based resources (unlike single-file agents/snippets)
    /// that contain a `SKILL.md` file plus supporting files. Contains all resolved
    /// skill dependencies with exact commit hashes, installation paths, and checksums.
    ///
    /// This field is omitted from TOML serialization if empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub skills: Vec<LockedResource>,

    /// Hash of manifest dependency specifications for fast path detection.
    ///
    /// This field stores a SHA-256 hash of the manifest's dependency sections
    /// (sources, agents, commands, etc.) at the time of resolution. On subsequent
    /// installs, if this hash matches the current manifest, we can skip resolution
    /// entirely for immutable dependencies.
    ///
    /// This field is omitted from TOML serialization if None (for backward compatibility).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub manifest_hash: Option<String>,

    /// Whether the lockfile contains any mutable dependencies.
    ///
    /// Mutable dependencies include:
    /// - Local file sources (no URL)
    /// - Branch-based versions (e.g., "main", "develop")
    ///
    /// When true, even if the manifest hash matches, we must re-validate
    /// mutable dependencies as they may have changed. When false, we can
    /// use the full fast path and skip resolution entirely.
    ///
    /// This field is omitted from TOML serialization if None (for backward compatibility).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub has_mutable_deps: Option<bool>,

    /// Total count of resources in the lockfile at time of resolution.
    ///
    /// This field is used for lockfile integrity validation during fast path checks.
    /// If the stored count doesn't match the actual resource count in the lockfile,
    /// it indicates the lockfile was manually edited and we should fall back to
    /// full resolution.
    ///
    /// This field is omitted from TOML serialization if None (for backward compatibility).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource_count: Option<usize>,
}

/// A locked source repository with resolved commit information.
///
/// Represents a Git repository that has been fetched and resolved to an exact
/// commit hash. This ensures reproducible access to source repositories across
/// different environments and times.
///
/// # Fields
///
/// - **name**: Unique identifier used in the manifest to reference this source
/// - **url**: Full Git repository URL (HTTP/HTTPS/SSH)
/// - **commit**: 40-character SHA-1 commit hash resolved at time of lock
/// - **`fetched_at`**: RFC 3339 timestamp of when the repository was last fetched
///
/// # Examples
///
/// A typical locked source in TOML format:
///
/// ```toml
/// [[sources]]
/// name = "community"
/// url = "https://github.com/example/agpm-community.git"
/// commit = "a1b2c3d4e5f6789abcdef0123456789abcdef012"
/// fetched_at = "2024-01-15T10:30:00Z"
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockedSource {
    /// Unique source name from the manifest.
    ///
    /// This corresponds to keys in the `[sources]` section of `agpm.toml`
    /// and is used to reference the source in resource definitions.
    pub name: String,

    /// Full Git repository URL.
    ///
    /// Supports HTTP, HTTPS, and SSH URLs. This is the exact URL used
    /// for cloning and fetching the repository.
    pub url: String,

    /// Timestamp of last successful fetch in RFC 3339 format.
    ///
    /// Records when the repository was last fetched from the remote.
    /// This helps track staleness and debugging fetch issues.
    pub fetched_at: String,
}

/// A locked resource (agent or snippet) with resolved version and integrity information.
///
/// Represents a specific resource file that has been resolved from either a source
/// repository or local filesystem. Contains all information needed to verify the
/// exact version and integrity of the installed resource.
///
/// # Local vs Remote Resources
///
/// Remote resources (from Git repositories) include:
/// - `source`: Source repository name
/// - `url`: Repository URL  
/// - `version`: Original version constraint
/// - `resolved_commit`: Exact commit containing the resource
///
/// Local resources (from filesystem) omit these fields since they don't
/// involve Git repositories.
///
/// # Integrity Verification
///
/// All resources include a SHA-256 checksum for integrity verification.
/// The checksum is calculated from the file content after installation
/// and can be used to detect corruption or tampering.
///
/// # Examples
///
/// Remote resource in TOML format:
///
/// ```toml
/// [[agents]]
/// name = "example-agent"
/// source = "community"
/// url = "https://github.com/example/repo.git"
/// path = "agents/example.md"
/// version = "^1.0"
/// resolved_commit = "a1b2c3d4e5f6..."
/// checksum = "sha256:abcdef123456..."
/// installed_at = "agents/example-agent.md"
/// ```
///
/// Local resource in TOML format:
///
/// ```toml
/// [[agents]]
/// name = "local-helper"
/// path = "../local/helper.md"
/// checksum = "sha256:fedcba654321..."
/// installed_at = "agents/local-helper.md"
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct LockedResource {
    /// Resource name from the manifest.
    ///
    /// This corresponds to keys in the `[agents]` or `[snippets]` sections
    /// of the manifest. Resources are uniquely identified by the combination
    /// of (name, source), allowing multiple sources to provide resources with
    /// the same name.
    pub name: String,

    /// Source repository name for remote resources.
    ///
    /// References a source defined in the `[sources]` section of the manifest.
    /// This field is `None` for local resources that don't come from Git repositories.
    ///
    /// Omitted from TOML serialization when `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,

    /// Source repository URL for remote resources.
    ///
    /// The full Git repository URL where this resource originates.
    /// This field is `None` for local resources.
    ///
    /// Omitted from TOML serialization when `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,

    /// Path to the resource file.
    ///
    /// For remote resources, this is the relative path within the source repository.
    /// For local resources, this is the filesystem path (may be relative or absolute).
    pub path: String,

    /// Resolved version for the resource.
    ///
    /// This stores the resolved version tag (e.g., "v1.0.0", "main") that was matched
    /// by the version constraint in `agpm.toml`. Like Cargo.lock, this provides
    /// human-readable context while `resolved_commit` ensures reproducibility.
    /// For local resources or resources without versions, this field is `None`.
    ///
    /// Omitted from TOML serialization when `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,

    /// Resolved Git commit hash for remote resources.
    ///
    /// The exact 40-character SHA-1 commit hash where this resource was found.
    /// This ensures reproducible installations even if the version constraint
    /// could match multiple commits. For local resources, this field is `None`.
    ///
    /// Omitted from TOML serialization when `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resolved_commit: Option<String>,

    /// SHA-256 checksum of the installed file content.
    ///
    /// Used for integrity verification to detect file corruption or tampering.
    /// The format is "sha256:" followed by the hexadecimal hash.
    ///
    /// Example: "sha256:a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3"
    pub checksum: String,

    /// SHA-256 checksum of the template rendering context (NEW FIELD).
    ///
    /// This is None for resources that don't use templating, and Some(checksum)
    /// for templated resources. The checksum is computed from the canonical
    /// serialization of the template context (dependencies, variant_inputs, etc.)
    /// and is used to detect when template inputs change, even if the rendered
    /// output happens to be identical.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_checksum: Option<String>,

    /// Installation path relative to the project root.
    ///
    /// Where the resource file is installed within the project directory.
    /// This path is always relative to the project root and uses forward
    /// slashes as separators for cross-platform compatibility.
    ///
    /// Examples: "agents/example-agent.md", "snippets/util-snippet.md"
    pub installed_at: String,

    /// Dependencies of this resource.
    ///
    /// Lists the direct dependencies that this resource requires, including
    /// both manifest dependencies and transitive dependencies discovered from
    /// the resource file itself. Each dependency is identified by its resource
    /// type and name (e.g., "agents/helper-agent", "snippets/utils").
    ///
    /// This field enables dependency graph analysis and ensures all required
    /// resources are installed. It follows the same model as Cargo.lock where
    /// each package lists its dependencies.
    ///
    /// Always included in TOML serialization, even when empty, to match Cargo.lock format.
    #[serde(default)]
    pub dependencies: Vec<String>,

    /// Resource type (agent, snippet, command, etc.)
    ///
    /// This field is populated during deserialization based on which TOML section
    /// the resource came from (`[[agents]]`, `[[snippets]]`, etc.) and is used internally
    /// for determining the correct lockfile section when adding/updating entries.
    ///
    /// It is never serialized to the lockfile - the section header provides this information.
    #[serde(skip)]
    pub resource_type: crate::core::ResourceType,

    /// Tool type for multi-tool support (claude-code, opencode, agpm, custom).
    ///
    /// Specifies which target AI coding assistant tool this resource is for. This determines
    /// where the resource is installed and how it's configured.
    ///
    /// When None during deserialization, will be set based on resource type's default
    /// (e.g., snippets default to "agpm", others to "claude-code").
    ///
    /// Always serialized for clarity and to avoid ambiguity.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool: Option<String>,

    /// Original manifest alias for pattern-expanded dependencies.
    ///
    /// When a pattern dependency (e.g., `agents/helpers/*.md` with alias "all-helpers")
    /// expands to multiple files, each file gets its own lockfile entry with a unique `name`
    /// (e.g., "helper-alpha", "helper-beta"). The `manifest_alias` field preserves the
    /// original pattern alias so patches defined under that alias can be correctly applied
    /// to all matched files.
    ///
    /// For non-pattern dependencies, this field is `None` since `name` already represents
    /// the manifest alias.
    ///
    /// Example lockfile entry for pattern-expanded resource:
    /// ```toml
    /// [[agents]]
    /// name = "helper-alpha"                    # Individual file name
    /// manifest_alias = "all-helpers"           # Original pattern alias
    /// path = "agents/helpers/helper-alpha.md"
    /// ...
    /// ```
    ///
    /// This enables pattern patching: all files matched by "all-helpers" pattern can
    /// have patches applied via `[patch.agents.all-helpers]` in the manifest.
    ///
    /// Omitted from TOML serialization when `None` (for non-pattern dependencies).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub manifest_alias: Option<String>,

    /// Applied patches from manifest configuration.
    ///
    /// Contains the key-value pairs that were applied to this resource's metadata
    /// via `[patch.<resource-type>.<alias>]` sections in agpm.toml or agpm.private.toml.
    ///
    /// This enables reproducible installations and provides visibility into which
    /// resources have been patched.
    ///
    /// Omitted from TOML serialization when empty.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub applied_patches: BTreeMap<String, toml::Value>,

    /// Whether this dependency should be installed to disk.
    ///
    /// When `false`, the dependency is resolved, fetched, and tracked in the lockfile,
    /// but the file is not written to the project directory. Instead, its content is
    /// made available in template context via `agpm.deps.<type>.<name>.content`.
    ///
    /// This is useful for snippet embedding use cases where you want to include
    /// content inline rather than as a separate file.
    ///
    /// Defaults to `true` (install the file) for backwards compatibility.
    ///
    /// Omitted from TOML serialization when `None` or `true`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub install: Option<bool>,

    /// Variant inputs for template rendering.
    ///
    /// Stores the template variable overrides that were specified in the manifest
    /// for this dependency. These overrides are applied when rendering templates
    /// to allow customization of generic templates for specific use cases.
    ///
    /// Encapsulates both the JSON value and its pre-computed hash for identity comparison.
    /// The hash is not serialized and is recomputed after deserialization.
    #[serde(
        default = "default_variant_inputs_struct",
        serialize_with = "serialize_variant_inputs_as_toml",
        deserialize_with = "deserialize_variant_inputs_from_toml"
    )]
    pub variant_inputs: crate::resolver::lockfile_builder::VariantInputs,

    /// Whether this resource came from agpm.private.toml.
    ///
    /// Private resources:
    /// - Install to `{resource_path}/private/` subdirectory
    /// - Are tracked in `agpm.private.lock` instead of `agpm.lock`
    /// - Don't affect team lockfile consistency
    ///
    /// Omitted from TOML serialization when false (the default).
    #[serde(default, skip_serializing_if = "is_false")]
    pub is_private: bool,

    /// Approximate token count of the installed file content.
    ///
    /// Computed using cl100k BPE encoding (compatible with Claude/GPT-4).
    /// Used for tracking context usage and warning on large resources.
    ///
    /// Omitted from TOML serialization when `None`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub approximate_token_count: Option<u64>,
}

/// Helper function for serde skip_serializing_if on bool fields.
fn is_false(b: &bool) -> bool {
    !*b
}

/// Builder for creating LockedResource instances.
///
/// This builder helps address clippy warnings about functions with too many arguments
/// by providing a fluent interface for constructing LockedResource instances.
pub struct LockedResourceBuilder {
    name: String,
    source: Option<String>,
    url: Option<String>,
    path: String,
    version: Option<String>,
    resolved_commit: Option<String>,
    checksum: String,
    installed_at: String,
    dependencies: Vec<String>,
    resource_type: crate::core::ResourceType,
    tool: Option<String>,
    manifest_alias: Option<String>,
    applied_patches: BTreeMap<String, toml::Value>,
    install: Option<bool>,
    context_checksum: Option<String>,
    variant_inputs: crate::resolver::lockfile_builder::VariantInputs,
    is_private: bool,
    approximate_token_count: Option<u64>,
}

impl LockedResourceBuilder {
    /// Create a new builder with the required fields.
    pub fn new(
        name: String,
        path: String,
        checksum: String,
        installed_at: String,
        resource_type: crate::core::ResourceType,
    ) -> Self {
        Self {
            name,
            source: None,
            url: None,
            path,
            version: None,
            resolved_commit: None,
            checksum,
            installed_at,
            dependencies: Vec::new(),
            resource_type,
            tool: None,
            manifest_alias: None,
            applied_patches: BTreeMap::new(),
            install: None,
            context_checksum: None,
            variant_inputs: crate::resolver::lockfile_builder::VariantInputs::default(),
            is_private: false,
            approximate_token_count: None,
        }
    }

    /// Set the source repository name.
    pub fn source(mut self, source: Option<String>) -> Self {
        self.source = source;
        self
    }

    /// Set the source repository URL.
    pub fn url(mut self, url: Option<String>) -> Self {
        self.url = url;
        self
    }

    /// Set the version.
    pub fn version(mut self, version: Option<String>) -> Self {
        self.version = version;
        self
    }

    /// Set the resolved commit.
    pub fn resolved_commit(mut self, resolved_commit: Option<String>) -> Self {
        self.resolved_commit = resolved_commit;
        self
    }

    /// Set the dependencies.
    pub fn dependencies(mut self, dependencies: Vec<String>) -> Self {
        self.dependencies = dependencies;
        self
    }

    /// Set the tool.
    pub fn tool(mut self, tool: Option<String>) -> Self {
        self.tool = tool;
        self
    }

    /// Set the manifest alias.
    pub fn manifest_alias(mut self, manifest_alias: Option<String>) -> Self {
        self.manifest_alias = manifest_alias;
        self
    }

    /// Set the applied patches.
    pub fn applied_patches(mut self, applied_patches: BTreeMap<String, toml::Value>) -> Self {
        self.applied_patches = applied_patches;
        self
    }

    /// Set the install flag.
    pub fn install(mut self, install: Option<bool>) -> Self {
        self.install = install;
        self
    }

    /// Set the context checksum.
    pub fn context_checksum(mut self, context_checksum: Option<String>) -> Self {
        self.context_checksum = context_checksum;
        self
    }

    /// Set the variant inputs.
    pub fn variant_inputs(
        mut self,
        variant_inputs: crate::resolver::lockfile_builder::VariantInputs,
    ) -> Self {
        self.variant_inputs = variant_inputs;
        self
    }

    /// Set the is_private flag.
    pub fn is_private(mut self, is_private: bool) -> Self {
        self.is_private = is_private;
        self
    }

    /// Set the approximate token count.
    pub fn approximate_token_count(mut self, count: Option<u64>) -> Self {
        self.approximate_token_count = count;
        self
    }

    /// Build the LockedResource.
    pub fn build(self) -> LockedResource {
        LockedResource {
            name: self.name,
            source: self.source,
            url: self.url,
            path: self.path,
            version: self.version,
            resolved_commit: self.resolved_commit,
            checksum: self.checksum,
            context_checksum: self.context_checksum,
            installed_at: self.installed_at,
            dependencies: self.dependencies,
            resource_type: self.resource_type,
            tool: self.tool,
            manifest_alias: self.manifest_alias,
            applied_patches: self.applied_patches,
            install: self.install,
            variant_inputs: self.variant_inputs,
            is_private: self.is_private,
            approximate_token_count: self.approximate_token_count,
        }
    }
}

impl LockedResource {
    /// Unique identifier combining name, source, tool, and variant_inputs hash.
    ///
    /// Canonical method for resource identification in checksum updates and lookups.
    #[must_use]
    pub fn id(&self) -> ResourceId {
        ResourceId::from_resource(self)
    }

    /// Check if resource matches ResourceId by comparing name, source, tool, and variant_inputs hash.
    ///
    /// Variant_inputs hash is part of identity - same resource with different variant_inputs
    /// produces different artifacts and must be tracked separately.
    #[must_use]
    pub fn matches_id(&self, id: &ResourceId) -> bool {
        self.name == id.name
            && self.source == id.source
            && self.tool == id.tool
            && self.variant_inputs.hash() == id.variant_inputs_hash
    }

    /// Parse the dependencies field into structured lockfile dependency references.
    ///
    /// Returns an iterator over successfully parsed dependency references.
    /// Invalid references are logged as warnings and skipped.
    ///
    /// This is the centralized way to parse lockfile dependencies, ensuring
    /// consistent handling of the lockfile format across the codebase.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use agpm_cli::lockfile::LockedResource;
    /// # let resource: LockedResource = unimplemented!();
    /// for dep in resource.parsed_dependencies() {
    ///     println!("Dependency: {} (type: {})", dep.path, dep.resource_type);
    /// }
    /// ```
    pub fn parsed_dependencies(
        &self,
    ) -> impl Iterator<Item = lockfile_dependency_ref::LockfileDependencyRef> + '_ {
        use std::str::FromStr;

        self.dependencies.iter().filter_map(|dep_str| {
            lockfile_dependency_ref::LockfileDependencyRef::from_str(dep_str)
                .map_err(|e| {
                    tracing::warn!(
                        "Failed to parse dependency '{}' for resource '{}': {}",
                        dep_str,
                        self.name,
                        e
                    );
                })
                .ok()
        })
    }

    /// Get the display name for user-facing contexts.
    ///
    /// Returns the manifest_alias if present (for direct manifest dependencies or
    /// pattern-expanded resources), otherwise returns the canonical name.
    /// This provides the most user-friendly name for display purposes.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use agpm_cli::lockfile::LockedResource;
    /// // Direct dependency with custom manifest name
    /// let resource = LockedResource {
    ///     name: "ai-helper".to_string(),  // canonical name from path
    ///     manifest_alias: Some("my-ai-helper".to_string()),  // user's chosen name
    ///     // ... other fields
    /// };
    /// assert_eq!(resource.display_name(), "my-ai-helper");
    ///
    /// // Pattern-expanded dependency
    /// let resource = LockedResource {
    ///     name: "helper-alpha".to_string(),  // canonical name
    ///     manifest_alias: Some("all-helpers".to_string()),  // pattern alias
    ///     // ... other fields
    /// };
    /// assert_eq!(resource.display_name(), "all-helpers");
    ///
    /// // Transitive dependency (no manifest_alias)
    /// let resource = LockedResource {
    ///     name: "utils".to_string(),  // canonical name
    ///     manifest_alias: None,
    ///     // ... other fields
    /// };
    /// assert_eq!(resource.display_name(), "utils");
    /// ```
    #[must_use]
    pub fn display_name(&self) -> &str {
        self.manifest_alias.as_ref().unwrap_or(&self.name)
    }

    /// Get the lookup name for patch resolution and manifest lookups.
    ///
    /// Returns the manifest_alias if present (for direct manifest dependencies or
    /// pattern-expanded resources), otherwise returns the canonical name.
    /// This ensures patches are looked up using the correct manifest key.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use agpm_cli::lockfile::LockedResource;
    /// // Direct dependency - patches defined under manifest key
    /// let resource = LockedResource {
    ///     name: "ai-helper".to_string(),  // canonical name from path
    ///     manifest_alias: Some("my-ai-helper".to_string()),  // manifest key
    ///     // ... other fields
    /// };
    /// assert_eq!(resource.lookup_name(), "my-ai-helper");
    ///
    /// // Transitive dependency - no manifest key
    /// let resource = LockedResource {
    ///     name: "utils".to_string(),  // canonical name
    ///     manifest_alias: None,
    ///     // ... other fields
    /// };
    /// assert_eq!(resource.lookup_name(), "utils");
    /// ```
    #[must_use]
    pub fn lookup_name(&self) -> &str {
        self.manifest_alias.as_ref().unwrap_or(&self.name)
    }

    /// Check if this resource represents a direct manifest dependency.
    ///
    /// Returns true if this resource was directly specified in the manifest
    /// (not discovered through transitive dependencies or pattern expansion).
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use agpm_cli::lockfile::LockedResource;
    /// // Direct dependency from manifest
    /// let resource = LockedResource {
    ///     name: "ai-helper".to_string(),
    ///     manifest_alias: Some("my-ai-helper".to_string()),
    ///     // ... other fields
    /// };
    /// assert!(resource.is_direct_manifest());
    ///
    /// // Transitive dependency
    /// let resource = LockedResource {
    ///     name: "utils".to_string(),
    ///     manifest_alias: None,
    ///     // ... other fields
    /// };
    /// assert!(!resource.is_direct_manifest());
    /// ```
    #[must_use]
    pub fn is_direct_manifest(&self) -> bool {
        // After the canonical naming change, direct dependencies will have manifest_alias set
        // to preserve the original manifest key. Transitive dependencies have no manifest_alias.
        self.manifest_alias.is_some() && !self.name.starts_with("generated-")
    }

    /// Check if this resource came from a pattern expansion.
    ///
    /// Returns true if this resource was created by expanding a pattern dependency
    /// from the manifest.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use agpm_cli::lockfile::LockedResource;
    /// // Pattern-expanded resource
    /// let resource = LockedResource {
    ///     name: "helper-alpha".to_string(),
    ///     manifest_alias: Some("all-helpers".to_string()),
    ///     // ... other fields
    /// };
    /// assert!(resource.is_pattern_expanded());
    ///
    /// // Direct dependency (single file)
    /// let resource = LockedResource {
    ///     name: "ai-helper".to_string(),
    ///     manifest_alias: None,  // Will change after implementation
    ///     // ... other fields
    /// };
    /// assert!(!resource.is_pattern_expanded());
    /// ```
    #[must_use]
    pub fn is_pattern_expanded(&self) -> bool {
        self.manifest_alias.is_some()
    }

    /// Check if this is a local resource (not from a Git repository).
    ///
    /// Local resources are filesystem-based dependencies that don't come from
    /// Git repositories. They are identified by having no `resolved_commit` field
    /// (or an empty one), indicating they weren't resolved from a Git ref.
    ///
    /// Local resources require different handling:
    /// - Source paths are resolved relative to manifest directory
    /// - No worktree checkouts are needed
    /// - Files are read directly from the filesystem
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use agpm_cli::lockfile::LockedResource;
    /// // Local resource (no resolved_commit)
    /// let local = LockedResource {
    ///     resolved_commit: None,
    ///     // ... other fields
    /// };
    /// assert!(local.is_local());
    ///
    /// // Remote resource (has resolved_commit)
    /// let remote = LockedResource {
    ///     resolved_commit: Some("abc123def456789012345678901234567890abcd".to_string()),
    ///     // ... other fields
    /// };
    /// assert!(!remote.is_local());
    /// ```
    #[must_use]
    pub fn is_local(&self) -> bool {
        self.resolved_commit.as_deref().is_none_or(str::is_empty)
    }
}

// Submodules for organized implementation
mod checksum;
mod helpers;
mod io;
pub mod lockfile_dependency_ref;
pub mod private_lock;
mod resource_ops;
mod validation;
pub use private_lock::PrivateLockFile;

// Patch display utilities
pub mod patch_display;

impl LockFile {
    /// Current lockfile format version.
    ///
    /// This constant defines the lockfile format version that this version of AGPM
    /// generates. It's used for compatibility checking when loading lockfiles that
    /// may have been created by different versions of AGPM.
    const CURRENT_VERSION: u32 = 1;

    /// Create a new empty lockfile with the current format version.
    ///
    /// Returns a fresh lockfile with no sources or resources. This is typically
    /// used when initializing a new project or regenerating a lockfile from scratch.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::lockfile::LockFile;
    ///
    /// let lockfile = LockFile::new();
    /// assert_eq!(lockfile.version, 1);
    /// assert!(lockfile.sources.is_empty());
    /// assert!(lockfile.agents.is_empty());
    /// assert!(lockfile.snippets.is_empty());
    /// ```
    #[must_use]
    pub const fn new() -> Self {
        Self {
            version: Self::CURRENT_VERSION,
            sources: Vec::new(),
            agents: Vec::new(),
            snippets: Vec::new(),
            commands: Vec::new(),
            mcp_servers: Vec::new(),
            scripts: Vec::new(),
            hooks: Vec::new(),
            skills: Vec::new(),
            manifest_hash: None,
            has_mutable_deps: None,
            resource_count: None,
        }
    }
}

impl LockFile {
    /// Normalize lockfile entries for backward compatibility.
    ///
    /// Converts old lockfile entries that don't follow the canonical naming convention
    /// to use canonical names with manifest_alias. This ensures that lockfiles created
    /// before the naming change remain compatible with the new system.
    ///
    /// # Returns
    ///
    /// A new LockFile with normalized entries
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use agpm_cli::lockfile::LockFile;
    /// let mut lockfile = LockFile::new();
    /// // Load or create entries...
    /// let normalized = lockfile.normalize();
    /// ```
    pub fn normalize(&self) -> Self {
        let mut normalized = self.clone();

        // Normalize each resource type
        Self::normalize_resources(&mut normalized.agents);
        Self::normalize_resources(&mut normalized.snippets);
        Self::normalize_resources(&mut normalized.commands);
        Self::normalize_resources(&mut normalized.scripts);
        Self::normalize_resources(&mut normalized.hooks);
        Self::normalize_resources(&mut normalized.mcp_servers);

        // Sort all resource vectors for deterministic lockfile output
        // This ensures the lockfile is identical across runs regardless of
        // HashMap iteration order during dependency resolution
        normalized.agents.sort_by(Self::compare_resources);
        normalized.snippets.sort_by(Self::compare_resources);
        normalized.commands.sort_by(Self::compare_resources);
        normalized.scripts.sort_by(Self::compare_resources);
        normalized.hooks.sort_by(Self::compare_resources);
        normalized.mcp_servers.sort_by(Self::compare_resources);

        normalized
    }

    /// Compare two resources for deterministic sorting.
    ///
    /// Sort order:
    /// 1. By name (lexicographic)
    /// 2. By source (None first, then lexicographic)
    /// 3. By tool (None first, then lexicographic)
    /// 4. By template_vars (lexicographic comparison of JSON strings)
    ///
    /// This ensures stable, deterministic lockfile ordering even when the same resource
    /// exists with different template_vars (e.g., backend-engineer with language=typescript
    /// vs language=javascript).
    fn compare_resources(a: &LockedResource, b: &LockedResource) -> std::cmp::Ordering {
        a.name
            .cmp(&b.name)
            .then_with(|| a.source.cmp(&b.source))
            .then_with(|| a.tool.cmp(&b.tool))
            .then_with(|| a.variant_inputs.hash().cmp(b.variant_inputs.hash()))
    }

    /// Normalize a vector of LockedResource entries.
    ///
    /// For each entry that doesn't follow canonical naming:
    /// - Compute canonical name from path
    /// - Move current name to manifest_alias if not already set
    /// - Update name to canonical value
    /// - Sort dependencies array for deterministic output
    fn normalize_resources(resources: &mut [LockedResource]) {
        use crate::resolver::pattern_expander::generate_dependency_name;

        for resource in resources.iter_mut() {
            // Sort dependencies array for deterministic lockfile output
            // This ensures dependencies appear in consistent order regardless of
            // HashMap iteration order during resolution
            resource.dependencies.sort();

            // Skip if already has manifest_alias (indicating it's already normalized)
            if resource.manifest_alias.is_some() {
                continue;
            }

            // Compute expected canonical name from path using appropriate source context
            let canonical_name = if let Some(source_name) = &resource.source {
                // Remote resource - use source name context
                let source_context =
                    crate::resolver::source_context::SourceContext::remote(source_name);
                generate_dependency_name(&resource.path, &source_context)
            } else {
                // Local resource - handle absolute vs relative paths correctly
                let path = std::path::Path::new(&resource.path);
                if path.is_absolute() {
                    // Absolute paths keep their absolute form (with file extension removed)
                    let without_ext = path.with_extension("");
                    crate::utils::normalize_path_for_storage(without_ext)
                } else {
                    // Relative paths - we don't have manifest context here, so use "local" prefix
                    // This ensures consistency but may not match the exact manifest-relative path
                    let source_context =
                        crate::resolver::source_context::SourceContext::remote("local");
                    generate_dependency_name(&resource.path, &source_context)
                }
            };

            // Skip if already has the correct canonical name
            if resource.name == canonical_name {
                continue;
            }

            // Move current name to manifest_alias and update to canonical name
            resource.manifest_alias = Some(resource.name.clone());
            resource.name = canonical_name;
        }
    }

    /// Validate the lockfile's fast-path metadata fields.
    ///
    /// Checks consistency of `manifest_hash` and `has_mutable_deps` fields:
    /// - Returns `true` if both fields are present (valid for fast path)
    /// - Returns `false` if either field is missing (cannot use fast path)
    ///
    /// This validation is used during installation to determine if the fast path
    /// can be safely used. Lockfiles from older AGPM versions may not have these
    /// fields, requiring full resolution.
    ///
    /// # Returns
    ///
    /// - `true` if `manifest_hash`, `has_mutable_deps`, and `resource_count` fields are all present
    /// - `false` if any field is missing (older lockfile format requires full resolution)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use agpm_cli::lockfile::LockFile;
    /// # use std::path::Path;
    /// let lockfile = LockFile::load(Path::new("agpm.lock")).unwrap();
    /// if lockfile.has_valid_fast_path_metadata() {
    ///     // Can potentially use fast path (still need to check manifest hash match)
    /// } else {
    ///     // Must do full resolution
    /// }
    /// ```
    #[must_use]
    pub fn has_valid_fast_path_metadata(&self) -> bool {
        // All fast-path metadata fields must be present for fast path to be valid
        // Old lockfiles won't have these fields and require full resolution
        self.manifest_hash.is_some()
            && self.has_mutable_deps.is_some()
            && self.resource_count.is_some()
    }

    /// Validate that the stored resource count matches the actual number of resources.
    ///
    /// This detects manual edits to the lockfile that removed resource entries.
    /// If the stored count doesn't match the actual count, the lockfile may have
    /// been tampered with and we should fall back to full resolution.
    ///
    /// # Note on Variants
    ///
    /// When the same resource has multiple `variant_inputs` (e.g., the same template
    /// with different `template_vars`), each variant is counted as a separate entry.
    /// This is intentional since each variant produces a distinct installed file.
    /// Adding new variants will legitimately increase the count and trigger re-resolution.
    ///
    /// # Returns
    ///
    /// - `true` if resource count is None (old lockfile) or matches actual count
    /// - `false` if stored count differs from actual resource count (tampered lockfile)
    #[must_use]
    pub fn has_valid_resource_count(&self) -> bool {
        match self.resource_count {
            None => true, // Old lockfile, can't validate
            Some(stored_count) => {
                let actual_count = self.all_resources().len();
                stored_count == actual_count
            }
        }
    }

    /// Validate that manifest_hash format is correct.
    ///
    /// The manifest hash should be in the format "sha256:<hex>" where <hex> is
    /// a 64-character lowercase hexadecimal string.
    ///
    /// # Returns
    ///
    /// `true` if the manifest_hash is None or has valid format, `false` if present but invalid.
    #[must_use]
    pub fn has_valid_manifest_hash_format(&self) -> bool {
        match &self.manifest_hash {
            None => true,
            Some(hash) => {
                if let Some(hex_part) = hash.strip_prefix("sha256:") {
                    hex_part.len() == 64 && hex_part.chars().all(|c| c.is_ascii_hexdigit())
                } else {
                    false
                }
            }
        }
    }

    /// Split the lockfile into public and private parts based on `is_private` flag.
    ///
    /// After dependency resolution, resources are partitioned:
    /// - Public resources (`is_private = false`) → main `agpm.lock`
    /// - Private resources (`is_private = true`) → `agpm.private.lock`
    ///
    /// This ensures team lockfiles remain consistent while allowing personal
    /// private dependencies without conflicts.
    ///
    /// # Returns
    ///
    /// A tuple of `(public_lockfile, private_lockfile)`.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use agpm_cli::lockfile::LockFile;
    /// # use std::path::Path;
    /// let combined = LockFile::new();
    /// // ... resolve dependencies ...
    /// let (public_lock, private_lock) = combined.split_by_privacy();
    ///
    /// // Save to separate files
    /// public_lock.save(Path::new("agpm.lock"))?;
    /// private_lock.save(Path::new("."))?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    #[must_use]
    pub fn split_by_privacy(&self) -> (Self, PrivateLockFile) {
        let mut public_lock = Self::new();
        let mut private_resources: Vec<LockedResource> = Vec::new();

        // Copy metadata to public lockfile
        public_lock.manifest_hash = self.manifest_hash.clone();
        public_lock.has_mutable_deps = self.has_mutable_deps;
        // Note: resource_count will be recalculated after split
        public_lock.sources = self.sources.clone();

        // Partition agents
        for resource in &self.agents {
            if resource.is_private {
                private_resources.push(resource.clone());
            } else {
                public_lock.agents.push(resource.clone());
            }
        }

        // Partition snippets
        for resource in &self.snippets {
            if resource.is_private {
                private_resources.push(resource.clone());
            } else {
                public_lock.snippets.push(resource.clone());
            }
        }

        // Partition commands
        for resource in &self.commands {
            if resource.is_private {
                private_resources.push(resource.clone());
            } else {
                public_lock.commands.push(resource.clone());
            }
        }

        // Partition scripts
        for resource in &self.scripts {
            if resource.is_private {
                private_resources.push(resource.clone());
            } else {
                public_lock.scripts.push(resource.clone());
            }
        }

        // Partition mcp_servers
        for resource in &self.mcp_servers {
            if resource.is_private {
                private_resources.push(resource.clone());
            } else {
                public_lock.mcp_servers.push(resource.clone());
            }
        }

        // Partition hooks
        for resource in &self.hooks {
            if resource.is_private {
                private_resources.push(resource.clone());
            } else {
                public_lock.hooks.push(resource.clone());
            }
        }

        // Partition skills
        for resource in &self.skills {
            if resource.is_private {
                private_resources.push(resource.clone());
            } else {
                public_lock.skills.push(resource.clone());
            }
        }

        // Update resource count for public lockfile only
        public_lock.resource_count = Some(public_lock.all_resources().len());

        let private_lock = PrivateLockFile::from_resources(private_resources);

        (public_lock, private_lock)
    }

    /// Merge private resources from a `PrivateLockFile` into this lockfile.
    ///
    /// When loading lockfiles, first load `agpm.lock`, then optionally merge
    /// `agpm.private.lock` to get the complete set of resources for this user.
    ///
    /// Private resources are added to the appropriate resource type vectors.
    /// Duplicates (same name, source, tool, variant_hash) are not checked;
    /// the caller is responsible for ensuring no conflicts.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use agpm_cli::lockfile::{LockFile, PrivateLockFile};
    /// # use std::path::Path;
    /// let mut lockfile = LockFile::load(Path::new("agpm.lock"))?;
    /// if let Some(private_lock) = PrivateLockFile::load(Path::new("."))? {
    ///     lockfile.merge_private(&private_lock);
    /// }
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    pub fn merge_private(&mut self, private_lock: &PrivateLockFile) {
        // Merge agents
        self.agents.extend(private_lock.agents.iter().cloned());

        // Merge snippets
        self.snippets.extend(private_lock.snippets.iter().cloned());

        // Merge commands
        self.commands.extend(private_lock.commands.iter().cloned());

        // Merge scripts
        self.scripts.extend(private_lock.scripts.iter().cloned());

        // Merge mcp_servers
        self.mcp_servers.extend(private_lock.mcp_servers.iter().cloned());

        // Merge hooks
        self.hooks.extend(private_lock.hooks.iter().cloned());

        // Update resource count to reflect merged total
        if self.resource_count.is_some() {
            self.resource_count = Some(self.all_resources().len());
        }
    }
}

impl Default for LockFile {
    /// Equivalent to [`LockFile::new()`] - creates empty lockfile with current format version.
    fn default() -> Self {
        Self::new()
    }
}

/// Default value for `template_vars` field.
///
/// Returns an empty JSON object which will serialize as `"{}"` in TOML.
fn default_variant_inputs_struct() -> crate::resolver::lockfile_builder::VariantInputs {
    crate::resolver::lockfile_builder::VariantInputs::new(serde_json::Value::Object(
        serde_json::Map::new(),
    ))
}

/// Serialize `VariantInputs` as a TOML table.
///
/// Converts the internal JSON value to a TOML value to enable proper nested table serialization.
fn serialize_variant_inputs_as_toml<S>(
    variant_inputs: &crate::resolver::lockfile_builder::VariantInputs,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    use crate::lockfile::patch_display::json_to_toml_value;

    let toml_value = json_to_toml_value(variant_inputs.json()).map_err(|e| {
        serde::ser::Error::custom(format!("Failed to convert variant_inputs to TOML: {}", e))
    })?;
    toml_value.serialize(serializer)
}

/// Deserialize `VariantInputs` from a TOML value.
///
/// Converts the TOML value back to JSON for internal storage.
fn deserialize_variant_inputs_from_toml<'de, D>(
    deserializer: D,
) -> Result<crate::resolver::lockfile_builder::VariantInputs, D::Error>
where
    D: serde::Deserializer<'de>,
{
    use crate::manifest::patches::toml_value_to_json;

    let toml_value = toml::Value::deserialize(deserializer)?;
    let json_value = toml_value_to_json(&toml_value).map_err(|e| {
        serde::de::Error::custom(format!("Failed to convert TOML to variant_inputs: {}", e))
    })?;
    Ok(crate::resolver::lockfile_builder::VariantInputs::new(json_value))
}

/// Find the lockfile in the current or parent directories.
///
/// Searches upward from the current working directory to find a `agpm.lock` file,
/// similar to how Git searches for `.git` directories. This enables running AGPM
/// commands from subdirectories within a project.
///
/// # Search Algorithm
///
/// 1. Start from current working directory
/// 2. Check for `agpm.lock` in current directory
/// 3. If found, return the path
/// 4. If not found, move to parent directory
/// 5. Repeat until root directory is reached
/// 6. Return `None` if no lockfile found
///
/// # Returns
///
/// * `Some(PathBuf)` - Path to the found lockfile
/// * `None` - No lockfile found in current or parent directories
///
/// # Examples
///
/// ```rust,no_run
/// use agpm_cli::lockfile::find_lockfile;
///
/// if let Some(lockfile_path) = find_lockfile() {
///     println!("Found lockfile: {}", lockfile_path.display());
/// } else {
///     println!("No lockfile found (run 'agpm install' to create one)");
/// }
/// ```
///
/// # Use Cases
///
/// - **CLI commands**: Find project root when run from subdirectories
/// - **Editor integration**: Locate project configuration
/// - **Build scripts**: Find lockfile for dependency information
/// - **Validation tools**: Check if project has lockfile
///
/// # Directory Structure Example
///
/// ```text
/// project/
/// ├── agpm.lock          # ← This will be found
/// ├── agpm.toml
/// └── src/
///     └── subdir/         # ← Commands run from here will find ../agpm.lock
/// ```
///
/// # Errors
///
/// This function does not return errors but rather `None` if:
/// - Cannot get current working directory (permission issues)
/// - No lockfile exists in the directory tree
/// - IO errors while checking file existence
///
/// For more robust error handling, consider using [`LockFile::load`] directly
/// with a known path.
#[must_use]
pub fn find_lockfile() -> Option<PathBuf> {
    let mut current = std::env::current_dir().ok()?;

    loop {
        let lockfile_path = current.join("agpm.lock");
        if lockfile_path.exists() {
            return Some(lockfile_path);
        }

        if !current.pop() {
            return None;
        }
    }
}