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
//! Everything vetting persists, in one place: `ProtectedConfig::vetting`.
//!
//! Protected rather than public because it names people. An application lists
//! who is vetting the applicant; the vetter desk lists who asked to be vetted
//! and, briefly, the card they showed. None of it belongs in plaintext config.
//!
//! V0 keeps this client-local. Moving tickets and the desk into VTA appstate is
//! V1, once `spec/vta/appstate/*` exists (design §11.2).

use super::protocol::{Admission, CriterionMeta, JoinProtocol};
use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use vta_sdk::protocols::join_requests::manifest;
use vta_sdk::protocols::vetting::{CheckShape, VettingRequirements, documentation};

use super::applicant::{Application, RequestState};
use super::queries::CommunityQuery;
use super::registry::VetterProfileRecord;
use super::tickets::{GuessThrottle, Ticket};
use super::vetter::{DeskEntry, DeskState, IssuedStatement, VetterError};
use crate::config::account::{Account, CommunityRecord, PersonaId};

/// A vetter's own rules (design §11.2). Every number is the vetter's choice;
/// the community decides what counts, not what a vetter must accept.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VetterPolicy {
    /// Requests a persona holds open at once; more are refused with
    /// `capacity`.
    pub max_open_requests: usize,
    /// How long a session stays open for the applicant to answer.
    pub session_minutes: i64,
    /// `validUntil` of a statement, from issue. A community's
    /// `maxStatementAge` is applied by the community regardless.
    pub statement_validity_days: i64,
    /// Days a received card is kept after the statement is issued or the
    /// request declined; afterwards only its digest remains.
    pub card_retention_days: i64,
    /// The documentation this vetter accepts (D16), offered to applicants.
    pub accepts_documentation: Vec<String>,
}

impl Default for VetterPolicy {
    fn default() -> Self {
        Self {
            max_open_requests: 10,
            session_minutes: 15,
            statement_validity_days: 180,
            card_retention_days: 7,
            accepts_documentation: vec![
                documentation::PASSPORT.into(),
                documentation::NATIONAL_ID.into(),
                documentation::DRIVER_LICENCE.into(),
            ],
        }
    }
}

impl VetterPolicy {
    fn is_default(&self) -> bool {
        self == &Self::default()
    }

    /// [`Self::session_minutes`] as a duration.
    #[must_use]
    pub fn session_length(&self) -> Duration {
        Duration::minutes(self.session_minutes.clamp(1, 60))
    }

    /// [`Self::statement_validity_days`] as a duration.
    #[must_use]
    pub fn statement_validity(&self) -> Duration {
        Duration::days(self.statement_validity_days.max(1))
    }
}

/// The claim types a session asks for when the community's requirements are
/// not known. Every vetter of one application must ask for the same set, or
/// the cards commit to different identities — so a vetter should fetch the
/// manifest rather than rely on this.
pub const FALLBACK_REQUIRED_CLAIMS: &[&str] = &["name.legal"];

/// A community's vetting criterion, as last read from its manifest.
///
/// No `PartialEq`: it carries the generated [`VettingRequirements`], and the
/// generated wire types derive only `Serialize`, `Deserialize`, `Clone` and
/// `Debug`. Two criteria are compared by what they serialise to
/// ([`same_requirements`]), which is what "the community changed what it asks"
/// actually means.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct KnownCriterion {
    /// The community.
    pub community: String,
    /// The criterion id.
    pub criterion_id: String,
    /// Its `requirementsDigest`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requirements_digest: Option<String>,
    /// What it requires.
    pub requirements: VettingRequirements,
    /// When it was read.
    pub fetched_at: DateTime<Utc>,
}

/// A community naming one of our personas a vetter: the role credential it
/// issued through `vtc/vetting/vetters/grant` (design §10.3). Presented to
/// applicants with every acceptance, and needed to hand out tickets.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VetterGrant {
    /// The community that issued it.
    pub community: String,
    /// Our persona it names.
    pub persona: PersonaId,
    /// The credential's `id`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub credential_id: Option<String>,
    /// Its `validUntil`. A grant without one is never treated as live.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub valid_until: Option<DateTime<Utc>>,
    /// When it arrived.
    pub received_at: DateTime<Utc>,
    /// The signed credential, exactly as delivered.
    pub credential: serde_json::Value,
}

/// Our hidden-vetting engine for one community and persona.
///
/// A vetter holds one of these per community that runs hidden vetting: the key its identifier
/// and every tag derive from, the class credentials it has been issued, and the tokens it has
/// drawn. It is created when the community first issues a class credential and kept until the
/// last label it holds has closed.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct HiddenVetterState {
    /// The community whose parameters this engine was built under.
    pub community: String,
    /// Our persona there — the member the community enrolled.
    pub persona: PersonaId,
    /// The community's published parameters, as they stood when we enrolled.
    ///
    /// Kept beside the engine rather than looked up per attestation, because a parsed criterion
    /// drops `ext` — the manifest's own extension point is where these live, and a
    /// `VettingRequirements` that has been through serde no longer carries them.
    pub params: super::hidden::HiddenParams,
    /// The engine, as [`openvtc_vetting_pcs::snapshot::VetterSnapshot`] stores it.
    pub snapshot: openvtc_vetting_pcs::snapshot::VetterSnapshot,
    /// The last drip tick we were served, **per token label**, so the next ask is the next tick
    /// and a restart does not re-ask for one the community has already served.
    ///
    /// Per label because a vetter in event mode owes two draws a tick: the event's, and the
    /// ordinary monthly one that must not be skipped while the event runs (§5.1). One counter
    /// would make the second draw look already served.
    #[serde(default)]
    pub last_ticks: std::collections::BTreeMap<String, u32>,
    /// When we last drew tokens. The drip is a schedule, not a response to demand (§5.1).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_drawn_at: Option<DateTime<Utc>>,
    /// Events we have asked to vet at, with where each request stands.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub events: Vec<HiddenEventState>,
}

impl HiddenVetterState {
    /// The event labels this vetter may draw under today, with the rate each yields.
    ///
    /// Only the approved ones, and only while their label is still accepted. A label the
    /// community publishes says an event exists; it never says we are in its group, and drawing
    /// under one we were not approved for would be refused — and would announce that we tried.
    #[must_use]
    pub fn event_draws(&self, today: chrono::NaiveDate) -> Vec<super::hidden::EventDraw> {
        self.events
            .iter()
            .filter(|e| e.state == super::wire::pcs::EVENT_APPROVED)
            .filter_map(|e| {
                let label = e.label.clone()?;
                let closes_after = e.closes_after?;
                (today <= closes_after).then_some(super::hidden::EventDraw {
                    label,
                    rate: e.drip_per_tick.unwrap_or(self.params.drip_per_tick),
                    closes_after,
                })
            })
            .collect()
    }
}

/// Where one event-mode request stands, as the community last answered it.
///
/// `group_size` is a count and never a roster: who else is at the event is the anonymity set the
/// event's smaller token label is bought with. It is kept because it is the only way a vetter
/// can tell the two reasons for waiting apart — nobody has approved it, or not enough people
/// have asked.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct HiddenEventState {
    /// The community's name for the gathering.
    pub event_id: String,
    /// The tier we asked for.
    pub tier: String,
    /// `pending` or `approved`, in the community's own words.
    pub state: String,
    pub group_size: usize,
    pub group_floor: usize,
    /// The token label, once the event is live. Absent while pending — reading one as
    /// permission to draw is the mistake this shape makes awkward.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub drip_per_tick: Option<usize>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub closes_after: Option<chrono::NaiveDate>,
    /// When we last heard about it.
    pub answered_at: DateTime<Utc>,
}

/// Where one community has put us as a vetter: its grant, and the profile we
/// last sent it. One row of the vetting desk's header.
#[derive(Clone, Debug, PartialEq)]
pub struct VetterStanding {
    /// The community that named us.
    pub community: String,
    /// Our persona it named.
    pub persona: PersonaId,
    /// When the grant lapses, if it says.
    pub valid_until: Option<DateTime<Utc>>,
    /// Whether it is live now. A lapsed row is still shown — see
    /// [`VettingBook::vetter_standing`].
    pub live: bool,
    /// Live, but not for much longer.
    pub expiring: bool,
    /// Where the profile we last sent this community stands, if we sent one.
    pub profile: Option<super::registry::ProfileState>,
}

/// A vetter grant that has lapsed, or is about to, and whose holder has not
/// been told.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GrantWarning {
    /// The community whose grant it is.
    pub community: String,
    /// Our persona it names.
    pub persona: PersonaId,
    /// Whether it has lapsed already, as opposed to being about to.
    pub expired: bool,
    /// When it lapses, or lapsed.
    pub valid_until: DateTime<Utc>,
}

impl GrantWarning {
    /// Its identity, for saying a thing once.
    ///
    /// Carries the expiry, so a *reissued* grant is a different warning rather
    /// than one already given — a renewal moves `validUntil`, and without it in
    /// the identity the next lapse would be silently treated as said.
    #[must_use]
    pub fn id(&self) -> String {
        format!(
            "vetter-grant:{}:{}:{}:{}",
            self.community,
            self.persona,
            self.valid_until.to_rfc3339(),
            if self.expired { "expired" } else { "expiring" }
        )
    }
}

/// How long before a vetter grant lapses the holder is told.
///
/// A lapsed grant is not a warning in the moment it matters: it is an
/// applicant's request refused as `notEligible`, at their end, for a reason
/// they cannot fix. Fourteen days is enough for the community to be asked and
/// answer — asking is `AskResend`, and the community has to act — without the
/// warning standing so long it becomes part of the furniture.
pub const GRANT_EXPIRY_WARNING_DAYS: i64 = 14;

impl VetterGrant {
    /// Unexpired at `now`. Revocation is the community's to apply: a revoked
    /// grant stops the vetter's statements counting there.
    #[must_use]
    pub fn is_live(&self, now: DateTime<Utc>) -> bool {
        self.valid_until.is_some_and(|until| until > now)
    }

    /// Live, but lapsing within [`GRANT_EXPIRY_WARNING_DAYS`].
    ///
    /// False once it has lapsed — an expired grant is not "expiring", and the
    /// two are different things to say. Use [`is_live`](Self::is_live) for
    /// that.
    #[must_use]
    pub fn is_expiring(&self, now: DateTime<Utc>) -> bool {
        self.is_live(now)
            && self.valid_until.is_some_and(|until| {
                until <= now + chrono::TimeDelta::days(GRANT_EXPIRY_WARNING_DAYS)
            })
    }
}

/// How a community presents itself, from its manifest's `branding`.
///
/// Presentation only: nothing is trusted because of it. Kept as this crate's
/// own type rather than the SDK's, which refuses unknown members — a config
/// written by a newer build must still open.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Branding {
    /// The name the community gives itself.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    /// `#rrggbb`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub accent_color: Option<String>,
}

impl Branding {
    fn is_default(&self) -> bool {
        self == &Self::default()
    }

    /// What of `branding` this client keeps: nothing, if it breaks its schema.
    fn from_manifest(branding: &manifest::v0_2::CommunityBranding) -> Self {
        if branding.check_shape().is_err() {
            return Self::default();
        }
        Self {
            display_name: branding
                .display_name
                .as_ref()
                .map(|n| n.as_str().to_string()),
            accent_color: branding
                .accent_color
                .as_ref()
                .map(|c| c.as_str().to_string()),
        }
    }

    /// The accent colour as RGB.
    #[must_use]
    pub fn accent_rgb(&self) -> Option<(u8, u8, u8)> {
        self.accent_color.as_deref().and_then(parse_accent)
    }
}

/// `#rrggbb` as RGB; `None` for anything else.
#[must_use]
pub fn parse_accent(color: &str) -> Option<(u8, u8, u8)> {
    let hex = color.strip_prefix('#')?;
    if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    let channel = |i: usize| u8::from_str_radix(&hex[i..i + 2], 16).ok();
    Some((channel(0)?, channel(2)?, channel(4)?))
}

/// A community whose manifest we have read — whether or not it vets.
///
/// The criteria alone cannot say "this community does not vet": a manifest
/// with no vetting criterion leaves none behind. This record is what tells
/// "does not vet" apart from "never asked".
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct KnownCommunity {
    /// The community.
    pub community: String,
    /// Its branding, if it publishes any.
    #[serde(default, skip_serializing_if = "Branding::is_default")]
    pub branding: Branding,
    /// What it asks an applicant to tell it about themselves
    /// (`requestedAttributes`). Empty when it asks nothing, and on a record
    /// written before this was kept — the next manifest read fills it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requested: Vec<crate::persona::join_answers::Asked>,
    /// When its manifest was last read.
    pub fetched_at: DateTime<Utc>,
    /// The `join-requests` version it answered its manifest in, which is the
    /// one its submit is sent in. `None` on a record written before this was
    /// kept, which reads as "ask 0.3 first" ([`super::protocol`]).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub protocol: Option<JoinProtocol>,
    /// Every criterion it publishes, vetting or not, in published order: the
    /// routes in, and what meeting each one does. [`VettingBook::criteria`]
    /// keeps only the vetting ones, with their requirements.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub routes: Vec<CommunityCriterion>,
}

/// One criterion a community publishes, as the join page and the submit need
/// it.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CommunityCriterion {
    pub id: String,
    /// What a submit names to be decided under it (`submit/0.3` `criterion`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requirements_digest: Option<String>,
    /// Whether meeting it admits or submits for review. `None` from a 0.2
    /// manifest, which does not say.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub admission: Option<Admission>,
    /// Whether it requires an invitation credential.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub invitation_required: Option<bool>,
    /// Whether it asks for vetting.
    #[serde(default)]
    pub vetting: bool,
}

/// What this book knows of whether a community vets its members.
///
/// No `PartialEq`: [`Knowledge::Vetting`] borrows a [`KnownCriterion`], which
/// carries the generated requirements. Match on it rather than compare it.
#[derive(Clone, Copy, Debug)]
pub enum Knowledge<'a> {
    /// Its manifest has not been read.
    Unknown,
    /// Its manifest names no vetting.
    NoVetting,
    /// It vets: its first vetting criterion.
    Vetting(&'a KnownCriterion),
}

/// Whether two published requirements are the same value.
///
/// The generated [`VettingRequirements`] derives no `PartialEq`, so they are
/// compared as what they serialise to — the wire value, which is what a
/// community actually changed.
#[must_use]
pub fn same_requirements(a: &VettingRequirements, b: &VettingRequirements) -> bool {
    serde_json::to_value(a).ok() == serde_json::to_value(b).ok()
}

/// All vetting state, for both sides.
///
/// No `PartialEq`: it holds applications, desk entries and criteria, and those
/// carry generated wire types that derive none.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct VettingBook {
    /// Our applications, one per community and persona.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub applications: Vec<Application>,
    /// Tickets we have issued as a vetter.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tickets: Vec<Ticket>,
    /// Requests people have made of us as a vetter.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub desk: Vec<DeskEntry>,
    /// Statements we have signed, kept so we can withdraw them.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub issued: Vec<IssuedStatement>,
    /// Recent wrong ticket codes.
    #[serde(default, skip_serializing_if = "GuessThrottle::is_empty")]
    pub throttle: GuessThrottle,
    /// Vetting criteria read from community manifests.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub criteria: Vec<KnownCriterion>,
    /// Our rules as a vetter.
    #[serde(default, skip_serializing_if = "VetterPolicy::is_default")]
    pub policy: VetterPolicy,
    /// Communities that named one of our personas a vetter.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub vetter_grants: Vec<VetterGrant>,
    /// Grant lapses we have already warned about, by
    /// [`GrantWarning::id`](GrantWarning::id).
    ///
    /// Persisted so the warning is raised **once** and stays dismissed. The
    /// inbox task itself cannot answer "have we said this yet?": dismissing a
    /// task removes it, so an absent task means either never-raised or
    /// read-and-dismissed, and re-deciding hourly would put a warning the
    /// operator has already dealt with back every hour until the community
    /// acts — which is not in their gift.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub grant_warnings: Vec<String>,
    /// Communities whose manifests we have read, with their branding.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub communities: Vec<KnownCommunity>,
    /// The `join-requests` version to ask a community in, learned from a
    /// refusal before any manifest arrived: a community that refused 0.3 as an
    /// unsupported version is asked in 0.2 from then on. A manifest's own
    /// version ([`KnownCommunity::protocol`]) takes precedence.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub protocol_hints: std::collections::BTreeMap<String, JoinProtocol>,
    /// The vetter profile we last sent each community, per persona.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub vetter_profiles: Vec<VetterProfileRecord>,
    /// Our hidden-vetting engine per community, where one runs it.
    ///
    /// **This carries secrets.** A snapshot's `usk` is the key every tag of ours derives from,
    /// so a copy of one links every attestation that persona ever made. It belongs exactly where
    /// the persona keys belong, and in the design's intended shape it lives in the VTA rather
    /// than here — see `openvtc_vetting_pcs::snapshot`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub hidden_vetter: Vec<HiddenVetterState>,
    /// Hidden-vetting parameters each community published in its manifest, by community DID.
    ///
    /// Kept whether or not we vet for that community, and separately from
    /// [`HiddenVetterState::params`], because the two answer different questions: this is *what
    /// the community publishes*, refreshed every time a manifest arrives, and that is *what we
    /// enrolled under*, which must not move beneath a credential we already hold.
    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
    pub hidden_published: std::collections::BTreeMap<String, super::hidden::HiddenParams>,
    /// What [`Self::retire_nonconformant`] set aside, one sentence each, for the
    /// Vetting page. Persisted so the notice survives the save that drops the
    /// credentials, and cleared by the operator ([`Self::clear_retired_for`]).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub retired: Vec<String>,
    /// Questions put to communities and not yet answered. Memory only — see
    /// [`super::queries`].
    #[serde(skip)]
    pub queries: Vec<CommunityQuery>,
    /// The blinding state of an enrolment in flight. **Memory only, and deliberately**: it is
    /// useless without the community's answer and dangerous to keep past it, so an answer that
    /// arrives after a restart is dropped and the vetter asks again. That costs nothing — a
    /// request whose answer was never unblinded issued no credential anyone will count.
    #[serde(skip)]
    pub pending_enrolment: Option<std::sync::Arc<openvtc_vetting_pcs::vetter::EnrolmentBlinding>>,
    /// Fields written by a newer build, preserved verbatim (D19).
    #[serde(flatten, default, skip_serializing_if = "serde_json::Map::is_empty")]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl VettingBook {
    /// Set aside every stored vetting credential that does not conform to DTG
    /// Credentials v1, and say so in [`Self::retired`]. Run once on load
    /// (`ProtectedConfig::parse`).
    ///
    /// Two stores hold credentials:
    ///
    /// - **vetter grants** — the community role credential we present to
    ///   applicants. A pre-v1 one (a role endorsement credential) is refused by
    ///   every applicant under the current specification, so presenting it only
    ///   produces `notEligible` at the far end. Dropped; the community has to
    ///   grant the role again, as a VAC.
    /// - **held statements** — the Vetting Statements an application collected.
    ///   A pre-v1 statement is not a `vetted/1` VSC and a community will not
    ///   count it. Dropped; the application asks for vetting again.
    ///
    /// What we *issued* as a vetter is kept: it records an id and a digest for
    /// withdrawal, not a credential.
    ///
    /// Returns how many were set aside.
    pub fn retire_nonconformant(&mut self) -> usize {
        let mut notes = Vec::new();
        self.vetter_grants.retain(|grant| {
            match crate::dtg::nonconformance(&grant.credential) {
                None => true,
                Some(reason) => {
                    tracing::warn!(
                        community = %grant.community,
                        %reason,
                        "dropping a stored vetter role credential that does not conform to DTG Credentials v1"
                    );
                    notes.push(format!(
                        "Your vetter role credential from {} pre-dates DTG Credentials v1 and \
                         was set aside. Ask the community to grant the vetter role again.",
                        grant.community
                    ));
                    false
                }
            }
        });
        for application in &mut self.applications {
            let community = application.community.clone();
            application.statements.retain(|held| {
                match crate::dtg::nonconformance(&held.credential) {
                    None => true,
                    Some(reason) => {
                        tracing::warn!(
                            %community,
                            vetter = %held.vetter,
                            %reason,
                            "dropping a stored vetting statement that does not conform to DTG Credentials v1"
                        );
                        notes.push(format!(
                            "A vetting statement from {} for {community} pre-dates DTG \
                             Credentials v1 and was set aside. Ask to be vetted again.",
                            held.vetter
                        ));
                        false
                    }
                }
            });
        }
        let count = notes.len();
        for note in notes {
            if !self.retired.contains(&note) {
                self.retired.push(note);
            }
        }
        count
    }

    /// Our hidden-vetting engine for `community` and `persona`, if one has been enrolled.
    #[must_use]
    pub fn hidden_vetter(&self, community: &str, persona: PersonaId) -> Option<&HiddenVetterState> {
        self.hidden_vetter
            .iter()
            .find(|h| h.community == community && h.persona == persona)
    }

    /// The same, to write.
    pub fn hidden_vetter_mut(
        &mut self,
        community: &str,
        persona: PersonaId,
    ) -> Option<&mut HiddenVetterState> {
        self.hidden_vetter
            .iter_mut()
            .find(|h| h.community == community && h.persona == persona)
    }

    /// Attest to a request the hidden way: no statement, no signature, nothing that names us.
    ///
    /// The facts are the ones [`Self::statement_draft`] builds — the same checklist, the same
    /// refusals, the same identity commitment and card digest — so a vetter's obligations do not
    /// change with the path. What changes is the last step: instead of signing an endorsement
    /// whose issuer is this persona, the engine spends a token and produces an attestation that
    /// carries a tag in place of a name.
    ///
    /// The desk entry moves to `Attested` with the attestation's own identifier in place of a
    /// statement id, so the request closes exactly as the named path closes it. Nothing is added
    /// to [`Self::issued`]: there is no statement to withdraw, and a withdrawal on this path is a
    /// different mechanism (design §4.4).
    ///
    /// # Errors
    ///
    /// - [`VetterError::NoSuchRequest`] / [`VetterError::WrongState`] as for the named path.
    /// - [`VetterError::Shape`] if the checklist does not support the statement.
    /// - [`VetterError::Hidden`] if this persona holds no engine for the community, if the
    ///   request carries no PCS identifier, or if the engine has no live credential or no free
    ///   token — the last is `atCapacity`, and the vetter declines rather than attests.
    pub fn attest_hidden<R: rand::RngCore + rand::CryptoRng>(
        &mut self,
        request_id: &str,
        vetter_did: &str,
        attestation: super::vetter::Attestation,
        now: DateTime<Utc>,
        rng: &mut R,
    ) -> Result<serde_json::Value, VetterError> {
        let entry = self
            .desk_entry(request_id)
            .ok_or(VetterError::NoSuchRequest)?
            .clone();
        let applicant_id = super::hidden::read_request_ext(
            entry
                .request
                .ext
                .as_ref()
                .map(|e| serde_json::to_value(e).unwrap_or(serde_json::Value::Null))
                .as_ref(),
        )
        .map_err(VetterError::Hidden)?
        .ok_or_else(|| {
            VetterError::Hidden(super::hidden::HiddenError::Unreadable(
                "this request carries no hidden-vetting identifier, so there is nobody to attest \
                 to under this community's criterion"
                    .into(),
            ))
        })?;

        // The same draft the named path signs. Building it here is what keeps one checklist:
        // a claim the card does not carry, or a documentary method with nothing to rely on, is
        // refused on both paths by the same code.
        let draft = self.statement_draft(request_id, vetter_did, attestation, now)?;
        // The digest the applicant asked under. A vetter attests to the criterion the
        // applicant is applying for, and the community checks that the two agree.
        let digest = entry
            .request
            .requirements_digest
            .as_ref()
            .map(|d| d.as_str().to_string())
            .unwrap_or_default();
        let meta =
            super::hidden::statement_meta(&draft, &entry.community, &digest).ok_or_else(|| {
                VetterError::Hidden(super::hidden::HiddenError::Unreadable(
                    "the statement carries no vetter members, so it is not a vetter's to attest \
                     with"
                        .into(),
                ))
            })?;

        let state = self
            .hidden_vetter_mut(&entry.community, entry.persona)
            .ok_or_else(|| {
                VetterError::Hidden(super::hidden::HiddenError::Unreadable(
                    "this persona holds no hidden-vetting credential for the community".into(),
                ))
            })?;
        let params = state.params.clone();
        let wire = super::hidden::attest(
            &entry.community,
            &params,
            &mut state.snapshot,
            &applicant_id,
            meta,
            rng,
        )
        .map_err(VetterError::Hidden)?;

        let entry = self
            .desk_entry_mut(request_id)
            .ok_or(VetterError::NoSuchRequest)?;
        let DeskState::CardReceived { card, .. } = &entry.state else {
            return Err(VetterError::WrongState("be attested"));
        };
        entry.state = DeskState::Attested {
            statement_id: format!("urn:openvtc:hidden-attestation:{request_id}"),
            issued_at: now,
            card: card.clone(),
        };
        entry.updated_at = now;
        Ok(wire)
    }

    /// Nothing to persist — keeps a config without vetting byte-identical.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.applications.is_empty()
            && self.tickets.is_empty()
            && self.desk.is_empty()
            && self.issued.is_empty()
            && self.throttle.is_empty()
            && self.criteria.is_empty()
            && self.policy.is_default()
            && self.vetter_grants.is_empty()
            && self.communities.is_empty()
            && self.vetter_profiles.is_empty()
            && self.retired.is_empty()
            && self.extra.is_empty()
    }

    /// Keep `grant`, replacing an earlier one from the same community for the
    /// same persona. Returns whether anything changed.
    pub fn keep_vetter_grant(&mut self, grant: VetterGrant) -> bool {
        let same = |g: &VetterGrant| g.community == grant.community && g.persona == grant.persona;
        if let Some(existing) = self.vetter_grants.iter_mut().find(|g| same(g)) {
            if existing.credential == grant.credential {
                return false;
            }
            let community = grant.community.clone();
            *existing = grant;
            self.clear_retired_for(&community);
        } else {
            self.clear_retired_for(&grant.community.clone());
            self.vetter_grants.push(grant);
        }
        true
    }

    /// Drop the [`Self::retired`] notices about `community` once a conformant
    /// replacement from it has been stored.
    pub fn clear_retired_for(&mut self, community: &str) {
        self.retired.retain(|note| !note.contains(community));
    }

    /// `persona`'s live vetter grant from `community`.
    #[must_use]
    pub fn vetter_grant(
        &self,
        community: &str,
        persona: PersonaId,
        now: DateTime<Utc>,
    ) -> Option<&VetterGrant> {
        self.vetter_grants
            .iter()
            .find(|g| g.community == community && g.persona == persona && g.is_live(now))
    }

    /// Where we stand as a vetter with every community that has ever named us
    /// one — the grant it issued, live or lapsed, and where the profile we last
    /// sent it got to.
    ///
    /// **Lapsed grants are included, deliberately.** Everything else on the
    /// vetter side filters to a *live* grant, which is right — a lapsed vetter
    /// cannot hand out tickets and their requests would be refused. But that
    /// makes a lapse invisible exactly when it needs explaining: the communities
    /// simply stop being listed, with nothing saying why or that asking for the
    /// grant again (`AskResend`) is the fix. This is the one view that shows the
    /// lapse.
    ///
    /// Ordered by community, so the rows do not reshuffle between frames.
    #[must_use]
    pub fn vetter_standing(&self, now: DateTime<Utc>) -> Vec<VetterStanding> {
        let mut standing: Vec<VetterStanding> = self
            .vetter_grants
            .iter()
            .map(|grant| VetterStanding {
                community: grant.community.clone(),
                persona: grant.persona,
                valid_until: grant.valid_until,
                live: grant.is_live(now),
                expiring: grant.is_expiring(now),
                profile: self
                    .vetter_profile(&grant.community, grant.persona)
                    .map(|record| record.state.clone()),
            })
            .collect();
        standing.sort_by(|a, b| {
            a.community
                .cmp(&b.community)
                .then(a.persona.cmp(&b.persona))
        });
        standing
    }

    /// Grants that have lapsed or are about to, for warning their holder.
    ///
    /// A grant with no `validUntil` is skipped: it is never live, so there is
    /// nothing to lose, and a standing warning about a credential that never
    /// worked helps nobody.
    #[must_use]
    pub fn grants_needing_attention(&self, now: DateTime<Utc>) -> Vec<&VetterGrant> {
        self.vetter_grants
            .iter()
            .filter(|g| g.valid_until.is_some() && (!g.is_live(now) || g.is_expiring(now)))
            .collect()
    }

    /// The grant warnings owed right now and not yet given, recording them as
    /// given. Also forgets warnings whose grant no longer needs one, so a
    /// reissued grant that later lapses is warned about again.
    ///
    /// Returns what to raise. Empty is the common case and writes nothing, so
    /// an hourly caller costs a scan of a short list.
    ///
    /// The identity includes the *state*, so the step from "about to lapse" to
    /// "lapsed" is a second, different warning rather than a repeat of the
    /// first — they say different things and the second is the one that
    /// explains a desk gone quiet.
    pub fn take_grant_warnings(&mut self, now: DateTime<Utc>) -> Vec<GrantWarning> {
        let owed: Vec<GrantWarning> = self
            .grants_needing_attention(now)
            .into_iter()
            .map(|g| GrantWarning {
                community: g.community.clone(),
                persona: g.persona,
                expired: !g.is_live(now),
                valid_until: g.valid_until.unwrap_or(now),
            })
            .collect();

        // Forget anything no longer owed: a renewed grant, or one whose
        // "expiring" warning has been superseded by its "expired" one.
        let live_ids: Vec<String> = owed.iter().map(GrantWarning::id).collect();
        self.grant_warnings.retain(|id| live_ids.contains(id));

        let mut new = Vec::new();
        for warning in owed {
            let id = warning.id();
            if !self.grant_warnings.contains(&id) {
                self.grant_warnings.push(id);
                new.push(warning);
            }
        }
        new
    }

    /// Remember `community`'s vetting criteria from its manifest, replacing
    /// what was known. Returns whether anything changed.
    /// What `community` asks an applicant to tell it about themselves, as of
    /// its last manifest read. Empty when it asks nothing or has not been read.
    #[must_use]
    pub fn requested_attributes(
        &self,
        community: &str,
    ) -> Vec<crate::persona::join_answers::Asked> {
        self.communities
            .iter()
            .find(|c| c.community == community)
            .map(|c| c.requested.clone())
            .unwrap_or_default()
    }

    pub fn learn_manifest(
        &mut self,
        community: &str,
        manifest: &manifest::v0_2::Response,
        now: DateTime<Utc>,
    ) -> bool {
        self.learn_manifest_in(community, manifest, None, &[], now)
    }

    /// [`Self::learn_manifest`], recording the version the manifest arrived in
    /// and what that version says about each criterion beyond its 0.2 shape
    /// ([`super::protocol::read_manifest`]).
    pub fn learn_manifest_in(
        &mut self,
        community: &str,
        manifest: &manifest::v0_2::Response,
        protocol: Option<JoinProtocol>,
        meta: &[CriterionMeta],
        now: DateTime<Utc>,
    ) -> bool {
        let routes: Vec<CommunityCriterion> = manifest
            .criteria
            .iter()
            .map(|c| {
                let id = c.id.as_str().to_string();
                let m = meta.iter().find(|m| m.id == id);
                CommunityCriterion {
                    requirements_digest: c
                        .requirements_digest
                        .as_ref()
                        .map(|d| d.as_str().to_string()),
                    admission: m.and_then(|m| m.admission),
                    invitation_required: m.and_then(|m| m.invitation_required),
                    vetting: c.vetting.is_some(),
                    id,
                }
            })
            .collect();
        let fresh: Vec<KnownCriterion> = manifest
            .criteria
            .iter()
            .filter_map(|c| {
                let requirements = c.vetting.clone()?;
                requirements.check_shape().ok()?;
                Some(KnownCriterion {
                    community: community.to_string(),
                    criterion_id: c.id.as_str().to_string(),
                    requirements_digest: c
                        .requirements_digest
                        .as_ref()
                        .map(|d| d.as_str().to_string()),
                    requirements,
                    fetched_at: now,
                })
            })
            .collect();
        let known: Vec<&KnownCriterion> = self
            .criteria
            .iter()
            .filter(|k| k.community == community)
            .collect();
        let unchanged = known.len() == fresh.len()
            && known.iter().zip(&fresh).all(|(a, b)| {
                a.criterion_id == b.criterion_id
                    && a.requirements_digest == b.requirements_digest
                    && same_requirements(&a.requirements, &b.requirements)
            });
        self.criteria.retain(|k| k.community != community);
        self.criteria.extend(fresh);

        let branding = manifest
            .branding
            .as_ref()
            .map(Branding::from_manifest)
            .unwrap_or_default();
        let requested = crate::persona::join_answers::asked(manifest);
        // A re-read refreshes `fetched_at` without counting as a change: the
        // same manifest again is not worth a save.
        let branding_changed = match self
            .communities
            .iter_mut()
            .find(|c| c.community == community)
        {
            Some(known) => {
                known.fetched_at = now;
                let changed = known.branding != branding
                    || known.requested != requested
                    || known.routes != routes
                    || (protocol.is_some() && known.protocol != protocol);
                known.branding = branding;
                known.requested = requested;
                known.routes = routes;
                if protocol.is_some() {
                    known.protocol = protocol;
                }
                changed
            }
            None => {
                self.communities.push(KnownCommunity {
                    community: community.to_string(),
                    branding,
                    requested,
                    fetched_at: now,
                    protocol,
                    routes,
                });
                true
            }
        };
        !unchanged || branding_changed
    }

    /// Whether `community` vets its members, as far as this book knows.
    ///
    /// Criteria recorded before communities were ([`KnownCommunity`]) still
    /// count as knowing that it vets.
    #[must_use]
    pub fn knowledge(&self, community: &str) -> Knowledge<'_> {
        if let Some(criterion) = self.criteria.iter().find(|k| k.community == community) {
            return Knowledge::Vetting(criterion);
        }
        if self.communities.iter().any(|c| c.community == community) {
            Knowledge::NoVetting
        } else {
            Knowledge::Unknown
        }
    }

    /// The `join-requests` version `community` answered in, or the one to ask
    /// first when it has not answered.
    #[must_use]
    pub fn protocol_for(&self, community: &str) -> JoinProtocol {
        self.communities
            .iter()
            .find(|c| c.community == community)
            .and_then(|c| c.protocol)
            .or_else(|| self.protocol_hints.get(community).copied())
            .unwrap_or_default()
    }

    /// `community` refused a request in `asked` as a version it does not
    /// serve: remember the version to fall back to and return it, or `None`
    /// when there is nothing older to try.
    pub fn fall_back_from(&mut self, community: &str, asked: JoinProtocol) -> Option<JoinProtocol> {
        let next = asked.fallback()?;
        self.protocol_hints.insert(community.to_string(), next);
        if let Some(known) = self
            .communities
            .iter_mut()
            .find(|c| c.community == community)
            && known.protocol == Some(asked)
        {
            known.protocol = Some(next);
        }
        Some(next)
    }

    /// Every criterion `community` publishes, in published order. Empty when
    /// its manifest has not been read.
    #[must_use]
    pub fn routes(&self, community: &str) -> &[CommunityCriterion] {
        self.communities
            .iter()
            .find(|c| c.community == community)
            .map_or(&[], |c| c.routes.as_slice())
    }

    /// `community`'s branding, if it publishes any.
    #[must_use]
    pub fn branding(&self, community: &str) -> Option<&Branding> {
        self.communities
            .iter()
            .find(|c| c.community == community)
            .map(|c| &c.branding)
            .filter(|b| !b.is_default())
    }

    /// Give application `application_id` the requirements already known for
    /// its community — the criterion it chose, else the first — so a new
    /// application shows them before its own manifest request is answered.
    /// Returns whether anything changed.
    pub fn adopt_known_requirements(&mut self, application_id: &str) -> bool {
        let Some(app) = self.applications.iter().find(|a| a.id == application_id) else {
            return false;
        };
        let mut known = self
            .criteria
            .iter()
            .filter(|k| k.community == app.community);
        let chosen = app
            .criterion_id
            .as_deref()
            .and_then(|id| {
                self.criteria
                    .iter()
                    .find(|k| k.community == app.community && k.criterion_id == id)
            })
            .or_else(|| known.next())
            .cloned();
        let (Some(criterion), Some(app)) = (chosen, self.application_by_id_mut(application_id))
        else {
            return false;
        };
        let changed = !app
            .requirements
            .as_ref()
            .is_some_and(|r| same_requirements(r, &criterion.requirements))
            || app.requirements_digest != criterion.requirements_digest
            || app.criterion_id.as_deref() != Some(criterion.criterion_id.as_str());
        app.criterion_id = Some(criterion.criterion_id);
        app.requirements = Some(criterion.requirements);
        app.requirements_digest = criterion.requirements_digest;
        changed
    }

    /// Active memberships holding no live vetter grant — where a member the
    /// community did name a vetter may simply never have received the
    /// credential, and can ask for it again.
    #[must_use]
    pub fn resend_candidates<'a>(
        &self,
        account: &'a Account,
        now: DateTime<Utc>,
    ) -> Vec<&'a CommunityRecord> {
        account
            .memberships()
            .filter(|m| m.status.is_active())
            .filter(|m| self.vetter_grant(&m.vtc_did, m.persona_ref, now).is_none())
            .collect()
    }

    /// The claim types a session for `community` should require: those of the
    /// criterion with `digest` (what the applicant named), else the community's
    /// first vetting criterion, else [`FALLBACK_REQUIRED_CLAIMS`]. The second
    /// value says whether the community's requirements were known.
    #[must_use]
    pub fn required_claims_for(
        &self,
        community: &str,
        digest: Option<&str>,
    ) -> (Vec<String>, bool) {
        let mut ours = self.criteria.iter().filter(|k| k.community == community);
        let chosen = digest
            .and_then(|d| {
                self.criteria.iter().find(|k| {
                    k.community == community && k.requirements_digest.as_deref() == Some(d)
                })
            })
            .or_else(|| ours.next());
        match chosen {
            // `requiredClaims` is an optional list of the generated `ClaimType`
            // on this line, so an absent list and an empty one are one case.
            Some(k) => (
                k.requirements
                    .required_claims
                    .iter()
                    .flatten()
                    .map(|c| c.as_str().to_string())
                    .collect(),
                true,
            ),
            None => (
                FALLBACK_REQUIRED_CLAIMS
                    .iter()
                    .map(ToString::to_string)
                    .collect(),
                false,
            ),
        }
    }

    /// How long `community` says it takes to decide a join (`decisionSla`),
    /// from our application as `persona` or else what we know of its criteria.
    /// `None` when it has not said, or said something unparseable.
    #[must_use]
    pub fn decision_sla(&self, community: &str, persona: PersonaId) -> Option<Duration> {
        let from_application = self
            .application(community, persona)
            .and_then(|a| a.requirements.as_ref())
            .and_then(|r| r.decision_sla.clone());
        let from_criteria = || {
            self.criteria
                .iter()
                .filter(|k| k.community == community)
                .find_map(|k| k.requirements.decision_sla.clone())
        };
        from_application
            .or_else(from_criteria)
            .and_then(|sla| vta_sdk::protocols::vetting::parse_iso8601_duration(sla.as_str()))
    }

    /// Our application to `community` as `persona`.
    #[must_use]
    pub fn application(&self, community: &str, persona: PersonaId) -> Option<&Application> {
        self.applications
            .iter()
            .find(|a| a.community == community && a.persona == persona)
    }

    /// Mutable [`Self::application`].
    pub fn application_mut(
        &mut self,
        community: &str,
        persona: PersonaId,
    ) -> Option<&mut Application> {
        self.applications
            .iter_mut()
            .find(|a| a.community == community && a.persona == persona)
    }

    /// The application with this id.
    pub fn application_by_id_mut(&mut self, id: &str) -> Option<&mut Application> {
        self.applications.iter_mut().find(|a| a.id == id)
    }

    /// The application `persona` is making to `community`, started if there is
    /// none yet. `join_did` is the persona's DID, and the design fixes it when
    /// the application starts (D13).
    ///
    /// # Errors
    ///
    /// Only if the platform has no randomness for the commitment salt.
    pub fn start_application(
        &mut self,
        community: &str,
        persona: PersonaId,
        join_did: &str,
        now: DateTime<Utc>,
    ) -> Result<&mut Application, vta_sdk::vetting::VettingError> {
        if let Some(i) = self
            .applications
            .iter()
            .position(|a| a.community == community && a.persona == persona)
        {
            return Ok(&mut self.applications[i]);
        }
        self.applications
            .push(Application::new(community, persona, join_did, now)?);
        Ok(self.applications.last_mut().expect("just pushed"))
    }

    /// Abandon an application, returning it.
    ///
    /// Vetting is client-side until the join is submitted: nothing was sent to
    /// the community, so there is nothing to withdraw from it and nobody to
    /// tell. What goes is local — the application, the statements gathered for
    /// it, and the record of which vetters were asked.
    ///
    /// The vetters are the part worth knowing about. A vetter who accepted a
    /// request still holds it at their desk; abandoning here does not reach
    /// them, and a session they open afterwards will find no application to
    /// answer. That is a loose end this cannot tidy from one side, and it is
    /// why the caller confirms first.
    ///
    /// Needed because an application is otherwise permanent. Started as the
    /// wrong persona — easy, since the persona is fixed for its whole life —
    /// it would own that community's vetting route forever.
    pub fn abandon_application(&mut self, id: &str) -> Option<Application> {
        let i = self.applications.iter().position(|a| a.id == id)?;
        Some(self.applications.remove(i))
    }

    /// The desk entry with our `request_id`.
    #[must_use]
    pub fn desk_entry(&self, request_id: &str) -> Option<&DeskEntry> {
        self.desk.iter().find(|e| e.request_id == request_id)
    }

    /// Mutable [`Self::desk_entry`].
    pub fn desk_entry_mut(&mut self, request_id: &str) -> Option<&mut DeskEntry> {
        self.desk.iter_mut().find(|e| e.request_id == request_id)
    }

    /// Requests `persona` has accepted and not yet finished.
    #[must_use]
    pub fn open_requests(&self, persona: PersonaId) -> usize {
        self.desk
            .iter()
            .filter(|e| e.persona == persona && e.state.is_open())
            .count()
    }

    /// Let time pass: close sessions nobody answered, forget cards past their
    /// retention, and drop tickets that can admit nothing. Returns whether
    /// anything changed.
    pub fn prune(&mut self, now: DateTime<Utc>) -> bool {
        let mut changed = false;

        let before = self.tickets.len();
        self.tickets
            .retain(|t| t.is_live(now) || now - t.expires_at.min(now) < Duration::days(1));
        changed |= self.tickets.len() != before;

        let retention = Duration::days(self.policy.card_retention_days.max(0));
        for entry in &mut self.desk {
            changed |= entry.expire_session(now);
            changed |= entry.forget_card_after(retention, now);
        }

        for application in &mut self.applications {
            for request in &mut application.requests {
                if let RequestState::Session {
                    request_id,
                    session,
                    ..
                } = &request.state
                    && session.expires_at <= now
                {
                    request.state = RequestState::Accepted {
                        request_id: request_id.clone(),
                        accepts_documentation: Vec::new(),
                        session_hint: None,
                    };
                    request.updated_at = now;
                    changed = true;
                }
            }
        }
        changed
    }
}

impl DeskState {
    /// Still needs the vetter.
    #[must_use]
    pub fn is_open(&self) -> bool {
        matches!(
            self,
            DeskState::Accepted | DeskState::Session { .. } | DeskState::CardReceived { .. }
        )
    }
}

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

    #[test]
    fn an_empty_book_is_not_written() {
        let book = VettingBook::default();
        assert!(book.is_empty());
        assert_eq!(serde_json::to_value(&book).unwrap(), serde_json::json!({}));
    }

    #[test]
    fn one_application_per_community_and_persona() {
        let mut book = VettingBook::default();
        let persona = PersonaId::new();
        let now = Utc::now();
        let first = book
            .start_application("did:web:vtc", persona, "did:key:zA", now)
            .unwrap()
            .id
            .clone();
        let again = book
            .start_application("did:web:vtc", persona, "did:key:zA", now)
            .unwrap()
            .id
            .clone();
        assert_eq!(first, again);
        book.start_application("did:web:other", persona, "did:key:zA", now)
            .unwrap();
        assert_eq!(book.applications.len(), 2);
    }

    /// The parallel half of the rule above: one application per *persona*,
    /// several per community. A community may be joined by more than one
    /// persona, and being vetted as one says nothing about another.
    #[test]
    fn a_second_persona_gets_its_own_application_to_the_same_community() {
        let mut book = VettingBook::default();
        let now = Utc::now();
        let alice = PersonaId::new();
        let bob = PersonaId::new();
        book.start_application("did:web:vtc", alice, "did:key:zA", now)
            .unwrap();
        book.start_application("did:web:vtc", bob, "did:key:zB", now)
            .unwrap();
        assert_eq!(book.applications.len(), 2);
    }

    /// Without this an application is permanent, and its persona is fixed for
    /// its whole life — so one started as the wrong persona would own that
    /// community's vetting route forever.
    #[test]
    fn an_application_can_be_abandoned() {
        let mut book = VettingBook::default();
        let now = Utc::now();
        let persona = PersonaId::new();
        let id = book
            .start_application("did:web:vtc", persona, "did:key:zA", now)
            .unwrap()
            .id
            .clone();

        let gone = book.abandon_application(&id).expect("it was there");
        assert_eq!(gone.id, id);
        assert!(book.applications.is_empty());

        // Abandoning it twice is not an error the caller has to guard against.
        assert!(book.abandon_application(&id).is_none());

        // And the same persona may apply again afterwards — abandoning is a
        // clearing, not a bar.
        book.start_application("did:web:vtc", persona, "did:key:zA", now)
            .unwrap();
        assert_eq!(book.applications.len(), 1);
    }

    /// A `requirementsDigest` the published criterion accepts: base58btc, and
    /// at least 16 characters. The old `"zDigest"` is refused on this line.
    const DIGEST: &str = "zQmbWqxBEKC3P8tqsKc98xmWNzrzDtRLMiMPL8wBuTGsMnR";

    fn manifest(
        branding: Option<manifest::v0_2::CommunityBranding>,
        vetting: bool,
    ) -> manifest::v0_2::Response {
        let requirements: VettingRequirements = serde_json::from_value(serde_json::json!({
            "version": "0.1",
            "statementType": vta_sdk::protocols::vetting::VETTED_PREDICATE,
            "minStatements": 1,
            "acceptedMethods": ["inPerson"],
            "requiredClaims": ["name.legal"],
            "eligibleVetters": { "role": "vetter" }
        }))
        .unwrap();
        let criterion = manifest::v0_2::Criterion::try_from(
            manifest::v0_2::Criterion::builder()
                .id("c1")
                .presentation_definition(serde_json::Map::new())
                .vetting(vetting.then_some(requirements))
                .requirements_digest(Some(
                    manifest::v0_2::DigestMultibase::try_from(DIGEST).unwrap(),
                )),
        )
        .unwrap();
        manifest::v0_2::Response::try_from(
            manifest::v0_2::Response::builder()
                .community_did("did:web:vtc")
                .criteria(vec![criterion])
                .branding(branding),
        )
        .unwrap()
    }

    #[test]
    fn a_manifest_says_whether_a_community_vets_and_how_it_looks() {
        let mut book = VettingBook::default();
        let now = Utc::now();
        assert!(matches!(book.knowledge("did:web:vtc"), Knowledge::Unknown));

        let branding = manifest::v0_2::CommunityBranding::try_from(
            manifest::v0_2::CommunityBranding::builder()
                .display_name(Some(
                    manifest::v0_2::CommunityBrandingDisplayName::try_from("Kernel").unwrap(),
                ))
                .accent_color(Some(
                    manifest::v0_2::CommunityBrandingAccentColor::try_from("#1a2B3c").unwrap(),
                )),
        )
        .unwrap();
        assert!(book.learn_manifest("did:web:vtc", &manifest(Some(branding.clone()), true), now));
        assert!(matches!(
            book.knowledge("did:web:vtc"),
            Knowledge::Vetting(_)
        ));
        let known = book.branding("did:web:vtc").unwrap();
        assert_eq!(known.display_name.as_deref(), Some("Kernel"));
        assert_eq!(known.accent_rgb(), Some((0x1a, 0x2b, 0x3c)));
        assert!(
            !book.learn_manifest("did:web:vtc", &manifest(Some(branding), true), now),
            "the same manifest again is not a change"
        );

        assert!(book.learn_manifest("did:web:open", &manifest(None, false), now));
        assert!(matches!(
            book.knowledge("did:web:open"),
            Knowledge::NoVetting
        ));
        assert!(book.branding("did:web:open").is_none());

        // An accent the published type refuses cannot be built at all now, so
        // what still reaches this client is branding the schema admits and
        // `check_shape` refuses by hand: a `logoUrl` that is not an absolute
        // https URI.
        assert!(manifest::v0_2::CommunityBrandingAccentColor::try_from("red").is_err());
        let broken: manifest::v0_2::CommunityBranding = serde_json::from_value(serde_json::json!({
            "displayName": "Elsewhere",
            "logoUrl": "http://vtc.example/logo.png"
        }))
        .expect("the schema admits it");
        book.learn_manifest("did:web:broken", &manifest(Some(broken), false), now);
        assert!(
            book.branding("did:web:broken").is_none(),
            "a bad branding is dropped whole"
        );
    }

    #[test]
    fn only_rrggbb_is_an_accent() {
        assert_eq!(parse_accent("#ff0080"), Some((255, 0, 128)));
        for bad in ["ff0080", "#ff008", "#ff00800", "#gg0080", "#ff0 80"] {
            assert_eq!(parse_accent(bad), None, "{bad}");
        }
    }

    #[test]
    fn a_new_application_takes_the_requirements_already_known() {
        let mut book = VettingBook::default();
        let now = Utc::now();
        book.learn_manifest("did:web:vtc", &manifest(None, true), now);
        let id = book
            .start_application("did:web:vtc", PersonaId::new(), "did:key:zA", now)
            .unwrap()
            .id
            .clone();
        assert!(book.adopt_known_requirements(&id));
        let app = book.application_by_id_mut(&id).unwrap();
        assert_eq!(app.criterion_id.as_deref(), Some("c1"));
        assert_eq!(app.requirements_digest.as_deref(), Some(DIGEST));
        assert!(
            !book.adopt_known_requirements(&id),
            "nothing new the second time"
        );
    }

    #[test]
    fn a_member_without_a_live_grant_can_ask_for_it_again() {
        let now = Utc::now();
        let mut account = Account::default();
        let persona = PersonaId::new();
        for (vtc, active) in [
            ("did:web:a", true),
            ("did:web:b", true),
            ("did:web:c", false),
        ] {
            let mut record = CommunityRecord::new_pending(
                vtc.to_string(),
                None,
                "openvtc/test".to_string(),
                persona,
                uuid::Uuid::new_v4(),
                now,
            );
            if active {
                record.activate(now);
            }
            account.add_membership(record);
        }
        let mut book = VettingBook::default();
        book.keep_vetter_grant(VetterGrant {
            community: "did:web:a".into(),
            persona,
            credential_id: None,
            valid_until: Some(now + Duration::days(30)),
            received_at: now,
            credential: serde_json::json!({}),
        });
        let candidates: Vec<&str> = book
            .resend_candidates(&account, now)
            .into_iter()
            .map(|m| m.vtc_did.as_str())
            .collect();
        assert_eq!(candidates, vec!["did:web:b"]);
    }

    /// A grant is warned about once as it approaches, once more when it
    /// actually lapses, and never again — a warning the operator has read and
    /// dismissed must not come back every hour for something only the community
    /// can fix.
    #[test]
    fn a_lapsing_grant_is_warned_about_once_per_state() {
        let now = Utc::now();
        let persona = PersonaId::new();
        let mut book = VettingBook::default();
        book.keep_vetter_grant(VetterGrant {
            community: "did:web:a".into(),
            persona,
            credential_id: None,
            valid_until: Some(now + Duration::days(3)),
            received_at: now,
            credential: serde_json::json!({}),
        });

        let first = book.take_grant_warnings(now);
        assert_eq!(first.len(), 1, "about to lapse");
        assert!(!first[0].expired);
        assert!(
            book.take_grant_warnings(now).is_empty(),
            "said once, not every sweep"
        );

        // It lapses. That is a second warning, and a different sentence: the
        // desk has stopped working rather than being about to.
        let later = now + Duration::days(4);
        let second = book.take_grant_warnings(later);
        assert_eq!(second.len(), 1);
        assert!(second[0].expired);
        assert!(book.take_grant_warnings(later).is_empty());
        assert_eq!(
            book.grant_warnings.len(),
            1,
            "the superseded 'expiring' warning is forgotten, not accumulated"
        );
    }

    /// A healthy grant says nothing, and a reissued one is warned about again
    /// when its own expiry comes round — the identity carries the expiry, so a
    /// renewal is not mistaken for something already said.
    #[test]
    fn a_renewed_grant_can_be_warned_about_again() {
        let now = Utc::now();
        let persona = PersonaId::new();
        let mut book = VettingBook::default();
        // A reissue is a different credential, not the same one with a new
        // date — `keep_vetter_grant` ignores a re-delivery of the identical
        // body, so the `validUntil` has to travel in the credential too.
        let grant = |until: DateTime<Utc>| VetterGrant {
            community: "did:web:a".into(),
            persona,
            credential_id: None,
            valid_until: Some(until),
            received_at: now,
            credential: serde_json::json!({ "validUntil": until.to_rfc3339() }),
        };

        book.keep_vetter_grant(grant(now + Duration::days(90)));
        assert!(
            book.take_grant_warnings(now).is_empty(),
            "a grant with months to run is not news"
        );

        book.keep_vetter_grant(grant(now + Duration::days(2)));
        assert_eq!(book.take_grant_warnings(now).len(), 1);

        // Reissued, then allowed to lapse again.
        book.keep_vetter_grant(grant(now + Duration::days(400)));
        assert!(book.take_grant_warnings(now).is_empty());
        assert!(
            book.grant_warnings.is_empty(),
            "the old warning is forgotten once the grant no longer needs it"
        );
        let much_later = now + Duration::days(395);
        assert_eq!(book.take_grant_warnings(much_later).len(), 1);
    }

    /// The desk header keeps a lapsed grant, alone among the vetter-side reads.
    /// Everything else filters to a live one, which is right and which is
    /// exactly why a lapse would otherwise be invisible: the communities simply
    /// stop being listed.
    #[test]
    fn the_standing_keeps_a_lapsed_grant_that_every_other_read_drops() {
        let now = Utc::now();
        let persona = PersonaId::new();
        let mut book = VettingBook::default();
        book.keep_vetter_grant(VetterGrant {
            community: "did:web:gone".into(),
            persona,
            credential_id: None,
            valid_until: Some(now - Duration::days(1)),
            received_at: now - Duration::days(400),
            credential: serde_json::json!({}),
        });

        assert!(
            book.vetter_grant("did:web:gone", persona, now).is_none(),
            "a lapsed grant is not a live one"
        );
        let standing = book.vetter_standing(now);
        assert_eq!(standing.len(), 1, "but the desk still shows it");
        assert!(!standing[0].live);
        assert!(
            !standing[0].expiring,
            "already gone is not 'about to go' — they are different sentences"
        );
        assert!(standing[0].profile.is_none(), "no profile was ever sent");
    }

    #[test]
    fn unknown_members_survive_a_round_trip() {
        let mut v = serde_json::to_value(VettingBook::default()).unwrap();
        v["vetterDirectory"] = serde_json::json!({ "listed": true });
        let book: VettingBook = serde_json::from_value(v).unwrap();
        assert!(!book.is_empty());
        assert_eq!(
            serde_json::to_value(&book).unwrap()["vetterDirectory"]["listed"],
            true
        );
    }

    /// A pre-v1 vetter grant is set aside on load with a notice, a conformant
    /// one stays, and a conformant replacement clears the notice.
    #[test]
    fn a_pre_v1_vetter_grant_is_set_aside_with_a_notice() {
        let community = "did:example:kernel";
        let grant = |credential: serde_json::Value| VetterGrant {
            community: community.to_string(),
            persona: PersonaId::new(),
            credential_id: None,
            valid_until: None,
            received_at: Utc::now(),
            credential,
        };
        let mut book = VettingBook::default();
        book.vetter_grants
            .push(grant(crate::dtg::fixtures::retired_role_endorsement(
                community,
                "did:example:m",
            )));
        book.vetter_grants
            .push(grant(crate::dtg::fixtures::role_vac(
                "did:example:other",
                "did:example:m",
                "vetter",
            )));
        assert_eq!(book.retire_nonconformant(), 1);
        assert_eq!(book.vetter_grants.len(), 1);
        assert_eq!(book.retired.len(), 1);
        assert!(book.retired[0].contains(community));
        assert!(!book.is_empty());

        book.keep_vetter_grant(grant(crate::dtg::fixtures::role_vac(
            community,
            "did:example:m",
            "vetter",
        )));
        assert!(
            book.retired.is_empty(),
            "the replacement answers the notice"
        );
    }
}