vtc-service 0.12.0

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

use affinidi_did_resolver_cache_sdk::DIDCacheClient;

use crate::credentials::vm_resolver::{DidVmResolver, check_issuer_binding};
use crate::routing::rate_limit::{RELATIONSHIPS_LIMITER, RateLimited};
use axum::http::StatusCode;
use chrono::Utc;
use dtg_credentials::IssuerScope;
use serde::{Deserialize, Serialize};
use serde_json::{Value as JsonValue, json};
use tracing::info;
use trust_tasks_rs::TrustTask as TrustTaskDoc;
use uuid::Uuid;
use vti_common::audit::{
    AuditEvent, VrcLifecycleData, VrcPublishedData, VrcRevokedData, VrcSupersededData,
};
use vti_common::error::AppError;

use crate::acl::get_acl_entry;
use crate::error::TaskError;
use crate::members::get_member;
use crate::policy::{
    PolicyPurpose, compile as compile_policy, evaluate as evaluate_policy, get_active_policy_id,
    get_policy,
};
use crate::relationships::{
    Relationship, delete_relationship, find_by_hash, issuer_counterparties_besides,
    store_relationship,
};
use crate::server::AppState;

// ─── Publish ─────────────────────────────────────────────

/// Which kind of identifier a VRC is issued under. A member picks per
/// relationship; the community declares which it expects (see the community
/// profile's `relationshipIdentifierDefault`). Both are permanent, supported
/// forms — neither is a migration state.
///
/// Read from the VRC's own `issuerScope` — the issuer's declaration of how
/// widely its identifier is recognised (DTG Credentials §issuerScope):
///
/// | `issuerScope` | form | why |
/// |---|---|---|
/// | `pairwise` | `pairwise` | an identifier for this one counterparty — the same claim |
/// | `directed` | `attributed` | a persona recognised by a set of counterparties; the edge names it |
/// | `public` | `attributed` | an identifier anyone can recognise, such as a membership DID |
///
/// `attributed` has no single `issuerScope` of its own: it means "not
/// per-counterparty", which `directed` and `public` both are. The policy also
/// receives the raw `issuer_scope`, so a community that distinguishes the two
/// can.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum IdentifierForm {
    /// Issued under the member's membership DID. The edge names them and the
    /// graph is correlatable by design — what a public community wants.
    Attributed,
    /// Issued under a relationship DID scoped to one counterparty, with a
    /// publish authorization proving control of it.
    Pairwise,
}

impl IdentifierForm {
    /// The form an `issuerScope` declares — see the type's table.
    fn from_scope(scope: IssuerScope) -> Self {
        match scope {
            IssuerScope::Pairwise => IdentifierForm::Pairwise,
            IssuerScope::Directed | IssuerScope::Public => IdentifierForm::Attributed,
        }
    }

    /// Wire value, and the string operator policies match on.
    fn as_str(self) -> &'static str {
        match self {
            IdentifierForm::Attributed => "attributed",
            IdentifierForm::Pairwise => "pairwise",
        }
    }
}

use trust_tasks_rs::specs::vtc::relationships as relationships_spec;

/// `vtc/relationships/publish:vrcInvalid` — the VRC failed verification, or
/// its issuer did not match the proof signer.
pub const PUBLISH_ERR_VRC_INVALID: &str =
    relationships_spec::publish::v0_2::error_codes::VRC_INVALID.code;
/// `vtc/relationships/publish:subjectNotMember` — the subject is not a member.
pub const PUBLISH_ERR_SUBJECT_NOT_MEMBER: &str =
    relationships_spec::publish::v0_2::error_codes::SUBJECT_NOT_MEMBER.code;
/// `vtc/relationships/revoke:notFound` — no relationship with that id.
pub const REVOKE_ERR_NOT_FOUND: &str =
    relationships_spec::revoke::v0_1::error_codes::NOT_FOUND.code;

#[derive(Debug, Deserialize, utoipa::ToSchema)]
pub struct PublishBody {
    /// The self-issued VRC, in the DTG Credentials wire form:
    /// `@context` carrying the W3C v2 and DTG contexts, `type`
    /// `["VerifiableCredential", "DTGCredential",
    /// "RelationshipCredential"]`, an `issuer`,
    /// `credentialSubject.id` naming the subject, and a
    /// data-integrity proof. Built by
    /// `dtg_credentials::DTGCredential::new_vrc`.
    pub vrc: JsonValue,
    /// Proof that the caller controls the key behind the VRC's
    /// `issuer`, when that is not the caller's session DID —
    /// i.e. whenever the credential is issued under a pairwise
    /// relationship DID rather than the member's membership DID.
    ///
    /// See [`verify_publish_authorization`]. Required unless
    /// `issuer` equals the session DID (the deprecated form).
    #[serde(default)]
    pub pop: Option<JsonValue>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[derive(utoipa::ToSchema)]
pub struct PublishResponse {
    pub id: Uuid,
    pub issuer_did: String,
    pub subject_did: String,
    pub vrc_digest_multibase: String,
}

/// Publish the VRC `doc` carries, on behalf of `signer_did` — called only
/// from the `vtc/relationships/publish/0.2` Trust Task on the spine
/// (`trust_tasks::member_tasks::handle_relationships_publish`), which has
/// already verified the document's proof (`verified_signer`). No REST route
/// calls this any more: the bearer-less REST route that used to verify the
/// proof itself had no caller once `vtc-client` signed the document instead
/// (#1845), and was removed.
///
/// `doc` is the whole document rather than its payload because the publish
/// authorization (`pop`) binds to the document's `id`. Returns `201` for a new
/// edge and `200` for an idempotent republish of one already held.
pub(crate) async fn publish_inner(
    state: &AppState,
    doc: &TrustTaskDoc<JsonValue>,
    signer_did: &str,
    now: chrono::DateTime<Utc>,
) -> Result<(StatusCode, PublishResponse), PublishError> {
    let signer_did = signer_did.to_string();

    // 0c. Per-DID rate limiting, keyed on the HMAC of the signer
    //     rather than the DID itself — the discipline the audit
    //     writer already applies, so the counter does not double as
    //     a live register of who is active in this community.
    //
    //     It runs *after* proof verification, because the DID does
    //     not exist until the proof is checked; it therefore cannot
    //     bound the cost of verification. That is the per-IP
    //     governor's job, and this route now sits behind it. Two
    //     different controls: one protects the server from anonymous
    //     load, this protects the graph from an admitted member.
    enforce_publish_rate_limit(state, &signer_did).await?;

    let body: PublishBody = serde_json::from_value(doc.payload.clone())
        .map_err(|e| AppError::Validation(format!("invalid publish payload: {e}")))?;

    // 1. Parse the VC's core fields without going through the
    //    typed `VerifiableCredential` — VRCs carry a few
    //    extensions the typed parser doesn't know about, and
    //    we want to store the JSON-LD verbatim either way.
    let vrc = &body.vrc;
    let issuer_did = extract_did_field(vrc, "issuer")?;
    let subject_did = extract_subject_id(vrc)?;

    // 2. Shape + validity window: is this even a relationship
    //    credential, and is it in date? Checked before anything
    //    expensive, and before authorization, because a
    //    malformed or expired body is a 400 whoever sent it.
    //
    //    `now` was read once at the top of the handler, so every
    //    check in this request evaluates at one instant.
    check_vrc_shape(vrc, now)?;

    // 3. Cheapest authorization gate first: a VRC issued under a
    //    DID that is not the session's must carry a publish
    //    authorization. Rejecting here keeps a caller error a
    //    caller error — the daemon-config prerequisites below
    //    would otherwise mask it with a 500.
    //
    //    An issuer the signer is not, and has not proven control of, is
    //    `publish:vrcInvalid` ("its issuer did not match the proof signer"),
    //    as is a VRC proof or publish authorization that does not verify
    //    (steps 4 and 6). Status and message are unchanged.
    if body.pop.is_none() && issuer_did != signer_did {
        return Err(TaskError::declared(
            PUBLISH_ERR_VRC_INVALID,
            AppError::Forbidden(format!(
                "VRC issuer ({issuer_did}) is not the document signer and no publish \
                 authorization (`pop`) was supplied — a VRC issued under a \
                 relationship DID must carry proof the caller controls it"
            )),
        )
        .into());
    }

    // 4. Verify the VC's data-integrity proof against the key
    //    the `issuer` field names. This establishes that the
    //    credential was made by the party it names as issuer —
    //    true whatever kind of identifier that is, and untouched
    //    by the authorization change below.
    let resolver = state.did_resolver.as_ref().cloned().ok_or_else(|| {
        AppError::Internal("DID resolver not configured — VRC publish requires it".into())
    })?;
    verify_di_proof(vrc, &issuer_did, &resolver)
        .await
        .map_err(|e| {
            TaskError::declared(
                PUBLISH_ERR_VRC_INVALID,
                AppError::Validation(format!("VrcProofInvalid: {e}")),
            )
        })?;

    // 5. Hash the VRC. This moves ahead of policy evaluation
    //    because the publish authorization binds to it.
    let vrc_digest_multibase = crate::credentials::ingress::digest_multibase(vrc)?;

    // 6. Authorize the *publication*, which is a separate act
    //    from the issuance verified at step 2. Issuing a VRC and
    //    publishing it to the community graph are different
    //    disclosures, and the second one is the issuer's to make:
    //    without this, any member who was ever handed a VRC could
    //    publish someone else's edge.
    //
    //    Previously this was `auth.did == issuer_did`, which
    //    forced the member's membership DID into the durable,
    //    publishable credential. The session proves membership;
    //    the authorization object proves control of the issuing
    //    key; neither requires them to be the same string (#1054).
    //    A member chooses this per relationship. Both forms are
    //    first-class and permanent — neither is a migration
    //    state:
    //
    //    **attributed** — the VRC is issued under the member's
    //    own membership DID. The edge names them, and the graph
    //    is correlatable by design. This is what a public
    //    community wants; DTG Credentials permits it directly
    //    ("the member may also assert the M-DID in any VRC where
    //    the member wishes to assert a VTC relationship").
    //
    //    **pairwise** — the VRC is issued under a relationship
    //    DID scoped to this counterparty, and the authorization
    //    object proves the caller controls it.
    //
    //    The community declares which it expects; the member
    //    decides each time. Only the *claim* is enforced here —
    //    see the uniqueness check below.
    if let Some(pop) = &body.pop {
        let vrc_digest = crate::credentials::ingress::digest_multibase(vrc)?;
        verify_publish_authorization(pop, &issuer_did, &doc.id, &vrc_digest, &resolver)
            .await
            .map_err(|e| {
                TaskError::declared(
                    PUBLISH_ERR_VRC_INVALID,
                    AppError::Forbidden(format!("VrcPublishAuthorizationInvalid: {e}")),
                )
            })?;
    } else if issuer_did != signer_did {
        // Rejected at step 3; restated rather than `unreachable!` so a
        // future edit that moves the gate cannot turn a caller error into
        // a panicking request handler.
        return Err(AppError::Forbidden(
            "VRC issuer is not the document signer and no publish \
             authorization (`pop`) was supplied"
                .into(),
        )
        .into());
    }

    //    The form is the credential's own declaration (`issuerScope`),
    //    checked against what the community can see of it: the member's
    //    membership DID is recognised by the whole community, so a VRC
    //    issued under it cannot truthfully declare `pairwise`.
    let issuer_scope = vrc_issuer_scope(vrc)?;
    let identifier_form = IdentifierForm::from_scope(issuer_scope);
    if identifier_form == IdentifierForm::Pairwise && issuer_did == signer_did {
        return Err(TaskError::declared(
            PUBLISH_ERR_VRC_INVALID,
            AppError::Validation(format!(
                "VRC declares issuerScope `pairwise` but is issued under your membership DID \
                 {issuer_did}, which the whole community recognises. Issue a pairwise edge \
                 under a relationship DID (with `pop`), or declare `public`"
            )),
        )
        .into());
    }

    //    An identifier presented as pairwise must actually be
    //    pairwise. DTG Credentials: "each entity MUST generate a
    //    new, unique R-DID for every single entity they connect
    //    with, even within the same community."
    //
    //    This is type integrity, not a privacy policy, which is
    //    why it is unconditional rather than something a
    //    community can switch off. A verifier reading a pairwise
    //    edge is entitled to conclude the identifier says nothing
    //    beyond that one relationship; a reused R-DID breaks that
    //    inference for every reader of the graph, not just for
    //    the member who reused it. A member who wants to be
    //    recognised across their relationships has a supported
    //    way to do it — the attributed form above.
    //
    //    The community is the only party that can see the
    //    violation: each counterparty sees only its own edge.
    if identifier_form == IdentifierForm::Pairwise {
        let others = issuer_counterparties_besides(
            &state.relationships_ks,
            &state.relationships_by_did_ks,
            &issuer_did,
            &subject_did,
        )
        .await?;
        if !others.is_empty() {
            return Err(AppError::Validation(format!(
                "relationship DID {issuer_did} already has an edge to {} other \
                 counterpart(y|ies) — a relationship DID must be unique to one \
                 counterparty. Mint a new one for this relationship, or issue \
                 under your membership DID to publish an attributed edge",
                others.len()
            ))
            .into());
        }
    }

    // 7. Enrich for the policy input.
    //
    //    `authenticated_member` is the caller — the party whose
    //    membership actually gates this publish. `issuer` and
    //    `subject` are the credential's own parties, which under
    //    pairwise identifiers are not resolvable to members and
    //    are not meant to be.
    //
    let member_current = is_current_member(state, &signer_did).await?;
    let issuer_current = is_current_member(state, &issuer_did).await?;
    let subject_current = is_current_member(state, &subject_did).await?;

    // The subject membership check only asks an answerable
    // question on the deprecated form, where the subject is named
    // by a membership DID. Under pairwise identifiers it is not
    // just unanswerable but the wrong question: DTG Credentials
    // §Community-Anchored ZKP is explicit that "community
    // membership is not a precondition for issuing, holding, or
    // presenting a VRC". The subject's consent to the edge is
    // their publication of the reciprocal VRC, not our assertion
    // that they exist.
    if identifier_form == IdentifierForm::Attributed
        && issuer_did == signer_did
        && !subject_current
        && get_acl_entry(&state.acl_ks, &subject_did).await?.is_none()
    {
        return Err(TaskError::declared(
            PUBLISH_ERR_SUBJECT_NOT_MEMBER,
            AppError::Validation(format!(
                "subject DID {subject_did} is not a current community member"
            )),
        )
        .into());
    }

    let policy_input = json!({
        "vrc": vrc,
        "authenticated_member": { "did": signer_did, "is_current": member_current },
        "identifier_form": identifier_form.as_str(),
        "issuer_scope": issuer_scope.as_str(),
        // `is_current` on the credential'"'"'s own parties is meaningful only for
        // the attributed form; under pairwise identifiers neither party is
        // resolvable to a member, and is not meant to be.
        "issuer": { "did": issuer_did, "is_current": issuer_current },
        "subject": { "did": subject_did, "is_current": subject_current },
        "action": "publish",
    });
    let allow = evaluate_relationships_policy(state, &policy_input).await?;
    if !allow {
        return Err(AppError::Forbidden(
            "RelationshipPolicyDenied: active relationships.rego rejected the publish".into(),
        )
        .into());
    }

    // 8. Idempotency: same hash → same id.
    if let Some(existing) = find_by_hash(&state.relationships_ks, &vrc_digest_multibase).await? {
        return Ok((
            StatusCode::OK,
            PublishResponse {
                id: existing.id,
                issuer_did: existing.issuer_did,
                subject_did: existing.subject_did,
                vrc_digest_multibase: existing.vrc_digest_multibase,
            },
        ));
    }

    // 9. Store the row + secondary-index entries.
    let id = Uuid::new_v4();
    let rel = Relationship {
        id,
        issuer_did: issuer_did.clone(),
        subject_did: subject_did.clone(),
        vrc_jsonld: vrc.clone(),
        vrc_digest_multibase: vrc_digest_multibase.clone(),
        created_at: Utc::now(),
        // A persona would be asserted separately, against an edge that
        // already exists; nothing does yet (vpc-persona-annotation.md).
        persona: None,
        // A freshly published edge has had nothing recorded against it. Every
        // later state — suspended, restored, superseded, withdrawn — is an
        // append to this log, never a mutation of the row's other fields.
        lifecycle: crate::relationships::LifecycleLog::default(),
    };
    store_relationship(
        &state.relationships_ks,
        &state.relationships_by_did_ks,
        &rel,
    )
    .await?;

    // 9b. A VRC to a counterparty this issuer already has an edge to is a new
    //     version of one assertion, not a second relationship — DTG
    //     Credentials makes an R-DID unique per counterparty, so the pair
    //     *is* the relationship. Record the displacement on the earlier rows
    //     so the graph can say which one the issuer currently stands behind.
    //
    //     After the store, not before: superseding first and then failing to
    //     write the replacement would leave the issuer with no edge at all,
    //     where this ordering's worst case is a brief window in which both
    //     stand. The redundant-but-live reading is the safe one.
    //
    //     The idempotent-publish branch above returns before reaching here, so
    //     re-sending the identical credential cannot supersede its own row.
    let superseded = crate::relationships::supersede_prior_edges(
        &state.relationships_ks,
        &state.relationships_by_did_ks,
        &issuer_did,
        &subject_did,
        id,
        &vrc_digest_multibase,
        now,
    )
    .await?;

    // 10. Audit.
    //
    //    The actor is the **authenticated member**, not the VRC's
    //    issuer. Under the pairwise form those differ, and the
    //    issuing relationship DID names nobody — recording it as
    //    the actor would leave the trail unable to answer "which
    //    member published this edge" for anyone, at any access
    //    level, ever.
    //
    //    This is a deliberate, narrow exception to the rule that
    //    the membership-to-relationship linkage must not be
    //    persisted, and it is confined to the one store built to
    //    hold privileged records: the audit envelope HMACs the
    //    actor under a rotating key, keeps the plaintext in a
    //    field that RTBF can null without breaking the
    //    tamper-evidence chain, and is admin-gated. What #1054
    //    set out to remove was *public, permanent, unavoidable*
    //    correlation — a membership DID welded into a credential
    //    anyone can retain and republish. Accountability inside
    //    an access-controlled, redactable, tamper-evident log is
    //    a different thing, and giving it up would buy nothing:
    //    `vrc_id` resolves to the row, and the row holds the
    //    relationship DIDs, so any trail that references the edge
    //    and names the member creates the mapping regardless.
    //
    //    The residual is real and worth stating: an operator with
    //    audit access can map every pairwise edge to its member.
    //    The `info!` below deliberately does *not* carry the
    //    member — logs have neither the redaction machinery nor
    //    the access controls that make this trade defensible.
    let edge_type = vrc
        .pointer("/credentialSubject/endorsement/type")
        .and_then(|v| v.as_str())
        .unwrap_or("recognition")
        .to_string();
    if let Some(writer) = state.audit_writer.as_ref() {
        writer
            .write(
                // The proven signer, which is now what "the member" means on
                // this route.
                &signer_did,
                Some(&subject_did),
                AuditEvent::VrcPublished(VrcPublishedData {
                    vrc_id: id.to_string(),
                    subject_did: Some(subject_did.clone()),
                    edge_type,
                }),
            )
            .await?;
    }

    // Supersession is a lifecycle change to an edge the community already
    // held, so it is audited in its own right rather than folded into the
    // publish entry — an operator asking "what happened to edge X" must find
    // the answer under X, not under the credential that replaced it.
    if let Some(writer) = state.audit_writer.as_ref() {
        for displaced in &superseded {
            writer
                .write(
                    &signer_did,
                    Some(&subject_did),
                    AuditEvent::VrcSuperseded(VrcSupersededData {
                        vrc_id: displaced.to_string(),
                        superseded_by_digest_multibase: vrc_digest_multibase.clone(),
                    }),
                )
                .await?;
        }
    }

    info!(
        vrc_id = %id,
        issuer = %issuer_did,
        subject = %subject_did,
        superseded = superseded.len(),
        "VRC published"
    );

    Ok((
        StatusCode::CREATED,
        PublishResponse {
            id,
            issuer_did,
            subject_did,
            vrc_digest_multibase,
        },
    ))
}

// ─── Revoke ──────────────────────────────────────────────

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[derive(utoipa::ToSchema)]
#[schema(as = RelationshipRevokeResponse)]
pub struct RevokeResponse {
    pub id: String,
}

/// `type` of the revoke authorization (`vtc/relationships/revoke/0.2`'s
/// `pop`). Distinct from the publish type so the authorization a member signs
/// every time they lodge an edge cannot be replayed to delete it.
const REVOKE_AUTHORIZATION_TYPE: &str = "VrcRevokeAuthorization";

/// Verify a `VrcRevokeAuthorization` — `vtc/relationships/revoke/0.2`'s `pop`,
/// the pairwise route's proof of possession of the relationship's own
/// `issuerDid`.
///
/// Same construction as [`verify_publish_authorization`], with the document's
/// own `id` and the edge's `id` in place of publish's `vrcDigestMultibase`:
/// `documentId` so a captured authorization is not replayable into another
/// document, and `relationship` so an authorization signed for one edge
/// cannot revoke another. Unlike the bearer route this replaces, it carries no
/// `sessionId` or `aud` — a signed Trust Task document has no session to bind
/// to (`vtc/relationships/revoke/0.2` §Security & Privacy).
///
/// **Verified and discarded.** Retaining it would accumulate a durable link
/// between a member and a relationship DID that names nobody — the same
/// reason [`verify_publish_authorization`] discards its own.
pub(crate) async fn verify_revoke_authorization(
    pop: &JsonValue,
    issuer_did: &str,
    expected_document_id: &str,
    expected_relationship_id: &str,
    resolver: &DIDCacheClient,
) -> Result<(), String> {
    let field = |name: &str| -> Result<String, String> {
        pop.get(name)
            .and_then(|v| v.as_str())
            .map(str::to_string)
            .ok_or_else(|| format!("authorization missing `{name}`"))
    };
    let ty = field("type")?;
    if ty != REVOKE_AUTHORIZATION_TYPE {
        return Err(format!(
            "authorization `type` must be `{REVOKE_AUTHORIZATION_TYPE}`, got `{ty}`"
        ));
    }
    if field("documentId")? != expected_document_id {
        return Err("authorization is bound to a different document".into());
    }
    if field("relationship")? != expected_relationship_id {
        return Err("authorization is bound to a different edge".into());
    }
    verify_di_proof(pop, issuer_did, resolver).await
}

/// Delete an edge whose control the door has already established, and audit
/// it — the effect behind the `vtc/relationships/revoke/{0.1,0.2}` Trust
/// Tasks. `revoked_by` is the capacity the door authorized `actor_did` in
/// (`"issuer"` or `"admin"`).
pub(crate) async fn revoke_authorized(
    state: &AppState,
    actor_did: &str,
    rel: &Relationship,
    revoked_by: &'static str,
) -> Result<RevokeResponse, AppError> {
    let id = rel.id;
    delete_relationship(&state.relationships_ks, &state.relationships_by_did_ks, id).await?;

    if let Some(writer) = state.audit_writer.as_ref() {
        writer
            .write(
                actor_did,
                Some(&rel.subject_did),
                AuditEvent::VrcRevoked(VrcRevokedData {
                    vrc_id: id.to_string(),
                    revoked_by: revoked_by.into(),
                }),
            )
            .await?;
    }

    info!(vrc_id = %id, revoked_by, "VRC revoked");

    Ok(RevokeResponse { id: id.to_string() })
}

// ─── Suspend / restore ───────────────────────────────────
//
// The two verbs #1079 says the graph has no vocabulary for. Until they
// existed, an edge had exactly two states — published and deleted — so a
// community with a reason to stop relying on an edge *temporarily* had to
// destroy it, and the member had to re-issue and re-publish to get it back.
// That is not a smaller version of revocation; it is a different act, and
// collapsing the two is what makes "suspended" unrepresentable.
//
// Neither verb touches the credential. The VRC's signature, its window and
// its digest are all unchanged — what changes is what this community records
// against it, and `credentials::lifecycle` states once how the two combine.
// That separation is what lets suspension exist at all for a credential type
// that deliberately carries no `credentialStatus` (planning-review D7).

/// The two verbs [`record_lifecycle_as`] serves.
///
/// An enum rather than a bundle of `&str` parameters because the things that
/// vary — the event appended and the audit variant emitted — must vary
/// *together*.
#[derive(Debug, Clone, Copy)]
pub(crate) enum EdgeLifecycleVerb {
    Suspend,
    Restore,
}

impl EdgeLifecycleVerb {
    /// The verb as it appears in a rejection message.
    fn as_str(self) -> &'static str {
        match self {
            Self::Suspend => "suspend",
            Self::Restore => "restore",
        }
    }

    fn event(self, reason: Option<String>) -> crate::relationships::LifecycleEventKind {
        match self {
            Self::Suspend => crate::relationships::LifecycleEventKind::Suspended { reason },
            Self::Restore => crate::relationships::LifecycleEventKind::Restored { reason },
        }
    }

    fn audit(self, data: VrcLifecycleData) -> AuditEvent {
        match self {
            Self::Suspend => AuditEvent::VrcSuspended(data),
            Self::Restore => AuditEvent::VrcRestored(data),
        }
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[derive(utoipa::ToSchema)]
pub struct LifecycleResponse {
    pub id: Uuid,
    /// The edge's resolved state after the event, as
    /// [`crate::credentials::lifecycle::resolve`] computes it.
    ///
    /// The *resolved* state, not the event that was just recorded, because
    /// those are not the same thing and the difference is the point of the
    /// precedence rule: restoring an edge whose `validUntil` has passed
    /// records a restoration and still answers `expired`.
    pub state: crate::relationships::InForce,
}

/// Append `verb`'s event to `rel` as `actor`, who acts as the edge's
/// `capacity` (`"issuer"` or `"admin"`) — `vtc/relationships/{suspend,restore}/0.1`.
///
/// The caller has already decided the capacity: the edge's issuer is the
/// document's signer itself, and a moderating administrator is resolved from
/// the signer's ACL row. Refused with a conflict if the edge is already
/// suspended (for a suspension), is not suspended (for a restoration), or has
/// been superseded or withdrawn.
pub(crate) async fn record_lifecycle_as(
    state: &AppState,
    actor: &str,
    capacity: &'static str,
    rel: &Relationship,
    verb: EdgeLifecycleVerb,
    reason: Option<String>,
) -> Result<LifecycleResponse, AppError> {
    let now = Utc::now();
    let id = rel.id;
    let updated = crate::relationships::record_lifecycle_event(
        &state.relationships_ks,
        &state.relationships_by_did_ks,
        id,
        verb.event(reason.clone()),
        now,
    )
    .await?;

    // The actor is the authenticated signer, not the edge's issuer, for the
    // reason the publish and persona trails record it that way: under a
    // pairwise identifier the issuer names nobody, so a trail keyed on it
    // could never answer who changed this edge's state.
    if let Some(writer) = state.audit_writer.as_ref() {
        let event = verb.audit(VrcLifecycleData {
            vrc_id: id.to_string(),
            recorded_by: capacity.into(),
            reason,
        });
        writer
            .write(actor, Some(&updated.subject_did), event)
            .await?;
    }

    info!(vrc_id = %id, capacity, verb = verb.as_str(), "VRC lifecycle event recorded");

    Ok(LifecycleResponse {
        id,
        state: updated.in_force_at(now),
    })
}

// ─── Helpers ─────────────────────────────────────────────

/// Extract a DID from a JSON-LD VC field that may be either a
/// string or an object with an `id` member (W3C spec allows
/// both shapes for `issuer`).
fn extract_did_field(vrc: &JsonValue, field: &str) -> Result<String, AppError> {
    let v = vrc
        .get(field)
        .ok_or_else(|| AppError::Validation(format!("VRC missing {field}")))?;
    match v {
        JsonValue::String(s) => Ok(s.clone()),
        JsonValue::Object(o) => o
            .get("id")
            .and_then(|x| x.as_str())
            .map(str::to_string)
            .ok_or_else(|| AppError::Validation(format!("VRC.{field}.id missing or not a string"))),
        _ => Err(AppError::Validation(format!(
            "VRC.{field} is neither a string nor an object"
        ))),
    }
}

fn extract_subject_id(vrc: &JsonValue) -> Result<String, AppError> {
    vrc.pointer("/credentialSubject/id")
        .and_then(|v| v.as_str())
        .map(str::to_string)
        .ok_or_else(|| {
            AppError::Validation("VRC.credentialSubject.id missing or not a string".into())
        })
}

/// Reject anything that is not a conformant, currently-valid VRC before it
/// becomes an edge in the community's trust graph.
///
/// The VTC does not mint VRCs — they are self-issued — but it decides what
/// enters the graph, and an edge is only interpretable if it says what it is.
/// Delegates to [`crate::credentials::ingress`], the one place the DTG common
/// structure and the validity window are checked, so this endpoint and every
/// other ingress point agree about what a DTG credential is and about when it
/// is in date.
///
/// Until #1069 this path read neither `validFrom` nor `validUntil`, so a VRC
/// that had already expired became a permanent edge — permanent because the
/// graph is read without re-checking dates, and because per D7 a VRC has no
/// `credentialStatus` to retract it with. The only removal is the issuer (or an
/// admin) calling `DELETE /v1/relationships/{id}`.
fn check_vrc_shape(vrc: &JsonValue, now: chrono::DateTime<Utc>) -> Result<(), AppError> {
    crate::credentials::ingress::require_dtg_type(
        vrc,
        dtg_credentials::DTGCredentialType::Relationship,
        now,
        "this endpoint publishes relationship edges",
    )
}

/// The `issuerScope` a VRC declares. [`check_vrc_shape`] has already refused
/// one without a valid value; this reads it.
fn vrc_issuer_scope(vrc: &JsonValue) -> Result<IssuerScope, AppError> {
    vrc.get("issuerScope")
        .and_then(JsonValue::as_str)
        .ok_or_else(|| AppError::Validation("VRC carries no `issuerScope`".into()))?
        .parse::<IssuerScope>()
        .map_err(|e| AppError::Validation(format!("VRC `issuerScope`: {e}")))
}

/// Bound how fast one member can publish.
///
/// The limiter and the reasoning behind it live in
/// [`crate::relationships::rate_limit`]; this is the route's use of it. A
/// refusal is a `429` in the shape [`crate::routing::rate_limit`] defines, so
/// an operator can tell from the response alone that this VTC refused, and
/// which of its limiters did.
async fn enforce_publish_rate_limit(state: &AppState, did: &str) -> Result<(), RateLimited> {
    state
        .publish_rate_limiter
        .check_and_record(did, Utc::now())
        .await
        .map_err(|retry_after_secs| {
            RateLimited::new(
                RELATIONSHIPS_LIMITER,
                retry_after_secs,
                format!(
                    "a member may publish at most {} relationship credentials per {}s",
                    crate::relationships::rate_limit::MAX_PER_WINDOW,
                    crate::relationships::rate_limit::WINDOW_SECS,
                ),
            )
        })
}

/// The publish handler's error: an ordinary [`AppError`], or a rate-limit
/// refusal, which needs response headers `AppError` cannot carry.
#[derive(Debug)]
pub enum PublishError {
    App(TaskError),
    RateLimited(RateLimited),
}

impl From<AppError> for PublishError {
    fn from(e: AppError) -> Self {
        Self::App(e.into())
    }
}

impl From<TaskError> for PublishError {
    fn from(e: TaskError) -> Self {
        Self::App(e)
    }
}

impl From<RateLimited> for PublishError {
    fn from(e: RateLimited) -> Self {
        Self::RateLimited(e)
    }
}

impl axum::response::IntoResponse for PublishError {
    fn into_response(self) -> axum::response::Response {
        match self {
            Self::App(e) => e.into_response(),
            Self::RateLimited(r) => r.into_response(),
        }
    }
}

/// `type` of the publish authorization object. Guarding on it stops a
/// signature the member made over some *other* object being replayed here as
/// authorization to publish.
const PUBLISH_AUTHORIZATION_TYPE: &str = "VrcPublishAuthorization";

/// Verify a publish authorization: proof that the caller controls the key
/// behind the VRC's `issuer`, bound to this document and this credential.
///
/// The document's own proof says a member sent this request. This says
/// somebody controls the key that issued the credential inside it. Both are
/// needed, because an edge may be published under a relationship DID that
/// names nobody: without this, any member ever handed a VRC could publish
/// another party's edge, and issuing a credential is a different disclosure
/// from publishing it to a community's graph.
///
/// Shape per `vtc/relationships/publish` (trustoverip/dtgwg-trust-tasks-tf#259):
///
/// | field                 | prevents                                        |
/// |-----------------------|-------------------------------------------------|
/// | `type`                | a signature over some other object being replayed |
/// | `documentId`          | replay into a different document                 |
/// | `vrcDigestMultibase`  | being moved to a different credential            |
///
/// **This is a different argument from the one it replaces.** The earlier form
/// bound to a REST session id, so a captured authorization was unusable by
/// another member because it named their session. Binding to the document is
/// available on every transport and is narrower — a session spans many
/// documents — but the document `id` is minted by the client, so a captured
/// authorization replayed inside a forged document carrying the same `id`
/// still verifies. That buys an attacker nothing: `vrcDigestMultibase` pins
/// the credential, and the stored edge carries the VRC's own issuer and
/// subject rather than the publisher's, so the forgery republishes a
/// credential that was already theirs to republish. The property holds; it
/// holds for a different reason, and that reason is worth writing down rather
/// than assuming the two are equivalent.
///
/// **Verified and discarded.** Retaining it would accumulate a durable link
/// between a member and a relationship DID that names nobody — the correlation
/// publishing under a relationship DID exists to avoid.
async fn verify_publish_authorization(
    pop: &JsonValue,
    issuer_did: &str,
    expected_document_id: &str,
    expected_vrc_digest: &str,
    resolver: &DIDCacheClient,
) -> Result<(), String> {
    let field = |name: &str| -> Result<String, String> {
        pop.get(name)
            .and_then(|v| v.as_str())
            .map(str::to_string)
            .ok_or_else(|| format!("authorization missing `{name}`"))
    };

    let ty = field("type")?;
    if ty != PUBLISH_AUTHORIZATION_TYPE {
        return Err(format!(
            "authorization `type` must be `{PUBLISH_AUTHORIZATION_TYPE}`, got `{ty}`"
        ));
    }
    if field("documentId")? != expected_document_id {
        return Err("authorization is bound to a different document".into());
    }
    if field("vrcDigestMultibase")? != expected_vrc_digest {
        return Err("authorization is bound to a different credential".into());
    }

    // Signed by the key the VRC's `issuer` names. `check_issuer_binding`
    // inside `verify_di_proof` is what makes this proof-of-possession rather
    // than proof-of-anything-signed.
    verify_di_proof(pop, issuer_did, resolver).await
}

/// Verify a data-integrity proof on a JSON document: bind the proof's
/// `verificationMethod` to the named controller, then let the DI library
/// resolve the key (via the shared [`DidVmResolver`]) and check the signature —
/// the same path the credential-exchange + recognition verifiers take.
///
/// Used for both the VRC itself (controller = the credential's `issuer`) and
/// the publish authorization object (controller = the same issuer, proving the
/// caller holds the key rather than merely holding the credential).
async fn verify_di_proof(
    doc: &JsonValue,
    controller_did: &str,
    resolver: &DIDCacheClient,
) -> Result<(), String> {
    let vrc = doc;
    let proof_value = vrc
        .get("proof")
        .ok_or_else(|| "document missing proof".to_string())?;
    // A proof SET. As elsewhere, `verificationMethod` was read off the raw
    // JSON, which is `None` for an array — so the binding check was
    // unreachable for a hybrid document rather than merely unperformed.
    let proofs = crate::credentials::proof_set::proof_set(proof_value)
        .map_err(|e| format!("parse proof: {e}"))?;

    for proof in &proofs {
        check_issuer_binding(&proof.verification_method, controller_did)
            .map_err(|e| e.to_string())?;
    }

    let mut vrc_without_proof = vrc.clone();
    if let Some(obj) = vrc_without_proof.as_object_mut() {
        obj.remove("proof");
    }

    let vm_resolver = DidVmResolver::new(Some(resolver.clone()));
    let mut outcomes: Vec<(String, Result<(), String>)> = Vec::with_capacity(proofs.len());
    for proof in &proofs {
        let did = crate::credentials::proof_set::proof_signer_did(proof).to_string();
        let r = crate::credentials::proof_set::verify_one(
            proof,
            &vrc_without_proof,
            &vm_resolver,
            vti_common::auth::ProofPurpose::AssertionMethod,
        )
        .await;
        outcomes.push((did, r));
    }

    crate::credentials::proof_set::accept_all(&outcomes).map_err(|e| format!("verify: {e}"))?;
    Ok(())
}

/// A member is `is_current` iff they have a live ACL row +
/// the Member row exists and isn't tombstoned. Either
/// missing → false.
async fn is_current_member(state: &AppState, did: &str) -> Result<bool, AppError> {
    let acl = get_acl_entry(&state.acl_ks, did).await?;
    if acl.is_none() {
        return Ok(false);
    }
    let member = get_member(&state.members_ks, did).await?;
    Ok(member.is_some_and(|m| !m.is_removed()))
}

/// Evaluate `relationships.rego.allow`. Fail-closed.
async fn evaluate_relationships_policy(
    state: &AppState,
    input: &JsonValue,
) -> Result<bool, AppError> {
    let Some(id) =
        get_active_policy_id(&state.active_policies_ks, PolicyPurpose::Relationships).await?
    else {
        return Ok(false);
    };
    let policy = get_policy(&state.policies_ks, id)
        .await?
        .ok_or_else(|| AppError::Internal(format!("active relationships policy {id} not found")))?;
    let compiled = compile_policy(&policy.rego_source, policy.id)?;
    let result = evaluate_policy(&compiled, "data.vtc.relationships.allow", input.clone())?;
    Ok(result
        .pointer("/result/0/expressions/0/value")
        .and_then(|v| v.as_bool())
        .unwrap_or(false))
}

// ── Connections graph (admin) ──────────────────────────────────────────────
//
// DTG Credentials defines a DTG edge as **two** VRCs, one in each direction.
// This endpoint used to return one entry per stored VRC, so a mutual
// relationship and a unilateral claim were indistinguishable: two members who
// had each vouched for the other looked the same as one member asserting an
// edge the other has never acknowledged (#1054).
//
// That distinction is the whole reason the subject-membership precondition
// could be dropped in #1061. The design there
// (`docs/05-design-notes/vrc-publish-proof-of-possession.md`) is that the
// subject's consent to an edge **is** their publication of the reciprocal VRC,
// rather than the community asserting on their behalf that they exist. If the
// graph cannot show whether that reciprocal VRC arrived, the consent signal the
// check was replaced with is invisible to the operator reading the graph.
//
// So the graph groups by unordered pair and reports the halves it holds.

/// One node in the connections graph — an identifier that is an endpoint of at
/// least one relationship (VRC). Isolated members (no VRCs) are not surfaced.
#[derive(Debug, Serialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct GraphNode {
    pub did: String,
}

/// One published VRC: a directed *half* of a DTG edge, from `issuerDid` (the
/// asserting party) to `subjectDid`. Body-free (no VRC JSON-LD) — the graph
/// shows the shape, not the credential contents. `id` is the row id, which is
/// what `DELETE /v1/relationships/{id}` takes.
#[derive(Debug, Serialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct GraphHalf {
    pub id: String,
    pub issuer_did: String,
    pub subject_did: String,
    pub created_at: String,
    /// The persona (P-DID) the issuer has asserted on this edge, if any.
    ///
    /// This is the one place the deliberate correlation a VPC exists to
    /// enable becomes visible: two pairwise edges carrying the same
    /// `personaDid` are the same party, said so by that party. Without it the
    /// annotation would be stored and never read, which is the state #1067
    /// describes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub persona_did: Option<String>,
}

/// One edge between a pair of identifiers, carrying every VRC published between
/// them.
#[derive(Debug, Serialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct GraphEdge {
    /// The two endpoints, DID-sorted. Always exactly two entries, and sorting
    /// them gives the pair one identity whichever half was published first.
    /// Both entries are equal only for a self-issued VRC.
    pub endpoints: Vec<String>,
    /// Every VRC published between the endpoints, oldest first. One for a
    /// half-edge, two for the ordinary complete edge; more only if a party
    /// published several VRCs in the same direction, which nothing prevents
    /// (idempotency is per credential hash, not per direction).
    pub halves: Vec<GraphHalf>,
    /// An **in-force** VRC exists in both directions — a complete DTG edge,
    /// and the only form in which both parties currently consent.
    ///
    /// "In force" and not merely "present" since #1079. A half whose VRC has
    /// expired, or which has been suspended, superseded or withdrawn, no
    /// longer completes an edge — resolved through
    /// [`Relationship::in_force_at`], which is the one place the precedence
    /// rule lives. Before this the graph was read back without re-checking
    /// anything, so a half-edge whose reciprocal had expired years ago was
    /// indistinguishable from a live mutual relationship.
    ///
    /// The halves themselves are still listed whatever their state: an
    /// operator looking at a graph needs to see that a VRC was published, and
    /// removing it would make a withdrawn edge look like one that never
    /// existed. Which halves are in force is not yet surfaced per half — that
    /// needs a field on `GraphHalf`, and `relationships/graph/0.2` pins the
    /// response shape with `additionalProperties: false`, so it waits on a
    /// spec revision upstream rather than shipping a body the task rejects.
    pub complete: bool,
}

#[derive(Debug, Serialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct RelationshipsGraph {
    pub nodes: Vec<GraphNode>,
    pub edges: Vec<GraphEdge>,
}

/// One directed half of a **membership** edge, lifted out of a member row into
/// the shape a published VRC contributes to the graph.
///
/// DTG Core Credentials makes VRCs and VMCs the two subtypes of *edge
/// credential*: "a bi-directional pair of credentials forms a complete DTG
/// edge" in both cases, and the community is a node like any other ("DTG node
/// types include persons, devices, AI agents, and VTCs"). A graph that renders
/// only VRC pairs is showing half the trust graph.
///
/// Membership halves are lifted rather than stored in the relationships
/// keyspace: they already exist, verified, on the member row. Copying them into
/// a second store would create two records of one fact, free to disagree — and
/// the VMC pair has its own lifecycle (status list, renewal, departure
/// handling) that the relationships keyspace does not model.
#[derive(Debug, Clone)]
pub struct MembershipHalf {
    /// The credential's own `id`. Not a relationships-keyspace row id, so it is
    /// not something `DELETE /v1/relationships/{id}` can take — a membership
    /// half is retracted by leaving the community, not by revoking an edge.
    pub id: String,
    pub issuer_did: String,
    pub subject_did: String,
    pub created_at: chrono::DateTime<Utc>,
    /// Whether this half currently stands. For the community's grant that is
    /// its validity window; for the member's acknowledgement it is the window
    /// **and** that its digest was verified against the grant — an unbound
    /// acknowledgement is still shown, but it does not complete an edge.
    pub in_force: bool,
}

/// Lift both halves of one member's membership edge.
///
/// Returns at most two halves: the community's grant (community → member) and
/// the member's acknowledgement (member → community). A member who has not
/// acknowledged yields one, which renders as the half-edge it is: the
/// community's claim, unanswered.
///
/// # A missing grant body does not fabricate a window
///
/// Rows written before the service kept credential bodies have the grant's `id`
/// but not its claims, so its window cannot be read. Such a half is treated as
/// standing — the ACL row is the community's live assertion of membership, and
/// it is the better evidence here than an absent document. This cannot
/// overstate an edge: the acknowledgement on those same rows is unbound, so the
/// edge is incomplete either way.
pub fn membership_halves(
    community_did: &str,
    member: &crate::members::Member,
    now: chrono::DateTime<Utc>,
) -> Vec<MembershipHalf> {
    /// Is a stored credential body inside its validity window? Absent body →
    /// `true`, per the doc comment above. Unreadable body → `false`: a document
    /// we cannot parse is not evidence of anything.
    fn window_stands(body: Option<&JsonValue>, now: chrono::DateTime<Utc>) -> bool {
        let Some(body) = body else {
            return true;
        };
        match crate::credentials::ingress::validity_window(body, "MembershipCredential") {
            Ok(window) => matches!(
                window.state_at(now),
                crate::credentials::lifecycle::InForce::Yes
            ),
            Err(_) => false,
        }
    }

    let mut halves = Vec::with_capacity(2);

    // The community's grant. A member with no `current_vmc_id` was admitted but
    // never issued to — no half to draw.
    if let Some(id) = &member.current_vmc_id {
        halves.push(MembershipHalf {
            id: id.clone(),
            issuer_did: community_did.to_string(),
            subject_did: member.did.clone(),
            created_at: member.joined_at,
            in_force: window_stands(member.current_vmc.as_ref(), now),
        });
    }

    // The member's acknowledgement.
    if let Some(id) = &member.member_vmc_id {
        halves.push(MembershipHalf {
            id: id.clone(),
            issuer_did: member.did.clone(),
            subject_did: community_did.to_string(),
            created_at: member.member_vmc_received_at.unwrap_or(member.joined_at),
            // `member_vmc_bound` is the digest check made at receipt. Without
            // it the acknowledgement names some grant, but not demonstrably
            // this one, and the spec is explicit that such a credential MUST
            // NOT be treated as completing a membership edge.
            in_force: member.member_vmc_bound && window_stands(member.member_vmc.as_ref(), now),
        });
    }

    halves
}

/// Group stored VRCs and lifted membership halves into pair-edges. Pure, so the
/// half/complete rule is testable without standing up a keyspace.
///
/// `now` is a parameter rather than read here because whether an edge is
/// complete is a question about an instant, and a test that cannot choose the
/// instant cannot pin an expiry boundary. Same reason the publish handler
/// reads `now` once at the top and passes it down.
fn build_graph(
    mut rels: Vec<Relationship>,
    memberships: Vec<MembershipHalf>,
    now: chrono::DateTime<Utc>,
) -> RelationshipsGraph {
    // Oldest first, id-tiebroken, so `halves` ordering is stable across calls
    // rather than inheriting whatever order the keyspace scan produced.
    rels.sort_by_key(|r| (r.created_at, r.id));

    let mut nodes = std::collections::BTreeSet::new();
    // BTreeMap, not HashMap: the response order is then a function of the data
    // and not of hash seeding, which keeps the admin view from reshuffling on
    // every poll.
    //
    // The resolved state rides alongside each half rather than on `GraphHalf`
    // itself: it decides `complete`, but it cannot be serialised until the
    // graph task's response schema admits it (see [`GraphEdge::complete`]).
    let mut pairs: std::collections::BTreeMap<(String, String), Vec<(GraphHalf, bool)>> =
        std::collections::BTreeMap::new();

    for r in rels {
        nodes.insert(r.issuer_did.clone());
        nodes.insert(r.subject_did.clone());
        let key = if r.issuer_did <= r.subject_did {
            (r.issuer_did.clone(), r.subject_did.clone())
        } else {
            (r.subject_did.clone(), r.issuer_did.clone())
        };
        let in_force = r.in_force_at(now).is_in_force();
        // Taken before the DIDs are moved into the half below.
        let persona_did = r.persona.map(|p| p.persona_did);
        pairs.entry(key).or_default().push((
            GraphHalf {
                id: r.id.to_string(),
                issuer_did: r.issuer_did,
                subject_did: r.subject_did,
                created_at: r.created_at.to_rfc3339(),
                persona_did,
            },
            in_force,
        ));
    }

    // Membership halves join the same pair map, so one `complete` rule covers
    // both kinds of edge. They are appended after the VRC halves and the pair's
    // halves are re-sorted below, rather than being merged in `created_at`
    // order here, because the two come from different stores and only the
    // combined list has a meaningful order.
    for half in memberships {
        nodes.insert(half.issuer_did.clone());
        nodes.insert(half.subject_did.clone());
        let key = if half.issuer_did <= half.subject_did {
            (half.issuer_did.clone(), half.subject_did.clone())
        } else {
            (half.subject_did.clone(), half.issuer_did.clone())
        };
        let in_force = half.in_force;
        pairs.entry(key).or_default().push((
            GraphHalf {
                id: half.id,
                issuer_did: half.issuer_did,
                subject_did: half.subject_did,
                created_at: half.created_at.to_rfc3339(),
                // A VPC annotates a relationship edge; membership is not
                // pseudonymous, so there is nothing to correlate here.
                persona_did: None,
            },
            in_force,
        ));
    }

    let edges = pairs
        .into_iter()
        .map(|((lo, hi), mut halves)| {
            // Oldest first across both sources, matching the `halves` contract.
            halves.sort_by(|a, b| {
                a.0.created_at
                    .cmp(&b.0.created_at)
                    .then(a.0.id.cmp(&b.0.id))
            });
            // A self-issued VRC (`lo == hi`) has no counterparty who could ever
            // reciprocate, so it can never be complete — without the `lo != hi`
            // guard the two `any` checks below would both match the same row
            // and report a self-vouch as a mutual relationship.
            //
            // Each direction must be satisfied by a half that is *in force*.
            // An expired or suspended VRC is still a published fact and still
            // appears below; what it no longer does is stand in for a party's
            // current consent.
            let live = |from: &String, to: &String| {
                halves
                    .iter()
                    .any(|(h, ok)| *ok && &h.issuer_did == from && &h.subject_did == to)
            };
            let complete = lo != hi && live(&lo, &hi) && live(&hi, &lo);
            GraphEdge {
                endpoints: vec![lo, hi],
                halves: halves.into_iter().map(|(h, _)| h).collect(),
                complete,
            }
        })
        .collect();

    RelationshipsGraph {
        nodes: nodes.into_iter().map(|did| GraphNode { did }).collect(),
        edges,
    }
}

/// `GET /v1/relationships/graph` — the community's relationship (VRC) graph for
/// the admin-UI connections view. Admin-gated; a full scan of the relationships
/// keyspace (communities are small and this is operator-only). Edge-derived
/// nodes — members with no VRCs don't appear.
///
/// Edges are pairs, not individual credentials: each carries the VRCs published
/// between its two endpoints and a `complete` flag saying whether both
/// directions are present. See the module comment above for why.
pub(crate) async fn graph(state: &AppState) -> Result<RelationshipsGraph, AppError> {
    let now = Utc::now();
    let rels = crate::relationships::list_all(&state.relationships_ks).await?;

    // Membership halves come from the member rows, where they already sit
    // verified — see [`membership_halves`] for why they are lifted rather than
    // copied into the relationships keyspace. A community with no DID
    // configured has no node to draw them against; the VRC graph still renders.
    let community_did = state.config.read().await.vtc_did.clone();
    let memberships = match community_did {
        Some(community_did) if !community_did.is_empty() => {
            crate::members::list_members(&state.members_ks)
                .await?
                .iter()
                .filter(|m| !m.is_removed())
                .flat_map(|m| membership_halves(&community_did, m, now))
                .collect()
        }
        _ => Vec::new(),
    };

    Ok(build_graph(rels, memberships, now))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn extract_did_field_handles_string_form() {
        let vrc = json!({ "issuer": "did:key:zA" });
        assert_eq!(extract_did_field(&vrc, "issuer").unwrap(), "did:key:zA");
    }

    #[test]
    fn extract_did_field_handles_object_form() {
        let vrc = json!({ "issuer": { "id": "did:key:zA", "name": "x" } });
        assert_eq!(extract_did_field(&vrc, "issuer").unwrap(), "did:key:zA");
    }

    #[test]
    fn extract_did_field_rejects_missing() {
        let vrc = json!({});
        assert!(extract_did_field(&vrc, "issuer").is_err());
    }

    #[test]
    fn extract_subject_id_extracts_nested() {
        let vrc = json!({
            "credentialSubject": { "id": "did:key:zSubject", "role": "member" }
        });
        assert_eq!(extract_subject_id(&vrc).unwrap(), "did:key:zSubject");
    }

    /// `check_vrc_shape` must accept exactly what the catalog mints as a VRC,
    /// and reject what it mints as anything else.
    ///
    /// Asserted against **catalog output** rather than a literal. A literal
    /// here could agree with the literal in `check_vrc_shape` while both
    /// disagreed with what clients actually send — the failure mode that let
    /// `VerifiableRecognitionCredential` live in this file's fixtures while no
    /// client ever emitted it, and that broke recognition in #1062 next door.
    #[test]
    fn accepts_what_the_catalog_mints_as_a_vrc_and_nothing_else() {
        use dtg_credentials::DTGCredential;

        use crate::test_support::dtg_json as body;

        let now = Utc::now();
        let vrc = DTGCredential::new_vrc(
            "did:peer:2.zR1".into(),
            IssuerScope::Pairwise,
            "did:peer:2.zR2".into(),
            now,
            None,
        );
        check_vrc_shape(&body(&vrc), now).expect("a catalog-minted VRC must be publishable");

        // Same catalog, different subtype — this endpoint publishes
        // relationship edges, and a membership edge has different issuance
        // rules.
        let vmc = DTGCredential::new_vmc(
            "did:web:community.example".into(),
            "did:key:zMember".into(),
            now,
            None,
            false,
        );
        let err = check_vrc_shape(&body(&vmc), now).expect_err("a VMC must not publish as a VRC");
        assert!(
            format!("{err:?}").contains("relationship edges"),
            "unexpected rejection: {err:?}"
        );
    }

    /// #1069: this endpoint read neither `validFrom` nor `validUntil`, so an
    /// expired VRC became a permanent edge — and per D7 a VRC has no
    /// `credentialStatus`, so nothing downstream would ever retract it.
    ///
    /// Asserted at the route's own gate rather than only in
    /// `credentials::ingress`, because the gap was this call site not doing
    /// the check, not the check being wrong.
    #[test]
    fn refuses_a_vrc_whose_validity_window_has_passed() {
        use chrono::Duration;
        use dtg_credentials::DTGCredential;

        use crate::test_support::dtg_json as body;

        let now = Utc::now();
        let expired = DTGCredential::new_vrc(
            "did:peer:2.zR1".into(),
            IssuerScope::Pairwise,
            "did:peer:2.zR2".into(),
            now - Duration::days(30),
            Some(now - Duration::days(1)),
        );
        let err = check_vrc_shape(&body(&expired), now)
            .expect_err("an expired VRC must not enter the graph");
        assert!(
            format!("{err:?}").contains("expired at"),
            "unexpected rejection: {err:?}"
        );

        // Same credential, evaluated while it was still in date: publishable.
        // Without this, a check that rejected everything would pass the test
        // above.
        check_vrc_shape(&body(&expired), now - Duration::days(2))
            .expect("the same VRC inside its window is publishable");
    }

    // ─── Half-edges vs complete edges ───────────────────────
    //
    // A DTG edge is two VRCs, one each way. These pin the rule that says which
    // is which, because getting it wrong is silent: the graph still renders, it
    // just tells the operator a unilateral claim is a mutual relationship.

    const A: &str = "did:key:zAlice";
    const B: &str = "did:key:zBob";
    const C: &str = "did:key:zCarol";

    /// A stored row whose body is minted by the same catalog constructor the
    /// publish path documents (`DTGCredential::new_vrc`) rather than
    /// hand-rolled JSON — a hand-rolled fixture agrees with the test that wrote
    /// it and with nothing that ships.
    fn row(issuer: &str, subject: &str, minute: u32) -> Relationship {
        use chrono::TimeZone;
        let valid_from = Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap();
        let vrc = dtg_credentials::DTGCredential::new_vrc(
            issuer.to_string(),
            IssuerScope::Public,
            subject.to_string(),
            valid_from,
            None,
        );
        let vrc_jsonld = serde_json::to_value(vrc.credential()).expect("VRC serialises");
        let vrc_digest_multibase =
            crate::credentials::ingress::digest_multibase(&vrc_jsonld).unwrap();
        Relationship {
            id: Uuid::new_v4(),
            issuer_did: issuer.into(),
            subject_did: subject.into(),
            vrc_jsonld,
            vrc_digest_multibase,
            created_at: Utc.with_ymd_and_hms(2026, 1, 1, 0, minute, 0).unwrap(),
            // These fixtures exercise the half/complete grouping, which is
            // independent of whether a persona was asserted. The persona
            // rendering has its own tests.
            persona: None,
            lifecycle: crate::relationships::LifecycleLog::default(),
        }
    }

    /// The instant the grouping tests resolve at: inside every `row`'s window
    /// and after every event they record. Fixed rather than `Utc::now()` so a
    /// test about grouping cannot start failing on a clock, and so the
    /// lifecycle tests below can name an instant on either side of an event.
    fn at(day: u32) -> chrono::DateTime<Utc> {
        use chrono::TimeZone;
        Utc.with_ymd_and_hms(2026, 2, day, 0, 0, 0).unwrap()
    }

    /// A member row with both halves of its membership pair, digest verified.
    fn member_row(did: &str, ack: Option<bool>) -> crate::members::Member {
        use chrono::TimeZone;
        let mut m = crate::members::Member::fresh(did);
        m.joined_at = Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap();

        let grant = dtg_credentials::DTGCredential::new_vmc(
            COMMUNITY.to_string(),
            did.to_string(),
            m.joined_at,
            None,
            false,
        )
        .with_id("urn:uuid:grant-1");
        let grant_json = crate::test_support::dtg_json(&grant);

        let role_vac = serde_json::json!({ "id": "urn:uuid:vac-1" });
        m.record_issued_credentials(grant_json.clone(), role_vac);

        if let Some(bound) = ack {
            // The grant's **wire** form: `DTGCommon` does not model `credentialStatus`, so
            // digesting a re-serialised parse would drop it and match nothing.
            // `new_member_vmc_for` takes the member independently of the grant
            // and refuses a grant that names somebody else.
            let ack = dtg_credentials::DTGCredential::new_member_vmc_for(
                &grant_json,
                did,
                IssuerScope::Directed,
                m.joined_at,
                None,
            )
            .expect("acknowledgement builds")
            .with_id("urn:uuid:ack-1");
            let ack_json = serde_json::to_value(ack.credential()).expect("ack serialises");
            m.record_member_vmc("urn:uuid:ack-1", ack_json, bound);
            m.member_vmc_received_at = Some(Utc.with_ymd_and_hms(2026, 1, 1, 0, 5, 0).unwrap());
        }

        m
    }

    const COMMUNITY: &str = "did:web:community.example";

    /// The membership pair is a DTG edge in exactly the way a VRC pair is —
    /// "in both cases, a bi-directional pair of credentials forms a complete
    /// DTG edge" — and the community is a node like any other. A graph that
    /// rendered only VRC pairs was showing half the trust graph.
    #[test]
    fn an_acknowledged_membership_is_one_complete_edge() {
        let member = member_row(A, Some(true));
        let g = build_graph(vec![], membership_halves(COMMUNITY, &member, at(1)), at(1));

        assert_eq!(g.edges.len(), 1, "grant + acknowledgement are ONE edge");
        assert_eq!(
            g.edges[0].endpoints,
            {
                let mut e = vec![COMMUNITY.to_string(), A.to_string()];
                e.sort();
                e
            },
            "endpoints are DID-sorted, as for any edge"
        );
        assert_eq!(g.edges[0].halves.len(), 2);
        assert!(g.edges[0].complete);
        assert_eq!(g.nodes.len(), 2, "the community is a node in its own graph");
    }

    /// A membership the member has not answered is the community's claim, not
    /// a relationship — the same reading a one-sided VRC gets.
    #[test]
    fn an_unacknowledged_membership_is_a_half_edge() {
        let member = member_row(A, None);
        let g = build_graph(vec![], membership_halves(COMMUNITY, &member, at(1)), at(1));

        assert_eq!(g.edges.len(), 1);
        assert_eq!(g.edges[0].halves.len(), 1);
        assert!(!g.edges[0].complete);
        assert_eq!(g.edges[0].halves[0].issuer_did, COMMUNITY);
    }

    /// The spec is explicit: an acknowledgement whose digest does not match a
    /// valid grant MUST NOT be treated as completing a membership edge. It is
    /// still *shown* — a published fact is not hidden because it is unbound —
    /// but it does not stand in for the member's consent.
    #[test]
    fn an_unbound_acknowledgement_does_not_complete_the_edge() {
        let member = member_row(A, Some(false));
        let g = build_graph(vec![], membership_halves(COMMUNITY, &member, at(1)), at(1));

        assert_eq!(g.edges.len(), 1);
        assert_eq!(
            g.edges[0].halves.len(),
            2,
            "both halves are listed; a stored credential is not hidden"
        );
        assert!(
            !g.edges[0].complete,
            "an unverified digest is not the member's consent to THIS membership"
        );
    }

    /// Membership and relationship edges share one graph and one `complete`
    /// rule. They must not merge into each other: a member's VRC to a peer and
    /// their VMC pair with the community are different edges.
    #[test]
    fn membership_and_relationship_edges_coexist() {
        let member = member_row(A, Some(true));
        let g = build_graph(
            vec![row(A, B, 0), row(B, A, 1)],
            membership_halves(COMMUNITY, &member, at(1)),
            at(1),
        );

        assert_eq!(g.edges.len(), 2, "A—B and A—community are separate edges");
        assert!(g.edges.iter().all(|e| e.complete));
        assert_eq!(g.nodes.len(), 3, "A, B, and the community");

        // An edge touching the community DID is the membership one. This is how
        // a consumer tells them apart without a schema change: the community
        // knows its own DID, and `relationships/graph/0.2` pins the response
        // shape with `additionalProperties: false`.
        let membership = g
            .edges
            .iter()
            .find(|e| e.endpoints.contains(&COMMUNITY.to_string()))
            .expect("the membership edge");
        assert_eq!(membership.halves.len(), 2);
    }

    /// An expired grant stops standing for a current membership, exactly as an
    /// expired VRC stops completing a relationship edge (#1079).
    #[test]
    fn an_expired_grant_does_not_complete_the_edge() {
        use chrono::TimeZone;
        let mut member = member_row(A, Some(true));

        // Re-issue the stored grant with a window that has already closed.
        if let Some(grant) = member.current_vmc.as_mut() {
            grant["validUntil"] = serde_json::Value::String(
                Utc.with_ymd_and_hms(2026, 1, 2, 0, 0, 0)
                    .unwrap()
                    .to_rfc3339(),
            );
        }

        let g = build_graph(vec![], membership_halves(COMMUNITY, &member, at(9)), at(9));
        assert_eq!(g.edges[0].halves.len(), 2, "both are still listed");
        assert!(!g.edges[0].complete);
    }

    /// Rows written before the service kept credential bodies still render a
    /// half — the id is enough to say the grant exists — and are honestly
    /// incomplete, because nothing verified the acknowledgement against it.
    #[test]
    fn a_pre_digest_row_renders_as_an_incomplete_edge() {
        let mut member = crate::members::Member::fresh(A);
        member.current_vmc_id = Some("urn:uuid:legacy-grant".into());
        member.member_vmc_id = Some("urn:uuid:legacy-ack".into());
        // `member_vmc_bound` defaults false: nothing checked a digest.

        let g = build_graph(vec![], membership_halves(COMMUNITY, &member, at(1)), at(1));
        assert_eq!(g.edges[0].halves.len(), 2);
        assert!(!g.edges[0].complete);
    }

    #[test]
    fn a_reciprocated_pair_is_one_complete_edge() {
        let g = build_graph(vec![row(A, B, 0), row(B, A, 1)], vec![], at(1));
        assert_eq!(g.edges.len(), 1, "two VRCs one each way are ONE edge");
        assert_eq!(g.edges[0].endpoints, vec![A.to_string(), B.to_string()]);
        assert_eq!(g.edges[0].halves.len(), 2);
        assert!(g.edges[0].complete);
        assert_eq!(g.nodes.len(), 2);
    }

    #[test]
    fn an_unreciprocated_vrc_is_a_half_edge() {
        let g = build_graph(vec![row(A, B, 0)], vec![], at(1));
        assert_eq!(g.edges.len(), 1);
        assert_eq!(g.edges[0].halves.len(), 1);
        assert!(
            !g.edges[0].complete,
            "B has never acknowledged this edge, so it is not complete"
        );
        // The subject still appears — the graph shows who was named, it just no
        // longer implies they agreed.
        assert_eq!(g.nodes.len(), 2);
    }

    /// The trap this whole change exists to close: several VRCs between two
    /// parties are not evidence of reciprocity if they all point one way.
    #[test]
    fn repeated_vrcs_in_one_direction_do_not_complete_an_edge() {
        let g = build_graph(
            vec![row(A, B, 0), row(A, B, 1), row(A, B, 2)],
            vec![],
            at(1),
        );
        assert_eq!(g.edges.len(), 1);
        assert_eq!(g.edges[0].halves.len(), 3);
        assert!(!g.edges[0].complete);
    }

    /// `endpoints` is DID-sorted, so the pair has one identity whichever half
    /// arrived first — otherwise the same relationship would appear as two
    /// edges depending on publish order.
    #[test]
    fn pair_identity_does_not_depend_on_publish_order() {
        let forward = build_graph(vec![row(A, B, 0), row(B, A, 1)], vec![], at(1));
        let reverse = build_graph(vec![row(B, A, 0), row(A, B, 1)], vec![], at(1));
        assert_eq!(forward.edges[0].endpoints, reverse.edges[0].endpoints);
        assert!(forward.edges[0].complete && reverse.edges[0].complete);
    }

    /// A VRC a party issued to themselves has no counterparty who could
    /// reciprocate. Both directions are the same direction, so the naive
    /// "a VRC each way" test would report it complete.
    #[test]
    fn a_self_issued_vrc_is_never_complete() {
        let g = build_graph(vec![row(A, A, 0)], vec![], at(1));
        assert_eq!(g.edges.len(), 1);
        assert_eq!(g.edges[0].endpoints, vec![A.to_string(), A.to_string()]);
        assert!(!g.edges[0].complete);
    }

    #[test]
    fn distinct_pairs_stay_distinct_and_ordering_is_stable() {
        let rows = vec![row(B, C, 2), row(A, B, 0), row(B, A, 1)];
        let g = build_graph(rows, vec![], at(1));
        assert_eq!(g.edges.len(), 2);
        // BTreeMap keyed on the sorted pair: (A,B) before (B,C).
        assert_eq!(g.edges[0].endpoints, vec![A.to_string(), B.to_string()]);
        assert_eq!(g.edges[1].endpoints, vec![B.to_string(), C.to_string()]);
        assert!(g.edges[0].complete);
        assert!(!g.edges[1].complete);
        // Halves are oldest-first regardless of the order rows came back in.
        assert_eq!(g.edges[0].halves[0].issuer_did, A);
        assert_eq!(g.edges[0].halves[1].issuer_did, B);
    }

    // ─── Precedence in the graph read (#1079) ───────────────
    //
    // Until this, the graph was read back without re-checking anything on the
    // reasoning that each edge had been validated at ingress. True, and
    // insufficient: it says nothing about the months since, and for a VRC
    // with no `validUntil` it says nothing at all. These pin the two ways an
    // edge can stop counting — its own window closing, and this community
    // recording something against it — as producing the same answer.

    /// A row whose VRC states an upper bound, so the window can be crossed
    /// inside a test.
    fn row_expiring(issuer: &str, subject: &str, minute: u32, until_day: u32) -> Relationship {
        use chrono::TimeZone;
        let mut rel = row(issuer, subject, minute);
        let until = Utc.with_ymd_and_hms(2026, 2, until_day, 0, 0, 0).unwrap();
        rel.vrc_jsonld["validUntil"] = json!(until.to_rfc3339());
        rel
    }

    /// The symptom #1079 names: "a half-edge whose reciprocal has expired is
    /// indistinguishable from one that never arrived". It is distinguishable
    /// now — the pair stops being complete the instant the reciprocal lapses,
    /// with no event recorded and nothing deleted.
    #[test]
    fn an_expired_reciprocal_no_longer_completes_an_edge() {
        let rows = || vec![row(A, B, 0), row_expiring(B, A, 1, 10)];

        let live = build_graph(rows(), vec![], at(9));
        assert!(
            live.edges[0].complete,
            "both halves in date: this is a mutual relationship"
        );

        let lapsed = build_graph(rows(), vec![], at(11));
        assert!(
            !lapsed.edges[0].complete,
            "B's half has expired, so B no longer consents to anything"
        );
        assert_eq!(
            lapsed.edges[0].halves.len(),
            2,
            "the expired half is still shown — it was published, and hiding it \
             would make a lapsed edge look like one that never existed"
        );
    }

    /// The other half of the precedence rule: a later recorded event beats a
    /// still-valid credential. Nothing about B's VRC has changed — its
    /// signature verifies and its window is open — and the edge is no longer
    /// complete.
    #[test]
    fn a_suspended_half_does_not_complete_an_edge() {
        let mut suspended = row(B, A, 1);
        suspended
            .lifecycle
            .record(
                crate::relationships::LifecycleEventKind::Suspended { reason: None },
                at(5),
            )
            .expect("first event on a fresh log");

        assert!(
            !build_graph(vec![row(A, B, 0), suspended.clone()], vec![], at(6)).edges[0].complete,
            "a suspended half is not consent"
        );
        // And it was genuinely the event doing the work: an instant before it
        // was recorded, the same rows read as complete.
        assert!(
            build_graph(vec![row(A, B, 0), suspended], vec![], at(4)).edges[0].complete,
            "the suspension must not apply before it was recorded"
        );
    }

    /// Restoration puts the edge back, which is the difference between
    /// suspension and revocation actually meaning something.
    #[test]
    fn a_restored_half_completes_the_edge_again() {
        let mut half = row(B, A, 1);
        let kinds = crate::relationships::LifecycleEventKind::Suspended { reason: None };
        half.lifecycle.record(kinds, at(5)).unwrap();
        half.lifecycle
            .record(
                crate::relationships::LifecycleEventKind::Restored { reason: None },
                at(7),
            )
            .unwrap();

        assert!(!build_graph(vec![row(A, B, 0), half.clone()], vec![], at(6)).edges[0].complete);
        assert!(build_graph(vec![row(A, B, 0), half], vec![], at(8)).edges[0].complete);
    }

    /// A superseded half is displaced, not deleted — and the replacement is
    /// what carries the pair. Without this, a re-issued edge would read as two
    /// live claims in the same direction.
    #[test]
    fn a_superseded_half_is_displaced_by_its_replacement() {
        let mut old_half = row(A, B, 0);
        old_half
            .lifecycle
            .record(
                crate::relationships::LifecycleEventKind::Superseded {
                    by: "zReplacement".into(),
                },
                at(5),
            )
            .unwrap();
        let replacement = row(A, B, 2);

        let g = build_graph(
            vec![old_half.clone(), replacement, row(B, A, 1)],
            vec![],
            at(6),
        );
        assert_eq!(g.edges[0].halves.len(), 3);
        assert!(g.edges[0].complete, "the replacement carries A's direction");

        // Remove the replacement and the pair is no longer complete: the
        // displaced half cannot stand in for it.
        let without = build_graph(vec![old_half, row(B, A, 1)], vec![], at(6));
        assert!(!without.edges[0].complete);
    }

    /// A stored VRC whose window will not parse resolves to
    /// `Indeterminate`, which is not in force. Rows written before #1075
    /// entered the graph without their window ever being read, so this is
    /// reachable — and treating an unreadable bound as "no bound stated" is
    /// the failure mode that makes the whole check ornamental.
    #[test]
    fn an_unreadable_window_is_not_in_force() {
        let mut broken = row(B, A, 1);
        broken.vrc_jsonld["validUntil"] = json!("whenever");
        assert!(matches!(
            broken.in_force_at(at(1)),
            crate::relationships::InForce::Indeterminate { .. }
        ));
        assert!(!build_graph(vec![row(A, B, 0), broken], vec![], at(1)).edges[0].complete);
    }
}