openvtc-core 0.3.1

OpenVTC Core Library
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
//! Routing an inbound message to the applicant or the vetter side.
//!
//! [`handle`] claims the messages that belong to vetting and returns `None` for
//! everything else, so the caller's existing routing is untouched. Two message
//! types are shared, and those are claimed only when they are vetting's:
//!
//! - `credential-exchange/issue` carries a community's membership and role
//!   credentials, a community's vetter grant, and a vetter's statement. Only
//!   the last two are claimed: a vetter grant, which would otherwise take the
//!   member's role credential's place, and a vetter's identity-vetting
//!   statement ([`wire::delivered_statement`]). Everything else — a `vetted/1`
//!   statement the community issued for itself among it — still reaches the
//!   join handler.
//! - `trust-task-error` answers any Trust Task. Only one threaded on a request
//!   or withdrawal of ours is claimed.
//!
//! Handling never sends. A reply comes back unsigned in [`Handled::reply`] for
//! the caller to sign as the named persona and send ([`wire::sign_and_send`]);
//! anything a person should see comes back as a [`Notice`]. An answer to a
//! question we put to a community — a directory page, a stored profile, a
//! resent grant — comes back as a [`CommunityAnswer`] for whoever is waiting.
//! A vetter's grant to check for revocation comes back as a [`GrantCheck`],
//! because the check fetches over HTTPS and the caller owns the network.

use std::sync::Arc;

use affinidi_tdk::didcomm::Message;
use chrono::{DateTime, Utc};
use serde::de::DeserializeOwned;
use serde_json::Value;
use tracing::{debug, info, warn};
use trust_tasks_rs::TrustTask;
use vta_sdk::protocols::PROBLEM_REPORT_TYPE;
use vta_sdk::protocols::credential_exchange::ISSUE as CREDENTIAL_ISSUE_TYPE;
use vta_sdk::protocols::vetting::{
    VETTER_ROLE, VETTING_DECLINE_TYPE, VETTING_REQUEST_RESPONSE_TYPE, VETTING_REQUEST_TYPE,
    VETTING_REVOKE_STATEMENT_RESPONSE_TYPE, VETTING_SESSION_RESPONSE_TYPE, VETTING_SESSION_TYPE,
    VETTING_VETTER_LIST_RESPONSE_TYPE, VETTING_VETTER_PROFILE_RESPONSE_TYPE,
    VETTING_VETTER_RESEND_RESPONSE_TYPE, decline, request, revoke_statement, role_matches, session,
    vetters,
};
use vta_sdk::trust_task_proof::TrustTaskVmResolver;
use vta_sdk::vetting::eligibility::{
    EligibilityExpectations, community_roles, verify_eligibility_vp,
};

use super::applicant::{GrantStatus, VetterEligibility};
use super::book::{VetterGrant, VettingBook};
use super::queries::{CommunityAnswer, CommunityQuery, QueryKind, refusal_words};
use super::status::GrantCheck;
use super::vetter::{IncomingRequest, Intake};
use super::wire;
use crate::config::account::{Account, PersonaId};
use crate::messaging::is_trust_task_error_type;
use crate::tasks::TaskType;

/// What handling needs to know about us.
pub struct Context<'a> {
    /// Our memberships — a vetter must be an active member.
    pub account: &'a Account,
    /// Resolves the DIDs whose proofs are checked.
    pub resolver: &'a TrustTaskVmResolver,
    /// Resolves a community's DID document, for the proofs whose key must be
    /// listed under a particular relationship (a community's replies and the
    /// vetter role credential it issues).
    pub did_resolver: &'a affinidi_did_resolver_cache_sdk::DIDCacheClient,
    /// A credential-issue's credential, already verified off the dispatch loop
    /// ([`crate::issued_credential::verify_issued_credential`]) — the vetter
    /// grant is taken from this rather than verified again inline. `None`
    /// means it was not checked, and a grant is then refused.
    pub issued_credential: Option<
        &'a Result<
            crate::issued_credential::VerifiedIssuedCredential,
            crate::issued_credential::IssuedCredentialError,
        >,
    >,
    /// A community answer's check ([`crate::operational::verify_operational`]),
    /// already run off the dispatch loop. `Some` is taken as the answer's
    /// verification (a failed or missing check refuses it); `None` means the
    /// caller did not run one, and it is verified here, inline. The TUI's
    /// dispatch always passes `Some`, so no resolve happens on its loop.
    pub community_answer: Option<
        &'a Result<crate::operational::VerifiedOperational, crate::operational::OperationalError>,
    >,
    /// Our persona the message was addressed to, and its DID.
    pub recipient: Option<(PersonaId, &'a str)>,
    /// The clock.
    pub now: DateTime<Utc>,
}

/// The result of handling one message.
#[derive(Debug, Default)]
pub struct Handled {
    /// The book changed and wants saving.
    pub changed: bool,
    /// A reply to sign and send.
    pub reply: Option<Reply>,
    /// Something a person should see.
    pub notice: Option<Notice>,
    /// An answer to a question we put to a community.
    pub answer: Option<CommunityAnswer>,
    /// A vetter's grant to check for revocation, off the handler.
    pub grant_check: Option<GrantCheck>,
}

/// A reply to sign as `persona` and send to the document's recipient.
#[derive(Debug)]
pub struct Reply {
    /// The persona to sign as.
    pub persona: PersonaId,
    /// The unsigned document.
    pub document: TrustTask<Value>,
    /// A presentation to attach as `eligibilityVp` before signing
    /// ([`wire::send_reply`]).
    pub eligibility: Option<EligibilityPresentation>,
}

/// The vetter role credential to present with an acceptance, bound to the
/// request it answers (`vetting/request/0.1` rule 5).
#[derive(Debug, Clone)]
pub struct EligibilityPresentation {
    /// The community's role credentials.
    pub credentials: Vec<Value>,
    /// The `id` of the request being answered.
    pub nonce: String,
    /// The applicant's `joinDid`.
    pub domain: String,
}

/// Something that happened that a person should know about. The ones marked
/// *act* need them to do something.
#[derive(Debug, Clone, PartialEq)]
pub enum Notice {
    /// Vetter: someone redeemed a ticket. *Act:* open a session when together.
    RequestAccepted {
        /// Our handle.
        request_id: String,
        /// Their join DID.
        applicant: String,
        /// The community.
        community: String,
    },
    /// Applicant: a vetter took our request.
    VetterAccepted {
        /// The application.
        application_id: String,
        /// The vetter.
        vetter: String,
        /// Their presentation showed the community named them a vetter.
        shown_eligible: bool,
    },
    /// Vetter: a request reached us and was turned away. Informational — the
    /// applicant was answered, and there is nothing at this desk to act on.
    RequestRefused {
        /// Their join DID.
        applicant: String,
        /// The error code sent back.
        code: String,
    },
    /// Vetter: a community named us a vetter.
    VetterGranted {
        /// The community.
        community: String,
        /// Until when.
        valid_until: Option<DateTime<Utc>>,
    },
    /// Applicant: a vetter refused our request.
    VetterRefused {
        /// The application.
        application_id: String,
        /// The vetter.
        vetter: String,
        /// The error code.
        code: String,
    },
    /// Applicant: a vetter opened a session. *Act:* confirm the code, send the card.
    SessionOpened {
        /// The application.
        application_id: String,
        /// The session.
        session_id: String,
        /// The vetter.
        vetter: String,
        /// The code to read aloud.
        match_code: String,
    },
    /// Vetter: a card arrived and verified. *Act:* check the person, attest or decline.
    CardReceived {
        /// Our handle.
        request_id: String,
        /// Their join DID.
        applicant: String,
    },
    /// Applicant: a statement arrived and verified.
    StatementReceived {
        /// The application.
        application_id: String,
        /// The statement.
        statement_id: String,
        /// The vetter.
        vetter: String,
    },
    /// Applicant: a vetter declined.
    Declined {
        /// The application.
        application_id: String,
        /// The vetter.
        vetter: String,
    },
    /// Applicant: the community's requirements are now known, or changed.
    RequirementsUpdated {
        /// The application.
        application_id: String,
        /// The community.
        community: String,
    },
    /// Applicant: the community requires something this build cannot honour, so the
    /// application stops here rather than gathering evidence the community will not accept
    /// ([`super::hidden`]).
    RequirementsUnsupported {
        /// The application.
        application_id: String,
        /// The community.
        community: String,
        /// What it asked for, in the applicant's words.
        detail: String,
    },
    /// Vetter: the community issued our class credential for a label.
    HiddenVetterEnrolled {
        /// The community.
        community: String,
        /// The label it issued under.
        label: String,
    },
    /// Vetter: a tick of the drip was served.
    HiddenTokensDrawn {
        /// The community.
        community: String,
        /// How many tokens it added.
        taken: usize,
    },
    /// Vetter: where our event-mode request stands.
    ///
    /// Sent on every answer, including the ones that change nothing, because the two reasons a
    /// request waits — nobody has approved it, not enough people have asked — look identical
    /// from the outside and only the counts tell them apart.
    HiddenEventMode {
        /// The community.
        community: String,
        /// The event, as the community names it.
        event_id: String,
        /// Whether the label is live for us yet.
        approved: bool,
        /// How many vetters have asked, including us.
        group_size: usize,
        /// How many this community needs.
        group_floor: usize,
    },
    /// Applicant: the community issued the challenge this submission must bind.
    ChallengeIssued {
        /// The application.
        application_id: String,
        /// When the challenge stops being accepted.
        expires_at: DateTime<Utc>,
    },
    /// Vetter or applicant: the community refused a hidden-vetting request.
    HiddenVettingRefused {
        /// The community.
        community: String,
        /// What was asked for, from [`super::queries::QueryKind::describe`].
        what: &'static str,
        /// Its declared code.
        code: String,
    },
    /// Applicant: a vetter's hidden attestation arrived and verified.
    ///
    /// It names no vetter, deliberately — the applicant knows who it sat with, and nothing
    /// in the notice or the store repeats it.
    AttestationReceived {
        /// The application.
        application_id: String,
        /// How many attestations this application now holds.
        held: usize,
    },
    /// Vetter: the community recorded our withdrawal.
    WithdrawalRecorded {
        /// The statement.
        statement_id: String,
    },
    /// Vetter: the community refused our withdrawal.
    WithdrawalRefused {
        /// The statement.
        statement_id: String,
        /// The error code.
        code: String,
    },
    /// Vetter: the community stored our vetter profile.
    ProfilePublished {
        /// The community.
        community: String,
        /// Whether it lists us in its directory.
        listed: bool,
    },
    /// Vetter: the community refused our vetter profile.
    ProfileRefused {
        /// The community.
        community: String,
        /// The error code, e.g. `notEligible`.
        code: String,
    },
    /// Vetter: the community is delivering our grant credential again.
    GrantResent {
        /// The community.
        community: String,
        /// The credential's `validUntil`.
        valid_until: DateTime<Utc>,
    },
    /// Vetter: the community refused to resend our grant credential.
    ResendRefused {
        /// The community.
        community: String,
        /// The error code, e.g. `notGranted`.
        code: String,
    },
}

impl Notice {
    /// One line for the activity log.
    #[must_use]
    pub fn describe(&self) -> String {
        match self {
            Notice::RequestAccepted { applicant, .. } => {
                format!(
                    "Vetting request from {applicant} accepted — open a session when you are together."
                )
            }
            Notice::VetterAccepted {
                vetter,
                shown_eligible: true,
                ..
            } => format!("{vetter} accepted your vetting request."),
            Notice::VetterAccepted { vetter, .. } => format!(
                "{vetter} accepted your vetting request, but did not show that the community \
                 named them a vetter — their statement may not count."
            ),
            Notice::VetterGranted {
                community,
                valid_until,
            } => match valid_until {
                Some(until) => format!(
                    "{community} named you a vetter until {}. You can hand out tickets.",
                    until.format("%Y-%m-%d")
                ),
                None => format!("{community} named you a vetter."),
            },
            Notice::RequestRefused { applicant, code } => format!(
                "Vetting request from {applicant} refused [{code}] — {}",
                super::queries::request_refusal_words(code)
            ),
            Notice::VetterRefused { vetter, code, .. } => format!(
                "{vetter} refused your vetting request [{code}] — {}",
                super::queries::request_refusal_words(code)
            ),
            Notice::SessionOpened {
                vetter, match_code, ..
            } => format!(
                "{vetter} opened a vetting session. Read the code {match_code} to each other, then send your card."
            ),
            Notice::CardReceived { applicant, .. } => {
                format!(
                    "Vetting card from {applicant} verified — check the person, then attest or decline."
                )
            }
            Notice::StatementReceived { vetter, .. } => {
                format!("{vetter} signed a vetting statement for you.")
            }
            Notice::Declined { vetter, .. } => format!("{vetter} declined to vet you."),
            Notice::RequirementsUpdated { community, .. } => {
                format!("Vetting requirements for {community} updated.")
            }
            Notice::RequirementsUnsupported { detail, .. } => detail.clone(),
            Notice::HiddenVetterEnrolled { community, label } => format!(
                "{community} enrolled you under {label}. Your attestations will name nobody."
            ),
            Notice::HiddenTokensDrawn { taken, .. } => format!(
                "Drew {taken} attestation token{}.",
                if *taken == 1 { "" } else { "s" }
            ),
            Notice::HiddenEventMode {
                event_id,
                approved: true,
                ..
            } => format!("You are in {event_id}. Your tokens there draw at the event's rate."),
            Notice::HiddenEventMode {
                event_id,
                group_size,
                group_floor,
                ..
            } => format!(
                "Asked to vet at {event_id}. {group_size} of {group_floor} vetters so far, and \
                 it still needs an approver."
            ),
            Notice::ChallengeIssued { expires_at, .. } => format!(
                "The community issued your submission challenge; it stands until {}.",
                expires_at.format("%H:%M")
            ),
            Notice::HiddenVettingRefused {
                community,
                what,
                code,
            } => format!("{community} refused {what} ({code})."),
            Notice::AttestationReceived { held, .. } => format!(
                "An attestation arrived and verified. You now hold {held} for this application."
            ),
            Notice::WithdrawalRecorded { statement_id } => {
                format!("The community recorded the withdrawal of statement {statement_id}.")
            }
            Notice::WithdrawalRefused { statement_id, code } => format!(
                "The community refused the withdrawal of statement {statement_id} [{code}]."
            ),
            Notice::ProfilePublished {
                community,
                listed: true,
            } => format!(
                "{community} published your vetter profile — applicants can find you in its \
                 directory."
            ),
            Notice::ProfilePublished { community, .. } => format!(
                "{community} stored your vetter profile. It is not listed, so only people you \
                 give a ticket to can reach you."
            ),
            Notice::ProfileRefused { community, code } => {
                refusal_words(QueryKind::VetterProfile, community, code)
            }
            Notice::GrantResent {
                community,
                valid_until,
            } => format!(
                "{community} is sending your vetter credential again (valid until {}).",
                valid_until.format("%Y-%m-%d")
            ),
            Notice::ResendRefused { community, code } => {
                refusal_words(QueryKind::VetterResend, community, code)
            }
        }
    }
}

impl Notice {
    /// The inbox task this notice raises, keyed by a stable id so a repeated
    /// message does not raise a second one. `None` for notices that only inform.
    #[must_use]
    pub fn task(&self) -> Option<(String, TaskType)> {
        match self {
            Notice::RequestAccepted {
                request_id,
                applicant,
                community,
            } => Some((
                format!("vetting-request-{request_id}"),
                TaskType::VettingRequestInbound {
                    request_id: request_id.clone(),
                    applicant: Arc::new(applicant.clone()),
                    community: community.clone(),
                },
            )),
            Notice::SessionOpened {
                application_id,
                session_id,
                vetter,
                ..
            } => Some((
                format!("vetting-session-{session_id}"),
                TaskType::VettingSessionInbound {
                    application_id: application_id.clone(),
                    session_id: session_id.clone(),
                    vetter: Arc::new(vetter.clone()),
                },
            )),
            Notice::CardReceived {
                request_id,
                applicant,
            } => Some((
                format!("vetting-card-{request_id}"),
                TaskType::VettingCardReceived {
                    request_id: request_id.clone(),
                    applicant: Arc::new(applicant.clone()),
                },
            )),
            _ => None,
        }
    }
}

/// Whether [`handle`] could claim a message of type `typ`. A cheap pre-check,
/// so a caller builds a DID resolver only for messages that may need one.
#[must_use]
pub fn may_claim(typ: &str) -> bool {
    typ.starts_with("https://trusttasks.org/spec/vetting/")
        || matches!(
            typ,
            VETTING_REVOKE_STATEMENT_RESPONSE_TYPE
                | VETTING_VETTER_LIST_RESPONSE_TYPE
                | VETTING_VETTER_PROFILE_RESPONSE_TYPE
                | VETTING_VETTER_RESEND_RESPONSE_TYPE
                | CREDENTIAL_ISSUE_TYPE
                | PROBLEM_REPORT_TYPE
        )
        || super::protocol::JoinProtocol::from_manifest_response(typ).is_some()
        || is_trust_task_error_type(typ)
}

/// Handle `message` from the authenticated `sender` if it is vetting's.
///
/// `seen` holds the ids of operational documents already acted on: a
/// community's answer is taken once ([`crate::operational`]).
pub async fn handle(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    seen: &mut crate::operational::SeenDocuments,
    message: &Message,
    sender: &str,
) -> Option<Handled> {
    // A community's answer is acted on only when the community signed it: the
    // transport sender is a routing hint, not proof of who wrote the reply.
    // Its id is checked against the replay set before acting, and recorded
    // only after — and only if the answer matched something of ours, so an
    // answer nobody asked for writes nothing.
    let pending = if is_community_answer_type(&message.typ) {
        match community_signed(ctx, seen, message, sender).await {
            Ok(verified) => Some(verified),
            Err(e) => {
                warn!(typ = %message.typ, reason = %e, "community answer refused");
                return Some(Handled::default());
            }
        }
    } else {
        None
    };
    let handled = match message.typ.as_str() {
        VETTING_REQUEST_TYPE => take_request(book, ctx, message, sender).await,
        VETTING_REQUEST_RESPONSE_TYPE => accepted(book, ctx, message, sender).await,
        VETTING_SESSION_TYPE => session(book, ctx, message, sender).await,
        VETTING_SESSION_RESPONSE_TYPE => card(book, ctx, message, sender).await,
        VETTING_DECLINE_TYPE => declined(book, ctx, message, sender).await,
        VETTING_REVOKE_STATEMENT_RESPONSE_TYPE => withdrawal_recorded(book, message, sender),
        VETTING_VETTER_LIST_RESPONSE_TYPE => vetter_list(book, message, sender),
        VETTING_VETTER_PROFILE_RESPONSE_TYPE => profile_stored(book, message, sender),
        VETTING_VETTER_RESEND_RESPONSE_TYPE => resent(book, message, sender),
        t if super::protocol::JoinProtocol::from_manifest_response(t).is_some() => {
            manifest(book, ctx, message, sender)
        }
        CREDENTIAL_ISSUE_TYPE => return statement(book, ctx, message, sender).await,
        wire::HIDDEN_ATTESTATION_TYPE => return attestation(book, ctx, message, sender),
        t if t == wire::pcs::response_of(wire::pcs::ROOT_TYPE) => {
            enrolled(book, ctx, message, sender)
        }
        t if t == wire::pcs::response_of(wire::pcs::TOKENS_TYPE) => {
            tokens_served(book, ctx, message, sender)
        }
        t if t == wire::pcs::response_of(wire::pcs::EVENT_MODE_TYPE) => {
            event_mode_answered(book, ctx, message, sender)
        }
        t if t == wire::pcs::response_of(wire::pcs::CHALLENGE_TYPE) => {
            challenge_issued(book, message, sender)
        }
        t if is_trust_task_error_type(t) => return refused(book, ctx, message, sender),
        PROBLEM_REPORT_TYPE => return problem_reported(book, ctx, message, sender),
        _ => return None,
    };
    if let Some(verified) = pending
        && (handled.changed || handled.answer.is_some() || handled.notice.is_some())
        && let Err(e) = verified.commit(seen, ctx.now)
    {
        warn!(reason = %e, "community answer acted on but not recorded");
    }
    Some(handled)
}

async fn opened<P: DeserializeOwned>(
    message: &Message,
    sender: &str,
    resolver: &TrustTaskVmResolver,
) -> Option<wire::Opened<P>> {
    match wire::open(message, sender, resolver).await {
        Ok(opened) => Some(opened),
        Err(e) => {
            warn!(typ = %message.typ, %sender, error = %e, "vetting document refused");
            None
        }
    }
}

/// The community answers — success responses the community signs — that are
/// acted on only once their proof verifies, as the community's operational
/// document ([`crate::operational`]).
pub fn is_community_answer_type(typ: &str) -> bool {
    matches!(
        typ,
        VETTING_REVOKE_STATEMENT_RESPONSE_TYPE
            | VETTING_VETTER_LIST_RESPONSE_TYPE
            | VETTING_VETTER_PROFILE_RESPONSE_TYPE
            | VETTING_VETTER_RESEND_RESPONSE_TYPE
    ) || super::protocol::JoinProtocol::from_manifest_response(typ).is_some()
}

/// Check a community's answer is its signed operational document: issued by
/// the community it came from, signed with its `authentication` key
/// (VTI-KEY-106), addressed to the persona it arrived for, fresh, and not seen
/// before (VTI-KEY-107).
async fn community_signed(
    ctx: &Context<'_>,
    seen: &crate::operational::SeenDocuments,
    message: &Message,
    sender: &str,
) -> Result<crate::operational::VerifiedOperational, String> {
    let Some((_, our_did)) = ctx.recipient else {
        return Err("it arrived for no persona of ours".to_string());
    };
    if let Some(checked) = ctx.community_answer {
        let verified = checked.clone().map_err(|e| e.to_string())?;
        // Checked against every persona of ours; it must be for this one.
        if verified.recipient() != our_did {
            return Err("it is addressed to another persona".to_string());
        }
        verified.check(seen, ctx.now).map_err(|e| e.to_string())?;
        return Ok(verified);
    }
    let verified = crate::operational::verify_operational(
        &message.body,
        sender,
        &[our_did],
        &message.typ,
        ctx.did_resolver,
        seen,
        ctx.now,
    )
    .await
    .map_err(|e| e.to_string())?;
    // Refuse a replay, or a community over its quota, before acting.
    verified.check(seen, ctx.now).map_err(|e| e.to_string())?;
    Ok(verified)
}

/// The thread a community's reply names: the envelope's, or the document's.
fn community_thread(message: &Message) -> Option<String> {
    message.thid.clone().or_else(|| {
        message
            .body
            .get("threadId")
            .and_then(Value::as_str)
            .map(str::to_string)
    })
}

/// A community reply's payload. Read only after [`community_signed`] has
/// checked the reply's proof (see [`handle`]).
fn community_payload<P: DeserializeOwned>(message: &Message) -> Result<P, String> {
    let payload = message.body.get("payload").cloned().unwrap_or(Value::Null);
    serde_json::from_value(payload).map_err(|e| e.to_string())
}

/// A document from a community, whose proof [`handle`] has already checked.
fn community_reply<P: DeserializeOwned>(message: &Message) -> Option<(Option<String>, P)> {
    match community_payload(message) {
        Ok(p) => Some((community_thread(message), p)),
        Err(e) => {
            warn!(typ = %message.typ, error = %e, "malformed community reply");
            None
        }
    }
}

/// A community's answer to a question of ours of `kind`, with the question.
///
/// `None` when it answers nothing we asked. A payload this client cannot read,
/// for a question we did ask, becomes [`CommunityAnswer::Unreadable`]. The
/// person waiting then hears that the community and this client disagree,
/// rather than waiting out the timeout and being told nobody answered.
fn answer_to<P: DeserializeOwned>(
    book: &mut VettingBook,
    message: &Message,
    sender: &str,
    kind: QueryKind,
) -> Option<(CommunityQuery, Result<P, CommunityAnswer>)> {
    let Some(thread) = community_thread(message) else {
        debug!(typ = %message.typ, %sender, "community answer with no thread — ignored");
        return None;
    };
    let Some(query) = book.take_query(sender, &thread, Some(kind)) else {
        debug!(typ = %message.typ, %sender, "community answer to nothing we asked — ignored");
        return None;
    };
    let payload = community_payload::<P>(message).map_err(|detail| {
        warn!(typ = %message.typ, %sender, error = %detail, "unreadable community answer");
        CommunityAnswer::Unreadable {
            query: query.document_id.clone(),
            community: sender.to_string(),
            kind,
            detail,
        }
    });
    Some((query, payload))
}

async fn take_request(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    message: &Message,
    sender: &str,
) -> Handled {
    let Some((persona, _)) = ctx.recipient else {
        return Handled::default();
    };
    let Some(opened) = opened::<request::v0_1::Payload>(message, sender, ctx.resolver).await else {
        return Handled::default();
    };
    let community = opened.payload.community.as_str().to_string();
    // A vetter is who the community named: an active member holding its live
    // role credential (design §10.3). The community checks again.
    let grant = book.vetter_grant(&community, persona, ctx.now).cloned();
    let eligible = grant.is_some()
        && ctx
            .account
            .membership(&community, persona)
            .is_some_and(|m| m.status.is_active());
    let throttle = book.throttle.clone();
    let intake = book.take_request(
        IncomingRequest {
            document_id: &opened.document.id,
            sender,
            persona,
            body: opened.payload,
            eligible,
        },
        ctx.now,
    );
    let throttled = book.throttle != throttle;
    match intake {
        Intake::Accepted(body) => {
            let request_id = body.request_id.as_str().to_string();
            let eligibility = grant.map(|g| EligibilityPresentation {
                credentials: vec![g.credential],
                nonce: opened.document.id.clone(),
                domain: sender.to_string(),
            });
            Handled {
                changed: true,
                reply: wire::response(&opened.document, &body)
                    .ok()
                    .map(|document| Reply {
                        persona,
                        document,
                        eligibility,
                    }),
                notice: Some(Notice::RequestAccepted {
                    request_id,
                    applicant: sender.to_string(),
                    community,
                }),
                ..Handled::default()
            }
        }
        Intake::Refused(code) => {
            info!(%sender, %code, "vetting request refused");
            Handled {
                changed: throttled,
                reply: wire::refusal(&opened.document, code, None)
                    .ok()
                    .map(|document| Reply {
                        persona,
                        document,
                        eligibility: None,
                    }),
                // A refusal used to leave nothing behind at all, so a vetter
                // whose applicant was turned away saw an empty desk and had no
                // way to find out why — the one end that can fix a stale
                // ticket learned nothing. Only refusals are noticed, never the
                // silent branch: that one exists so a guesser cannot discover
                // the vetter, and a log line they could provoke would hand
                // them the same discovery from the other side.
                notice: Some(Notice::RequestRefused {
                    applicant: sender.to_string(),
                    code: code.to_string(),
                }),
                ..Handled::default()
            }
        }
        Intake::Silent => {
            debug!(%sender, "vetting request without a matching ticket — no answer");
            Handled {
                changed: throttled,
                ..Handled::default()
            }
        }
    }
}

async fn accepted(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    message: &Message,
    sender: &str,
) -> Handled {
    let Some(opened) = opened::<request::v0_1::Response>(message, sender, ctx.resolver).await
    else {
        return Handled::default();
    };
    let Some(thread) = opened.document.thread_id.as_deref() else {
        return Handled::default();
    };
    let Some(application) = book.applications.iter_mut().find(|a| a.sent(thread)) else {
        warn!(%sender, "vetting acceptance for no request of ours");
        return Handled::default();
    };
    // Bound to our request by `nonce` and to us by `domain`, so a presentation
    // made for someone else, or before the vetter lost the role, does not pass.
    // A verified grant's `credentialStatus` is kept for the revocation check.
    let mut grant_status_entry: Option<Option<Value>> = None;
    // The presentation is verified **as received** rather than re-serialised
    // from the parsed response: it carries its own proof, and a parsed value
    // written back out is not guaranteed to be the same bytes.
    let presented = opened.document.payload.get("eligibilityVp");
    let eligibility = match presented {
        None => VetterEligibility::NotShown,
        Some(vp) => {
            let expect = EligibilityExpectations {
                vetter: sender,
                community: &application.community,
                role: application.vetter_role(),
                challenge: thread,
                domain: &application.join_did,
                now: ctx.now,
            };
            match verify_eligibility_vp(vp, &expect, ctx.resolver).await {
                Ok(verified) => {
                    grant_status_entry = Some(verified.credential_status().cloned());
                    VetterEligibility::Shown {
                        credential_id: verified.credential_id().map(str::to_string),
                        valid_until: verified.valid_until(),
                    }
                }
                Err(e) => {
                    warn!(%sender, error = %e, "vetter eligibility presentation did not verify");
                    VetterEligibility::Failed {
                        reason: e.to_string(),
                    }
                }
            }
        }
    };
    let shown_eligible = matches!(eligibility, VetterEligibility::Shown { .. });
    match application.on_accepted(thread, sender, opened.payload, eligibility, ctx.now) {
        Ok(()) => {
            let grant_check = match grant_status_entry {
                Some(Some(credential_status)) => {
                    let checking = GrantStatus::Checking { since: ctx.now };
                    let _ = application.record_grant_status(thread, sender, checking);
                    Some(GrantCheck {
                        application_id: application.id.clone(),
                        request_document_id: thread.to_string(),
                        vetter: sender.to_string(),
                        issuer: application.community.clone(),
                        credential_status,
                    })
                }
                Some(None) => {
                    let unknown = GrantStatus::Unknown {
                        reason: "the vetter's credential names no status list to check".into(),
                        checked_at: ctx.now,
                    };
                    let _ = application.record_grant_status(thread, sender, unknown);
                    None
                }
                None => None,
            };
            Handled {
                changed: true,
                notice: Some(Notice::VetterAccepted {
                    application_id: application.id.clone(),
                    vetter: sender.to_string(),
                    shown_eligible,
                }),
                grant_check,
                ..Handled::default()
            }
        }
        Err(e) => {
            warn!(%sender, error = %e, "vetting acceptance not applied");
            Handled::default()
        }
    }
}

async fn session(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    message: &Message,
    sender: &str,
) -> Handled {
    let Some((persona, _)) = ctx.recipient else {
        return Handled::default();
    };
    let Some(opened) = opened::<session::v0_1::Payload>(message, sender, ctx.resolver).await else {
        return Handled::default();
    };
    let Some(application) = book.application_mut(opened.payload.domain.as_str(), persona) else {
        warn!(%sender, "vetting session for a community we are not applying to");
        return Handled::default();
    };
    // The body is the signed document as it arrived: the statement that
    // closes this session cites its task digest, so it is kept verbatim.
    match application.on_session(
        &opened.document.id,
        &message.body,
        sender,
        opened.payload,
        ctx.now,
    ) {
        Ok(session) => Handled {
            changed: true,
            notice: Some(Notice::SessionOpened {
                application_id: application.id.clone(),
                session_id: session.id,
                vetter: sender.to_string(),
                match_code: session.match_code,
            }),
            ..Handled::default()
        },
        Err(e) => {
            warn!(%sender, error = %e, "vetting session not opened");
            Handled::default()
        }
    }
}

async fn card(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    message: &Message,
    sender: &str,
) -> Handled {
    let Some((_, our_did)) = ctx.recipient else {
        return Handled::default();
    };
    // Opened as the payload it arrived as: the card's `digestMultibase` — what
    // the statement names — is taken over the bytes the applicant signed, so the
    // card is never parsed and written back out on the way to verification.
    let Some(opened) = opened::<Value>(message, sender, ctx.resolver).await else {
        return Handled::default();
    };
    let Some(session_id) = opened.document.thread_id.clone() else {
        return Handled::default();
    };
    let Some(card) = opened.payload.get("card") else {
        warn!(%sender, "vetting session response carries no card");
        return Handled::default();
    };
    match book
        .receive_card(our_did, sender, &session_id, card, ctx.resolver, ctx.now)
        .await
    {
        Ok(entry) => Handled {
            changed: true,
            notice: Some(Notice::CardReceived {
                request_id: entry.request_id.clone(),
                applicant: sender.to_string(),
            }),
            ..Handled::default()
        },
        Err(e) => {
            warn!(%sender, error = %e, "vetting card refused");
            Handled::default()
        }
    }
}

async fn declined(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    message: &Message,
    sender: &str,
) -> Handled {
    let Some(opened) = opened::<decline::v0_1::Payload>(message, sender, ctx.resolver).await else {
        return Handled::default();
    };
    for application in &mut book.applications {
        if application
            .on_decline(sender, opened.payload.clone(), ctx.now)
            .is_ok()
        {
            return Handled {
                changed: true,
                notice: Some(Notice::Declined {
                    application_id: application.id.clone(),
                    vetter: sender.to_string(),
                }),
                ..Handled::default()
            };
        }
    }
    warn!(%sender, "vetting decline for no request of ours");
    Handled::default()
}

async fn statement(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    message: &Message,
    sender: &str,
) -> Option<Handled> {
    // Read where the dispatcher read it for the proof check: a community pushes
    // every `issue` as a signed document, the credential under `payload`.
    let issued = crate::messaging::credential_in_issue(message);
    if let Some(credential) = issued.as_ref()
        && let Some((community, roles)) = community_roles(credential)
        && roles.iter().any(|role| role_matches(role, VETTER_ROLE))
    {
        // The delivery first: signed by the community that sent it, under
        // `authentication`. A grant that arrives any other way is not the
        // community's hand-off, however well the credential inside is signed.
        if let Err(e) = wire::open::<Value>(message, sender, ctx.resolver).await {
            warn!(%sender, reason = %e, "vetter grant delivery refused");
            return Some(Handled::default());
        }
        // Then the grant itself: it is what makes this persona a vetter, and
        // the transport sender is not proof the community issued it.
        return Some(match ctx.issued_credential {
            Some(Ok(verified)) if verified.value() == credential => {
                vetter_grant(book, ctx, verified.value(), community, sender)
            }
            Some(Err(e)) => {
                warn!(reason = %e, "vetter role credential refused");
                Handled::default()
            }
            _ => {
                warn!("vetter role credential not checked — refused");
                Handled::default()
            }
        });
    }
    // Claimed on sight, taken only once the delivery opens: signed by the
    // vetter who sent it, for `authentication`. The statement inside is then
    // checked on its own proof by `on_statement`.
    wire::delivered_statement(&message.body)?;
    let Some((persona, _)) = ctx.recipient else {
        return Some(Handled::default());
    };
    let opened = match wire::open::<Value>(message, sender, ctx.resolver).await {
        Ok(opened) => opened,
        Err(e) => {
            warn!(%sender, reason = %e, "vetting statement delivery refused");
            return Some(Handled::default());
        }
    };
    let Some(credential) = wire::statement_in(&opened.payload) else {
        warn!(%sender, "signed issue carries no vetting statement — ignored");
        return Some(Handled::default());
    };
    for application in book
        .applications
        .iter_mut()
        .filter(|a| a.persona == persona && a.requests.iter().any(|r| r.vetter == sender))
    {
        match application
            .on_statement(sender, credential, ctx.resolver, ctx.now)
            .await
        {
            Ok(held) => {
                let community = application.community.clone();
                book.retired
                    .retain(|note| !(note.contains(&community) && note.contains(sender)));
                return Some(Handled {
                    changed: true,
                    notice: Some(Notice::StatementReceived {
                        application_id: application.id.clone(),
                        statement_id: held.id,
                        vetter: sender.to_string(),
                    }),
                    ..Handled::default()
                });
            }
            Err(e) => warn!(%sender, error = %e, "vetting statement refused"),
        }
    }
    Some(Handled::default())
}

/// `vtc/vetting/vetters/pcs-root/0.1#response` — the community enrolled us.
///
/// The blinding state is held in memory for the round trip (`pending_enrolment`), because it is
/// useless without this answer and dangerous to keep past it. An answer that arrives after a
/// restart therefore cannot be unblinded — the vetter asks again, which costs nothing, because a
/// request that was never unblinded issued no credential the community will count.
fn enrolled(book: &mut VettingBook, ctx: &Context<'_>, message: &Message, sender: &str) -> Handled {
    let Some((query, body)) =
        answer_to::<wire::pcs::RootResponse>(book, message, sender, QueryKind::PcsRoot)
    else {
        return Handled::default();
    };
    let body = match body {
        Ok(body) => body,
        Err(unreadable) => {
            return Handled {
                answer: Some(unreadable),
                ..Handled::default()
            };
        }
    };
    let Some(blinding) = book.pending_enrolment.take() else {
        warn!(community = %sender, "enrolled, but the blinding state is gone — asking again");
        return Handled::default();
    };
    let Some(state) = book.hidden_vetter_mut(sender, query.persona) else {
        return Handled::default();
    };
    let params = state.params.clone();
    let mut snapshot = state.snapshot.clone();
    match super::hidden::accept_enrolment(sender, &params, &mut snapshot, &body, &blinding) {
        Ok(()) => {
            if let Some(state) = book.hidden_vetter_mut(sender, query.persona) {
                state.snapshot = snapshot;
            }
            Handled {
                changed: true,
                notice: Some(Notice::HiddenVetterEnrolled {
                    community: sender.to_string(),
                    label: body.label,
                }),
                ..Handled::default()
            }
        }
        Err(e) => {
            warn!(community = %sender, error = %e, "enrolment answer did not unblind");
            let _ = ctx;
            Handled::default()
        }
    }
}

/// `vtc/vetting/vetters/pcs-tokens/0.1#response` — a tick of the drip was served.
fn tokens_served(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    message: &Message,
    sender: &str,
) -> Handled {
    let Some((query, body)) =
        answer_to::<wire::pcs::TokensResponse>(book, message, sender, QueryKind::PcsTokens)
    else {
        return Handled::default();
    };
    let body = match body {
        Ok(body) => body,
        Err(unreadable) => {
            return Handled {
                answer: Some(unreadable),
                ..Handled::default()
            };
        }
    };
    let Some(state) = book.hidden_vetter_mut(sender, query.persona) else {
        return Handled::default();
    };
    let params = state.params.clone();
    let mut snapshot = state.snapshot.clone();
    match super::hidden::accept_drip(sender, &params, &mut snapshot, &body) {
        Ok(taken) => {
            if let Some(state) = book.hidden_vetter_mut(sender, query.persona) {
                state.snapshot = snapshot;
                state.last_ticks.insert(body.label.clone(), body.tick);
                state.last_drawn_at = Some(ctx.now);
            }
            Handled {
                changed: true,
                notice: Some(Notice::HiddenTokensDrawn {
                    community: sender.to_string(),
                    taken,
                }),
                ..Handled::default()
            }
        }
        Err(e) => {
            warn!(community = %sender, error = %e, "served tokens did not verify");
            Handled::default()
        }
    }
}

/// `vtc/vetting/vetters/event-mode/0.1#response` — where our event-mode request stands.
///
/// The answer is recorded whatever it says, and `pending` is an answer. What it is **not** is a
/// grant: only an `approved` answer carrying a label opens one, and [`HiddenVetterState::
/// event_draws`](super::book::HiddenVetterState::event_draws) is what the schedule reads, so a
/// pending row can never put a label into the drip.
fn event_mode_answered(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    message: &Message,
    sender: &str,
) -> Handled {
    let Some((query, body)) =
        answer_to::<wire::pcs::EventModeResponse>(book, message, sender, QueryKind::PcsEventMode)
    else {
        return Handled::default();
    };
    let body = match body {
        Ok(body) => body,
        Err(unreadable) => {
            return Handled {
                answer: Some(unreadable),
                ..Handled::default()
            };
        }
    };
    let approved = body.state == wire::pcs::EVENT_APPROVED;
    let Some(state) = book.hidden_vetter_mut(sender, query.persona) else {
        return Handled::default();
    };
    let row = super::book::HiddenEventState {
        event_id: body.event_id.clone(),
        tier: body.tier,
        state: body.state,
        group_size: body.group_size,
        group_floor: body.group_floor,
        label: body.label,
        drip_per_tick: body.drip_per_tick,
        closes_after: body.closes_after,
        answered_at: ctx.now,
    };
    match state.events.iter_mut().find(|e| e.event_id == row.event_id) {
        Some(existing) => *existing = row,
        None => state.events.push(row),
    }
    Handled {
        changed: true,
        notice: Some(Notice::HiddenEventMode {
            community: sender.to_string(),
            event_id: body.event_id,
            approved,
            group_size: body.group_size,
            group_floor: body.group_floor,
        }),
        ..Handled::default()
    }
}

/// `vtc/vetting/pcs-challenge/0.1#response` — the nonce this submission must bind.
fn challenge_issued(book: &mut VettingBook, message: &Message, sender: &str) -> Handled {
    let Some((query, body)) =
        answer_to::<wire::pcs::ChallengeResponse>(book, message, sender, QueryKind::PcsChallenge)
    else {
        return Handled::default();
    };
    let body = match body {
        Ok(body) => body,
        Err(unreadable) => {
            return Handled {
                answer: Some(unreadable),
                ..Handled::default()
            };
        }
    };
    let Some(application) = book
        .applications
        .iter_mut()
        .find(|a| a.community == sender && a.persona == query.persona)
    else {
        return Handled::default();
    };
    application.hidden_challenge = Some(body.challenge);
    Handled {
        changed: true,
        notice: Some(Notice::ChallengeIssued {
            application_id: application.id.clone(),
            expires_at: body.expires_at,
        }),
        ..Handled::default()
    }
}

/// `vetting/attestation/0.1` — a hidden attestation from a vetter we asked.
///
/// The applicant verifies it **here**, on arrival, rather than discovering at submit that it
/// holds something unusable: an attestation that does not verify under the community's published
/// parameters, or is not bound to the card it showed, is dropped with a warning and never
/// reaches the application.
///
/// The sender is authenticated by the envelope and is deliberately **not** recorded beside the
/// attestation. Keeping it would rebuild, in the applicant's own store, the link the whole
/// exchange removes (design §18).
fn attestation(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    message: &Message,
    sender: &str,
) -> Option<Handled> {
    let Some((persona, _)) = ctx.recipient else {
        return Some(Handled::default());
    };
    for application in book
        .applications
        .iter_mut()
        .filter(|a| a.persona == persona && a.hidden.is_some())
    {
        match application.receive_hidden_attestation(&message.body) {
            Ok(()) => {
                return Some(Handled {
                    changed: true,
                    notice: Some(Notice::AttestationReceived {
                        application_id: application.id.clone(),
                        held: application.hidden_held(),
                    }),
                    ..Handled::default()
                });
            }
            // Not for this application — try the next one; the last error is reported.
            Err(e) => warn!(%sender, error = %e, "hidden attestation refused"),
        }
    }
    Some(Handled::default())
}

/// A community's vetter role credential for one of our personas.
///
/// Kept when the community that it names issued and signed it (its proof is
/// verified by the caller against the community's `assertionMethod` keys), and
/// it names the persona it was addressed to, which must hold a membership
/// there.
fn vetter_grant(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    credential: &Value,
    community: String,
    sender: &str,
) -> Handled {
    let Some((persona, our_did)) = ctx.recipient else {
        return Handled::default();
    };
    let issuer = credential
        .get("issuer")
        .and_then(|i| i.as_str().or_else(|| i.get("id").and_then(Value::as_str)));
    let subject = credential
        .pointer("/credentialSubject/id")
        .and_then(Value::as_str);
    if community != sender || issuer != Some(sender) || subject != Some(our_did) {
        warn!(%sender, %community, "vetter role credential not from its community, or not for us — ignored");
        return Handled::default();
    }
    if ctx.account.membership(&community, persona).is_none() {
        warn!(%community, "vetter role credential from a community we are not a member of — ignored");
        return Handled::default();
    }
    let valid_until = credential
        .get("validUntil")
        .and_then(Value::as_str)
        .and_then(|s| DateTime::parse_from_rfc3339(s).ok())
        .map(|d| d.with_timezone(&Utc));
    let changed = book.keep_vetter_grant(VetterGrant {
        community: community.clone(),
        persona,
        credential_id: credential
            .get("id")
            .and_then(Value::as_str)
            .map(str::to_string),
        valid_until,
        received_at: ctx.now,
        credential: credential.clone(),
    });
    Handled {
        changed,
        notice: changed.then_some(Notice::VetterGranted {
            community,
            valid_until,
        }),
        ..Handled::default()
    }
}

fn refused(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    message: &Message,
    sender: &str,
) -> Option<Handled> {
    let thread = message
        .thid
        .as_deref()
        .or_else(|| message.body.get("threadId").and_then(Value::as_str))?;
    let code = message
        .body
        .pointer("/payload/code")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string();
    let detail = message
        .body
        .pointer("/payload/message")
        .and_then(Value::as_str)
        .map(str::to_string);
    refusal_of(book, ctx, thread, sender, code, detail)
}

/// A DIDComm problem-report threaded on something vetting is waiting for.
///
/// A community refuses at the DIDComm layer — before the Trust Task pipeline,
/// so with no `trust-task-error` — when it cannot take the message at all: a
/// document typed as its task URI rather than carried in the binding envelope
/// is the case VTI #1687 made universal. The report threads on the message id,
/// which is the document id the question is filed under, so it answers the
/// question exactly as a `trust-task-error` would. Without this the person
/// asking waited out the timeout and was told nobody answered.
///
/// `None` when it threads on nothing of vetting's, so the join handler after
/// this still sees the reports that are its own.
fn problem_reported(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    message: &Message,
    sender: &str,
) -> Option<Handled> {
    let thread = message.thid.as_deref()?;
    let (code, comment) = vta_sdk::protocols::extract_problem_report(&message.body);
    let detail = (!comment.is_empty()).then_some(comment);
    refusal_of(book, ctx, thread, sender, code, detail)
}

/// Re-ask `query`, a manifest question `community` refused as an unsupported
/// version, in the version before the one asked. `None` when there is nothing
/// older to ask in, or the persona that asked no longer has a DID — the refusal
/// is then reported like any other.
fn retry_manifest_in_older_version(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    query: &super::queries::CommunityQuery,
    community: &str,
) -> Option<Handled> {
    let asked = book.protocol_for(community);
    let applicant_did = ctx.account.personas.get(&query.persona)?.did.clone();
    let next = book.fall_back_from(community, asked)?;
    let document = match wire::manifest_request(&applicant_did, community, next) {
        Ok(d) => d,
        Err(e) => {
            warn!(%community, error = %e, "could not build the older manifest request");
            return None;
        }
    };
    info!(
        %community, ?asked, ?next,
        "community does not serve this join-requests version; asking in the older one"
    );
    book.ask(super::queries::CommunityQuery {
        document_id: document.id.clone(),
        community: community.to_string(),
        persona: query.persona,
        kind: QueryKind::Manifest,
        sent_at: ctx.now,
    });
    Some(Handled {
        changed: true,
        reply: Some(Reply {
            persona: query.persona,
            document,
            eligibility: None,
        }),
        ..Handled::default()
    })
}

/// Apply a refusal of whatever vetting sent on `thread`: an application's
/// request to a vetter, a question to a community, or a statement withdrawal.
fn refusal_of(
    book: &mut VettingBook,
    ctx: &Context<'_>,
    thread: &str,
    sender: &str,
    code: String,
    detail: Option<String>,
) -> Option<Handled> {
    if let Some(application) = book.applications.iter_mut().find(|a| a.sent(thread)) {
        return Some(
            match application.on_refused(thread, sender, code.clone(), detail, ctx.now) {
                Ok(()) => Handled {
                    changed: true,
                    notice: Some(Notice::VetterRefused {
                        application_id: application.id.clone(),
                        vetter: sender.to_string(),
                        code,
                    }),
                    ..Handled::default()
                },
                Err(e) => {
                    warn!(%sender, error = %e, "vetting refusal not applied");
                    Handled::default()
                }
            },
        );
    }
    if let Some(query) = book.take_query(sender, thread, None) {
        // A manifest question refused as a version the community does not
        // serve is asked again in the older one, and the person waiting keeps
        // waiting: this is not an answer, it is the community saying which
        // language to ask in ([`super::protocol`]).
        if query.kind == QueryKind::Manifest
            && super::protocol::is_version_refusal(&code)
            && let Some(retry) = retry_manifest_in_older_version(book, ctx, &query, sender)
        {
            return Some(retry);
        }
        info!(community = %sender, %code, kind = ?query.kind, "community refused a question of ours");
        let (changed, notice) = match query.kind {
            QueryKind::VetterProfile => (
                book.on_profile_refused(sender, query.persona, &code, ctx.now),
                Some(Notice::ProfileRefused {
                    community: sender.to_string(),
                    code: code.clone(),
                }),
            ),
            QueryKind::VetterResend => (
                false,
                Some(Notice::ResendRefused {
                    community: sender.to_string(),
                    code: code.clone(),
                }),
            ),
            // Hidden vetting: the community refused to enrol us, to serve a tick, or to
            // issue a challenge. Each is worth saying in the operator's own terms, because
            // each has a different answer — a vetter who is not granted, a tick already
            // served, a criterion that does not run hidden vetting at all.
            QueryKind::PcsRoot
            | QueryKind::PcsTokens
            | QueryKind::PcsEventMode
            | QueryKind::PcsChallenge => (
                false,
                Some(Notice::HiddenVettingRefused {
                    community: sender.to_string(),
                    what: query.kind.describe(),
                    code: code.clone(),
                }),
            ),
            QueryKind::Manifest | QueryKind::VetterList => (false, None),
        };
        return Some(Handled {
            changed,
            notice,
            answer: Some(CommunityAnswer::Refused {
                query: query.document_id,
                community: sender.to_string(),
                kind: query.kind,
                code,
                message: detail,
            }),
            ..Handled::default()
        });
    }
    let statement_id = book
        .issued
        .iter()
        .find(|s| {
            s.community == sender
                && s.withdrawal
                    .as_ref()
                    .is_some_and(|w| w.document_id == thread)
        })?
        .id
        .clone();
    warn!(community = %sender, %code, "vetting statement withdrawal refused");
    Some(Handled {
        notice: Some(Notice::WithdrawalRefused { statement_id, code }),
        ..Handled::default()
    })
}

fn withdrawal_recorded(book: &mut VettingBook, message: &Message, sender: &str) -> Handled {
    let Some((Some(thread), body)) = community_reply::<revoke_statement::v0_1::Response>(message)
    else {
        return Handled::default();
    };
    match book.on_withdrawal_recorded(sender, &thread, body.recorded_at) {
        Some(issued) => Handled {
            changed: true,
            notice: Some(Notice::WithdrawalRecorded {
                statement_id: issued.id.clone(),
            }),
            ..Handled::default()
        },
        None => Handled::default(),
    }
}

fn manifest(book: &mut VettingBook, ctx: &Context<'_>, message: &Message, sender: &str) -> Handled {
    let thread = community_thread(message);
    // Taken only from a community we have reason to hear from: one we asked,
    // one we are applying to, or one we belong to. Anyone else's manifest,
    // signed or not, is not ours to learn.
    let solicited = book
        .queries
        .iter()
        .any(|q| q.community == sender && q.kind == super::queries::QueryKind::Manifest)
        || book.applications.iter().any(|a| a.community == sender)
        || !ctx.account.memberships_for(sender).is_empty();
    if !solicited {
        debug!(typ = %message.typ, "manifest from a community we have no business with — ignored");
        return Handled::default();
    }
    // The version the community answered in is the one its submit goes in.
    let protocol =
        super::protocol::JoinProtocol::from_manifest_response(&message.typ).unwrap_or_default();
    let read = community_payload::<Value>(message)
        .and_then(|v| super::protocol::read_manifest(protocol, &v).map_err(|e| e.to_string()));
    let (body, meta) = match read {
        Ok(read) => read,
        Err(detail) => {
            warn!(typ = %message.typ, error = %detail, "malformed community reply");
            // Whoever is waiting on this manifest hears why, now.
            let answer = book
                .take_manifest_queries(sender, thread.as_deref())
                .into_iter()
                .next()
                .map(|q| CommunityAnswer::Unreadable {
                    query: q.document_id,
                    community: sender.to_string(),
                    kind: QueryKind::Manifest,
                    detail,
                });
            return Handled {
                answer,
                ..Handled::default()
            };
        }
    };
    // The payload as received. A generated criterion drops the members its schema does not
    // name, and `vetting.ext` is one of them until this workspace takes a `trust-tasks-rs`
    // release carrying it, so the mode is read from these bytes (`vetting::hidden`).
    let raw = message.body.get("payload").cloned().unwrap_or(Value::Null);
    let mut handled = Handled {
        changed: book.learn_manifest_in(sender, &body, Some(protocol), &meta, ctx.now),
        ..Handled::default()
    };
    // What this community publishes about hidden vetting, kept whether or not we have an
    // application here — a vetter has no application, and this is how its client learns the
    // community runs the mode at all. The first criterion that publishes parameters wins: a
    // community running two hidden criteria under different keys is not a shape this build
    // serves, and picking one silently is better than picking one silently *and* saying so.
    let published = raw
        .get("criteria")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .find_map(|c| match super::hidden::read_mode(c) {
            Ok(super::hidden::Mode::Hidden(p)) => Some(*p),
            _ => None,
        });
    match published {
        Some(params) => {
            if book.hidden_published.get(sender) != Some(&params) {
                book.hidden_published.insert(sender.to_string(), params);
                handled.changed = true;
            }
        }
        // It stopped publishing them, so stop believing it does. An engine we already hold is
        // left alone: a credential does not become worthless because the advertisement moved.
        None => {
            if book.hidden_published.remove(sender).is_some() {
                handled.changed = true;
            }
        }
    }
    for application in book
        .applications
        .iter_mut()
        .filter(|a| a.community == sender)
    {
        match application.adopt_manifest(&body, &raw) {
            Ok(true) => {
                handled.changed = true;
                handled.notice = Some(Notice::RequirementsUpdated {
                    application_id: application.id.clone(),
                    community: sender.to_string(),
                });
            }
            Ok(false) => {}
            // A refusal the applicant has to see: the community requires something this build
            // cannot honour, and carrying on would gather evidence it does not accept.
            Err(e @ super::applicant::ApplicantError::Hidden(_)) => {
                handled.notice = Some(Notice::RequirementsUnsupported {
                    application_id: application.id.clone(),
                    community: sender.to_string(),
                    detail: e.to_string(),
                });
                warn!(community = %sender, error = %e, "community requires an unsupported extension");
            }
            Err(e) => warn!(community = %sender, error = %e, "community manifest not adopted"),
        }
    }
    if !book
        .take_manifest_queries(sender, thread.as_deref())
        .is_empty()
    {
        handled.answer = Some(CommunityAnswer::Manifest {
            community: sender.to_string(),
        });
    }
    handled
}

fn vetter_list(book: &mut VettingBook, message: &Message, sender: &str) -> Handled {
    let Some((query, page)) =
        answer_to::<vetters::list::v0_1::Response>(book, message, sender, QueryKind::VetterList)
    else {
        return Handled::default();
    };
    Handled {
        answer: Some(match page {
            Ok(page) => CommunityAnswer::Vetters {
                query: query.document_id,
                community: sender.to_string(),
                page,
            },
            Err(unreadable) => unreadable,
        }),
        ..Handled::default()
    }
}

fn profile_stored(book: &mut VettingBook, message: &Message, sender: &str) -> Handled {
    let Some((query, body)) = answer_to::<vetters::profile::v0_1::Response>(
        book,
        message,
        sender,
        QueryKind::VetterProfile,
    ) else {
        return Handled::default();
    };
    match body {
        Ok(body) => Handled {
            changed: book.on_profile_stored(sender, query.persona, &body),
            notice: Some(Notice::ProfilePublished {
                community: sender.to_string(),
                listed: body.listed,
            }),
            answer: Some(CommunityAnswer::ProfileStored {
                community: sender.to_string(),
                listed: body.listed,
                updated_at: body.updated_at,
            }),
            ..Handled::default()
        },
        Err(unreadable) => Handled {
            answer: Some(unreadable),
            ..Handled::default()
        },
    }
}

fn resent(book: &mut VettingBook, message: &Message, sender: &str) -> Handled {
    let Some((_, body)) = answer_to::<vetters::resend::v0_1::Response>(
        book,
        message,
        sender,
        QueryKind::VetterResend,
    ) else {
        return Handled::default();
    };
    match body {
        Ok(body) => Handled {
            notice: Some(Notice::GrantResent {
                community: sender.to_string(),
                valid_until: body.valid_until,
            }),
            answer: Some(CommunityAnswer::Resent {
                community: sender.to_string(),
                valid_until: body.valid_until,
            }),
            ..Handled::default()
        },
        Err(unreadable) => Handled {
            answer: Some(unreadable),
            ..Handled::default()
        },
    }
}