phora 0.6.0

A git-based artifact package manager and multiplexer for content-addressed file distribution
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
//! Lock file DTOs (`phora.lock`, `phora.local.lock`) and resolution matching.

use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};

use crate::config::{Host, ParsedSource, Protocol, Refspec, SourceMode};
use crate::source::NormalizedUrl;

pub const LOCK_SCHEMA_VERSION: u32 = 1;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Lock {
    pub version: u32,
    #[serde(default)]
    pub sources: Vec<LockedSource>,
    /// Skip-serialized when empty so a no-transitive lock keeps the bare source-table layout.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub trusted_hooks: Vec<TrustedHook>,
    /// Discovered-but-untrusted transitive hooks, surfaced with their commit-bound preimage so a
    /// consumer can pin an approval; carries no trust. Skip-serialized when empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub candidate_hooks: Vec<CandidateHookRecord>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrustedHook {
    pub dep_instance: String,
    pub hook_id: String,
    pub preimage: String,
    pub approved_at: String,
    /// Consumer-facing root import name scoping `phora trust <source>`; `default` keeps old locks parseable.
    #[serde(default)]
    pub source: String,
    /// Dep commit this approval trusted; the `from` side of the inspect-before-trust diff.
    #[serde(default)]
    pub commit: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CandidateHookRecord {
    pub dep_instance: String,
    pub hook_id: String,
    pub preimage: String,
    pub command: String,
    /// Consumer-facing root import name scoping `phora trust <source>`; `default` keeps old locks parseable.
    #[serde(default)]
    pub source: String,
    /// Dep commit this candidate resolved to; the `to` side of the inspect-before-trust diff.
    #[serde(default)]
    pub commit: String,
}

impl Lock {
    #[must_use]
    pub fn find_source(&self, name: &str) -> Option<&LockedSource> {
        self.sources.iter().find(|s| s.name == name)
    }

    #[must_use]
    pub fn find_entry(&self, name: &str, r#ref: Option<&str>) -> Option<&LockedSource> {
        self.sources
            .iter()
            .find(|s| s.name == name && s.r#ref.as_deref() == r#ref)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LockedSource {
    pub name: String,
    pub git: String,
    pub resolved: String,
    pub commit: String,
    pub digest: String,
    /// Hash of export-affecting config at the time `digest` was computed; a mismatch
    /// re-digests the pinned commit without moving it.
    pub config_digest: String,
    /// Kind-tagged effective ref, set only when this entry overrides the source's
    /// default refspec; `None` for the canonical entry so bare locks stay byte-identical.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub r#ref: Option<String>,
    /// Owning `Instance.stable_key()` for a transitive node; `None` for a consumer root.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub instance: Option<String>,
    /// Build key of a `build` source: its command plus the materialized inputs it ran over.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub build: Option<String>,
}

/// The `resolved` value of a build source's entry.
pub const BUILD_RESOLVED: &str = "build";

/// Kind-tagged so `Branch("x")` and `Tag("x")` never collide.
#[must_use]
pub fn encode_ref(r: &Refspec) -> String {
    match r {
        Refspec::Branch(s) => format!("branch:{s}"),
        Refspec::Tag(s) => format!("tag:{s}"),
        Refspec::Rev(s) => format!("rev:{s}"),
        Refspec::Default => "default".to_owned(),
        Refspec::None => "url".to_owned(),
    }
}

/// The `ref` field value for an entry: `None` when the effective ref equals the
/// source's default, else the kind-tagged override.
#[must_use]
pub fn ref_discriminator(effective_ref: &Refspec, source_default: &Refspec) -> Option<String> {
    let encoded = encode_ref(effective_ref);
    (encoded != encode_ref(source_default)).then_some(encoded)
}

/// Effective lock merges base and local locks; local entries override base by name.
#[must_use]
pub fn merge_locks(base: &Lock, local: Option<&Lock>) -> Lock {
    let mut merged = base.clone();
    if let Some(local) = local {
        for local_source in &local.sources {
            // `instance` in the key keeps a transitive node from collapsing a consumer source.
            merged.sources.retain(|s| {
                !(s.name == local_source.name
                    && s.r#ref == local_source.r#ref
                    && s.instance == local_source.instance)
            });
            merged.sources.push(local_source.clone());
        }
        for local_hook in &local.trusted_hooks {
            merged.trusted_hooks.retain(|h| {
                !(h.dep_instance == local_hook.dep_instance && h.hook_id == local_hook.hook_id)
            });
            merged.trusted_hooks.push(local_hook.clone());
        }
    }
    merged
}

/// Whether a locked pin still belongs to `source`: same remote identity and refspec.
/// Selection config (include, exclude, root, export policy) is not part of the pin.
/// A source that fails to resolve never matches.
#[must_use]
pub fn source_matches(
    source: &ParsedSource,
    locked: &LockedSource,
    hosts: &BTreeMap<String, Host>,
    protocol: Protocol,
) -> bool {
    entry_matches(source, &source.refspec(), locked, hosts, protocol)
}

/// Like [`source_matches`] but checks `effective_ref` against the lock's `resolved`,
/// so a ref-overriding binding reuses only its own (source, ref) entry. A build
/// source has no remote pin; its config digest is its identity.
#[must_use]
pub fn entry_matches(
    source: &ParsedSource,
    effective_ref: &Refspec,
    locked: &LockedSource,
    hosts: &BTreeMap<String, Host>,
    protocol: Protocol,
) -> bool {
    if let (SourceMode::Url, Some(url)) = (source.mode(), source.source_url()) {
        // The synthetic commit addresses the whole download, so the url alone identifies the pin.
        return NormalizedUrl::parse(url) == NormalizedUrl::parse(&locked.git);
    }

    if source.mode() == SourceMode::Build {
        return locked.resolved == BUILD_RESOLVED && source.config_digest() == locked.config_digest;
    }

    let Ok(resolved) = source.resolved_remote(hosts, protocol) else {
        return false;
    };
    // Protocol-independent: https/ssh/literal forms of one repo share an identity.
    NormalizedUrl::parse(&resolved) == NormalizedUrl::parse(&locked.git)
        && effective_ref.to_string() == locked.resolved
}

/// Routes resolved sources into the base lock and the local lock (`None` when no
/// source name appears in `local_override_names`).
#[must_use]
pub fn split_locks(
    resolved: Vec<(String, LockedSource)>,
    local_override_names: &BTreeSet<String>,
) -> (Lock, Option<Lock>) {
    let mut base = Vec::new();
    let mut local = Vec::new();
    for (name, locked) in resolved {
        // A transitive node always lands in the base namespace, ignoring the override set.
        if locked.instance.is_none() && local_override_names.contains(&name) {
            local.push(locked);
        } else {
            base.push(locked);
        }
    }
    let base_lock = Lock {
        version: LOCK_SCHEMA_VERSION,
        sources: base,
        trusted_hooks: Vec::new(),
        candidate_hooks: Vec::new(),
    };
    let local_lock = (!local.is_empty()).then_some(Lock {
        version: LOCK_SCHEMA_VERSION,
        sources: local,
        trusted_hooks: Vec::new(),
        candidate_hooks: Vec::new(),
    });
    (base_lock, local_lock)
}

/// Keeps `prior`'s shared pin for every root source in `shadowed`: a local override
/// resolves into the local lock, so the base lock would otherwise lose the pin other
/// checkouts deploy from.
pub fn carry_shadowed_pins(base: &mut Lock, prior: &Lock, shadowed: &BTreeSet<String>) {
    for (position, locked) in prior.sources.iter().enumerate() {
        let is_shadowed_root = locked.instance.is_none() && shadowed.contains(&locked.name);
        let already_pinned = base
            .sources
            .iter()
            .any(|kept| kept.instance.is_none() && kept.name == locked.name);
        if is_shadowed_root && !already_pinned {
            let at = position.min(base.sources.len());
            base.sources.insert(at, locked.clone());
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use super::*;
    use crate::config::{Config, Host, Protocol};
    use crate::source::NormalizedUrl;

    fn no_hosts() -> BTreeMap<String, Host> {
        BTreeMap::new()
    }

    fn hosts_from(toml: &str) -> BTreeMap<String, Host> {
        Config::parse(toml).expect("hosts toml parses").hosts
    }

    fn locked(name: &str, git: &str, resolved: &str) -> LockedSource {
        LockedSource {
            name: name.to_owned(),
            git: git.to_owned(),
            resolved: resolved.to_owned(),
            commit: "c0ffee".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: "blake3:cfg".to_owned(),
            r#ref: None,
            instance: None,
            build: None,
        }
    }

    fn transitive(name: &str, git: &str, resolved: &str, instance: &str) -> LockedSource {
        LockedSource {
            instance: Some(instance.to_owned()),
            ..locked(name, git, resolved)
        }
    }

    fn source_from(toml_body: &str) -> ParsedSource {
        let toml = format!("version = 1\n\n[sources.s]\n{toml_body}");
        let raw = Config::parse(&toml)
            .expect("source toml parses")
            .sources
            .remove("s")
            .expect("source `s` present");
        ParsedSource::parse("s", &raw).expect("source parses to typed form")
    }

    // PAM-009: lock TOML round-trip

    #[test]
    fn lock_round_trips_through_toml() {
        let lock = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: vec![
                locked("dotfiles", "https://github.com/me/dotfiles.git", "main"),
                locked(
                    "company-configs",
                    "https://github.com/company/shared-configs.git",
                    "v2.1",
                ),
            ],
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };

        let text = toml::to_string(&lock).expect("lock serializes to toml");
        let parsed: Lock = toml::from_str(&text).expect("lock deserializes from toml");

        assert_eq!(parsed.version, lock.version);
        assert_eq!(parsed.sources.len(), lock.sources.len());
        let a = &parsed.sources[0];
        let b = &lock.sources[0];
        assert_eq!(a.name, b.name);
        assert_eq!(a.git, b.git);
        assert_eq!(a.resolved, b.resolved);
        assert_eq!(a.commit, b.commit);
        assert_eq!(a.digest, b.digest);
        assert_eq!(a.config_digest, b.config_digest);
    }

    #[test]
    fn lock_toml_uses_sources_array_of_tables_with_spec_field_names() {
        let lock = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: vec![locked(
                "dotfiles",
                "https://github.com/me/dotfiles.git",
                "main",
            )],
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };

        let text = toml::to_string(&lock).expect("lock serializes to toml");

        assert!(text.contains("version = 1"), "version field, got:\n{text}");
        assert!(
            text.contains("[[sources]]"),
            "sources must be an array-of-tables, got:\n{text}"
        );
        for field in [
            "name",
            "git",
            "resolved",
            "commit",
            "digest",
            "config_digest",
        ] {
            assert!(
                text.contains(&format!("{field} =")),
                "missing `{field}` field in:\n{text}"
            );
        }
    }

    // PAM-010: merge_locks (regression guard)

    #[test]
    fn merge_locks_local_overrides_base_by_name() {
        let base = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: vec![locked(
                "loqui",
                "https://github.com/srnnkls/loqui.git",
                "v1.0",
            )],
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };
        let local = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: vec![locked("loqui", "/home/soeren/dev/loqui", "main")],
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };

        let merged = merge_locks(&base, Some(&local));

        let loqui = merged.find_source("loqui").expect("loqui kept");
        assert_eq!(loqui.git, "/home/soeren/dev/loqui");
        assert_eq!(loqui.resolved, "main");
        assert_eq!(
            merged.sources.iter().filter(|s| s.name == "loqui").count(),
            1,
            "override replaces, does not duplicate"
        );
    }

    #[test]
    fn merge_locks_keeps_base_only_and_adds_local_only() {
        let base = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: vec![locked(
                "dotfiles",
                "https://github.com/me/dotfiles.git",
                "main",
            )],
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };
        let local = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: vec![locked("extra", "/home/soeren/dev/extra", "main")],
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };

        let merged = merge_locks(&base, Some(&local));

        assert!(merged.find_source("dotfiles").is_some(), "base-only kept");
        assert!(merged.find_source("extra").is_some(), "local-only added");
    }

    #[test]
    fn source_matches_when_git_refspec_and_config_digest_all_agree() {
        let source =
            source_from("git = \"https://github.com/me/dotfiles.git\"\nbranch = \"main\"\n");
        let locked = LockedSource {
            name: "dotfiles".to_owned(),
            git: "https://github.com/me/dotfiles.git".to_owned(),
            resolved: source.refspec().to_string(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: source.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert!(
            source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "identical git + refspec + config_digest must reuse the lock"
        );
    }

    #[test]
    fn source_does_not_match_when_git_differs() {
        let source =
            source_from("git = \"https://github.com/me/dotfiles.git\"\nbranch = \"main\"\n");
        let locked = LockedSource {
            name: "dotfiles".to_owned(),
            git: "https://github.com/OTHER/dotfiles.git".to_owned(),
            resolved: source.refspec().to_string(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: source.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert!(
            !source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "different git URL must not match"
        );
    }

    #[test]
    fn source_does_not_match_when_refspec_differs() {
        let source =
            source_from("git = \"https://github.com/me/dotfiles.git\"\nbranch = \"main\"\n");
        let locked = LockedSource {
            name: "dotfiles".to_owned(),
            git: "https://github.com/me/dotfiles.git".to_owned(),
            resolved: "develop".to_owned(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: source.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert!(
            !source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "different resolved refspec must not match"
        );
    }

    #[test]
    fn source_matches_when_only_config_digest_differs() {
        let source = source_from(
            "git = \"https://github.com/me/dotfiles.git\"\nbranch = \"main\"\ninclude = [\"editor\"]\n",
        );
        let other = source_from(
            "git = \"https://github.com/me/dotfiles.git\"\nbranch = \"main\"\ninclude = [\"lint\"]\n",
        );
        let locked = LockedSource {
            name: "dotfiles".to_owned(),
            git: "https://github.com/me/dotfiles.git".to_owned(),
            resolved: source.refspec().to_string(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: other.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert_ne!(
            source.config_digest(),
            other.config_digest(),
            "changing include must change the config digest (guards the test premise)"
        );
        assert!(
            source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "same git + refspec with changed selection config must keep the locked commit"
        );
    }

    #[test]
    fn literal_git_lock_still_matches_literal_git_source() {
        let source =
            source_from("git = \"https://github.com/me/dotfiles.git\"\nbranch = \"main\"\n");
        let locked = LockedSource {
            name: "dotfiles".to_owned(),
            // lock git lacks `.git`: raw-string compare fails, NormalizedUrl matches.
            git: "https://github.com/me/dotfiles".to_owned(),
            resolved: source.refspec().to_string(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: source.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert!(
            source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "a literal-git lock must still match its literal-git source under \
             normalized-identity comparison"
        );
    }

    #[test]
    fn host_path_source_matches_equivalent_literal_github_lock() {
        let source =
            source_from("host = \"github\"\npath = \"srnnkls/tropos\"\nbranch = \"main\"\n");
        let locked = LockedSource {
            name: "tropos".to_owned(),
            git: "https://github.com/srnnkls/tropos.git".to_owned(),
            resolved: source.refspec().to_string(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: source.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert!(
            source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "a host+path source resolving (via built-in github) to the locked literal \
             github URL must match, so sync suppresses the fetch"
        );
    }

    #[test]
    fn lock_written_https_still_matches_source_resolved_as_ssh() {
        let source =
            source_from("host = \"github\"\npath = \"srnnkls/tropos\"\nbranch = \"main\"\n");

        let ssh_remote = source
            .resolved_remote(&no_hosts(), Protocol::Ssh)
            .expect("symbolic github ssh resolves");
        assert!(
            ssh_remote.starts_with("git@github.com:"),
            "test premise: the ssh resolution must be the scp-style form, got {ssh_remote}"
        );

        let locked = LockedSource {
            name: "tropos".to_owned(),
            git: "https://github.com/srnnkls/tropos.git".to_owned(),
            resolved: source.refspec().to_string(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: source.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert_ne!(
            ssh_remote, locked.git,
            "premise: the raw ssh and https strings differ — a raw-string compare would reject this"
        );
        assert_eq!(
            NormalizedUrl::parse(&ssh_remote),
            NormalizedUrl::parse(&locked.git),
            "premise: both forms normalize to one identity"
        );

        assert!(
            source_matches(&source, &locked, &no_hosts(), Protocol::Ssh),
            "an https-written lock must still match the same repo resolved as ssh: \
             flipping protocol must not force a refetch"
        );
    }

    #[test]
    fn source_does_not_match_when_remote_identity_differs() {
        let source =
            source_from("host = \"github\"\npath = \"srnnkls/tropos\"\nbranch = \"main\"\n");
        let locked = LockedSource {
            name: "tropos".to_owned(),
            git: "https://github.com/srnnkls/OTHER-REPO.git".to_owned(),
            resolved: source.refspec().to_string(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: source.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert!(
            !source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "a different repo identity must not match, even under normalized comparison"
        );
    }

    #[test]
    fn source_does_not_match_when_remote_cannot_resolve() {
        let source =
            source_from("host = \"nonesuch\"\npath = \"srnnkls/tropos\"\nbranch = \"main\"\n");
        let locked = LockedSource {
            name: "tropos".to_owned(),
            git: "https://github.com/srnnkls/tropos.git".to_owned(),
            resolved: source.refspec().to_string(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: source.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert!(
            !source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "a source whose remote cannot be resolved must not match any lock"
        );
    }

    #[test]
    fn host_override_resolution_flows_into_source_matches() {
        let hosts = hosts_from(
            "version = 1\n\n[hosts.github]\nremote = { https = \"https://ghe.corp/{path}.git\", \
             ssh = \"git@ghe.corp:{path}.git\" }\n",
        );
        let source =
            source_from("host = \"github\"\npath = \"srnnkls/tropos\"\nbranch = \"main\"\n");

        let enterprise_lock = LockedSource {
            name: "tropos".to_owned(),
            git: "https://ghe.corp/srnnkls/tropos.git".to_owned(),
            resolved: source.refspec().to_string(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: source.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert!(
            source_matches(&source, &enterprise_lock, &hosts, Protocol::Https),
            "the [hosts.github] override must flow into resolution so the source matches the \
             ghe.corp lock"
        );

        let builtin_lock = LockedSource {
            git: "https://github.com/srnnkls/tropos.git".to_owned(),
            ..enterprise_lock.clone()
        };
        assert!(
            !source_matches(&source, &builtin_lock, &hosts, Protocol::Https),
            "with the override active the source resolves to ghe.corp, so a builtin-github lock \
             must NOT match — proving the hosts arg drove resolution, not the builtin"
        );
    }

    #[test]
    fn existing_literal_git_lock_deserializes_and_matches() {
        let toml = "\
name = \"dotfiles\"
git = \"https://github.com/me/dotfiles.git\"
resolved = \"main\"
commit = \"abc123\"
digest = \"blake3:artifact\"
config_digest = \"PLACEHOLDER\"
";
        let source =
            source_from("git = \"https://github.com/me/dotfiles.git\"\nbranch = \"main\"\n");
        let toml = toml.replace("PLACEHOLDER", &source.config_digest());

        let locked: LockedSource =
            toml::from_str(&toml).expect("an existing literal-git lock must still deserialize");

        assert!(
            source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "an existing lock written with only today's fields must still match its source — \
             no version bump, no new required field"
        );
    }

    #[test]
    fn host_path_source_matches_when_only_config_digest_differs() {
        let source = source_from(
            "host = \"github\"\npath = \"srnnkls/tropos\"\nbranch = \"main\"\ninclude = [\"editor\"]\n",
        );
        let other = source_from(
            "host = \"github\"\npath = \"srnnkls/tropos\"\nbranch = \"main\"\ninclude = [\"lint\"]\n",
        );
        let locked = LockedSource {
            name: "tropos".to_owned(),
            git: "https://github.com/srnnkls/tropos.git".to_owned(),
            resolved: source.refspec().to_string(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: other.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert_ne!(
            source.config_digest(),
            other.config_digest(),
            "changing include must change the config digest (guards the test premise)"
        );
        assert!(
            source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "a symbolic host+path source whose remote + refspec match keeps its pin when only \
             the config_digest differs"
        );
    }

    // HTP-006: url-source lock identity (no resolved_remote, no refspec)

    /// A url-mode `Source`: only `url` set, so `mode()` is `SourceMode::Url` and
    /// `resolved_remote` fabricates a bogus github url that must NOT be consulted.
    fn url_source(url: &str) -> ParsedSource {
        source_from(&format!("url = \"{url}\"\n"))
    }

    #[test]
    fn url_source_matches_lock_with_same_url_and_config_digest() {
        let source = url_source("https://example.com/p.tar.gz");
        assert_eq!(
            source.mode(),
            crate::config::SourceMode::Url,
            "premise: the source must classify as a url source"
        );
        let locked = LockedSource {
            name: "s".to_owned(),
            git: "https://example.com/p.tar.gz".to_owned(),
            resolved: "url".to_owned(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: source.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert!(
            source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "a url source whose locked git equals its url and whose config_digest agrees must \
             reuse the lock — comparison must ignore resolved_remote (which fabricates a github \
             url) and the refspec"
        );
    }

    #[test]
    fn url_source_does_not_match_when_url_differs() {
        let source = url_source("https://example.com/p.tar.gz");
        let locked = LockedSource {
            name: "s".to_owned(),
            git: "https://example.com/OTHER.tar.gz".to_owned(),
            resolved: "url".to_owned(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: source.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert!(
            !source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "a different download url must not match, even though both are url sources"
        );
    }

    #[test]
    fn url_source_matches_when_only_config_digest_differs() {
        let source = url_source("https://example.com/p.tar.gz");
        let other = source_from("url = \"https://example.com/p.tar.gz\"\nallow_symlinks = true\n");
        let locked = LockedSource {
            name: "s".to_owned(),
            git: "https://example.com/p.tar.gz".to_owned(),
            resolved: "url".to_owned(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: other.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert_ne!(
            source.config_digest(),
            other.config_digest(),
            "changing allow_symlinks must change the config digest (guards the test premise)"
        );
        assert!(
            source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "same url with a changed export config must keep the locked url import"
        );
    }

    #[test]
    fn git_source_matching_is_unchanged_by_url_branch() {
        let source =
            source_from("git = \"https://github.com/me/dotfiles.git\"\nbranch = \"main\"\n");
        let locked = LockedSource {
            name: "dotfiles".to_owned(),
            git: "https://github.com/me/dotfiles.git".to_owned(),
            resolved: source.refspec().to_string(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: source.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert!(
            source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "adding a url branch to source_matches must not regress git matching: a git source \
             with agreeing remote + refspec + config_digest still matches"
        );
    }

    // ARCH-005: local `path` source has the same lock identity as its `git=<localpath>` alias

    #[test]
    fn local_path_source_matches_lock_keyed_by_the_local_path() {
        let source = source_from("path = \"/home/me/dev/loqui\"\nbranch = \"main\"\n");
        let locked = LockedSource {
            name: "loqui".to_owned(),
            git: "/home/me/dev/loqui".to_owned(),
            resolved: source.refspec().to_string(),
            commit: "abc123".to_owned(),
            digest: "blake3:artifact".to_owned(),
            config_digest: source.config_digest(),
            r#ref: None,
            instance: None,
            build: None,
        };

        assert!(
            source_matches(&source, &locked, &no_hosts(), Protocol::Https),
            "a local `path` source must reuse a lock whose `git` field is that same local path, \
             keeping lock identity byte-identical with the `git = <localpath>` alias"
        );
    }

    #[test]
    fn local_path_and_git_localpath_alias_produce_identical_lock_git_field() {
        let via_path = source_from("path = \"/home/me/dev/loqui\"\nbranch = \"main\"\n");
        let via_git = source_from("git = \"/home/me/dev/loqui\"\nbranch = \"main\"\n");
        assert_eq!(
            via_path
                .resolved_remote(&no_hosts(), Protocol::Https)
                .expect("path local resolves"),
            via_git
                .resolved_remote(&no_hosts(), Protocol::Https)
                .expect("git-alias local resolves"),
            "the resolved remote written into the lock `git` field must be identical whether the \
             local source is declared via `path` or the `git = <localpath>` alias"
        );
    }

    // PTV-004: merge dedups by (name, resolved ref), not name alone

    #[test]
    fn merge_locks_dedups_ref_split_source_by_name_and_ref_not_name_alone() {
        let git = "https://github.com/junegunn/fzf.git";
        let base = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: vec![
                LockedSource {
                    name: "fzf".to_owned(),
                    git: git.to_owned(),
                    resolved: "v0.55.0".to_owned(),
                    commit: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_owned(),
                    digest: "blake3:v55".to_owned(),
                    config_digest: "blake3:cfg".to_owned(),
                    r#ref: Some("tag:v0.55.0".to_owned()),
                    instance: None,
                    build: None,
                },
                LockedSource {
                    name: "fzf".to_owned(),
                    git: git.to_owned(),
                    resolved: "v0.56.0".to_owned(),
                    commit: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb".to_owned(),
                    digest: "blake3:v56".to_owned(),
                    config_digest: "blake3:cfg".to_owned(),
                    r#ref: Some("tag:v0.56.0".to_owned()),
                    instance: None,
                    build: None,
                },
            ],
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };
        // Local overrides only the v0.56.0 split (e.g. repointed at a local checkout).
        let local = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: vec![LockedSource {
                name: "fzf".to_owned(),
                git: "/home/me/dev/fzf".to_owned(),
                resolved: "v0.56.0".to_owned(),
                commit: "cccccccccccccccccccccccccccccccccccccccc".to_owned(),
                digest: "blake3:local56".to_owned(),
                config_digest: "blake3:cfg".to_owned(),
                r#ref: Some("tag:v0.56.0".to_owned()),
                instance: None,
                build: None,
            }],
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };

        let merged = merge_locks(&base, Some(&local));

        let fzf: Vec<&LockedSource> = merged.sources.iter().filter(|s| s.name == "fzf").collect();
        assert_eq!(
            fzf.len(),
            2,
            "merge must dedup by (name, ref): the v0.55.0 base split survives and only the \
             v0.56.0 split is replaced — a name-only dedup wrongly collapses to one entry, got {fzf:?}"
        );

        let v55 = fzf
            .iter()
            .find(|s| s.resolved == "v0.55.0")
            .expect("the un-overridden v0.55.0 base split must survive the merge");
        assert_eq!(
            v55.commit, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            "the surviving v0.55.0 split must keep its base commit, untouched by the local override"
        );

        let v56 = fzf
            .iter()
            .find(|s| s.resolved == "v0.56.0")
            .expect("the v0.56.0 split must still be present after override");
        assert_eq!(
            v56.git, "/home/me/dev/fzf",
            "the local override must REPLACE the matching (name, v0.56.0) split"
        );
        assert_eq!(
            v56.commit, "cccccccccccccccccccccccccccccccccccccccc",
            "the replaced v0.56.0 split must carry the local override's commit"
        );
    }

    // PAM-011: split_locks

    #[test]
    fn split_locks_without_overrides_yields_no_local_lock() {
        let resolved = vec![
            (
                "dotfiles".to_owned(),
                locked("dotfiles", "https://github.com/me/dotfiles.git", "main"),
            ),
            (
                "loqui".to_owned(),
                locked("loqui", "https://github.com/srnnkls/loqui.git", "v1.0"),
            ),
        ];

        let (base, local) = split_locks(resolved, &BTreeSet::new());

        assert_eq!(
            base.version, LOCK_SCHEMA_VERSION,
            "base lock declares the schema version"
        );
        assert_eq!(base.sources.len(), 2, "all sources land in the base lock");
        assert!(local.is_none(), "no overrides => no local lock");
    }

    #[test]
    fn carry_shadowed_pins_keeps_the_prior_position() {
        let lock = |names: &[&str]| Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: names
                .iter()
                .map(|name| locked(name, "https://example.invalid/r.git", "main"))
                .collect(),
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };
        let prior = lock(&["ripgrep", "ordinata", "salsa", "zoekt"]);
        let mut base = lock(&["ripgrep", "salsa", "zoekt"]);
        let shadowed: BTreeSet<String> = ["ordinata".to_owned()].into_iter().collect();

        carry_shadowed_pins(&mut base, &prior, &shadowed);

        let names: Vec<&str> = base.sources.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(names, ["ripgrep", "ordinata", "salsa", "zoekt"]);
    }

    #[test]
    fn split_locks_routes_overrides_to_local_lock_only() {
        let resolved = vec![
            (
                "dotfiles".to_owned(),
                locked("dotfiles", "https://github.com/me/dotfiles.git", "main"),
            ),
            (
                "loqui".to_owned(),
                locked("loqui", "/home/soeren/dev/loqui", "main"),
            ),
        ];
        let overrides: BTreeSet<String> = ["loqui".to_owned()].into_iter().collect();

        let (base, local) = split_locks(resolved, &overrides);

        assert!(
            base.find_source("dotfiles").is_some(),
            "non-overridden in base"
        );
        assert!(
            base.find_source("loqui").is_none(),
            "overridden source must NOT appear in the committed base lock"
        );

        let local = local.expect("override present => local lock exists");
        assert_eq!(
            local.version, LOCK_SCHEMA_VERSION,
            "local lock declares the schema version"
        );
        assert!(
            local.find_source("loqui").is_some(),
            "override in local lock"
        );
        assert!(
            local.find_source("dotfiles").is_none(),
            "non-overridden source must NOT appear in the local lock"
        );
    }

    #[test]
    fn split_locks_stamps_schema_version_and_keeps_source_fields() {
        let resolved = vec![(
            "dotfiles".to_owned(),
            locked("dotfiles", "https://github.com/me/dotfiles.git", "main"),
        )];

        let (base, _local) = split_locks(resolved, &BTreeSet::new());

        assert_eq!(
            base.version, LOCK_SCHEMA_VERSION,
            "a freshly written base lock must declare the schema version"
        );

        let dotfiles = base
            .find_source("dotfiles")
            .expect("split_locks must NOT drop the resolved source entry");
        assert_eq!(
            dotfiles.git, "https://github.com/me/dotfiles.git",
            "the source must retain its git url"
        );
        assert_eq!(
            dotfiles.resolved, "main",
            "the source must retain its resolved ref"
        );
        assert_eq!(
            dotfiles.commit, "c0ffee",
            "the source must retain its pinned commit"
        );
        assert_eq!(
            dotfiles.digest, "blake3:artifact",
            "the source must retain its artifact digest"
        );
    }

    #[test]
    fn split_locks_stamps_schema_version_into_local_lock_too() {
        let resolved = vec![(
            "loqui".to_owned(),
            locked("loqui", "/home/me/dev/loqui", "main"),
        )];
        let overrides: BTreeSet<String> = ["loqui".to_owned()].into_iter().collect();

        let (_base, local) = split_locks(resolved, &overrides);

        let local = local.expect("override present => local lock exists");
        assert_eq!(
            local.version, LOCK_SCHEMA_VERSION,
            "a freshly written local lock must also declare the schema version"
        );

        let loqui = local
            .find_source("loqui")
            .expect("split_locks must NOT drop the locally-overridden source entry");
        assert_eq!(
            loqui.git, "/home/me/dev/loqui",
            "the local override must retain its overridden path"
        );
        assert_eq!(
            loqui.resolved, "main",
            "the local override must retain its resolved ref"
        );
        assert_eq!(
            loqui.commit, "c0ffee",
            "the local override must retain its pinned commit"
        );
        assert_eq!(
            loqui.digest, "blake3:artifact",
            "the local override must retain its artifact digest"
        );
    }

    #[test]
    fn flat_source_lock_parses_without_error_or_loss() {
        let flat_toml = "\
version = 1

[[sources]]
name = \"dotfiles\"
git = \"https://github.com/me/dotfiles.git\"
resolved = \"main\"
commit = \"abc123\"
digest = \"blake3:artifact\"
config_digest = \"blake3:cfg\"

[[sources]]
name = \"loqui\"
git = \"https://github.com/srnnkls/loqui.git\"
resolved = \"v1.0\"
commit = \"def456\"
digest = \"blake3:loqui\"
config_digest = \"blake3:cfg\"
";

        let lock: Lock =
            toml::from_str(flat_toml).expect("a flat source lock must parse — never hard-error");

        assert_eq!(
            lock.sources.len(),
            2,
            "no entry may be dropped when a flat lock is read as a consumer-only root namespace, got: {lock:?}"
        );
        assert!(
            lock.find_source("dotfiles").is_some(),
            "the dotfiles entry must survive the read"
        );
        assert!(
            lock.find_source("loqui").is_some(),
            "the loqui entry must survive the read"
        );

        let resolved: Vec<(String, LockedSource)> = lock
            .sources
            .iter()
            .map(|s| (s.name.clone(), s.clone()))
            .collect();
        let (rewritten, _local) = split_locks(resolved, &BTreeSet::new());
        assert_eq!(
            rewritten.version, LOCK_SCHEMA_VERSION,
            "a rewritten lock must declare the schema version"
        );
        assert_eq!(
            rewritten.sources.len(),
            2,
            "the rewrite must preserve every entry of the flat lock"
        );
    }

    #[test]
    fn lock_with_no_sources_table_parses_as_empty_lock() {
        let lock: Lock = toml::from_str("version = 1\n")
            .expect("a lock with no [[sources]] table is a legitimate empty lock");

        assert_eq!(
            lock.version, LOCK_SCHEMA_VERSION,
            "the declared schema version survives"
        );
        assert!(
            lock.sources.is_empty(),
            "an absent [[sources]] table parses to an empty source list, not a hard error"
        );
    }

    #[test]
    fn no_transitive_lock_source_tables_serialize_without_extra_keys() {
        let resolved = vec![(
            "dotfiles".to_owned(),
            locked("dotfiles", "https://github.com/me/dotfiles.git", "main"),
        )];

        let (base, _local) = split_locks(resolved, &BTreeSet::new());
        let text = toml::to_string(&base).expect("lock serializes");

        let expected = "\
version = 1

[[sources]]
name = \"dotfiles\"
git = \"https://github.com/me/dotfiles.git\"
resolved = \"main\"
commit = \"c0ffee\"
digest = \"blake3:artifact\"
config_digest = \"blake3:cfg\"
";

        assert_eq!(
            text, expected,
            "a no-transitive lock must serialize with the bare source-table layout; any extra key \
             in the [[sources]] table means a transitive graph / trusted_hooks field leaked into \
             the empty-transitive case"
        );
    }

    #[test]
    fn no_transitive_lock_emits_no_trusted_hooks_table() {
        let resolved = vec![(
            "dotfiles".to_owned(),
            locked("dotfiles", "https://github.com/me/dotfiles.git", "main"),
        )];

        let (base, _local) = split_locks(resolved, &BTreeSet::new());
        let text = toml::to_string(&base).expect("lock serializes");

        assert!(
            !text.contains("trusted_hooks"),
            "with no transitive data the lock must NOT emit a trusted_hooks section, got:\n{text}"
        );
        assert!(
            !text.contains("transitive"),
            "with no transitive data the lock must NOT emit any transitive graph section, got:\n{text}"
        );
    }

    #[test]
    fn bare_lock_golden_round_trips() {
        let resolved = vec![(
            "dotfiles".to_owned(),
            locked("dotfiles", "https://github.com/me/dotfiles.git", "main"),
        )];
        let (lock, _local) = split_locks(resolved, &BTreeSet::new());

        let text = toml::to_string(&lock).expect("bare lock serializes");
        assert!(
            text.contains("version = 1"),
            "the freshly written bare-lock golden must carry the schema version, got:\n{text}"
        );

        let reparsed: Lock = toml::from_str(&text).expect("the bare-lock golden must round-trip");

        assert_eq!(
            reparsed.version, LOCK_SCHEMA_VERSION,
            "the bare lock round-trips at the schema version"
        );
        assert_eq!(reparsed.sources.len(), 1, "the single bare source survives");
        let s = &reparsed.sources[0];
        assert_eq!(s.name, "dotfiles");
        assert!(
            s.r#ref.is_none(),
            "a bare lock carries no per-binding ref override after the round-trip"
        );
    }

    // Guards existing_literal_git_lock_deserializes_and_matches: a future optional lock field (PTV-004) must skip-serialize so bare locks stay byte-identical.
    #[test]
    fn bare_locked_source_serializes_only_existing_fields() {
        let lock = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: vec![locked(
                "dotfiles",
                "https://github.com/me/dotfiles.git",
                "main",
            )],
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };

        let text = toml::to_string(&lock).expect("lock serializes to toml");

        let value: toml::Value = toml::from_str(&text).expect("serialized lock re-parses as toml");
        let sources = value
            .get("sources")
            .and_then(toml::Value::as_array)
            .expect("serialized lock has a [[sources]] array");
        assert_eq!(sources.len(), 1, "fixture has exactly one locked source");
        let source = sources[0]
            .as_table()
            .expect("the single [[sources]] entry is a table");

        let mut keys: Vec<&str> = source.keys().map(String::as_str).collect();
        keys.sort_unstable();
        assert_eq!(
            keys,
            [
                "commit",
                "config_digest",
                "digest",
                "git",
                "name",
                "resolved"
            ],
            "a bare lock (no per-binding ref) must serialize EXACTLY this key set; any extra key \
             means a new optional lock field was not skip-serialized when absent, so old configs \
             would not lock byte-identically, got:\n{text}"
        );
    }

    // TDEP-LOCK-001: dependency-instance namespaced graph + consumer-owned trusted hooks

    #[test]
    fn transitive_locked_source_emits_instance_key() {
        let lock = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: vec![transitive(
                "deadbeefcafe0001%1%inner",
                "https://github.com/dep/inner.git",
                "main",
                "deadbeefcafe0001",
            )],
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };

        let text = toml::to_string(&lock).expect("a transitive-node lock serializes");

        assert!(
            text.contains("instance = \"deadbeefcafe0001\""),
            "a transitive node must serialize its owning Instance.stable_key() under `instance`, \
             so split/merge can route it to the base namespace, got:\n{text}"
        );
    }

    #[test]
    fn consumer_root_lock_skip_serializes_instance() {
        let lock = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: vec![locked(
                "dotfiles",
                "https://github.com/me/dotfiles.git",
                "main",
            )],
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };

        let text = toml::to_string(&lock).expect("a consumer-root lock serializes");

        assert!(
            !text.contains("instance"),
            "a consumer-root source (instance = None) must skip-serialize the `instance` key so \
             bare locks keep the no-transitive layout, got:\n{text}"
        );
    }

    #[test]
    fn instance_round_trips_through_toml() {
        let lock = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: vec![transitive(
                "ns%1%inner",
                "https://github.com/dep/inner.git",
                "main",
                "owninginstance01",
            )],
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };

        let text = toml::to_string(&lock).expect("transitive lock serializes");
        let parsed: Lock = toml::from_str(&text).expect("transitive lock deserializes");

        assert_eq!(
            parsed.sources[0].instance.as_deref(),
            Some("owninginstance01"),
            "the instance key must survive a toml round-trip so re-reads keep namespace identity"
        );
    }

    #[test]
    fn populated_trusted_hooks_emit_array_of_tables_with_all_four_fields() {
        let lock = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: Vec::new(),
            trusted_hooks: vec![TrustedHook {
                dep_instance: "owninginstance01".to_owned(),
                hook_id: "post-deploy".to_owned(),
                preimage: "blake3:hookpreimage".to_owned(),
                approved_at: "2026-06-20T00:00:00Z".to_owned(),
                source: "nvim-kit".to_owned(),
                commit: "c0ffeecommit".to_owned(),
            }],
            candidate_hooks: Vec::new(),
        };

        let text = toml::to_string(&lock).expect("a lock with trusted hooks serializes");

        assert!(
            text.contains("[[trusted_hooks]]"),
            "trusted hooks must serialize as a serde array-of-tables, got:\n{text}"
        );
        for field in ["dep_instance", "hook_id", "preimage", "approved_at"] {
            assert!(
                text.contains(&format!("{field} =")),
                "the trusted_hooks table must carry the `{field}` field, got:\n{text}"
            );
        }
    }

    #[test]
    fn empty_trusted_hooks_skip_serialize() {
        let lock = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: vec![locked(
                "dotfiles",
                "https://github.com/me/dotfiles.git",
                "main",
            )],
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };

        let text = toml::to_string(&lock).expect("a lock with no trusted hooks serializes");

        assert!(
            !text.contains("trusted_hooks"),
            "an empty trusted_hooks vec must skip-serialize so a no-hooks lock keeps the \
             no-transitive layout, got:\n{text}"
        );
    }

    #[test]
    fn merge_locks_keeps_same_inner_name_under_distinct_instances() {
        let base = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: vec![
                transitive(
                    "a%1%cfg",
                    "https://github.com/dep-a/cfg.git",
                    "main",
                    "instanceaaaa0001",
                ),
                transitive(
                    "b%1%cfg",
                    "https://github.com/dep-b/cfg.git",
                    "main",
                    "instancebbbb0002",
                ),
            ],
            trusted_hooks: Vec::new(),
            candidate_hooks: Vec::new(),
        };

        let merged = merge_locks(&base, None);

        let cfgs: Vec<&LockedSource> = merged
            .sources
            .iter()
            .filter(|s| s.instance.is_some())
            .collect();
        assert_eq!(
            cfgs.len(),
            2,
            "two transitive deps sharing the inner-source name `cfg` but owned by distinct \
             instances must remain two entries; a dedup ignoring `instance` wrongly collapses \
             them, got {cfgs:?}"
        );
    }

    #[test]
    fn merge_locks_merges_trusted_hooks_local_overrides_base_by_dep_instance_and_hook_id() {
        let base = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: Vec::new(),
            trusted_hooks: vec![
                TrustedHook {
                    dep_instance: "inst0001".to_owned(),
                    hook_id: "post-deploy".to_owned(),
                    preimage: "blake3:old".to_owned(),
                    approved_at: "2026-01-01T00:00:00Z".to_owned(),
                    source: String::new(),
                    commit: String::new(),
                },
                TrustedHook {
                    dep_instance: "inst0002".to_owned(),
                    hook_id: "pre-build".to_owned(),
                    preimage: "blake3:keep".to_owned(),
                    approved_at: "2026-01-01T00:00:00Z".to_owned(),
                    source: String::new(),
                    commit: String::new(),
                },
            ],
            candidate_hooks: Vec::new(),
        };
        let local = Lock {
            version: LOCK_SCHEMA_VERSION,
            sources: Vec::new(),
            trusted_hooks: vec![TrustedHook {
                dep_instance: "inst0001".to_owned(),
                hook_id: "post-deploy".to_owned(),
                preimage: "blake3:new".to_owned(),
                approved_at: "2026-06-20T00:00:00Z".to_owned(),
                source: String::new(),
                commit: String::new(),
            }],
            candidate_hooks: Vec::new(),
        };

        let merged = merge_locks(&base, Some(&local));

        let overridden = merged
            .trusted_hooks
            .iter()
            .find(|h| h.dep_instance == "inst0001" && h.hook_id == "post-deploy")
            .expect("the (inst0001, post-deploy) approval survives the merge");
        assert_eq!(
            overridden.preimage, "blake3:new",
            "local must override the base trusted-hook approval matched by (dep_instance, hook_id)"
        );
        assert_eq!(
            merged
                .trusted_hooks
                .iter()
                .filter(|h| h.dep_instance == "inst0001" && h.hook_id == "post-deploy")
                .count(),
            1,
            "the override must replace, not duplicate, the matching approval"
        );
        assert!(
            merged
                .trusted_hooks
                .iter()
                .any(|h| h.dep_instance == "inst0002" && h.preimage == "blake3:keep"),
            "a base-only approval not touched by local must survive the merge"
        );
    }

    #[test]
    fn split_locks_routes_transitive_nodes_to_base_even_when_name_matches_local_override() {
        let resolved = vec![
            (
                "ns%1%loqui".to_owned(),
                transitive(
                    "ns%1%loqui",
                    "https://github.com/dep/loqui.git",
                    "main",
                    "owninginst000001",
                ),
            ),
            (
                "loqui".to_owned(),
                locked("loqui", "/home/me/dev/loqui", "main"),
            ),
        ];
        let overrides: BTreeSet<String> = ["loqui".to_owned(), "ns%1%loqui".to_owned()]
            .into_iter()
            .collect();

        let (base, local) = split_locks(resolved, &overrides);

        assert!(
            base.sources.iter().any(|s| s.instance.is_some()),
            "a transitive node (instance.is_some()) must always route to the BASE lock, never the \
             local override lock, regardless of its namespaced name matching an override"
        );
        let local = local.expect("the consumer override still yields a local lock");
        assert!(
            local.sources.iter().all(|s| s.instance.is_none()),
            "no instance-tagged transitive node may leak into the local override lock"
        );
    }
}