verify-trust 0.4.13

CI verifier for VGI: checks that every commit in a git range is signed by a DID the community's Trust Registry currently authorizes.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
//! `verify-trust`: verify a git commit range against the VTC Trust Registry.
//!
//! For every commit in a range this module answers two questions, in order:
//!
//! 1. **Who signed it, cryptographically?** The commit names a DID on its
//!    `committer` header; that DID is resolved, its document must publish the
//!    Ed25519 key embedded in the commit's sshsig, and the signature must
//!    verify over the exact bytes git signed.
//! 2. **Is that DID trusted, right now?** The signer DID is checked against
//!    the Trust Registry with a TRQP authorization query
//!    (`{entity: signer, authority, action, resource}`) via `trql-client`,
//!    where `authority` is the **VTC's** DID — the community the tuple is
//!    evaluated under.
//!
//! The registry's endpoint is discovered from its DID document rather than
//! configured alongside it: [`resolve_registry_endpoint`] picks the
//! highest-preference transport both sides support (TSP, then DIDComm, then
//! HTTPS). Over the HTTPS binding the registry's answer carries no signature —
//! the registry DID is only stamped on the *outgoing* request as `recipient` —
//! so the endpoint is what the answer's trustworthiness rests on, and deriving
//! it from the DID document keeps it bound to an identifier with integrity
//! behind it.
//!
//! The signer set is **derived from the commits themselves** — there is no
//! per-repository allowlist. The committer header is author-controlled text,
//! so it is treated strictly as a lookup hint: the claim is only ever as good
//! as the two checks that follow it. A commit claiming a DID it cannot sign
//! for fails step 1 (the DID does not publish the signing key, or the
//! signature does not verify over a payload that includes the claim itself);
//! a commit signed by a DID nobody enrolled fails step 2.
//!
//! That places every question of *who may sign here* in the registry, where
//! enrolment, rotation and revocation already live. `--resource` is
//! consequently the only thing scoping a signer to this repository, and is
//! security-relevant input: widening it, or widening `--fallback-resource`,
//! widens who may sign, with nothing in the repository to contradict it.
//! [`resource`] decides which form it takes (`owner/repo`, or forge-qualified
//! `github.com/owner/repo`) and derives its default from the CI environment.
//!
//! Failure is closed at every layer: an unsigned commit, a committer naming no
//! DID, a DID that will not resolve, a signature by a key that DID does not
//! publish, a cryptographically invalid signature, an unauthorized DID, and an
//! unreachable registry all fail the check — each with its own status so an
//! operator can tell which remediation applies.
//!
//! Signers are reported by **agent name** where one is available
//! (`example.com/@alice`) rather than by raw DID. Names come out of the DID
//! documents this crate already resolves, and render through
//! [`vta_sdk::display_name`] — the same seam the PNM, CNM and VTC operator
//! surfaces use, so a DID is abbreviated identically wherever it appears.

pub mod pgp_exempt;
pub mod resource;

use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;

use anyhow::{Context, Result, bail};
use serde::Serialize;
use ssh_key::{SshSig, public::KeyData};
use trql_client::{
    HttpsTransport, HttpsTransportConfig, ServiceCapabilities, TransportKind, TrqlClient,
    TrqlError, TrqpQuery,
};
use vgi_core::{
    GIT_SSHSIG_NAMESPACE, committer_identity, conflicting_signer_dids, ed25519_keys_from_doc,
    normalize_sshsig_armor, signer_did, split_signed_commit,
};
use vta_sdk::display_name::{DisplayName, NameBook, NameSource};

use crate::pgp_exempt::ExemptKeyring;

/// Everything `verify-trust` needs for one run.
#[derive(Debug, Clone)]
pub struct VerifyTrustArgs {
    /// Repository to verify (a working tree with `git` available).
    pub repo_dir: PathBuf,
    /// Commit range in `git rev-list` syntax, e.g. `origin/main..HEAD`.
    pub range: String,
    /// Ceiling on the number of *distinct* DIDs a range may claim, each of
    /// which costs one resolution.
    ///
    /// The signer set is derived from the commits, so a pull request chooses
    /// which identifiers CI resolves — and for the network-resolved methods
    /// (`did:web`, `did:webvh`) that means an outbound fetch to a host the
    /// author picked. Distinct DIDs are deduplicated first; this bounds what
    /// remains. Exceeding it fails the run rather than resolving anyway.
    pub max_signers: usize,
    /// Base URL of the Trust Registry (`POST <url>/trust-tasks`).
    ///
    /// `None` until discovery fills it in from `registry_did`'s DID document;
    /// set explicitly to override discovery (a local or dev registry that
    /// publishes no service endpoint). [`verify_prepared`] requires it
    /// resolved — [`handle_verify_trust`] does that before calling.
    ///
    /// Prefer discovery. Over the HTTPS binding the registry's answer is not
    /// signed — `registry_did` is only stamped on the outgoing request as
    /// `recipient` — so trust in "is this DID authorized" rests on reaching
    /// the right host. Deriving the URL from the DID document makes the
    /// endpoint inherit that DID's integrity instead of being a second,
    /// independently mutable value that nothing cross-checks.
    pub registry_url: Option<String>,
    /// DID of the registry (the `recipient` on every query document, and what
    /// the endpoint is discovered from).
    pub registry_did: String,
    /// DID of the **VTC** — the community whose authority the trust tuple is
    /// evaluated under, sent as TRQP's `authority_id`.
    pub vtc_did: String,
    /// TRQP action, e.g. `git.commit.sign`.
    pub action: String,
    /// TRQP resource: the `org/repo` slug, or forge-qualified
    /// (`github.com/org/repo`) under `--resource-format qualified`. Already in
    /// its final form here — [`resource::select_resources`] chooses it.
    ///
    /// With no committed signer index, this is the **only** thing scoping a
    /// signer to this repository: a grant is accepted exactly when the
    /// registry authorizes the tuple under this resource (or the fallback).
    /// Treat it as security-relevant configuration.
    pub resource: String,
    /// Broader resource to try when the primary one does not authorize
    /// (e.g. the org for an org-wide grant). Grant semantics are
    /// `resource OR fallback`: the registry's wire contract cannot
    /// distinguish "no record" from an explicit `authorized: false`, so a
    /// repo-level record cannot veto an org-level grant.
    pub fallback_resource: Option<String>,
    /// Optional armored PGP keyring of exempt platform keys (e.g. GitHub's
    /// web-flow key); relative paths resolve against `repo_dir`. Absent means
    /// no exemptions: every PGP-signed commit fails.
    pub exempt_keyring: Option<PathBuf>,
    /// Round-trip the agent names the signers' DID documents claim, so a
    /// verified name renders unqualified instead of tagged `[unverified]`.
    ///
    /// Costs one outbound HTTPS fetch per claimed name, to a host the
    /// *document's author* chose, so it is opt-in — the same rule the PNM and
    /// CNM CLIs apply to their `--resolve-agent-names` flag. With it off the
    /// claims still show (they come free with the documents this crate must
    /// resolve anyway), but as the self-assertions they are.
    pub resolve_agent_names: bool,
    /// Emit machine-readable JSON on stdout instead of human lines.
    pub json: bool,
}

/// Outcome for one commit. Ordered worst-first so a report can sort on it.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase", tag = "status", content = "detail")]
pub enum CommitStatus {
    /// No `gpgsig` header on the commit.
    Unsigned,
    /// The signature did not parse as an Ed25519 sshsig.
    Malformed(String),
    /// Signed, but the `committer` header names no DID, so the commit asserts
    /// no identity to resolve or authorize.
    NoSignerDid { committer: String },
    /// The commit carries both a `Signed-by-DID:` trailer and a DID committer
    /// identity, and they name different DIDs.
    ConflictingSignerDids { trailer: String, committer: String },
    /// The claimed DID could not be resolved, so its published keys are
    /// unknown. Fails closed: an unresolvable signer is not a trusted one.
    UnresolvedSigner { did: String, error: String },
    /// The claimed DID resolved, but publishes no verification method holding
    /// the key that signed this commit.
    UnknownKey { did: String, fingerprint: String },
    /// The DID publishes the key, but the signature does not verify.
    BadSignature { signer_did: String },
    /// Valid signature, but the registry did not authorize the signer.
    Unauthorized { signer_did: String },
    /// Valid signature, but the registry could not be consulted. Fails the
    /// run (closed), distinctly from a denial.
    RegistryUnavailable { signer_did: String, error: String },
    /// PGP-signed (a platform commit), but the signature verifies against no
    /// key in the exempt keyring — or no keyring is configured.
    PgpRejected { detail: String },
    /// Signed by an exempt platform key, but not a merge commit: a web-UI
    /// file edit, a REST Contents API commit, a squash merge or a Dependabot
    /// commit. The platform signs whatever it writes on anyone's behalf, so
    /// its signature on a single-parent commit vouches for nobody. Fix:
    /// re-sign the commit with `did-git-sign` (see the runbook, §5).
    PlatformSignedEdit { fingerprint: String },
    /// A merge signed by an exempt platform key, but `parent` neither passes
    /// in this range nor lies below the range's base. The merge would carry
    /// that parent's unverified content in with it.
    PlatformMergeUnverifiedParent { fingerprint: String, parent: String },
    /// A merge signed by an exempt platform key whose tree is not the clean
    /// merge of its parents — typically conflicts resolved in the web UI,
    /// which writes content no verified parent holds.
    PlatformMergeAltered { fingerprint: String, detail: String },
    /// A merge commit PGP-signed by a key in the committed exempt keyring
    /// (e.g. a GitHub web-UI merge), whose parents all pass and whose tree is
    /// their clean merge. Passes, reported distinctly from `Trusted`.
    Exempt { fingerprint: String },
    /// Valid signature by a registry-authorized signer. `resource` is the
    /// tuple resource the grant was found under (the primary one or the
    /// fallback).
    Trusted {
        signer_did: String,
        resource: String,
    },
}

impl CommitStatus {
    /// Signed by a registry-authorized DID.
    pub fn is_trusted(&self) -> bool {
        matches!(self, Self::Trusted { .. })
    }

    /// Whether the commit passes the check: DID-trusted or keyring-exempt.
    pub fn passes(&self) -> bool {
        matches!(self, Self::Trusted { .. } | Self::Exempt { .. })
    }
}

/// One commit's verdict, as reported.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CommitVerdict {
    pub sha: String,
    #[serde(flatten)]
    pub status: CommitStatus,
}

/// The full report for a range.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustReport {
    pub ok: bool,
    pub commits: Vec<CommitVerdict>,
    /// Claimed DIDs whose resolution failed, each with the reason. Their
    /// commits already carry `unresolvedSigner`; this aggregates the set for
    /// a consumer that wants it without walking every commit.
    pub unresolved_signers: BTreeMap<String, String>,
    /// Display name per named signer DID, with its provenance. Only DIDs that
    /// have a name appear. The commit entries keep full DIDs, so a consumer
    /// that does not care about names is unaffected.
    pub signer_names: BTreeMap<String, DisplayName>,
}

/// The DIDs a range claimed, resolved: the keys each publishes, why any of
/// them could not be resolved, and what to call them.
///
/// Produced by [`resolve_signer_keys`] and consumed by [`verify_with_keys`],
/// which tests construct directly via [`ResolvedSigners::from_keys`].
#[derive(Debug, Default)]
pub struct ResolvedSigners {
    /// DID → the Ed25519 keys its document publishes. Keyed by DID rather
    /// than by key so a commit is checked against *the identity it claims*,
    /// not against whatever identity happens to publish the signing key.
    pub keys: BTreeMap<String, Vec<[u8; 32]>>,
    /// Claimed DID → why it did not resolve.
    pub unresolved: BTreeMap<String, String>,
    /// DID → display name, for every signer whose document names it.
    pub names: NameBook,
}

impl ResolvedSigners {
    /// A signer set with keys but no names — the shape a test wants when it
    /// supplies keys directly instead of resolving DID documents.
    #[must_use]
    pub fn from_keys<I, D>(keys: I) -> Self
    where
        I: IntoIterator<Item = (D, Vec<[u8; 32]>)>,
        D: Into<String>,
    {
        Self {
            keys: keys.into_iter().map(|(did, k)| (did.into(), k)).collect(),
            ..Self::default()
        }
    }

    /// The keys `did` publishes, or `None` if it never resolved.
    fn published(&self, did: &str) -> Option<&[[u8; 32]]> {
        self.keys.get(did).map(Vec::as_slice)
    }
}

/// Run the check end to end: discover the registry endpoint, collect the DIDs
/// the range claims, resolve them, then verify. Returns the process exit code
/// (0 = every commit passes).
pub async fn handle_verify_trust(mut args: VerifyTrustArgs) -> Result<i32> {
    let exempt = load_exempt_keyring(&args)?;
    let commits = read_range(&args.repo_dir, &args.range)?;
    let claimed = claimed_signer_dids(&commits, args.max_signers)?;

    // One resolver for both lookups: the registry's endpoint and the signers'
    // keys come from the same cache.
    let tdk = build_resolver(args.resolve_agent_names).await?;
    if args.registry_url.is_none() {
        args.registry_url = Some(resolve_registry_endpoint(&tdk, &args.registry_did).await?);
    }
    let signers = resolve_signer_keys(&tdk, &claimed).await?;

    let report = verify_prepared(&args, &commits, &signers, exempt.as_ref()).await?;
    print_report(&args, &report)?;
    Ok(if report.ok { 0 } else { 1 })
}

/// One commit of the range, read once so the object is not fetched again for
/// the claim pass and the verification pass.
#[derive(Debug, Clone)]
pub struct RangeCommit {
    pub sha: String,
    pub raw: Vec<u8>,
}

/// Read every commit object in the range, oldest first.
pub fn read_range(repo_dir: &Path, range: &str) -> Result<Vec<RangeCommit>> {
    list_commits(repo_dir, range)?
        .into_iter()
        .map(|sha| {
            let raw = read_commit_raw(repo_dir, &sha)?;
            Ok(RangeCommit { sha, raw })
        })
        .collect()
}

/// The distinct DIDs the range's commits claim on their committer headers.
///
/// Deduplicated, then bounded by `max_signers`: the set is chosen by whoever
/// wrote the commits, and each entry costs a resolution. Commits claiming no
/// DID contribute nothing here — they fail later, individually, with a status
/// that says so.
pub fn claimed_signer_dids(commits: &[RangeCommit], max_signers: usize) -> Result<Vec<String>> {
    let dids: BTreeSet<String> = commits
        .iter()
        .filter(|commit| conflicting_signer_dids(&commit.raw).is_none())
        .filter_map(|commit| signer_did(&commit.raw))
        .collect();
    if dids.len() > max_signers {
        bail!(
            "range claims {} distinct signer DIDs, over the limit of {max_signers}; \
             each costs a resolution to a host the commit's author chose. Raise \
             --max-signers only if this range is legitimately that wide.",
            dids.len()
        );
    }
    Ok(dids.into_iter().collect())
}

/// Verify commits already read and resolved. Split from
/// [`handle_verify_trust`] so tests can supply keys without a live resolver.
pub async fn verify_prepared(
    args: &VerifyTrustArgs,
    commits: &[RangeCommit],
    signers: &ResolvedSigners,
    exempt: Option<&ExemptKeyring>,
) -> Result<TrustReport> {
    // Pass 1: cryptographic verification, collecting the DIDs that signed.
    let mut checked = Vec::with_capacity(commits.len());
    let mut signer_dids = BTreeSet::new();
    for commit in commits {
        let signature = check_commit_signature(&commit.raw, signers, exempt);
        if let SignatureCheck::Valid { signer_did } = &signature {
            signer_dids.insert(signer_did.clone());
        }
        checked.push((commit.sha.clone(), signature));
    }

    // Pass 2: one registry query per distinct signer DID.
    let decisions = query_registry(args, &signer_dids).await?;

    let mut verdicts: Vec<CommitVerdict> = checked
        .into_iter()
        .map(|(sha, signature)| CommitVerdict {
            sha,
            status: status_of(signature, &decisions),
        })
        .collect();

    // Pass 3: a platform signature exempts only merges of passing parents.
    apply_platform_merge_policy(&args.repo_dir, &args.range, commits, &mut verdicts)?;
    let commits = verdicts;

    // Names are reported for the signers that actually signed something here
    // — a name for a DID absent from the range is noise.
    let signer_names = signer_dids
        .iter()
        .filter_map(|did| {
            signers
                .names
                .get(did)
                .map(|name| (did.clone(), name.clone()))
        })
        .collect();

    // An empty range passes vacuously (nothing new to verify).
    let ok = commits.iter().all(|c| c.status.passes());
    Ok(TrustReport {
        ok,
        commits,
        unresolved_signers: signers.unresolved.clone(),
        signer_names,
    })
}

// --- platform-signed commits -----------------------------------------------------

/// Narrow the platform-key exemption to merge commits, in place.
///
/// The signature layer reports every commit that verifies against the exempt
/// keyring as `Exempt`. That alone proves only that *the platform* wrote the
/// bytes — and GitHub's `web-flow` key signs everything GitHub writes on
/// anyone's behalf: web-UI file edits (including a fork author editing their
/// own branch on github.com), commits made through the REST Contents API by
/// any writer, squash merges and Dependabot commits alike. Accepting the
/// signature as-is let a single-parent web edit skip DID signing entirely.
///
/// What a platform signature *can* vouch for is a merge, because a merge
/// introduces no content of its own: its tree is determined by its parents.
/// So a platform-signed commit keeps `Exempt` only if
///
/// 1. it is a merge — a single-parent or root commit is `PlatformSignedEdit`;
/// 2. each parent either passes in this range (`Trusted`, or itself an
///    `Exempt` merge) or is a **boundary** commit of the range — excluded from
///    it and therefore reachable from its base, i.e. already on the branch the
///    range is measured against. A merge must not launder a parent that did
///    not verify, so anything else is `PlatformMergeUnverifiedParent`;
/// 3. its tree is exactly the clean merge of those parents, recomputed here
///    with `git merge-tree --write-tree` (the merge-ort machinery GitHub's own
///    merges use). "Content derives from the parents" is only true of a clean
///    merge: GitHub's web conflict editor lets whoever can push the head
///    branch — a fork author included — write arbitrary text into the
///    conflicted files and have web-flow sign the result. A tree that differs,
///    or parents that do not merge cleanly, is `PlatformMergeAltered`.
///
///    The recomputation ignores `.gitattributes`: a checked-out attribute such
///    as `merge=union` would turn a conflict into a "clean" merge and so
///    accept a hand-written resolution. Attributes are read from the empty
///    tree (`--attr-source`, git 2.40+) with no global attributes file; an
///    older git is a hard error rather than an unpinned recomputation. A
///    repository whose real merges depend on committed merge attributes gets
///    `PlatformMergeAltered` for them — failing closed.
///
/// The parent and tree headers are read from the commit object the platform
/// signature covers, so they cannot be rewritten without breaking it.
///
/// Dependabot commits are single-parent and are **not** exempted. Their only
/// distinguishing mark is the `author` header (`dependabot[bot]`), with the
/// same `GitHub <noreply@github.com>` committer as any web edit, and nothing
/// binds that header to the Dependabot app: GitHub documents no guarantee
/// that a web-flow-signed commit's author is the actor who caused it, does
/// not document who the author of a squash commit is, and a flaw in exactly
/// this check once let anyone obtain web-flow-signed commits with an
/// arbitrary author (<https://iter.ca/post/gh-sig-pwn/>, fixed 2023). A
/// maintainer re-signs a Dependabot PR's commits with `did-git-sign`, or the
/// PR lands through a clean merge commit on top of a verified base.
///
/// A merge can appear before a parent merge in `rev-list` order when commit
/// dates are skewed, so verdicts are settled to a fixpoint rather than in one
/// pass.
fn apply_platform_merge_policy(
    repo_dir: &Path,
    range: &str,
    commits: &[RangeCommit],
    verdicts: &mut [CommitVerdict],
) -> Result<()> {
    let mut undecided: BTreeSet<usize> = verdicts
        .iter()
        .enumerate()
        .filter(|(_, v)| matches!(v.status, CommitStatus::Exempt { .. }))
        .map(|(i, _)| i)
        .collect();
    if undecided.is_empty() {
        return Ok(());
    }
    let position: BTreeMap<&str, usize> = commits
        .iter()
        .enumerate()
        .map(|(i, c)| (c.sha.as_str(), i))
        .collect();
    // Fetched only if some platform merge has a parent outside the range.
    let mut boundary: Option<BTreeSet<String>> = None;
    // Checked once, before the first merge is recomputed.
    let mut git_checked = false;

    while !undecided.is_empty() {
        let mut settled = Vec::new();
        for &i in &undecided {
            let CommitStatus::Exempt { fingerprint } = &verdicts[i].status else {
                continue;
            };
            let fingerprint = fingerprint.clone();
            let parents = commit_parents(&commits[i].raw);
            if parents.len() < 2 {
                settled.push((i, CommitStatus::PlatformSignedEdit { fingerprint }));
                continue;
            }

            let mut failed = None;
            let mut waiting = false;
            for parent in &parents {
                match position.get(parent.as_str()) {
                    Some(&j) if undecided.contains(&j) => waiting = true,
                    Some(&j) if verdicts[j].status.passes() => {}
                    Some(_) => {
                        failed = Some(parent.clone());
                        break;
                    }
                    None => {
                        let boundary = match &mut boundary {
                            Some(set) => set,
                            empty => empty.insert(range_boundary(repo_dir, range)?),
                        };
                        if !boundary.contains(parent) {
                            failed = Some(parent.clone());
                            break;
                        }
                    }
                }
            }

            let status = if let Some(parent) = failed {
                CommitStatus::PlatformMergeUnverifiedParent {
                    fingerprint,
                    parent,
                }
            } else if waiting {
                continue;
            } else {
                if !git_checked {
                    require_attr_source_git(repo_dir)?;
                    git_checked = true;
                }
                match clean_merge_mismatch(repo_dir, &commits[i].raw, &parents) {
                    None => CommitStatus::Exempt { fingerprint },
                    Some(detail) => CommitStatus::PlatformMergeAltered {
                        fingerprint,
                        detail,
                    },
                }
            };
            settled.push((i, status));
        }

        if settled.is_empty() {
            // Unreachable for a real commit graph (it is acyclic), but a
            // verdict that cannot be settled must not stay a pass.
            for &i in &undecided {
                if let CommitStatus::Exempt { fingerprint } = &verdicts[i].status {
                    verdicts[i].status = CommitStatus::PlatformMergeUnverifiedParent {
                        fingerprint: fingerprint.clone(),
                        parent: "(cyclic parent chain)".to_string(),
                    };
                }
            }
            break;
        }
        for (i, status) in settled {
            undecided.remove(&i);
            verdicts[i].status = status;
        }
    }
    Ok(())
}

/// The header block of a raw commit object: everything before the first
/// blank line, without continuation lines (the `gpgsig` armor).
///
/// Split on bytes before decoding: the message (and an `encoding` header's
/// charset) need not be UTF-8, and must not cost the commit its parents.
/// A header line that is not UTF-8 is skipped; `tree` and `parent` are hex.
fn commit_headers(raw: &[u8]) -> impl Iterator<Item = &str> {
    let end = raw
        .windows(2)
        .position(|w| w == b"\n\n")
        .unwrap_or(raw.len());
    raw[..end]
        .split(|&b| b == b'\n')
        .filter(|line| !line.starts_with(b" "))
        .filter_map(|line| std::str::from_utf8(line).ok())
}

/// The commit's parent SHAs, in order.
fn commit_parents(raw: &[u8]) -> Vec<String> {
    commit_headers(raw)
        .filter_map(|line| line.strip_prefix("parent "))
        .map(str::to_string)
        .collect()
}

/// `None` if the commit's tree is the clean merge of `parents`; otherwise why
/// not.
fn clean_merge_mismatch(repo_dir: &Path, raw: &[u8], parents: &[String]) -> Option<String> {
    let [ours, theirs] = parents else {
        return Some(format!(
            "{}-parent merge; the platform creates only two-parent merges",
            parents.len()
        ));
    };
    let Some(tree) = commit_headers(raw).find_map(|line| line.strip_prefix("tree ")) else {
        return Some("commit has no tree header".to_string());
    };
    let output = match Command::new("git")
        .arg("-C")
        .arg(repo_dir)
        // Attributes from the empty tree only: see `apply_platform_merge_policy`.
        .arg(format!("--attr-source={EMPTY_TREE}"))
        .args(["-c", "core.attributesFile=/dev/null"])
        .args([
            "merge-tree",
            "--write-tree",
            "--no-messages",
            "--end-of-options",
            ours,
            theirs,
        ])
        .output()
    {
        Ok(output) => output,
        Err(e) => return Some(format!("could not run git merge-tree: {e}")),
    };
    match output.status.code() {
        Some(0) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            let merged = stdout.lines().next().unwrap_or("").trim();
            if merged == tree {
                None
            } else {
                Some(format!(
                    "tree {tree} is not the clean merge of its parents ({merged}); \
                     the merge added content of its own"
                ))
            }
        }
        Some(1) => Some(
            "its parents do not merge cleanly, so the conflicts were resolved by hand \
             (e.g. in the web UI) and that resolution is unsigned content"
                .to_string(),
        ),
        _ => Some(format!(
            "could not recompute the merge (it needs the full history, not a \
             shallow clone): {}",
            String::from_utf8_lossy(&output.stderr).trim()
        )),
    }
}

/// git's well-known empty tree.
const EMPTY_TREE: &str = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";

/// The oldest git whose merge recomputation can be pinned to no attributes:
/// `--attr-source` arrived in 2.40 (`merge-tree --write-tree` in 2.38).
const MIN_GIT: (u32, u32) = (2, 40);

/// Refuse to recompute merges on a git that cannot ignore `.gitattributes`.
fn require_attr_source_git(repo_dir: &Path) -> Result<()> {
    let version = git(repo_dir, &["version"])?;
    match parse_git_version(&version) {
        Some(found) if found >= MIN_GIT => Ok(()),
        _ => bail!(
            "verifying platform-signed merges needs git {}.{} or newer (for \
             --attr-source), found {version:?}; GitHub-hosted runners ship a newer git",
            MIN_GIT.0,
            MIN_GIT.1
        ),
    }
}

/// `(major, minor)` from `git version 2.50.1 (Apple Git-155)`.
fn parse_git_version(output: &str) -> Option<(u32, u32)> {
    let number = output.trim().strip_prefix("git version ")?;
    let mut parts = number.split(|c: char| !c.is_ascii_digit());
    let major = parts.next()?.parse().ok()?;
    let minor = parts.next()?.parse().ok()?;
    Some((major, minor))
}

// --- signature layer ---------------------------------------------------------

/// Result of the cryptographic check for one commit.
#[derive(Debug, Clone, PartialEq)]
pub enum SignatureCheck {
    Unsigned,
    Malformed(String),
    NoSignerDid { committer: String },
    ConflictingSignerDids { trailer: String, committer: String },
    UnresolvedSigner { did: String, error: String },
    UnknownKey { did: String, fingerprint: String },
    BadSignature { signer_did: String },
    PgpRejected { detail: String },
    Exempt { fingerprint: String },
    Valid { signer_did: String },
}

/// Verify one raw commit object against the resolved signers.
///
/// The identity comes from the commit's own `committer` header, and is checked
/// against itself: the DID it claims must publish the key that signed, and the
/// signature must verify over a payload that includes that very header. The
/// claim is therefore never trusted — it only selects which document to check
/// the key against, and a commit naming a DID it cannot sign for fails here.
pub fn check_commit_signature(
    raw: &[u8],
    signers: &ResolvedSigners,
    exempt: Option<&ExemptKeyring>,
) -> SignatureCheck {
    let (payload, pem) = match split_signed_commit(raw) {
        Ok(Some(parts)) => parts,
        Ok(None) => return SignatureCheck::Unsigned,
        Err(e) => return SignatureCheck::Malformed(e.to_string()),
    };
    // Platform commits (GitHub web-UI merges and edits, Dependabot) are
    // PGP-signed; they can pass only via the explicitly committed exempt
    // keyring. `Exempt` here is provisional: `verify_prepared` keeps it only
    // for clean merges of passing parents (see `apply_platform_merge_policy`).
    if pem.starts_with("-----BEGIN PGP SIGNATURE-----") {
        let Some(keyring) = exempt else {
            return SignatureCheck::PgpRejected {
                detail: "PGP-signed commit, but no exempt keyring is configured".to_string(),
            };
        };
        return match keyring.verify(&pem, &payload) {
            Ok(fingerprint) => SignatureCheck::Exempt { fingerprint },
            Err(detail) => SignatureCheck::PgpRejected { detail },
        };
    }
    let sig = match SshSig::from_pem(normalize_sshsig_armor(&pem).as_bytes()) {
        Ok(sig) => sig,
        Err(e) => return SignatureCheck::Malformed(format!("sshsig did not parse: {e}")),
    };
    let KeyData::Ed25519(embedded) = sig.public_key() else {
        return SignatureCheck::Malformed(format!(
            "unsupported signature algorithm: {}",
            sig.algorithm()
        ));
    };
    let key_bytes: [u8; 32] = embedded.0;

    // The identity is read from the payload — the bytes the signature covers —
    // so a claim that survives verification is one the signer committed to.
    if let Some((trailer, committer)) = conflicting_signer_dids(&payload) {
        return SignatureCheck::ConflictingSignerDids { trailer, committer };
    }
    let Some(claimed) = signer_did(&payload) else {
        return SignatureCheck::NoSignerDid {
            committer: committer_identity(&payload).unwrap_or_else(|| "(absent)".to_string()),
        };
    };
    let Some(published) = signers.published(&claimed) else {
        let error = signers
            .unresolved
            .get(&claimed)
            .cloned()
            .unwrap_or_else(|| "not resolved".to_string());
        return SignatureCheck::UnresolvedSigner {
            did: claimed,
            error,
        };
    };
    if !published.contains(&key_bytes) {
        return SignatureCheck::UnknownKey {
            did: claimed,
            fingerprint: hex::encode(key_bytes),
        };
    }
    let public_key = ssh_key::PublicKey::from(sig.public_key().clone());
    match public_key.verify(GIT_SSHSIG_NAMESPACE, &payload, &sig) {
        Ok(()) => SignatureCheck::Valid {
            signer_did: claimed,
        },
        Err(_) => SignatureCheck::BadSignature {
            signer_did: claimed,
        },
    }
}

/// Load the exempt keyring named by the args, resolving relative to the repo.
fn load_exempt_keyring(args: &VerifyTrustArgs) -> Result<Option<ExemptKeyring>> {
    let Some(path) = &args.exempt_keyring else {
        return Ok(None);
    };
    let path = if path.is_absolute() {
        path.clone()
    } else {
        args.repo_dir.join(path)
    };
    Ok(Some(ExemptKeyring::load(&path)?))
}

// --- DID resolution ----------------------------------------------------------

/// Build the DID resolver used for both the registry endpoint and the signers.
///
/// `resolve_agent_names` turns on the resolver's shortcut derivation, which
/// round-trips each claimed name before it is treated as its DID's — see
/// [`VerifyTrustArgs::resolve_agent_names`].
///
/// **Public hosts only.** Every DID this resolver is asked about is chosen by
/// the author of the commits under review: the `Signed-by-DID` trailer and the
/// committer header are attacker-supplied on a fork pull request, and resolving
/// a `did:web`/`did:webvh` DID is an outbound fetch of the host the DID names.
/// On a self-hosted runner with internal reachability, that would be an SSRF
/// primitive with the per-signer resolution error as its oracle. `PublicOnly`
/// refuses non-public names outright, refuses a name whose resolved addresses
/// are non-public, connects only to the addresses it checked, follows no
/// redirect and ignores proxy environment variables.
///
/// It is stated rather than left to the default deliberately: `with_host_policy`
/// does not exist before `affinidi-did-resolver-cache-sdk` 0.8.37, the release
/// that first guards `did:webvh`, so a downgrade fails to compile instead of
/// quietly reopening the fetch. There is **no opt-out here by design** — a DID
/// on an internal host is not an identity this verifier can be asked to trust,
/// and `max_signers` bounds the count rather than the reach.
pub async fn build_resolver(resolve_agent_names: bool) -> Result<affinidi_tdk::TDK> {
    use affinidi_did_resolver_cache_sdk::network_resolvers::HostPolicy;
    use affinidi_tdk::TDK;
    use affinidi_tdk::common::config::TDKConfig;
    use affinidi_tdk::did_resolver::config::DIDCacheConfigBuilder;

    // `with_resolve_shortcuts` exists because `vta-sdk/agent-names` turns on
    // `affinidi-did-resolver-cache-sdk/agent-names`, which cargo unifies onto
    // the resolver the TDK builds here.
    TDK::new(
        TDKConfig::builder()
            .with_load_environment(false)
            .with_did_resolver_config(
                DIDCacheConfigBuilder::default()
                    .with_host_policy(HostPolicy::PublicOnly)
                    .with_resolve_shortcuts(resolve_agent_names)
                    .build(),
            )
            .build()
            .context("TDK config")?,
        None,
    )
    .await
    .context("TDK init")
}

/// Discover the Trust Registry's endpoint from its DID document.
///
/// The document advertises one service entry per binding it serves;
/// [`ServiceCapabilities::select`] takes the highest-preference transport
/// present in **both** the document and this build — TSP, then DIDComm, then
/// HTTPS. `TransportKind::compiled()` is what this binary can actually
/// construct, so a registry offering only bindings we were not built with
/// fails with both sides listed rather than silently downgrading.
///
/// There is deliberately **no fallback to guessing a URL from the DID's
/// domain**. `vta-sdk` does that for a VTA, where a wrong host merely fails
/// authentication; here a wrong host is one whose authorization answers we
/// would believe. A registry that advertises nothing is an error, and
/// [`VerifyTrustArgs::registry_url`] is the explicit override.
pub async fn resolve_registry_endpoint(
    tdk: &affinidi_tdk::TDK,
    registry_did: &str,
) -> Result<String> {
    let response = tdk
        .did_resolver()
        .resolve(registry_did)
        .await
        .map_err(|e| anyhow::anyhow!("could not resolve registry DID {registry_did}: {e}"))?;
    let doc = serde_json::to_value(&response.doc)
        .with_context(|| format!("DID document for {registry_did} did not serialize"))?;

    let capabilities = ServiceCapabilities::from_document(&doc);
    let choice = capabilities
        .select(&TransportKind::compiled())
        .with_context(|| format!("no usable Trust Registry transport on {registry_did}"))?;

    match choice.kind {
        TransportKind::Https => {
            tracing::debug!(endpoint = %choice.endpoint, "discovered registry REST endpoint");
            Ok(choice.endpoint)
        }
        // Unreachable while `compiled()` is HTTPS-only, but the TSP and DIDComm
        // endpoints are *mediator DIDs*, not URLs — handing one to an HTTPS
        // transport would be a category error, so refuse explicitly.
        kind => bail!(
            "registry {registry_did} was selected for the {kind} binding, whose endpoint \
             ({}) is a mediator DID rather than a URL; verify-trust can only query over \
             HTTPS. Set --registry-url to a REST endpoint.",
            choice.endpoint
        ),
    }
}

/// Resolve every DID the range claimed: collect the Ed25519 keys their
/// documents publish, and name each signer from the same document. A DID that
/// fails to resolve is recorded (its commits fail as `unresolvedSigner`)
/// without blocking the others.
pub async fn resolve_signer_keys(
    tdk: &affinidi_tdk::TDK,
    dids: &[String],
) -> Result<ResolvedSigners> {
    let mut signers = ResolvedSigners::default();
    for did in dids {
        match tdk.did_resolver().resolve(did).await {
            Ok(response) => {
                // A shortcut is only ever set after the resolver checked the
                // claimed name resolves back to this DID; anything else the
                // document claims is a bare self-assertion.
                let name = signer_display_name(
                    response.shortcut.as_ref().map(|s| s.label()),
                    &vta_sdk::display_name::agent_name::claimed_names(&response.doc),
                );
                if let Some(name) = name {
                    signers.names.insert(did.clone(), name);
                }

                let doc = serde_json::to_value(&response.doc)
                    .with_context(|| format!("DID document for {did} did not serialize"))?;
                let published = ed25519_keys_from_doc(&doc);
                if published.is_empty() {
                    // Left out of `keys` deliberately: a document with no
                    // Ed25519 method can verify nothing, and recording it as
                    // resolved-but-empty would report its commits as an
                    // unknown key rather than as this, the actual cause.
                    signers.unresolved.insert(
                        did.clone(),
                        "DID document publishes no Ed25519 verification keys".to_string(),
                    );
                } else {
                    signers.keys.insert(did.clone(), published);
                }
            }
            Err(e) => {
                signers
                    .unresolved
                    .insert(did.clone(), format!("resolution failed: {e}"));
            }
        }
    }
    Ok(signers)
}

/// Pick what to call a signer, given the name its resolution verified (if any)
/// and the names its document claims.
///
/// A verified shortcut wins outright. Otherwise the first claim is reported
/// **unverified**: `alsoKnownAs` is self-asserted, so a hostile DID can claim
/// `mybank.com/@treasury` and a verifier that printed that bare would have
/// told the reviewer, in an authoritative voice, that the bank signed this
/// commit. The claim still surfaces — a DID *attempting* to present as
/// someone else is exactly what a reviewer should see — but tagged, and
/// ranked below every trusted source. See [`vta_sdk::display_name`].
fn signer_display_name(verified: Option<&str>, claimed: &[String]) -> Option<DisplayName> {
    if let Some(name) = verified {
        return Some(DisplayName::new(
            name,
            NameSource::AgentName { verified: true },
        ));
    }
    claimed
        .first()
        .map(|name| DisplayName::new(name, NameSource::AgentName { verified: false }))
}

// --- registry layer -----------------------------------------------------------

/// Per-DID registry decision: `Ok(Some(resource))` = authorized under that
/// tuple resource, `Ok(None)` = denied everywhere queried, `Err` =
/// registry unavailable.
type RegistryDecisions = BTreeMap<String, Result<Option<String>, String>>;

/// One TRQP authorization query per distinct signer DID.
async fn query_registry(
    args: &VerifyTrustArgs,
    signer_dids: &BTreeSet<String>,
) -> Result<RegistryDecisions> {
    let mut decisions = RegistryDecisions::new();
    if signer_dids.is_empty() {
        return Ok(decisions);
    }
    // Resolved by `handle_verify_trust` (discovered from `registry_did`, or
    // taken from the explicit override) before this point.
    let registry_url = args.registry_url.as_deref().context(
        "registry URL not resolved: discover it from --registry-did or pass --registry-url",
    )?;
    let transport = HttpsTransport::new(HttpsTransportConfig::new(registry_url))?;
    let client = TrqlClient::new(Arc::new(transport), &args.registry_did);
    // The primary resource, then the broader fallback if it did not grant.
    let mut resources = vec![args.resource.clone()];
    if let Some(fallback) = &args.fallback_resource
        && fallback != &args.resource
    {
        resources.push(fallback.clone());
    }
    for did in signer_dids {
        let mut decision: Result<Option<String>, String> = Ok(None);
        for resource in &resources {
            // The VTC's DID is TRQP's `authority_id`.
            let query = TrqpQuery::new(did, &args.vtc_did, &args.action, resource);
            match client.authorization(query).await {
                Ok(response) if response.authorized => {
                    decision = Ok(Some(resource.clone()));
                    break;
                }
                Ok(_) => {}
                Err(e @ TrqlError::Rejected { .. }) => {
                    // The registry answered and said no (e.g. unknown tuple
                    // rejected rather than answered false) — a denial, not
                    // an availability problem; the fallback may still grant.
                    tracing::debug!("registry rejected the query for {did}: {e}");
                }
                Err(e) => {
                    // Fail closed: with any scope undeterminable, "denied"
                    // cannot be distinguished from "unreachable".
                    decision = Err(e.to_string());
                    break;
                }
            }
        }
        decisions.insert(did.clone(), decision);
    }
    Ok(decisions)
}

/// Combine the signature check with the registry decision.
fn status_of(signature: SignatureCheck, decisions: &RegistryDecisions) -> CommitStatus {
    match signature {
        SignatureCheck::Unsigned => CommitStatus::Unsigned,
        SignatureCheck::Malformed(detail) => CommitStatus::Malformed(detail),
        SignatureCheck::NoSignerDid { committer } => CommitStatus::NoSignerDid { committer },
        SignatureCheck::ConflictingSignerDids { trailer, committer } => {
            CommitStatus::ConflictingSignerDids { trailer, committer }
        }
        SignatureCheck::UnresolvedSigner { did, error } => {
            CommitStatus::UnresolvedSigner { did, error }
        }
        SignatureCheck::UnknownKey { did, fingerprint } => {
            CommitStatus::UnknownKey { did, fingerprint }
        }
        SignatureCheck::BadSignature { signer_did } => CommitStatus::BadSignature { signer_did },
        SignatureCheck::PgpRejected { detail } => CommitStatus::PgpRejected { detail },
        SignatureCheck::Exempt { fingerprint } => CommitStatus::Exempt { fingerprint },
        SignatureCheck::Valid { signer_did } => match decisions.get(&signer_did) {
            Some(Ok(Some(resource))) => CommitStatus::Trusted {
                signer_did,
                resource: resource.clone(),
            },
            Some(Ok(None)) => CommitStatus::Unauthorized { signer_did },
            Some(Err(error)) => CommitStatus::RegistryUnavailable {
                signer_did,
                error: error.clone(),
            },
            None => CommitStatus::RegistryUnavailable {
                signer_did,
                error: "no registry decision recorded".to_string(),
            },
        },
    }
}

// --- git plumbing --------------------------------------------------------------

/// List the commits in `range`, oldest first.
///
/// `range` is caller-supplied (a CI input), so it must never reach git as an
/// option: a leading `-` is rejected outright, and `--end-of-options` (git
/// 2.24+) makes git itself treat whatever follows as a revision.
pub fn list_commits(repo_dir: &Path, range: &str) -> Result<Vec<String>> {
    if range.starts_with('-') {
        bail!("--range must be a revision range, not an option: {range:?}");
    }
    let output = git(
        repo_dir,
        &["rev-list", "--reverse", "--end-of-options", range],
    )?;
    Ok(output.lines().map(str::to_string).collect())
}

/// The range's boundary: commits outside it that are parents of commits in
/// it. Git computes these as the excluded parents reachable from the range's
/// negative side (the `A` of `A..B`), so a boundary commit is one already on
/// the base branch. A parent missing from the repository (a shallow clone) is
/// never on this list.
pub fn range_boundary(repo_dir: &Path, range: &str) -> Result<BTreeSet<String>> {
    if range.starts_with('-') {
        bail!("--range must be a revision range, not an option: {range:?}");
    }
    let output = git(
        repo_dir,
        &["rev-list", "--boundary", "--end-of-options", range],
    )?;
    Ok(output
        .lines()
        .filter_map(|line| line.strip_prefix('-'))
        .map(str::to_string)
        .collect())
}

/// Read one raw commit object.
pub fn read_commit_raw(repo_dir: &Path, sha: &str) -> Result<Vec<u8>> {
    let output = Command::new("git")
        .arg("-C")
        .arg(repo_dir)
        .args(["cat-file", "commit", sha])
        .output()
        .context("running git cat-file")?;
    if !output.status.success() {
        bail!(
            "git cat-file commit {sha} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
    Ok(output.stdout)
}

fn git(repo_dir: &Path, args: &[&str]) -> Result<String> {
    let output = Command::new("git")
        .arg("-C")
        .arg(repo_dir)
        .args(args)
        .output()
        .with_context(|| format!("running git {}", args.join(" ")))?;
    if !output.status.success() {
        bail!(
            "git {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr)
        );
    }
    Ok(String::from_utf8(output.stdout)?.trim_end().to_string())
}

// --- reporting ------------------------------------------------------------------

fn print_report(args: &VerifyTrustArgs, report: &TrustReport) -> Result<()> {
    if args.json {
        println!("{}", serde_json::to_string_pretty(report)?);
        return Ok(());
    }

    // Per-commit lines name the signer and abbreviate its DID; the signer
    // block below carries every DID in full, so nothing a reviewer has to
    // check against the registry is lost to the abbreviation.
    let signer = |did: &str| render_signer(report, did);

    for commit in &report.commits {
        let short = &commit.sha[..commit.sha.len().min(12)];
        match &commit.status {
            CommitStatus::Trusted {
                signer_did,
                resource,
            } => {
                println!(
                    "TRUSTED      {short}  {} (via {resource})",
                    signer(signer_did)
                );
            }
            CommitStatus::Exempt { fingerprint } => {
                println!("EXEMPT       {short}  PGP-signed by exempt platform key {fingerprint}");
            }
            CommitStatus::PgpRejected { detail } => {
                println!("PGP-REJECTED {short}  {detail}");
            }
            CommitStatus::PlatformSignedEdit { fingerprint } => {
                println!(
                    "PLAT-EDIT    {short}  signed by platform key {fingerprint}, but not a merge: \
                     the platform signs any web or API edit, so only merges are exempt. \
                     Re-sign this commit with did-git-sign: `git rebase -i <base>` and add \
                     `exec git commit --amend --no-edit -S` after its pick (runbook §5)"
                );
            }
            CommitStatus::PlatformMergeUnverifiedParent {
                fingerprint,
                parent,
            } => {
                println!(
                    "PLAT-MERGE   {short}  merge signed by platform key {fingerprint} has parent \
                     {parent}, which neither passes nor is on the base branch; fix that commit"
                );
            }
            CommitStatus::PlatformMergeAltered {
                fingerprint,
                detail,
            } => {
                println!(
                    "PLAT-MERGE   {short}  merge signed by platform key {fingerprint}: {detail}; \
                     merge locally and sign it with did-git-sign"
                );
            }
            CommitStatus::Unauthorized { signer_did } => {
                println!(
                    "UNAUTHORIZED {short}  {} is not authorized by the registry",
                    signer(signer_did)
                );
            }
            CommitStatus::RegistryUnavailable { signer_did, error } => {
                println!(
                    "UNAVAILABLE  {short}  signed by {}; registry check failed: {error}",
                    signer(signer_did)
                );
            }
            CommitStatus::BadSignature { signer_did } => {
                println!(
                    "BAD-SIG      {short}  signature by {} does not verify",
                    signer(signer_did)
                );
            }
            CommitStatus::UnknownKey { did, fingerprint } => {
                println!(
                    "UNKNOWN-KEY  {short}  {} publishes no key {fingerprint}",
                    signer(did)
                );
            }
            CommitStatus::UnresolvedSigner { did, error } => {
                println!("UNRESOLVED   {short}  claimed signer {did} did not resolve: {error}");
            }
            CommitStatus::NoSignerDid { committer } => {
                println!("NO-SIGNER    {short}  committer <{committer}> is not a DID");
            }
            CommitStatus::ConflictingSignerDids { trailer, committer } => {
                println!(
                    "CONFLICT     {short}  Signed-by-DID {trailer} disagrees with committer DID {committer}"
                );
            }
            CommitStatus::Malformed(detail) => {
                println!("MALFORMED    {short}  {detail}");
            }
            CommitStatus::Unsigned => {
                println!("UNSIGNED     {short}  commit carries no signature");
            }
        }
    }

    print_signer_block(args, report);

    let passing = report.commits.iter().filter(|c| c.status.passes()).count();
    println!(
        "{}: {passing}/{} commits pass",
        if report.ok { "PASS" } else { "FAIL" },
        report.commits.len()
    );
    Ok(())
}

/// A signer for one commit line: `name (did:webvh:QmXk…:example.com)`, or the
/// abbreviated DID alone when nothing names it. Unverified names carry the
/// `[unverified]` tag `NameBook` appends — surfaces must not strip it.
fn render_signer(report: &TrustReport, did: &str) -> String {
    match report.signer_names.get(did) {
        Some(name) if name.is_trusted() => {
            format!(
                "{} ({})",
                name.name,
                vta_sdk::display_name::shorten_did(did)
            )
        }
        Some(name) => format!(
            "{}{} ({})",
            name.name,
            vta_sdk::display_name::UNVERIFIED_SUFFIX,
            vta_sdk::display_name::shorten_did(did)
        ),
        None => vta_sdk::display_name::shorten_did(did),
    }
}

/// The signers that signed this range, each with its full DID.
///
/// Emitted only when something was named — on a repo whose signers claim no
/// agent names this would be a list of DIDs already on every line above.
fn print_signer_block(args: &VerifyTrustArgs, report: &TrustReport) {
    if report.signer_names.is_empty() {
        return;
    }
    println!();
    println!("Signers:");
    for (did, name) in &report.signer_names {
        let tag = if name.is_trusted() {
            String::new()
        } else {
            format!(" {}", vta_sdk::display_name::UNVERIFIED_SUFFIX.trim())
        };
        println!("  {}{tag}", name.name);
        println!("    {did}");
    }
    if !args.resolve_agent_names && report.signer_names.values().any(|n| !n.is_trusted()) {
        println!();
        println!(
            "  Names above are claimed by the DID and were not checked. Pass \
             --resolve-agent-names to resolve each claim back to its DID."
        );
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use super::*;
    use ed25519_dalek::SigningKey;
    use vgi_core::create_ssh_signature;

    fn test_key() -> (SigningKey, [u8; 32]) {
        let signing = SigningKey::from_bytes(&[7u8; 32]);
        let public = signing.verifying_key().to_bytes();
        (signing, public)
    }

    const SIGNER: &str = "did:webvh:QmSigner:example.com";

    /// An unsigned commit whose committer claims `SIGNER`, as `did-git-sign`
    /// writes it: `user.email` is the verification-method id.
    fn unsigned_commit() -> String {
        commit_committed_by(&format!("{SIGNER}#key-0"))
    }

    fn commit_committed_by(committer: &str) -> String {
        format!(
            "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\
             author A U Thor <a@example.com> 1700000000 +0000\n\
             committer A U Thor <{committer}> 1700000000 +0000\n\
             \n\
             a message\n"
        )
    }

    /// A signer set in which `SIGNER` publishes `public`.
    fn signers_publishing(public: [u8; 32]) -> ResolvedSigners {
        ResolvedSigners::from_keys([(SIGNER, vec![public])])
    }

    /// Insert a gpgsig header before the blank line, continuation-indented,
    /// exactly as git stores it.
    fn signed_commit(payload: &str, armored: &str) -> String {
        let (headers, body) = payload.split_once("\n\n").unwrap();
        let mut sig_header = String::from("gpgsig ");
        let mut lines = armored.trim_end().split('\n');
        sig_header.push_str(lines.next().unwrap());
        for line in lines {
            sig_header.push('\n');
            sig_header.push(' ');
            sig_header.push_str(line);
        }
        format!("{headers}\n{sig_header}\n\n{body}")
    }

    fn sign_commit(payload: &str, key: &SigningKey) -> String {
        let armored = create_ssh_signature(
            key,
            &key.verifying_key(),
            GIT_SSHSIG_NAMESPACE,
            payload.as_bytes(),
        )
        .unwrap();
        signed_commit(payload, &armored)
    }

    #[test]
    fn split_returns_none_for_unsigned_commit() {
        assert!(
            split_signed_commit(unsigned_commit().as_bytes())
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn split_recovers_exact_payload_and_signature() {
        let payload = unsigned_commit();
        let (key, _) = test_key();
        let commit = sign_commit(&payload, &key);

        let (recovered_payload, pem) = split_signed_commit(commit.as_bytes()).unwrap().unwrap();
        assert_eq!(recovered_payload, payload.as_bytes());
        assert!(pem.starts_with("-----BEGIN SSH SIGNATURE-----"));
        assert!(pem.trim_end().ends_with("-----END SSH SIGNATURE-----"));
    }

    #[test]
    fn our_encoder_and_the_decoder_agree() {
        // Cross-check: a signature produced by sign.rs verifies through the
        // ssh-key crate's independent implementation.
        let payload = unsigned_commit();
        let (key, public) = test_key();
        let commit = sign_commit(&payload, &key);

        let check = check_commit_signature(commit.as_bytes(), &signers_publishing(public), None);
        assert_eq!(
            check,
            SignatureCheck::Valid {
                signer_did: SIGNER.to_string()
            }
        );
    }

    #[test]
    fn the_signer_is_the_did_the_commit_claims() {
        // The identity is not configuration: it comes off the commit's own
        // committer header, with the fragment stripped.
        let payload = unsigned_commit();
        let (key, public) = test_key();
        let commit = sign_commit(&payload, &key);

        let SignatureCheck::Valid { signer_did } =
            check_commit_signature(commit.as_bytes(), &signers_publishing(public), None)
        else {
            panic!("expected a valid signature");
        };
        assert_eq!(signer_did, SIGNER, "the bare DID, not the key id");
    }

    #[test]
    fn claiming_a_did_that_does_not_publish_the_signing_key_fails() {
        // The spoof the committer header invites: sign with your own key while
        // naming someone else's DID. The claim selects whose document to
        // check, and that document does not publish this key.
        let payload = commit_committed_by("did:webvh:QmVictim:example.com#key-0");
        let (key, public) = test_key();
        let commit = sign_commit(&payload, &key);

        let signers = ResolvedSigners::from_keys([
            (SIGNER, vec![public]),
            ("did:webvh:QmVictim:example.com", vec![[0u8; 32]]),
        ]);
        assert_eq!(
            check_commit_signature(commit.as_bytes(), &signers, None),
            SignatureCheck::UnknownKey {
                did: "did:webvh:QmVictim:example.com".to_string(),
                fingerprint: hex::encode(public),
            },
            "a key published by another DID must not authenticate this claim"
        );
    }

    #[test]
    fn a_committer_that_is_not_a_did_has_no_identity_to_check() {
        let payload = commit_committed_by("alice@example.com");
        let (key, public) = test_key();
        let commit = sign_commit(&payload, &key);

        assert_eq!(
            check_commit_signature(commit.as_bytes(), &signers_publishing(public), None),
            SignatureCheck::NoSignerDid {
                committer: "alice@example.com".to_string()
            }
        );
    }

    #[test]
    fn conflicting_trailer_and_committer_dids_fail_closed() {
        let payload = format!(
            "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\
             author A U Thor <a@example.com> 1700000000 +0000\n\
             committer A U Thor <did:webvh:QmCommitter:example.com#key-0> 1700000000 +0000\n\
             \n\
             a message\n\
             \n\
             Signed-by-DID: {SIGNER}#key-0\n"
        );
        let (key, public) = test_key();
        let commit = sign_commit(&payload, &key);

        assert_eq!(
            check_commit_signature(commit.as_bytes(), &signers_publishing(public), None),
            SignatureCheck::ConflictingSignerDids {
                trailer: SIGNER.to_string(),
                committer: "did:webvh:QmCommitter:example.com".to_string(),
            }
        );
    }

    #[test]
    fn a_claimed_did_that_did_not_resolve_fails_closed() {
        let payload = unsigned_commit();
        let (key, _) = test_key();
        let commit = sign_commit(&payload, &key);

        let mut signers = ResolvedSigners::default();
        signers
            .unresolved
            .insert(SIGNER.to_string(), "resolution failed: no such host".into());

        assert_eq!(
            check_commit_signature(commit.as_bytes(), &signers, None),
            SignatureCheck::UnresolvedSigner {
                did: SIGNER.to_string(),
                error: "resolution failed: no such host".to_string(),
            },
            "an unresolvable signer is not a trusted one"
        );
    }

    #[test]
    fn the_claim_is_read_from_the_bytes_the_signature_covers() {
        // Rewriting the committer after signing invalidates the signature, so
        // a surviving claim is one the signer committed to.
        let payload = unsigned_commit();
        let (key, public) = test_key();
        let commit = sign_commit(&payload, &key).replace(
            &format!("{SIGNER}#key-0"),
            "did:webvh:QmOther:example.com#key-0",
        );

        let signers = ResolvedSigners::from_keys([
            (SIGNER, vec![public]),
            ("did:webvh:QmOther:example.com", vec![public]),
        ]);
        assert_eq!(
            check_commit_signature(commit.as_bytes(), &signers, None),
            SignatureCheck::BadSignature {
                signer_did: "did:webvh:QmOther:example.com".to_string()
            },
            "tampering with the claimed identity breaks the signature over it"
        );
    }

    #[test]
    fn distinct_claimed_dids_are_deduplicated_and_bounded() {
        let (key, _) = test_key();
        let commits: Vec<RangeCommit> = ["QmA", "QmB", "QmA"]
            .iter()
            .enumerate()
            .map(|(i, scid)| RangeCommit {
                sha: format!("{i:040}"),
                raw: sign_commit(
                    &commit_committed_by(&format!("did:webvh:{scid}:example.com#key-0")),
                    &key,
                )
                .into_bytes(),
            })
            .collect();

        let claimed = claimed_signer_dids(&commits, 32).unwrap();
        assert_eq!(
            claimed,
            vec![
                "did:webvh:QmA:example.com".to_string(),
                "did:webvh:QmB:example.com".to_string(),
            ],
            "three commits, two identities, two resolutions"
        );
        assert!(
            claimed_signer_dids(&commits, 1).is_err(),
            "a range may not make CI resolve more hosts than the cap allows"
        );
    }

    #[test]
    fn legacy_76_column_armor_still_verifies() {
        // Signatures created before sign.rs matched ssh-keygen's 70-column
        // wrapping are permanent in git history and must keep verifying.
        let payload = unsigned_commit();
        let (key, public) = test_key();
        let armored = create_ssh_signature(
            &key,
            &key.verifying_key(),
            GIT_SSHSIG_NAMESPACE,
            payload.as_bytes(),
        )
        .unwrap();
        let body: String = armored
            .lines()
            .filter(|l| !l.starts_with("-----"))
            .collect();
        let mut legacy = String::from("-----BEGIN SSH SIGNATURE-----\n");
        for chunk in body.as_bytes().chunks(76) {
            legacy.push_str(std::str::from_utf8(chunk).unwrap());
            legacy.push('\n');
        }
        legacy.push_str("-----END SSH SIGNATURE-----\n");

        let commit = signed_commit(&payload, &legacy);
        assert_eq!(
            check_commit_signature(commit.as_bytes(), &signers_publishing(public), None),
            SignatureCheck::Valid {
                signer_did: SIGNER.to_string()
            }
        );
    }

    #[test]
    fn a_key_the_claimed_did_does_not_publish_is_reported_with_its_fingerprint() {
        let payload = unsigned_commit();
        let (key, public) = test_key();
        let commit = sign_commit(&payload, &key);

        // The DID resolved, but publishes a different key.
        let signers = ResolvedSigners::from_keys([(SIGNER, vec![[3u8; 32]])]);
        assert_eq!(
            check_commit_signature(commit.as_bytes(), &signers, None),
            SignatureCheck::UnknownKey {
                did: SIGNER.to_string(),
                fingerprint: hex::encode(public),
            }
        );
    }

    #[test]
    fn tampered_payload_is_a_bad_signature() {
        let payload = unsigned_commit();
        let (key, public) = test_key();
        let commit = sign_commit(&payload, &key).replace("a message", "b message");

        let check = check_commit_signature(commit.as_bytes(), &signers_publishing(public), None);
        assert_eq!(
            check,
            SignatureCheck::BadSignature {
                signer_did: SIGNER.to_string()
            }
        );
    }

    #[test]
    fn parents_are_read_from_the_header_block_only() {
        // A body line, or a line of the signature armor, that happens to read
        // `parent …` must not add a parent — that would turn an edit into a
        // "merge".
        let merge = "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\
                     parent 1111111111111111111111111111111111111111\n\
                     parent 2222222222222222222222222222222222222222\n\
                     author A U Thor <a@example.com> 1700000000 +0000\n\
                     committer GitHub <noreply@github.com> 1700000000 +0000\n\
                     \n\
                     Merge pull request #1\n";
        assert_eq!(
            commit_parents(merge.as_bytes()),
            vec!["1".repeat(40), "2".repeat(40),]
        );

        let edit = "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\
                    parent 1111111111111111111111111111111111111111\n\
                    author A U Thor <a@example.com> 1700000000 +0000\n\
                    committer GitHub <noreply@github.com> 1700000000 +0000\n\
                    \n\
                    Update a.txt\n\
                    \n\
                    parent 2222222222222222222222222222222222222222\n";
        let signed = signed_commit(
            edit,
            "-----BEGIN PGP SIGNATURE-----\n\
             parent 3333333333333333333333333333333333333333\n\
             -----END PGP SIGNATURE-----\n",
        );
        assert_eq!(commit_parents(signed.as_bytes()), vec!["1".repeat(40)]);
    }

    #[test]
    fn a_non_utf8_message_does_not_cost_a_merge_its_parents() {
        let mut merge = b"tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\n\
                          parent 1111111111111111111111111111111111111111\n\
                          parent 2222222222222222222222222222222222222222\n\
                          author A U Thor <a@example.com> 1700000000 +0000\n\
                          committer GitHub <noreply@github.com> 1700000000 +0000\n\
                          encoding ISO-8859-1\n\
                          \n\
                          Merge "
            .to_vec();
        merge.extend_from_slice(&[0xe9, 0xe8, 0xff, b'\n']);
        assert!(std::str::from_utf8(&merge).is_err());
        assert_eq!(commit_parents(&merge).len(), 2);
        assert_eq!(
            commit_headers(&merge).find_map(|l| l.strip_prefix("tree ")),
            Some(EMPTY_TREE)
        );
    }

    #[test]
    fn git_versions_parse_and_compare() {
        assert_eq!(
            parse_git_version("git version 2.50.1 (Apple Git-155)\n"),
            Some((2, 50))
        );
        assert_eq!(parse_git_version("git version 2.39.5"), Some((2, 39)));
        assert_eq!(
            parse_git_version("git version 2.40.0.windows.1"),
            Some((2, 40))
        );
        assert!(parse_git_version("git version 2.39.5").unwrap() < MIN_GIT);
        assert!(parse_git_version("git version 3.0.0").unwrap() >= MIN_GIT);
        assert_eq!(parse_git_version("not git"), None);
    }

    #[test]
    fn unsigned_commit_is_unsigned() {
        let check = check_commit_signature(
            unsigned_commit().as_bytes(),
            &ResolvedSigners::default(),
            None,
        );
        assert_eq!(check, SignatureCheck::Unsigned);
    }

    // --- registry endpoint discovery ---

    /// The `service` block from the Trust Registry DID document in the
    /// workspace's DID_SERVICE_DISCOVERY design note: one entry per binding,
    /// `#rest` carrying both types via the set form, TSP/DIDComm endpoints
    /// being mediator DIDs rather than URLs.
    fn registry_document() -> serde_json::Value {
        serde_json::json!({
            "id": "did:webvh:QmRegistryScid:registry.example",
            "service": [
                {
                    "id": "did:webvh:QmRegistryScid:registry.example#rest",
                    "type": ["TRQPRest", "TrustRegistry"],
                    "serviceEndpoint": {
                        "uri": "https://registry.example",
                        "profile": "https://trustoverip.org/profiles/trqp/v2"
                    }
                },
                {
                    "id": "did:webvh:QmRegistryScid:registry.example#didcomm",
                    "type": "DIDCommMessaging",
                    "serviceEndpoint": {
                        "uri": "did:web:mediator.example",
                        "accept": ["didcomm/v2"],
                        "routingKeys": []
                    }
                },
                {
                    "id": "did:webvh:QmRegistryScid:registry.example#tsp",
                    "type": "TSPTransport",
                    "serviceEndpoint": "did:web:mediator.example"
                }
            ]
        })
    }

    #[test]
    fn all_three_bindings_are_parsed_from_the_registry_document() {
        let caps = ServiceCapabilities::from_document(&registry_document());
        assert_eq!(caps.https.as_deref(), Some("https://registry.example"));
        assert_eq!(caps.tsp.as_deref(), Some("did:web:mediator.example"));
        assert_eq!(caps.didcomm.as_deref(), Some("did:web:mediator.example"));
        assert_eq!(
            caps.advertised(),
            vec![
                TransportKind::Tsp,
                TransportKind::Didcomm,
                TransportKind::Https
            ],
            "advertised order is the preference order: TSP, DIDComm, HTTPS"
        );
    }

    #[test]
    fn selection_prefers_tsp_then_didcomm_then_https() {
        let caps = ServiceCapabilities::from_document(&registry_document());
        // Against a client that speaks everything, TSP wins outright.
        assert_eq!(
            caps.select(&[
                TransportKind::Tsp,
                TransportKind::Didcomm,
                TransportKind::Https
            ])
            .unwrap()
            .kind,
            TransportKind::Tsp
        );
        // Drop TSP and DIDComm is next, ahead of the HTTPS floor.
        assert_eq!(
            caps.select(&[TransportKind::Didcomm, TransportKind::Https])
                .unwrap()
                .kind,
            TransportKind::Didcomm
        );
    }

    #[test]
    fn this_build_selects_https_because_that_is_what_it_can_construct() {
        // `compiled()` is feature-gated, and verify-trust takes trql-client's
        // default features (https only): the preference order is honoured, we
        // simply cannot construct the two above it. Selecting against what we
        // advertise rather than a hard-coded list is what stops us choosing a
        // transport and then failing to build it.
        let compiled = TransportKind::compiled();
        assert_eq!(compiled, vec![TransportKind::Https]);

        let choice = ServiceCapabilities::from_document(&registry_document())
            .select(&compiled)
            .unwrap();
        assert_eq!(choice.kind, TransportKind::Https);
        assert_eq!(choice.endpoint, "https://registry.example");
    }

    #[test]
    fn a_registry_offering_no_binding_we_speak_fails_with_both_sides_named() {
        // TSP and DIDComm only. Failing loudly beats guessing a URL: the error
        // carries what each side offers so the mismatch is diagnosable.
        let doc = serde_json::json!({
            "id": "did:webvh:QmRegistryScid:registry.example",
            "service": [{
                "id": "did:webvh:QmRegistryScid:registry.example#tsp",
                "type": "TSPTransport",
                "serviceEndpoint": "did:web:mediator.example"
            }]
        });
        let error = ServiceCapabilities::from_document(&doc)
            .select(&[TransportKind::Https])
            .unwrap_err();
        let rendered = error.to_string();
        assert!(
            rendered.contains("https") && rendered.contains("tsp"),
            "the error must name both sides' transports: {rendered}"
        );
    }

    #[test]
    fn a_document_advertising_nothing_yields_no_endpoint() {
        // No service block at all: there is nothing to discover, and no
        // domain-guessing fallback exists to paper over it.
        let caps = ServiceCapabilities::from_document(&serde_json::json!({
            "id": "did:webvh:QmRegistryScid:registry.example"
        }));
        assert_eq!(caps, ServiceCapabilities::default());
        assert!(caps.select(&TransportKind::compiled()).is_err());
    }

    #[test]
    fn statuses_compose_signature_and_registry_decisions() {
        let did = "did:example:signer".to_string();
        let mut decisions = RegistryDecisions::new();
        decisions.insert(did.clone(), Ok(Some("example/repo".to_string())));
        assert!(
            status_of(
                SignatureCheck::Valid {
                    signer_did: did.clone()
                },
                &decisions
            )
            .is_trusted()
        );

        decisions.insert(did.clone(), Ok(None));
        assert_eq!(
            status_of(
                SignatureCheck::Valid {
                    signer_did: did.clone()
                },
                &decisions
            ),
            CommitStatus::Unauthorized {
                signer_did: did.clone()
            }
        );

        decisions.insert(did.clone(), Err("connect refused".to_string()));
        assert!(matches!(
            status_of(SignatureCheck::Valid { signer_did: did }, &decisions),
            CommitStatus::RegistryUnavailable { .. }
        ));
    }

    // --- signer naming ---

    #[test]
    fn a_verified_shortcut_is_the_name() {
        let name = signer_display_name(
            Some("example.com/@alice"),
            &["https://example.com/@alice".to_string()],
        )
        .unwrap();
        assert_eq!(name.name, "example.com/@alice");
        assert!(name.is_trusted());
    }

    #[test]
    fn an_unchecked_claim_is_never_trusted() {
        // The spoof this exists for: a signer's document claims the bank's
        // name. Nothing resolved it back, so it must not render as the bank.
        let name =
            signer_display_name(None, &["https://mybank.com/@treasury".to_string()]).unwrap();
        assert_eq!(name.source, NameSource::AgentName { verified: false });
        assert!(!name.is_trusted());
    }

    #[test]
    fn a_signer_claiming_nothing_has_no_name() {
        assert!(signer_display_name(None, &[]).is_none());
    }

    #[test]
    fn an_unverified_name_renders_tagged_beside_its_did() {
        let did = "did:webvh:QmScidAbCdEfGhIj:example.com:ops";
        let report = TrustReport {
            ok: true,
            commits: Vec::new(),
            unresolved_signers: BTreeMap::new(),
            signer_names: BTreeMap::from([(
                did.to_string(),
                DisplayName::new(
                    "mybank.com/@treasury",
                    NameSource::AgentName { verified: false },
                ),
            )]),
        };
        let rendered = render_signer(&report, did);
        assert!(
            rendered.contains("unverified"),
            "an unchecked claim must never render as a plain name: {rendered}"
        );
        assert!(
            rendered.contains("example.com"),
            "the DID must stay visible beside the name: {rendered}"
        );
    }

    #[test]
    fn an_unnamed_signer_falls_back_to_its_did() {
        let did = "did:webvh:QmScidAbCdEfGhIj:example.com:ops";
        let report = TrustReport {
            ok: true,
            commits: Vec::new(),
            unresolved_signers: BTreeMap::new(),
            signer_names: BTreeMap::new(),
        };
        assert_eq!(
            render_signer(&report, did),
            vta_sdk::display_name::shorten_did(did)
        );
    }
}