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
//! Lockfile building and management functionality.
//!
//! This module handles the creation, updating, and maintenance of lockfile entries,
//! including conflict detection, stale entry removal, and transitive dependency management.

use crate::core::ResourceType;
use crate::lockfile::{LockFile, LockedResource, lockfile_dependency_ref::LockfileDependencyRef};
use crate::manifest::{Manifest, ResourceDependency};
use crate::resolver::types as dependency_helpers;
use anyhow::Result;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::str::FromStr;

// Type aliases for internal lookups
type ResourceKey = (ResourceType, String, Option<String>);
type ResourceInfo = (Option<String>, Option<String>);

/// Checks if two lockfile entries should be considered duplicates.
///
/// Two entries are duplicates if they have the same:
/// 1. name, source, tool, AND variant_inputs (standard deduplication)
/// 2. path, tool, AND variant_inputs for local dependencies (source = None)
///
/// **CRITICAL**: template_vars are part of the resource identity! Resources with
/// different template_vars are DISTINCT resources that must all exist in the lockfile.
/// For example, `backend-engineer` with `language=typescript` and `language=javascript`
/// are TWO DIFFERENT resources.
///
/// The second case handles situations where a direct dependency and a transitive
/// dependency point to the same local file but have different names (e.g., manifest
/// name vs path-based name). This prevents false conflicts.
pub fn is_duplicate_entry(existing: &LockedResource, new_entry: &LockedResource) -> bool {
    tracing::info!(
        "is_duplicate_entry: existing.name='{}', new.name='{}', existing.manifest_alias={:?}, new.manifest_alias={:?}, existing.path='{}', new.path='{}'",
        existing.name,
        new_entry.name,
        existing.manifest_alias,
        new_entry.manifest_alias,
        existing.path,
        new_entry.path
    );

    // CRITICAL: manifest_alias is part of resource identity for PATTERN-EXPANDED dependencies!
    // When BOTH entries have manifest_alias (both are direct or pattern-expanded),
    // different aliases mean different resources, even with identical paths/variant_inputs.
    //
    // Example case where we should NOT deduplicate:
    //   - backend-engineer (manifest_alias = Some("backend-engineer"))
    //   - backend-engineer-python (manifest_alias = Some("backend-engineer-python"))
    // Both from same path but represent distinct manifest entries.
    //
    // Example case where we SHOULD deduplicate (let merge strategy decide which wins):
    //   - general-purpose (manifest_alias = Some("general-purpose"), direct from manifest)
    //   - general-purpose (manifest_alias = None, transitive dependency)
    // One is direct, one is transitive - merge strategy will pick the direct one.
    if existing.manifest_alias.is_some()
        && new_entry.manifest_alias.is_some()
        && existing.manifest_alias != new_entry.manifest_alias
    {
        tracing::debug!(
            "NOT duplicates - both are direct/pattern deps with different manifest_alias: existing={:?} vs new={:?} (path={})",
            existing.manifest_alias,
            new_entry.manifest_alias,
            existing.path
        );
        return false; // Different direct dependencies = NOT duplicates
    }

    // Determine if one is direct and one is transitive
    let existing_is_direct = existing.manifest_alias.is_some();
    let new_is_direct = new_entry.manifest_alias.is_some();
    let one_direct_one_transitive = existing_is_direct != new_is_direct;

    // Standard deduplication logic:
    // variant_inputs are ALWAYS part of resource identity - resources with different
    // template_vars are distinct resources that must both exist in the lockfile.
    // This applies regardless of whether dependencies are direct, transitive, or mixed.
    let basic_match = existing.name == new_entry.name
        && existing.source == new_entry.source
        && existing.tool == new_entry.tool;

    let is_duplicate = basic_match && existing.variant_inputs == new_entry.variant_inputs;

    if is_duplicate {
        tracing::debug!(
            "Deduplicating entries: name={}, source={:?}, tool={:?}, manifest_alias existing={:?} new={:?}, one_direct_one_transitive={}",
            existing.name,
            existing.source,
            existing.tool,
            existing.manifest_alias,
            new_entry.manifest_alias,
            one_direct_one_transitive
        );
        return true;
    }

    // Local dependency deduplication: same path and tool
    // Apply same logic as above: variant_inputs are ALWAYS part of resource identity
    if existing.source.is_none() && new_entry.source.is_none() {
        let path_tool_match = existing.path == new_entry.path && existing.tool == new_entry.tool;
        let is_local_duplicate =
            path_tool_match && existing.variant_inputs == new_entry.variant_inputs;

        if is_local_duplicate {
            tracing::debug!(
                "Deduplicating local deps: path={}, tool={:?}, one_direct_one_transitive={}",
                existing.path,
                existing.tool,
                one_direct_one_transitive
            );
            return true;
        }
    }

    tracing::debug!(
        "NOT duplicates: name existing={} new={}, source existing={:?} new={:?}, variant_inputs match={}",
        existing.name,
        new_entry.name,
        existing.source,
        new_entry.source,
        existing.variant_inputs == new_entry.variant_inputs
    );
    false
}

/// Determines if a new lockfile entry should replace an existing duplicate entry.
///
/// Uses a deterministic merge strategy to ensure consistent lockfile generation
/// regardless of processing order (e.g., HashMap iteration order).
///
/// # Merge Priority Rules (highest to lowest)
///
/// 1. **Manifest dependencies win** - Direct manifest dependencies (with `manifest_alias`)
///    always take precedence over transitive dependencies
/// 2. **install=true wins** - Dependencies that create files (`install=true`) are
///    preferred over content-only dependencies (`install=false`)
/// 3. **First wins** - If both have equal priority, keep the existing entry
///
/// This ensures that the lockfile is deterministic even when:
/// - Dependencies are processed in different orders
/// - HashMap iteration order varies between runs
/// - Multiple parents declare the same transitive dependency with different settings
///
/// # Arguments
///
/// * `existing` - The current entry in the lockfile
/// * `new_entry` - The new entry being added
///
/// # Returns
///
/// `true` if the new entry should replace the existing one, `false` otherwise
pub fn should_replace_duplicate(existing: &LockedResource, new_entry: &LockedResource) -> bool {
    let is_new_manifest = new_entry.manifest_alias.is_some();
    let is_existing_manifest = existing.manifest_alias.is_some();
    let new_install = new_entry.install.unwrap_or(true);
    let existing_install = existing.install.unwrap_or(true);

    let should_replace = if is_new_manifest != is_existing_manifest {
        // Rule 1: Manifest dependencies always win
        is_new_manifest
    } else if new_install != existing_install {
        // Rule 2: Prefer install=true (files that should be written)
        new_install
    } else if !is_new_manifest && !is_existing_manifest {
        // Rule 3: Both are transitive with same priority - use deterministic tiebreaker
        // Prefer semver versions over branch/ref names for stability, then alphabetical
        deterministic_version_comparison(existing, new_entry)
    } else {
        // Rule 4: Both are manifest deps with same priority - keep existing (first wins)
        false
    };

    if new_install != existing_install {
        tracing::debug!(
            "Merge decision for {}: existing.install={:?}, new.install={:?}, should_replace={}",
            new_entry.name,
            existing.install,
            new_entry.install,
            should_replace
        );
    }

    should_replace
}

/// Deterministic comparison for transitive dependencies with equal priority.
///
/// Returns `true` if `new_entry` should replace `existing`.
///
/// # Strategy
/// 1. Prefer semver versions (v1.0.0) over branch/ref names (main, HEAD)
/// 2. If both or neither are semver, compare versions alphabetically
/// 3. If versions are equal, compare resolved commits alphabetically
fn deterministic_version_comparison(existing: &LockedResource, new_entry: &LockedResource) -> bool {
    use crate::version::constraints::VersionConstraint;

    let existing_version = existing.version.as_deref().unwrap_or("");
    let new_version = new_entry.version.as_deref().unwrap_or("");

    // Check if version is a semver constraint (Exact or Requirement) vs GitRef (branches)
    let existing_is_semver = matches!(
        VersionConstraint::parse(existing_version),
        Ok(VersionConstraint::Exact { .. }) | Ok(VersionConstraint::Requirement { .. })
    );
    let new_is_semver = matches!(
        VersionConstraint::parse(new_version),
        Ok(VersionConstraint::Exact { .. }) | Ok(VersionConstraint::Requirement { .. })
    );

    if existing_is_semver != new_is_semver {
        // Prefer semver over non-semver (branches like "main")
        let replace = new_is_semver;
        tracing::debug!(
            "Deterministic merge for {}: preferring semver {} over {}, replace={}",
            new_entry.name,
            if new_is_semver {
                new_version
            } else {
                existing_version
            },
            if new_is_semver {
                existing_version
            } else {
                new_version
            },
            replace
        );
        return replace;
    }

    // Both have same semver status - compare versions alphabetically
    match new_version.cmp(existing_version) {
        std::cmp::Ordering::Greater => {
            tracing::debug!(
                "Deterministic merge for {}: new version '{}' > existing '{}', replacing",
                new_entry.name,
                new_version,
                existing_version
            );
            true
        }
        std::cmp::Ordering::Less => {
            tracing::debug!(
                "Deterministic merge for {}: existing version '{}' > new '{}', keeping",
                new_entry.name,
                existing_version,
                new_version
            );
            false
        }
        std::cmp::Ordering::Equal => {
            // Versions equal - use resolved commit as final tiebreaker
            let existing_sha = existing.resolved_commit.as_deref().unwrap_or("");
            let new_sha = new_entry.resolved_commit.as_deref().unwrap_or("");
            let replace = new_sha > existing_sha;
            tracing::debug!(
                "Deterministic merge for {}: versions equal, comparing SHAs: new {} {} existing {}, replace={}",
                new_entry.name,
                &new_sha.get(..8).unwrap_or(new_sha),
                if replace {
                    ">"
                } else {
                    "<="
                },
                &existing_sha.get(..8).unwrap_or(existing_sha),
                replace
            );
            replace
        }
    }
}

/// Manages lockfile operations including entry creation, updates, and cleanup.
pub struct LockfileBuilder<'a> {
    manifest: &'a Manifest,
}

impl<'a> LockfileBuilder<'a> {
    /// Create a new lockfile builder with the given manifest.
    pub fn new(manifest: &'a Manifest) -> Self {
        Self {
            manifest,
        }
    }

    /// Add or update a lockfile entry with deterministic merging for duplicates.
    ///
    /// This method handles deduplication by using (name, source, tool) tuples as the unique key.
    /// When duplicates are found, it uses a deterministic merge strategy to ensure consistent
    /// lockfile generation across runs, regardless of processing order.
    ///
    /// # Merge Strategy (deterministic, order-independent)
    ///
    /// When merging duplicate entries:
    /// 1. **Prefer direct manifest dependencies** (has `manifest_alias`) over transitive dependencies
    /// 2. **Prefer install=true** over install=false (prefer dependencies that create files)
    /// 3. Otherwise, keep the existing entry (first-wins for same priority)
    ///
    /// This ensures that even with non-deterministic HashMap iteration order, the same
    /// logical dependency structure produces the same lockfile.
    ///
    /// # Arguments
    ///
    /// * `lockfile` - The mutable lockfile to update
    /// * `name` - The name of the dependency (for documentation purposes)
    /// * `entry` - The locked resource entry to add or update
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// let mut lockfile = LockFile::new();
    /// let entry = LockedResource {
    ///     name: "my-agent".to_string(),
    ///     source: Some("community".to_string()),
    ///     tool: "claude-code".to_string(),
    ///     // ... other fields
    /// };
    ///
    /// resolver.add_or_update_lockfile_entry(&mut lockfile, entry);
    ///
    /// // Later updates use deterministic merge strategy
    /// let updated_entry = LockedResource {
    ///     name: "my-agent".to_string(),
    ///     source: Some("community".to_string()),
    ///     tool: "claude-code".to_string(),
    ///     // ... updated fields
    /// };
    /// resolver.add_or_update_lockfile_entry(&mut lockfile, updated_entry);
    /// ```
    pub fn add_or_update_lockfile_entry(&self, lockfile: &mut LockFile, entry: LockedResource) {
        let resources = lockfile.get_resources_mut(&entry.resource_type);

        if let Some(existing) = resources.iter_mut().find(|e| is_duplicate_entry(e, &entry)) {
            // Use deterministic merge strategy to ensure consistent lockfile generation
            let should_replace = should_replace_duplicate(existing, &entry);

            tracing::trace!(
                "Duplicate entry for {}: existing.install={:?}, new.install={:?}, should_replace={}",
                entry.name,
                existing.install,
                entry.install,
                should_replace
            );

            if should_replace {
                *existing = entry;
            }
            // Otherwise keep existing entry (deterministic: first-wins for same priority)
        } else {
            resources.push(entry);
        }
    }

    /// Removes stale lockfile entries that are no longer in the manifest.
    ///
    /// This method removes lockfile entries for direct manifest dependencies that have been
    /// commented out or removed from the manifest. This must be called BEFORE
    /// `remove_manifest_entries_for_update()` to ensure stale entries don't cause conflicts
    /// during resolution.
    ///
    /// A manifest-level entry is identified by:
    /// - `manifest_alias.is_none()` - Direct dependency with no pattern expansion
    /// - `manifest_alias.is_some()` - Pattern-expanded dependency (alias must be in manifest)
    ///
    /// For each stale entry found, this also removes its transitive children to maintain
    /// lockfile consistency.
    ///
    /// # Arguments
    ///
    /// * `lockfile` - The mutable lockfile to clean
    ///
    /// # Examples
    ///
    /// If a user comments out an agent in agpm.toml:
    /// ```toml
    /// # [agents]
    /// # example = { source = "community", path = "agents/example.md", version = "v1.0.0" }
    /// ```
    ///
    /// This function will remove the "example" agent from the lockfile and all its transitive
    /// dependencies before the update process begins.
    pub fn remove_stale_manifest_entries(&self, lockfile: &mut LockFile) {
        // Collect all current manifest keys for each resource type
        let manifest_agents: HashSet<String> =
            self.manifest.agents.keys().map(|k| k.to_string()).collect();
        let manifest_snippets: HashSet<String> =
            self.manifest.snippets.keys().map(|k| k.to_string()).collect();
        let manifest_commands: HashSet<String> =
            self.manifest.commands.keys().map(|k| k.to_string()).collect();
        let manifest_scripts: HashSet<String> =
            self.manifest.scripts.keys().map(|k| k.to_string()).collect();
        let manifest_hooks: HashSet<String> =
            self.manifest.hooks.keys().map(|k| k.to_string()).collect();
        let manifest_mcp_servers: HashSet<String> =
            self.manifest.mcp_servers.keys().map(|k| k.to_string()).collect();
        let manifest_skills: HashSet<String> =
            self.manifest.skills.keys().map(|k| k.to_string()).collect();

        // Helper to get the right manifest keys for a resource type
        let get_manifest_keys = |resource_type: ResourceType| match resource_type {
            ResourceType::Agent => &manifest_agents,
            ResourceType::Snippet => &manifest_snippets,
            ResourceType::Command => &manifest_commands,
            ResourceType::Script => &manifest_scripts,
            ResourceType::Hook => &manifest_hooks,
            ResourceType::McpServer => &manifest_mcp_servers,
            ResourceType::Skill => &manifest_skills,
        };

        // Collect (name, source) pairs to remove
        let mut entries_to_remove: HashSet<(String, Option<String>)> = HashSet::new();
        let mut direct_entries: Vec<(String, Option<String>)> = Vec::new();

        // Find all manifest-level entries that are no longer in the manifest
        for resource_type in ResourceType::all() {
            let manifest_keys = get_manifest_keys(*resource_type);
            let resources = lockfile.get_resources(resource_type);

            for entry in resources {
                // Determine if this is a stale manifest-level entry (no longer in manifest)
                let is_stale = if let Some(ref alias) = entry.manifest_alias {
                    // Pattern-expanded entry: stale if alias is NOT in manifest
                    !manifest_keys.contains(alias)
                } else {
                    // Direct entry: stale if name is NOT in manifest
                    !manifest_keys.contains(&entry.name)
                };

                if is_stale {
                    let key = (entry.name.clone(), entry.source.clone());
                    entries_to_remove.insert(key.clone());
                    direct_entries.push(key);
                }
            }
        }

        // For each stale entry, recursively collect its transitive children
        for (parent_name, parent_source) in direct_entries {
            for resource_type in ResourceType::all() {
                if let Some(parent_entry) = lockfile
                    .get_resources(resource_type)
                    .iter()
                    .find(|e| e.name == parent_name && e.source == parent_source)
                {
                    Self::collect_transitive_children(
                        lockfile,
                        parent_entry,
                        &mut entries_to_remove,
                    );
                }
            }
        }

        // Remove all marked entries
        let should_remove = |entry: &LockedResource| {
            entries_to_remove.contains(&(entry.name.clone(), entry.source.clone()))
        };

        lockfile.agents.retain(|entry| !should_remove(entry));
        lockfile.snippets.retain(|entry| !should_remove(entry));
        lockfile.commands.retain(|entry| !should_remove(entry));
        lockfile.scripts.retain(|entry| !should_remove(entry));
        lockfile.hooks.retain(|entry| !should_remove(entry));
        lockfile.mcp_servers.retain(|entry| !should_remove(entry));
    }

    /// Removes lockfile entries for manifest dependencies that will be re-resolved.
    ///
    /// This method removes old entries for direct manifest dependencies before updating,
    /// which handles the case where a dependency's source or resource type changes.
    /// This prevents duplicate entries with the same name but different sources.
    ///
    /// Pattern-expanded and transitive dependencies are preserved because:
    /// - Pattern expansions will be re-added during resolution with (name, source) matching
    /// - Transitive dependencies aren't manifest keys and won't be removed
    ///
    /// # Arguments
    ///
    /// * `lockfile` - The mutable lockfile to clean
    /// * `manifest_keys` - Set of manifest dependency keys being updated
    pub fn remove_manifest_entries_for_update(
        &self,
        lockfile: &mut LockFile,
        manifest_keys: &HashSet<String>,
    ) {
        // Collect (name, source) pairs to remove
        // We use (name, source) tuples to distinguish same-named resources from different sources
        let mut entries_to_remove: HashSet<(String, Option<String>)> = HashSet::new();

        // Step 1: Find direct manifest entries and collect them for transitive traversal
        let mut direct_entries: Vec<(String, Option<String>)> = Vec::new();

        for resource_type in ResourceType::all() {
            let resources = lockfile.get_resources(resource_type);
            for entry in resources {
                // Check if this entry originates from a manifest key being updated
                if manifest_keys.contains(&entry.name)
                    || entry
                        .manifest_alias
                        .as_ref()
                        .is_some_and(|alias| manifest_keys.contains(alias))
                {
                    let key = (entry.name.clone(), entry.source.clone());
                    entries_to_remove.insert(key.clone());
                    direct_entries.push(key);
                }
            }
        }

        // Step 2: For each direct entry, recursively collect its transitive children
        // This ensures that when "agent-A" changes from repo1 to repo2, we also remove
        // all transitive dependencies that came from repo1 via agent-A
        for (parent_name, parent_source) in direct_entries {
            // Find the parent entry in the lockfile
            for resource_type in ResourceType::all() {
                if let Some(parent_entry) = lockfile
                    .get_resources(resource_type)
                    .iter()
                    .find(|e| e.name == parent_name && e.source == parent_source)
                {
                    // Walk its dependency tree
                    Self::collect_transitive_children(
                        lockfile,
                        parent_entry,
                        &mut entries_to_remove,
                    );
                }
            }
        }

        // Step 3: Remove all marked entries
        let should_remove = |entry: &LockedResource| {
            entries_to_remove.contains(&(entry.name.clone(), entry.source.clone()))
        };

        lockfile.agents.retain(|entry| !should_remove(entry));
        lockfile.snippets.retain(|entry| !should_remove(entry));
        lockfile.commands.retain(|entry| !should_remove(entry));
        lockfile.scripts.retain(|entry| !should_remove(entry));
        lockfile.hooks.retain(|entry| !should_remove(entry));
        lockfile.mcp_servers.retain(|entry| !should_remove(entry));
    }

    /// Recursively collect all transitive children of a lockfile entry.
    ///
    /// This walks the dependency graph starting from `parent`, following the `dependencies`
    /// field to find all resources that transitively depend on the parent. Only dependencies
    /// with the same source as the parent are collected (to avoid removing unrelated resources).
    ///
    /// The `dependencies` field contains strings in the format:
    /// - `"resource_type/name"` for dependencies from the same source
    /// - `"source:resource_type/name:version"` for explicit source references
    ///
    /// # Arguments
    ///
    /// * `lockfile` - The lockfile to search for dependencies
    /// * `parent` - The parent entry whose children we want to collect
    /// * `entries_to_remove` - Set of (name, source) pairs to populate with found children
    fn collect_transitive_children(
        lockfile: &LockFile,
        parent: &LockedResource,
        entries_to_remove: &mut HashSet<(String, Option<String>)>,
    ) {
        // For each dependency declared by this parent
        for dep_ref in parent.parsed_dependencies() {
            let dep_path = &dep_ref.path;
            let resource_type = dep_ref.resource_type;

            // Extract the resource name from the path (filename without extension)
            let dep_name = dependency_helpers::extract_filename_from_path(dep_path)
                .unwrap_or_else(|| dep_path.to_string());

            // Determine the source: use explicit source from dep_ref if present, otherwise inherit from parent
            let dep_source = dep_ref.source.or_else(|| parent.source.clone());

            // Find the dependency entry with matching name and source
            if let Some(dep_entry) = lockfile
                .get_resources(&resource_type)
                .iter()
                .find(|e| e.name == dep_name && e.source == dep_source)
            {
                let key = (dep_entry.name.clone(), dep_entry.source.clone());

                // Add to removal set and recurse (if not already processed)
                if !entries_to_remove.contains(&key) {
                    entries_to_remove.insert(key);
                    // Recursively collect this dependency's children
                    Self::collect_transitive_children(lockfile, dep_entry, entries_to_remove);
                }
            }
        }
    }
}

/// Adds pattern-expanded entries to the lockfile with deterministic deduplication.
///
/// This function adds multiple resolved entries from a pattern dependency to the
/// appropriate resource type collection in the lockfile. When duplicates are found,
/// it uses the same deterministic merge strategy as `add_or_update_lockfile_entry`
/// to ensure consistent lockfile generation.
///
/// # Arguments
///
/// * `lockfile` - The mutable lockfile to update
/// * `entries` - Vector of resolved resources from pattern expansion
/// * `resource_type` - The type of resource being added
///
/// # Deduplication
///
/// Uses deterministic merge strategy:
/// 1. Prefer manifest dependencies over transitive dependencies
/// 2. Prefer install=true over install=false
/// 3. Otherwise keep existing entry
pub fn add_pattern_entries(
    lockfile: &mut LockFile,
    entries: Vec<LockedResource>,
    resource_type: ResourceType,
) {
    let resources = lockfile.get_resources_mut(&resource_type);

    for entry in entries {
        if let Some(existing) = resources.iter_mut().find(|e| is_duplicate_entry(e, &entry)) {
            // Use deterministic merge strategy to ensure consistent lockfile generation
            if should_replace_duplicate(existing, &entry) {
                *existing = entry;
            }
        } else {
            resources.push(entry);
        }
    }
}

/// Rewrites a dependency string to include version information.
///
/// This helper function transforms dependency strings by looking up version information
/// in the provided maps and updating the dependency reference accordingly.
///
/// # Arguments
///
/// * `dep` - The original dependency string (must be properly formatted)
/// * `lookup_map` - Map of (resource_type, path, source) -> name for resolving dependencies
/// * `resource_info_map` - Map of (resource_type, name, source) -> (source, version) for version info
/// * `parent_source` - The source of the parent resource (for inheritance)
///
/// # Returns
///
/// The updated dependency string with version information included, or the original
/// dependency string if it cannot be parsed or no version info is found
fn rewrite_dependency_string(
    dep: &str,
    lookup_map: &HashMap<(ResourceType, String, Option<String>), String>,
    resource_info_map: &HashMap<ResourceKey, ResourceInfo>,
    parent_source: Option<String>,
) -> String {
    // Parse dependency using DependencyReference - only support properly formatted dependencies
    if let Ok(existing_dep) = LockfileDependencyRef::from_str(dep) {
        // If it's already a properly formatted dependency, try to add version info if missing
        let dep_source = existing_dep.source.clone().or_else(|| parent_source.clone());
        let dep_resource_type = existing_dep.resource_type;
        let dep_path = existing_dep.path.clone();

        // Look up resource in same source
        if let Some(dep_name) = lookup_map.get(&(
            dep_resource_type,
            dependency_helpers::normalize_lookup_path(&dep_path),
            dep_source.clone(),
        )) {
            if let Some((_source, Some(ver))) =
                resource_info_map.get(&(dep_resource_type, dep_name.clone(), dep_source.clone()))
            {
                // Create updated dependency reference with version
                return LockfileDependencyRef::git(
                    dep_source.clone().unwrap_or_default(),
                    dep_resource_type,
                    dep_path,
                    Some(ver.clone()),
                )
                .to_string();
            }
        }

        // Return as-is if no version info found
        existing_dep.to_string()
    } else {
        // Return as-is if parsing fails
        dep.to_string()
    }
}

// ============================================================================
// Lockfile Helper Operations
// ============================================================================

/// Get patches for a specific resource from the manifest.
///
/// Looks up patches defined in `[patch.<resource_type>.<alias>]` sections
/// and returns them as a HashMap ready for inclusion in the lockfile.
///
/// For pattern-expanded resources, the manifest_alias should be provided to ensure
/// patches are looked up using the original pattern name rather than the concrete
/// resource name.
///
/// # Arguments
///
/// * `manifest` - Reference to the project manifest containing patches
/// * `resource_type` - Type of the resource (agent, snippet, command, etc.)
/// * `name` - Resource name to look up patches for
/// * `manifest_alias` - Optional manifest alias for pattern-expanded resources
///
/// # Returns
///
/// BTreeMap of patch key-value pairs, or empty BTreeMap if no patches defined
pub(super) fn get_patches_for_resource(
    manifest: &Manifest,
    resource_type: ResourceType,
    name: &str,
    manifest_alias: Option<&str>,
) -> BTreeMap<String, toml::Value> {
    // Use manifest_alias for pattern-expanded resources, name for regular resources
    let lookup_name = manifest_alias.unwrap_or(name);

    let patches = match resource_type {
        ResourceType::Agent => &manifest.patches.agents,
        ResourceType::Snippet => &manifest.patches.snippets,
        ResourceType::Command => &manifest.patches.commands,
        ResourceType::Script => &manifest.patches.scripts,
        ResourceType::Hook => &manifest.patches.hooks,
        ResourceType::McpServer => &manifest.patches.mcp_servers,
        ResourceType::Skill => &manifest.patches.skills,
    };

    patches.get(lookup_name).cloned().unwrap_or_default()
}

/// Build the complete merged template variable context for a dependency.
///
/// This creates the full variant_inputs that should be stored in the lockfile,
/// combining both the global project configuration and any dependency-specific
/// variant_inputs overrides.
///
/// This ensures lockfile entries contain the exact template context that was
/// used during dependency resolution, enabling reproducible builds.
///
/// # Arguments
///
/// * `manifest` - Reference to the project manifest containing global project config
/// * `dep` - The dependency to build variant_inputs for
///
/// # Returns
///
/// Complete merged variant_inputs (always returns a Value, empty if no variables)
pub(super) fn build_merged_variant_inputs(
    manifest: &Manifest,
    dep: &ResourceDependency,
) -> serde_json::Value {
    use crate::templating::deep_merge_json;

    // Start with dependency-level template_vars (if any)
    let dep_vars = dep.get_template_vars();

    tracing::debug!(
        "[DEBUG] build_merged_variant_inputs: dep_path='{}', has_dep_vars={}, dep_vars={:?}",
        dep.get_path(),
        dep_vars.is_some(),
        dep_vars
    );

    // Get global project config as JSON
    let global_project = manifest
        .project
        .as_ref()
        .map(|p| p.to_json_value())
        .unwrap_or(serde_json::Value::Object(serde_json::Map::new()));

    tracing::debug!("[DEBUG] build_merged_variant_inputs: global_project={:?}", global_project);

    // Build complete context
    let mut merged_map = serde_json::Map::new();

    // If dependency has template_vars, start with those
    if let Some(vars) = dep_vars {
        if let Some(obj) = vars.as_object() {
            merged_map.extend(obj.clone());
        }
    }

    // Extract project overrides from dependency template_vars (if present)
    let project_overrides = dep_vars
        .and_then(|v| v.get("project").cloned())
        .unwrap_or(serde_json::Value::Object(serde_json::Map::new()));

    // Deep merge global project config with dependency-specific overrides
    let merged_project = deep_merge_json(global_project, &project_overrides);

    // Add merged project config to the template_vars only if it's not empty
    if let Some(project_obj) = merged_project.as_object() {
        if !project_obj.is_empty() {
            merged_map.insert("project".to_string(), merged_project);
        }
    }

    // Always return a Value (empty object if nothing else)
    let result = serde_json::Value::Object(merged_map);

    tracing::debug!(
        "[DEBUG] build_merged_variant_inputs: dep_path='{}', result={:?}",
        dep.get_path(),
        result
    );

    result
}

/// Compute the variant inputs hash for a dependency.
///
/// This helper combines `build_merged_variant_inputs` and `compute_variant_inputs_hash`
/// into a single call, ensuring consistent hash computation across the codebase.
/// The hash includes both the dependency's template_vars and the manifest's global
/// project configuration.
///
/// # Arguments
///
/// * `manifest` - The project manifest containing global project config
/// * `dep` - The resource dependency to compute the hash for
///
/// # Returns
///
/// A SHA-256 hash string in the format `"sha256:hexdigest"`, or the empty
/// variant inputs hash if computation fails.
pub(super) fn compute_merged_variant_hash(manifest: &Manifest, dep: &ResourceDependency) -> String {
    let merged_variant_inputs = build_merged_variant_inputs(manifest, dep);
    crate::utils::compute_variant_inputs_hash(&merged_variant_inputs)
        .unwrap_or_else(|_| crate::utils::EMPTY_VARIANT_INPUTS_HASH.to_string())
}

/// Variant inputs with JSON value and computed hash.
///
/// This struct holds the variant inputs as a JSON value along with its
/// pre-computed SHA-256 hash for identity comparison. Computing the hash
/// once ensures consistency throughout the codebase.
///
/// Uses `#[serde(transparent)]` so it serializes as the JSON value directly,
/// which becomes a TOML table when serialized to TOML.
/// The hash is transient and recomputed after deserialization.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(transparent)]
pub struct VariantInputs {
    /// The JSON value
    json: serde_json::Value,
    /// SHA-256 hash of the serialized JSON (not serialized, computed on load)
    #[serde(skip)]
    hash: String,
}

impl PartialEq for VariantInputs {
    fn eq(&self, other: &Self) -> bool {
        // Compare by hash for performance (avoid deep JSON comparison)
        self.hash == other.hash
    }
}

impl Eq for VariantInputs {}

impl Default for VariantInputs {
    fn default() -> Self {
        Self::new(serde_json::Value::Object(serde_json::Map::new()))
    }
}

impl VariantInputs {
    /// Create a new VariantInputs from a JSON value, computing the hash once.
    pub fn new(json: serde_json::Value) -> Self {
        // Compute hash using centralized function
        let hash = crate::utils::compute_variant_inputs_hash(&json).unwrap_or_else(|_| {
            // Fallback to empty hash if serialization fails (shouldn't happen)
            tracing::error!("Failed to compute variant_inputs_hash, using empty hash");
            "sha256:".to_string()
        });

        Self {
            json,
            hash,
        }
    }

    /// Get the JSON value
    pub fn json(&self) -> &serde_json::Value {
        &self.json
    }

    /// Get the SHA-256 hash
    pub fn hash(&self) -> &str {
        &self.hash
    }

    /// Recompute the hash from the JSON value.
    ///
    /// This is called after deserialization since the hash field is skipped.
    pub fn recompute_hash(&mut self) {
        self.hash = crate::utils::compute_variant_inputs_hash(&self.json).unwrap_or_else(|_| {
            tracing::error!("Failed to recompute variant_inputs_hash");
            "sha256:".to_string()
        });
    }
}

/// Detects conflicts where multiple dependencies resolve to the same installation path.
///
/// This method validates that no two dependencies will overwrite each other during
/// installation. It builds a map of all resolved `installed_at` paths and checks for
/// collisions across all resource types.
///
/// # Arguments
///
/// * `lockfile` - The lockfile containing all resolved dependencies
///
/// # Returns
///
/// Returns `Ok(())` if no conflicts are detected, or an error describing the conflicts.
///
/// # Errors
///
/// Returns an error if:
/// - Two or more dependencies resolve to the same `installed_at` path
/// - The error message lists all conflicting dependency names and the shared path
pub(super) fn detect_target_conflicts(lockfile: &LockFile) -> Result<()> {
    // Map of (installed_at path, resolved_commit) -> list of dependency names
    // Two dependencies with the same path AND same commit are NOT a conflict
    let mut path_map: HashMap<(String, Option<String>), Vec<String>> = HashMap::new();

    // Collect all resources from lockfile
    // Note: Hooks and MCP servers are excluded because they're configuration-only
    // resources that are designed to share config files (.claude/settings.local.json
    // for hooks, .mcp.json for MCP servers), not individual files that would conflict.
    // Also skip resources with install=false since they don't create files.
    let all_resources: Vec<(&str, &LockedResource)> = lockfile
        .agents
        .iter()
        .filter(|r| r.install != Some(false))
        .map(|r| (r.name.as_str(), r))
        .chain(
            lockfile
                .snippets
                .iter()
                .filter(|r| r.install != Some(false))
                .map(|r| (r.name.as_str(), r)),
        )
        .chain(
            lockfile
                .commands
                .iter()
                .filter(|r| r.install != Some(false))
                .map(|r| (r.name.as_str(), r)),
        )
        .chain(
            lockfile
                .scripts
                .iter()
                .filter(|r| r.install != Some(false))
                .map(|r| (r.name.as_str(), r)),
        )
        // Hooks and MCP servers intentionally omitted - they share config files
        .collect();

    // Build the path map with commit information
    for (name, resource) in &all_resources {
        let key = (resource.installed_at.clone(), resource.resolved_commit.clone());
        path_map.entry(key).or_default().push((*name).to_string());
    }

    // Now check for actual conflicts: same path but DIFFERENT commits
    // Group by path only to find potential conflicts
    let mut path_only_map: HashMap<String, Vec<(&str, &LockedResource)>> = HashMap::new();
    for (name, resource) in &all_resources {
        path_only_map.entry(resource.installed_at.clone()).or_default().push((name, resource));
    }

    // Detect conflicts: resources installing to the same path with different content.
    // For Git dependencies: different commits = conflict
    // For local dependencies: different checksums = conflict
    // Same SHA or checksum = identical content = not a conflict
    let mut conflicts: Vec<(String, Vec<String>)> = Vec::new();

    tracing::debug!("DEBUG: Checking {} resources for conflicts", all_resources.len());
    for (path, resources) in path_only_map {
        if resources.len() > 1 {
            tracing::debug!("DEBUG: Checking path {} with {} resources", path, resources.len());
            // Check if all resources share the same canonical name AND source
            // If yes, they're version variants (already handled by SHA-based conflict detection)
            let canonical_names: HashSet<_> = resources.iter().map(|(_, r)| &r.name).collect();
            let sources: HashSet<_> = resources.iter().map(|(_, r)| &r.source).collect();
            let manifest_aliases: HashSet<_> =
                resources.iter().map(|(_, r)| &r.manifest_alias).collect();

            tracing::debug!(
                "DEBUG: canonical_names: {:?}, sources: {:?}, manifest_aliases: {:?}",
                canonical_names,
                sources,
                manifest_aliases
            );

            // If they share the same canonical name, source, AND manifest_alias, they're version variants
            // However, if manifest_aliases differ (e.g., agent-a vs agent-b), it's a conflict
            if canonical_names.len() == 1 && sources.len() == 1 && manifest_aliases.len() == 1 {
                tracing::debug!("DEBUG: Skipping - version variants");
                continue;
            }

            let commits: HashSet<_> = resources.iter().map(|(_, r)| &r.resolved_commit).collect();
            let all_local = commits.len() == 1 && commits.contains(&None);

            // Collect names once
            let names: Vec<String> = resources.iter().map(|(n, _)| (*n).to_string()).collect();

            tracing::debug!("DEBUG: commits: {:?}, all_local: {}", commits, all_local);

            if commits.len() > 1 {
                conflicts.push((path, names));
            } else if all_local {
                // For local dependencies, any duplicate path is a conflict
                // even if content is identical, because it represents
                // multiple manifest entries pointing to same file
                tracing::debug!("DEBUG: Adding local conflict for path: {}", path);
                conflicts.push((path, names));
            }
        }
    }

    if !conflicts.is_empty() {
        // Build a detailed error message
        let mut error_msg = String::from(
            "Target path conflicts detected:\n\n\
             Multiple dependencies resolve to the same installation path with different content.\n\
             This would cause files to overwrite each other.\n\n",
        );

        for (path, names) in &conflicts {
            error_msg.push_str(&format!("  Path: {}\n  Conflicts: {}\n\n", path, names.join(", ")));
        }

        error_msg.push_str(
            "To resolve this conflict:\n\
             1. Use custom 'target' field to specify different installation paths:\n\
                Example: target = \"custom/subdir/file.md\"\n\n\
             2. Use custom 'filename' field to specify different filenames:\n\
                Example: filename = \"utils-v2.md\"\n\n\
             3. For transitive dependencies, add them as direct dependencies with custom target/filename\n\n\
             4. Ensure pattern dependencies don't overlap with single-file dependencies\n\n\
             Note: This often occurs when different dependencies have transitive dependencies\n\
             with the same name but from different sources.",
        );

        return Err(anyhow::anyhow!(error_msg));
    }

    Ok(())
}

/// Add version information to dependency references in all lockfile entries.
///
/// This post-processing step updates the `dependencies` field of each locked resource
/// to include version information (e.g., converting "agent/helper" to "agent/helper@v1.0.0").
///
/// # Arguments
///
/// * `lockfile` - The mutable lockfile to update
pub(super) fn add_version_to_all_dependencies(lockfile: &mut LockFile) {
    use crate::resolver::types as dependency_helpers;

    // Build lookup map: (resource_type, normalized_path, source) -> name
    let mut lookup_map: HashMap<(ResourceType, String, Option<String>), String> = HashMap::new();

    // Build lookup from all lockfile entries
    for resource_type in ResourceType::all() {
        for entry in lockfile.get_resources(resource_type) {
            let normalized_path = dependency_helpers::normalize_lookup_path(&entry.path);
            lookup_map.insert(
                (*resource_type, normalized_path.clone(), entry.source.clone()),
                entry.name.clone(),
            );

            // Also store by filename for backward compatibility
            if let Some(filename) = dependency_helpers::extract_filename_from_path(&entry.path) {
                lookup_map
                    .insert((*resource_type, filename, entry.source.clone()), entry.name.clone());
            }

            // Also store by type-stripped path
            if let Some(stripped) =
                dependency_helpers::strip_resource_type_directory(&normalized_path)
            {
                lookup_map
                    .insert((*resource_type, stripped, entry.source.clone()), entry.name.clone());
            }
        }
    }

    // Build resource info map: (resource_type, name, source) -> (source, version)
    let mut resource_info_map: HashMap<ResourceKey, ResourceInfo> = HashMap::new();

    for resource_type in ResourceType::all() {
        for entry in lockfile.get_resources(resource_type) {
            resource_info_map.insert(
                (*resource_type, entry.name.clone(), entry.source.clone()),
                (entry.source.clone(), entry.version.clone()),
            );
        }
    }

    // Update dependencies in all resources
    for resource_type in ResourceType::all() {
        let resources = lockfile.get_resources_mut(resource_type);
        for entry in resources {
            let parent_source = entry.source.clone();

            let updated_deps: Vec<String> = entry
                .dependencies
                .iter()
                .map(|dep| {
                    rewrite_dependency_string(
                        dep,
                        &lookup_map,
                        &resource_info_map,
                        parent_source.clone(),
                    )
                })
                .collect();

            entry.dependencies = updated_deps;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::ResourceType;
    use crate::lockfile::LockedResource;
    use crate::manifest::ResourceDependency;

    fn create_test_manifest() -> Manifest {
        let mut manifest = Manifest::default();
        manifest.agents.insert(
            "test-agent".to_string(),
            ResourceDependency::Simple("agents/test-agent.md".to_string()),
        );
        manifest.snippets.insert(
            "test-snippet".to_string(),
            ResourceDependency::Simple("snippets/test-snippet.md".to_string()),
        );
        manifest
    }

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

        // Add some test entries
        lockfile.agents.push(LockedResource {
            name: "test-agent".to_string(),
            source: Some("community".to_string()),
            url: Some("https://github.com/test/repo.git".to_string()),
            path: "agents/test-agent.md".to_string(),
            version: Some("v1.0.0".to_string()),
            resolved_commit: Some("abc123".to_string()),
            checksum: "sha256:test".to_string(),
            installed_at: ".claude/agents/test-agent.md".to_string(),
            dependencies: vec![],
            resource_type: ResourceType::Agent,
            tool: Some("claude-code".to_string()),
            manifest_alias: None,
            context_checksum: None,
            applied_patches: std::collections::BTreeMap::new(),
            install: None,
            variant_inputs: crate::resolver::lockfile_builder::VariantInputs::default(),
            is_private: false,
            approximate_token_count: None,
        });

        lockfile.snippets.push(LockedResource {
            name: "test-snippet".to_string(),
            source: Some("community".to_string()),
            url: Some("https://github.com/test/repo.git".to_string()),
            path: "snippets/test-snippet.md".to_string(),
            version: Some("v1.0.0".to_string()),
            resolved_commit: Some("def456".to_string()),
            checksum: "sha256:test2".to_string(),
            installed_at: ".claude/snippets/test-snippet.md".to_string(),
            dependencies: vec![],
            resource_type: ResourceType::Snippet,
            tool: Some("claude-code".to_string()),
            manifest_alias: None,
            context_checksum: None,
            applied_patches: std::collections::BTreeMap::new(),
            install: None,
            variant_inputs: crate::resolver::lockfile_builder::VariantInputs::default(),
            is_private: false,
            approximate_token_count: None,
        });

        lockfile
    }

    #[test]
    fn test_add_or_update_lockfile_entry_new() {
        let manifest = create_test_manifest();
        let builder = LockfileBuilder::new(&manifest);
        let mut lockfile = LockFile::default();

        let entry = LockedResource {
            resource_type: ResourceType::Agent,
            name: "new-agent".to_string(),
            source: Some("community".to_string()),
            url: Some("https://github.com/test/repo.git".to_string()),
            path: "agents/new-agent.md".to_string(),
            version: Some("v1.0.0".to_string()),
            tool: Some("claude-code".to_string()),
            manifest_alias: None,
            context_checksum: None,
            installed_at: ".claude/agents/new-agent.md".to_string(),
            resolved_commit: Some("xyz789".to_string()),
            checksum: "sha256:new".to_string(),
            dependencies: vec![],
            applied_patches: std::collections::BTreeMap::new(),
            install: None,
            variant_inputs: crate::resolver::lockfile_builder::VariantInputs::default(),
            is_private: false,
            approximate_token_count: None,
        };

        builder.add_or_update_lockfile_entry(&mut lockfile, entry);

        assert_eq!(lockfile.agents.len(), 1);
        assert_eq!(lockfile.agents[0].name, "new-agent");
    }

    #[test]
    fn test_add_or_update_lockfile_entry_replace() {
        let manifest = create_test_manifest();
        let builder = LockfileBuilder::new(&manifest);
        let mut lockfile = create_test_lockfile();

        let updated_entry = LockedResource {
            resource_type: ResourceType::Agent,
            name: "test-agent".to_string(),
            source: Some("community".to_string()),
            url: Some("https://github.com/test/repo.git".to_string()),
            path: "agents/test-agent.md".to_string(),
            version: Some("v1.0.0".to_string()),
            tool: Some("claude-code".to_string()),
            manifest_alias: Some("test-agent".to_string()), // Manifest dependency being updated
            context_checksum: None,
            installed_at: ".claude/agents/test-agent.md".to_string(),
            resolved_commit: Some("updated123".to_string()), // Updated commit
            checksum: "sha256:updated".to_string(),          // Updated checksum
            dependencies: vec![],
            applied_patches: std::collections::BTreeMap::new(),
            install: None,
            variant_inputs: crate::resolver::lockfile_builder::VariantInputs::default(),
            is_private: false,
            approximate_token_count: None,
        };

        builder.add_or_update_lockfile_entry(&mut lockfile, updated_entry);

        assert_eq!(lockfile.agents.len(), 1);
        assert_eq!(lockfile.agents[0].resolved_commit, Some("updated123".to_string()));
        assert_eq!(lockfile.agents[0].checksum, "sha256:updated");
    }

    #[test]
    fn test_remove_stale_manifest_entries() {
        let mut manifest = create_test_manifest();
        // Remove one agent from manifest to make it stale
        manifest.agents.remove("test-agent");

        let builder = LockfileBuilder::new(&manifest);
        let mut lockfile = create_test_lockfile();

        builder.remove_stale_manifest_entries(&mut lockfile);

        // test-agent should be removed, test-snippet should remain
        assert_eq!(lockfile.agents.len(), 0);
        assert_eq!(lockfile.snippets.len(), 1);
        assert_eq!(lockfile.snippets[0].name, "test-snippet");
    }

    #[test]
    fn test_remove_manifest_entries_for_update() {
        let manifest = create_test_manifest();
        let builder = LockfileBuilder::new(&manifest);
        let mut lockfile = create_test_lockfile();

        let mut manifest_keys = HashSet::new();
        manifest_keys.insert("test-agent".to_string());

        builder.remove_manifest_entries_for_update(&mut lockfile, &manifest_keys);

        // test-agent should be removed, test-snippet should remain
        assert_eq!(lockfile.agents.len(), 0);
        assert_eq!(lockfile.snippets.len(), 1);
        assert_eq!(lockfile.snippets[0].name, "test-snippet");
    }

    #[test]
    fn test_collect_transitive_children() {
        let lockfile = create_test_lockfile();
        let mut entries_to_remove = HashSet::new();

        // Create a parent with dependencies
        let parent = LockedResource {
            resource_type: ResourceType::Agent,
            name: "parent".to_string(),
            source: Some("community".to_string()),
            url: Some("https://github.com/test/repo.git".to_string()),
            path: "agents/parent.md".to_string(),
            version: Some("v1.0.0".to_string()),
            tool: Some("claude-code".to_string()),
            manifest_alias: None,
            context_checksum: None,
            installed_at: ".claude/agents/parent.md".to_string(),
            resolved_commit: Some("parent123".to_string()),
            checksum: "sha256:parent".to_string(),
            dependencies: vec!["agent:agents/test-agent".to_string()], // Reference to test-agent (new format)
            applied_patches: std::collections::BTreeMap::new(),
            install: None,
            variant_inputs: crate::resolver::lockfile_builder::VariantInputs::default(),
            is_private: false,
            approximate_token_count: None,
        };

        LockfileBuilder::collect_transitive_children(&lockfile, &parent, &mut entries_to_remove);

        // Should find the test-agent dependency
        assert!(
            entries_to_remove.contains(&("test-agent".to_string(), Some("community".to_string())))
        );
    }

    #[test]
    fn test_build_merged_variant_inputs_preserves_all_keys() {
        use crate::manifest::DetailedDependency;
        use serde_json::json;

        // Create a manifest with no global project config
        let manifest_toml = r#"
[sources]
test-repo = "https://example.com/repo.git"
        "#;

        let manifest: Manifest = toml::from_str(manifest_toml).unwrap();

        // Create a dependency with template_vars containing both project and config
        let dep = ResourceDependency::Detailed(Box::new(DetailedDependency {
            source: Some("test-repo".to_string()),
            path: "agents/test.md".to_string(),
            version: Some("v1.0.0".to_string()),
            branch: None,
            rev: None,
            command: None,
            args: None,
            target: None,
            filename: None,
            dependencies: None,
            tool: None,
            flatten: None,
            install: None,
            template_vars: Some(json!({
                "project": { "name": "Production" },
                "config": { "model": "claude-3-opus", "temperature": 0.5 }
            })),
        }));

        // Call build_merged_variant_inputs
        let result = build_merged_variant_inputs(&manifest, &dep);

        // Print the result for debugging
        println!(
            "Result: {}",
            serde_json::to_string_pretty(&result).unwrap_or_else(|_| "{}".to_string())
        );

        // Verify both project and config are present
        assert!(result.get("project").is_some(), "project should be present in variant_inputs");
        assert!(result.get("config").is_some(), "config should be present in variant_inputs");

        let config = result.get("config").unwrap();
        assert_eq!(config.get("model").unwrap().as_str().unwrap(), "claude-3-opus");
        assert_eq!(config.get("temperature").unwrap().as_f64().unwrap(), 0.5);
    }

    #[test]
    fn test_direct_vs_transitive_with_different_template_vars_should_not_deduplicate() {
        use serde_json::json;

        // Create direct dependency with template_vars = {lang: "rust"}
        let direct = LockedResource {
            name: "agents/generic".to_string(),
            manifest_alias: Some("generic-rust".to_string()), // Direct from manifest
            source: Some("community".to_string()),
            url: Some("https://github.com/test/repo.git".to_string()),
            path: "agents/generic.md".to_string(),
            version: Some("v1.0.0".to_string()),
            resolved_commit: Some("abc123".to_string()),
            checksum: "sha256:direct".to_string(),
            installed_at: ".claude/agents/generic-rust.md".to_string(),
            dependencies: vec![],
            resource_type: ResourceType::Agent,
            tool: Some("claude-code".to_string()),
            context_checksum: None,
            applied_patches: std::collections::BTreeMap::new(),
            install: None,
            variant_inputs: VariantInputs::new(json!({"lang": "rust"})),
            is_private: false,
            approximate_token_count: None,
        };

        // Create transitive dependency with template_vars = {lang: "python"}
        let transitive = LockedResource {
            name: "agents/generic".to_string(),
            manifest_alias: None, // Transitive dependency
            source: Some("community".to_string()),
            url: Some("https://github.com/test/repo.git".to_string()),
            path: "agents/generic.md".to_string(),
            version: Some("v1.0.0".to_string()),
            resolved_commit: Some("abc123".to_string()),
            checksum: "sha256:transitive".to_string(),
            installed_at: ".claude/agents/generic.md".to_string(),
            dependencies: vec![],
            resource_type: ResourceType::Agent,
            tool: Some("claude-code".to_string()),
            context_checksum: None,
            applied_patches: std::collections::BTreeMap::new(),
            install: None,
            variant_inputs: VariantInputs::new(json!({"lang": "python"})),
            is_private: false,
            approximate_token_count: None,
        };

        // According to the CRITICAL note in the code:
        // "template_vars are part of the resource identity! Resources with
        // different template_vars are DISTINCT resources that must all exist in the lockfile."
        //
        // Therefore, these should NOT be considered duplicates even though
        // one is direct and one is transitive.
        let is_dup = is_duplicate_entry(&direct, &transitive);

        assert!(
            !is_dup,
            "Direct and transitive dependencies with different template_vars should NOT be duplicates. \
             They represent distinct resources that both need to exist in the lockfile."
        );
    }
}