openvtc-core 0.4.0

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
//! The applicant's side: one application to one community (design §9–§12).
//!
//! An application collects statements from vetters until the community's
//! published requirements are met, then rides the join request. Each vetter
//! goes through the same short life:
//!
//! ```text
//! Sent ──#response──▶ Accepted ──vetting/session──▶ Session ──statement──▶ Attested
//!   │                    │                             │
//!   └─trust-task-error─▶ Refused        vetting/decline └──▶ Declined
//! ```
//!
//! The checklist ([`Application::checklist`]) is **advisory**. It counts what
//! this client can verify — proofs, subject, community, commitment, age,
//! method floors — and assumes every vetter is eligible, because only the
//! community knows that. Copy built on it says "meets the published
//! requirements", never "approved" (D12).

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use uuid::Uuid;
use vta_sdk::protocols::join_requests::manifest;
use vta_sdk::protocols::vetting::{
    CheckShape, ShapeError, VETTER_ROLE, VettingMethod, VettingRelationship, VettingRequirements,
    check_request, decline, request, session,
};
use vta_sdk::trust_task_proof::TrustTaskVmResolver;
use vta_sdk::vetting::VettingError;
use vta_sdk::vetting::card::{
    CardDraft, CardExpectations, MAX_CARD_VALIDITY, new_commitment_salt, verify_card,
};
use vta_sdk::vetting::match_code::vetting_match_code;
use vta_sdk::vetting::requirements::{
    Evaluation, REQUIREMENTS_DIGEST_MEMBER, StatementFacts, evaluate,
};
use vta_sdk::vetting::statement::verify_statement;
use vta_sdk::vetting::status::StatusCheck;
use vta_sdk::vetting::ticket_uri::{self, TicketUri};

use crate::config::account::PersonaId;
use crate::persona::disclosure::ReleasedClaim;

/// Why an applicant-side step was refused.
#[derive(Debug, thiserror::Error)]
pub enum ApplicantError {
    /// The criterion asks for something this build cannot honour ([`super::hidden`]).
    #[error(transparent)]
    Hidden(#[from] super::hidden::HiddenError),
    /// Nothing we sent matches this reply.
    #[error("no request of ours matches this reply")]
    NoMatchingRequest,
    /// The request exists but cannot take this step now.
    #[error("the request cannot {0} in its current state")]
    WrongState(&'static str),
    /// A payload broke its schema.
    #[error(transparent)]
    Shape(#[from] ShapeError),
    /// The session names another community.
    #[error("the session is for a different community")]
    WrongCommunity,
    /// The session has closed.
    #[error("the session has expired")]
    SessionExpired,
    /// The card would lack a claim the session requires.
    #[error("the card needs a `{0}` claim")]
    MissingClaim(String),
    /// A claim was released without its value — proved as a predicate — and a
    /// vetter has to read the value to check it against a document.
    #[error("your face releases `{0}` without its value, and a vetter has to read it")]
    ValueWithheld(String),
    /// A credential-backed claim can no longer be proven.
    #[error("`{0}` can no longer be proven — refresh it under My Identity")]
    StaleClaim(String),
    /// The face now shows a value other than the one earlier cards committed to.
    #[error(
        "your face now shows a different `{0}` than the cards you already sent — the \
         community would refer the application"
    )]
    IdentityChanged(String),
    /// Building or verifying an artifact failed.
    #[error(transparent)]
    Vetting(#[from] VettingError),
    /// A statement is not about this application.
    #[error("the statement's {0} does not match this application")]
    Binding(&'static str),
    /// The community's manifest names no vetting.
    #[error("the community does not ask for vetting")]
    NoVettingCriterion,
    /// The community's requirements cannot be evaluated.
    #[error("the community's vetting requirements are unusable: {0}")]
    InvalidRequirements(String),
}

/// Why a pasted ticket link cannot be used for this application.
#[derive(Debug, thiserror::Error)]
pub enum TicketUriError {
    /// Not a ticket link this client can read.
    #[error("that is not a vetting ticket link this client can read: {0}")]
    Unreadable(VettingError),
    /// A ticket for vetting in another community.
    #[error(
        "that ticket is for vetting in another community ({0}), not the one this application is to"
    )]
    OtherCommunity(String),
}

/// What an applicant should do next, from where the application stands.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum NextStep {
    /// A vetter opened a session and is waiting for the card.
    SendCard {
        /// The session.
        session_id: String,
    },
    /// The community's requirements are not known yet.
    LearnRequirements,
    /// The published requirements are met: join.
    Join,
    /// Nothing has been shown to a vetter yet: choose the face they see.
    ChooseFace,
    /// More statements are needed and no vetter is working on one.
    AskVetter,
    /// Vetters have the request; wait for them.
    WaitForVetters,
}

/// The face an application shows vetters.
///
/// The `profile_id` is what identifies it — a face can be renamed, and a name
/// read once and stored would then label the wrong thing. `name` is kept only
/// so a screen can say which face without a round trip to the agent, and is
/// refreshed whenever the faces are listed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChosenFace {
    /// The profile the VTA knows it by.
    pub profile_id: String,
    /// Its display name, as last read.
    pub name: String,
}

/// One application.
///
/// No `PartialEq`: it carries the community's generated requirements and the
/// generated card claims, and the generated wire types derive only
/// `Serialize`, `Deserialize`, `Clone` and `Debug`. Requirements are compared
/// with [`super::book::same_requirements`].
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Application {
    /// Local handle.
    pub id: String,
    /// The community's VTC DID.
    pub community: String,
    /// The persona joining.
    pub persona: PersonaId,
    /// The DID every card is signed by and every statement names (D13).
    pub join_did: String,
    /// The VTA context the persona's face for this community is worn in. Set
    /// the first time a face is chosen or a card is sent, and reused as the
    /// membership's sub-context when the join goes through, so the face the
    /// vetters saw is the face the community sees.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub context_id: Option<String>,
    /// The manifest criterion being gathered for.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub criterion_id: Option<String>,
    /// What that criterion requires, as last read from the manifest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requirements: Option<VettingRequirements>,
    /// The criterion's `requirementsDigest`, sent with requests and the join.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requirements_digest: Option<String>,
    /// The hidden-vetter parameters this community published for the chosen criterion, when it
    /// publishes any ([`super::hidden`]). Absent is the named path, which is every community
    /// today.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hidden: Option<super::hidden::HiddenParams>,
    /// The applicant's own engine state for a hidden-vetting application: its key, and the
    /// attestations gathered so far ([`super::hidden`]). Absent on the named path.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hidden_state: Option<openvtc_vetting_pcs::snapshot::ApplicantSnapshot>,
    /// The proof built for the next submit, held between building it and sending it. Not
    /// persisted: it is bound to a challenge that does not outlive the exchange.
    #[serde(skip)]
    pub hidden_submission: Option<Value>,
    /// The challenge the community issued for this submission, once one has been asked for.
    ///
    /// Persisted, unlike the proof above: the community spends it at submit, so an applicant
    /// that restarts between asking and submitting keeps the one it was given rather than
    /// asking for a second and stranding the first.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub hidden_challenge: Option<String>,
    /// One salt for the whole application, so every vetter sees the same
    /// identity commitment. Goes to vetters, never to the community.
    pub commitment_salt: String,
    /// The face this application shows vetters, once one has been chosen.
    ///
    /// The binding at the VTA is the source of truth for what is *worn*; this
    /// records that a face was chosen for this application at all. That is a
    /// distinct fact, and the one the next step turns on: the claims are only
    /// read from the face when the first card goes out, so nothing else on the
    /// application distinguishes "no face yet" from "face chosen, no vetter
    /// asked". It is persisted so that distinction survives a restart.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub face: Option<ChosenFace>,
    /// The identity vetters have been shown, as the persona's face disclosed
    /// it. Every later card must show the same values: two cards that spell a
    /// name differently commit to different identities, and the community
    /// refers the application.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub identity_claims: Vec<session::v0_1::VettingCardClaim>,
    /// Requests to vetters, newest last.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requests: Vec<OutboundRequest>,
    /// Statements received.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub statements: Vec<HeldStatement>,
    /// When the application started.
    pub created_at: DateTime<Utc>,
    /// 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, Value>,
}

/// What an applicant could establish about a vetter from the eligibility
/// presentation that came with their acceptance.
///
/// Advisory, like the checklist: the community checks the vetter again when
/// it decides, and does not count a statement from one it has not named.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "result", rename_all = "snake_case")]
pub enum VetterEligibility {
    /// The community's vetter role credential for this vetter verified, bound
    /// to our request. Whether the community has since revoked it is not
    /// checked here.
    Shown {
        /// The role credential's `id`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        credential_id: Option<String>,
        /// Its `validUntil`.
        valid_until: DateTime<Utc>,
    },
    /// The vetter presented nothing.
    NotShown,
    /// What they presented did not verify.
    Failed {
        /// Why.
        reason: String,
    },
}

/// Whether the community has revoked the grant a vetter presented, as far as
/// this client could find out (design §7.1). Advisory, like
/// [`VetterEligibility`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "result", rename_all = "snake_case")]
pub enum GrantStatus {
    /// The status list is being fetched.
    Checking {
        /// Since when.
        since: DateTime<Utc>,
    },
    /// The community's signed status list shows the grant unrevoked.
    Active {
        /// When.
        checked_at: DateTime<Utc>,
    },
    /// The community has revoked (or suspended) the grant.
    Revoked {
        /// When this was learned.
        checked_at: DateTime<Utc>,
    },
    /// It could not be established; never read as active.
    Unknown {
        /// Why, for the person and the log.
        reason: String,
        /// When the check gave up.
        checked_at: DateTime<Utc>,
    },
}

impl GrantStatus {
    /// The result of a status check made at `now`.
    #[must_use]
    pub fn from_check(check: StatusCheck, now: DateTime<Utc>) -> Self {
        match check {
            StatusCheck::Active => GrantStatus::Active { checked_at: now },
            StatusCheck::Revoked => GrantStatus::Revoked { checked_at: now },
            StatusCheck::Unknown(reason) => GrantStatus::Unknown {
                reason,
                checked_at: now,
            },
        }
    }
}

/// One request to one vetter.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OutboundRequest {
    /// Our `vetting/request` document id — what the vetter's reply threads on.
    pub document_id: String,
    /// The vetter's DID.
    pub vetter: String,
    /// Where it stands.
    pub state: RequestState,
    /// What the vetter's acceptance showed of their eligibility.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub eligibility: Option<VetterEligibility>,
    /// Whether the community has since revoked the grant they showed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub grant_status: Option<GrantStatus>,
    /// When we sent it.
    pub sent_at: DateTime<Utc>,
    /// When it last moved.
    pub updated_at: DateTime<Utc>,
}

/// Where a request stands.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "state", rename_all = "snake_case")]
pub enum RequestState {
    /// Sent; no answer yet.
    Sent,
    /// The vetter took it.
    Accepted {
        /// The vetter's handle.
        request_id: String,
        /// What documentation the vetter accepts.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        accepts_documentation: Vec<String>,
        /// How the vetter proposes to meet.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        session_hint: Option<String>,
    },
    /// The vetter opened a session; we owe them a card.
    Session {
        /// The vetter's handle.
        request_id: String,
        /// The open session.
        session: Box<OpenSession>,
        /// The card we sent, once we have.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        card: Option<SentCard>,
    },
    /// We hold the vetter's statement.
    Attested {
        /// The vetter's handle.
        request_id: String,
        /// The statement's id.
        statement_id: String,
    },
    /// The vetter declined.
    Declined {
        /// Their reason code, if they gave one.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        code: Option<decline::v0_1::PayloadCode>,
        /// Their note, if any.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        message: Option<String>,
    },
    /// The vetter refused the request itself (`trust-task-error`).
    Refused {
        /// The error code, e.g. `vetting/request:capacity`.
        code: String,
        /// Their note, if any.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        message: Option<String>,
    },
}

/// A session a vetter opened with us.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct OpenSession {
    /// The `vetting/session` document id.
    pub id: String,
    /// What the card must carry.
    pub challenge: String,
    /// What the card must carry.
    pub domain: String,
    /// The method.
    pub method: VettingMethod,
    /// Claim types the card must carry.
    pub required_claims: Vec<String>,
    /// Claim types the card may carry.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub optional_claims: Vec<String>,
    /// After this we do not present.
    pub expires_at: DateTime<Utc>,
    /// The code both people read aloud.
    pub match_code: String,
    /// The signed `vetting/session` document as it arrived. A statement for
    /// this session must cite it — `taskContext` its `id`, `taskDigestMultibase`
    /// its task digest — or it is not the statement for this session.
    /// `None` on a session recorded before statements carried the digest.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub document: Option<Box<Value>>,
}

/// The card we sent into a session.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SentCard {
    /// The card id.
    pub id: String,
    /// Its `digestMultibase` — the statement must name it.
    pub digest_multibase: String,
    /// Its commitment — the statement must repeat it.
    pub identity_commitment: String,
    /// When we sent it.
    pub sent_at: DateTime<Utc>,
}

/// A statement we hold.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct HeldStatement {
    /// The statement id.
    pub id: String,
    /// The vetter.
    pub vetter: String,
    /// How they vetted us.
    pub method: VettingMethod,
    /// The relationship they declared.
    pub declared_relationship: VettingRelationship,
    /// What they relied on.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub document_classes: Vec<String>,
    /// Claim types they verified.
    pub claims_verified: Vec<String>,
    /// Our identity commitment, as they signed it.
    pub identity_commitment: String,
    /// Start of validity.
    pub valid_from: DateTime<Utc>,
    /// End of validity.
    pub valid_until: DateTime<Utc>,
    /// When it arrived.
    pub received_at: DateTime<Utc>,
    /// The signed credential, exactly as received.
    pub credential: Value,
}

/// What a request to a vetter says besides the ticket.
#[derive(Clone, Debug, Default)]
pub struct RequestDraft {
    /// The method the applicant would prefer.
    pub preferred_method: Option<VettingMethod>,
    /// BCP 47 tags.
    pub languages: Vec<String>,
    /// A short note.
    pub message: Option<String>,
    /// Free-text availability.
    pub availability: Option<String>,
}

impl Application {
    /// A new application with a fresh commitment salt.
    ///
    /// # Errors
    ///
    /// Only if the platform has no randomness.
    pub fn new(
        community: &str,
        persona: PersonaId,
        join_did: &str,
        now: DateTime<Utc>,
    ) -> Result<Self, VettingError> {
        Ok(Self {
            id: Uuid::new_v4().to_string(),
            community: community.to_string(),
            persona,
            join_did: join_did.to_string(),
            context_id: None,
            face: None,
            criterion_id: None,
            requirements: None,
            requirements_digest: None,
            hidden: None,
            hidden_state: None,
            hidden_submission: None,
            hidden_challenge: None,
            commitment_salt: new_commitment_salt()?,
            identity_claims: Vec::new(),
            requests: Vec::new(),
            statements: Vec::new(),
            created_at: now,
            extra: serde_json::Map::new(),
        })
    }

    /// Take the community's requirements from its manifest (0.2). Keeps the
    /// criterion already chosen when it still exists; otherwise the first that
    /// asks for vetting. Returns whether the requirements changed — a changed
    /// digest mid-application is worth telling the applicant about.
    ///
    /// # Errors
    ///
    /// [`ApplicantError::NoVettingCriterion`] or
    /// [`ApplicantError::InvalidRequirements`].
    /// `raw` is the manifest payload **as received**. The criterion is read from it rather
    /// than from `manifest`, because a generated type drops the members it does not name and
    /// `vetting.ext` is where a community publishes what this version does not enumerate
    /// ([`super::hidden`]).
    pub fn adopt_manifest(
        &mut self,
        manifest: &manifest::v0_2::Response,
        raw: &Value,
    ) -> Result<bool, ApplicantError> {
        let with_vetting = |c: &&manifest::v0_2::Criterion| c.vetting.is_some();
        let chosen = self
            .criterion_id
            .as_deref()
            .and_then(|id| {
                manifest
                    .criteria
                    .iter()
                    .filter(with_vetting)
                    .find(|c| c.id.as_str() == id)
            })
            .or_else(|| manifest.criteria.iter().find(with_vetting))
            .ok_or(ApplicantError::NoVettingCriterion)?;
        let requirements = chosen.vetting.clone().expect("filtered on vetting");
        requirements
            .check_shape()
            .map_err(|e| ApplicantError::InvalidRequirements(e.to_string()))?;
        let digest = chosen
            .requirements_digest
            .as_ref()
            .map(|d| d.as_str().to_string());
        let changed = !self
            .requirements
            .as_ref()
            .is_some_and(|r| super::book::same_requirements(r, &requirements))
            || self.requirements_digest != digest;
        // What the criterion asks of this client. A criterion that marks a namespace critical
        // which this build cannot honour is refused here: applying without it would send the
        // community something it does not accept, and neither side would learn why.
        let raw_criterion = raw
            .get("criteria")
            .and_then(Value::as_array)
            .and_then(|cs| {
                cs.iter()
                    .find(|c| c.get("id").and_then(Value::as_str) == Some(chosen.id.as_str()))
            });
        let hidden = match raw_criterion {
            Some(raw) => match super::hidden::read_mode(raw)? {
                super::hidden::Mode::Hidden(params) => Some(*params),
                super::hidden::Mode::Named => None,
            },
            None => None,
        };
        let changed = changed || self.hidden != hidden;
        // A key of this application's own, minted once. Every tag a vetter produces for this
        // applicant is derived from it, so it never moves between applications.
        if let Some(params) = &hidden
            && self.hidden_state.is_none()
        {
            self.hidden_state = Some(super::hidden::start(
                &self.community,
                params,
                &self.join_did,
                &mut rand::rngs::OsRng,
            )?);
        }
        self.criterion_id = Some(chosen.id.as_str().to_string());
        self.requirements = Some(requirements);
        self.requirements_digest = digest;
        self.hidden = hidden;
        Ok(changed)
    }

    /// Build the `vetting/request` payload to `vetter` and record it as sent
    /// under `document_id`.
    ///
    /// # Errors
    ///
    /// [`ShapeError`] if the payload breaks the schema.
    pub fn prepare_request(
        &mut self,
        document_id: &str,
        vetter: &str,
        ticket: request::v0_1::Ticket,
        draft: RequestDraft,
        now: DateTime<Utc>,
    ) -> Result<request::v0_1::Payload, ShapeError> {
        let schema = |e: &dyn std::fmt::Display| ShapeError::Schema(e.to_string());
        let languages = draft
            .languages
            .iter()
            .map(|l| {
                request::v0_1::PayloadLanguagesItem::try_from(l.as_str()).map_err(|e| schema(&e))
            })
            .collect::<Result<Vec<_>, ShapeError>>()?;
        let message = draft
            .message
            .map(|m| request::v0_1::PayloadMessage::try_from(m).map_err(|e| schema(&e)))
            .transpose()?;
        let availability = draft
            .availability
            .map(|a| request::v0_1::PayloadAvailability::try_from(a).map_err(|e| schema(&e)))
            .transpose()?;
        // The request task carries its own copy of the method vocabulary.
        let preferred = draft
            .preferred_method
            .map(|m| {
                super::same_token::<_, request::v0_1::VettingMethod>(&m).map_err(|e| schema(&e))
            })
            .transpose()?;
        let digest = self
            .requirements_digest
            .as_deref()
            .map(|d| request::v0_1::DigestMultibase::try_from(d).map_err(|e| schema(&e)))
            .transpose()?;
        let body = request::v0_1::Payload::try_from(
            request::v0_1::Payload::builder()
                .community(self.community.as_str())
                .join_did(self.join_did.as_str())
                .ticket(Some(ticket))
                .requirements_digest(digest)
                .preferred_method(preferred)
                // An empty `languages` is sent as `[]` on this line where it
                // used to be omitted, so "no preference" stays absent.
                .languages((!languages.is_empty()).then_some(languages))
                .message(message)
                .availability(availability),
        )
        .map_err(|e| schema(&e))?;
        // Under a hidden criterion the vetter needs the identifier it will attest to, and the
        // join DID is not that name. It travels in the framework's own extension point, so a
        // community that does not run hidden vetting sees a request it already understands.
        let body = match self.hidden_id() {
            Some(id) => {
                let ext = super::hidden::request_ext(super::hidden::SUITE, id);
                let mut raw = serde_json::to_value(&body).map_err(|e| schema(&e))?;
                if let Some(obj) = raw.as_object_mut() {
                    obj.insert("ext".into(), ext);
                }
                serde_json::from_value(raw).map_err(|e| schema(&e))?
            }
            None => body,
        };
        check_request(&body, &self.join_did)?;
        self.requests.push(OutboundRequest {
            document_id: document_id.to_string(),
            vetter: vetter.to_string(),
            state: RequestState::Sent,
            eligibility: None,
            grant_status: None,
            sent_at: now,
            updated_at: now,
        });
        Ok(body)
    }

    /// Forget a request that never left — its send failed — so a retry is not
    /// shadowed by a record the vetter never saw. Returns whether one was removed.
    pub fn forget_unsent(&mut self, document_id: &str) -> bool {
        let before = self.requests.len();
        self.requests
            .retain(|r| !(r.document_id == document_id && r.state == RequestState::Sent));
        self.requests.len() != before
    }

    /// Whether we sent the request `document_id` (a reply's thread).
    #[must_use]
    pub fn sent(&self, document_id: &str) -> bool {
        self.requests.iter().any(|r| r.document_id == document_id)
    }

    fn by_thread(
        &mut self,
        thread: &str,
        vetter: &str,
    ) -> Result<&mut OutboundRequest, ApplicantError> {
        self.requests
            .iter_mut()
            .find(|r| r.document_id == thread && r.vetter == vetter)
            .ok_or(ApplicantError::NoMatchingRequest)
    }

    fn by_request_id(
        &mut self,
        request_id: &str,
        vetter: &str,
    ) -> Result<&mut OutboundRequest, ApplicantError> {
        self.requests
            .iter_mut()
            .rev()
            .find(|r| {
                r.vetter == vetter
                    && match &r.state {
                        RequestState::Accepted { request_id: id, .. }
                        | RequestState::Session { request_id: id, .. }
                        | RequestState::Attested { request_id: id, .. } => id == request_id,
                        _ => false,
                    }
            })
            .ok_or(ApplicantError::NoMatchingRequest)
    }

    /// The role a vetter must hold: the requirements' `eligibleVetters.role`,
    /// or `vetter` while they are unknown.
    #[must_use]
    pub fn vetter_role(&self) -> &str {
        self.requirements
            .as_ref()
            .map_or(VETTER_ROLE, |r| r.eligible_vetters.role.as_str())
    }

    /// The vetter accepted (`vetting/request#response`, threaded on our
    /// request), and `eligibility` is what its presentation showed. A repeat
    /// of the same acceptance is harmless.
    ///
    /// # Errors
    ///
    /// No matching request, a request already past acceptance, or a payload
    /// breaking its schema.
    pub fn on_accepted(
        &mut self,
        thread: &str,
        vetter: &str,
        body: request::v0_1::Response,
        eligibility: VetterEligibility,
        now: DateTime<Utc>,
    ) -> Result<(), ApplicantError> {
        body.check_shape()?;
        let request = self.by_thread(thread, vetter)?;
        match &request.state {
            RequestState::Sent => {}
            RequestState::Accepted { request_id, .. }
                if request_id.as_str() == body.request_id.as_str() => {}
            _ => return Err(ApplicantError::WrongState("be accepted")),
        }
        request.eligibility = Some(eligibility);
        request.grant_status = None;
        request.state = RequestState::Accepted {
            request_id: body.request_id.as_str().to_string(),
            // `acceptsDocumentation` is absent rather than empty when a vetter
            // accepts none, so an absent list and an empty one are one case.
            accepts_documentation: body
                .accepts_documentation
                .iter()
                .flatten()
                .map(|d| d.as_str().to_string())
                .collect(),
            session_hint: body.session_hint.map(|h| h.as_str().to_string()),
        };
        request.updated_at = now;
        Ok(())
    }

    /// Record what is known of whether the community revoked the grant the
    /// vetter showed on request `request_document_id`.
    ///
    /// # Errors
    ///
    /// No request of ours to that vetter with that id.
    pub fn record_grant_status(
        &mut self,
        request_document_id: &str,
        vetter: &str,
        status: GrantStatus,
    ) -> Result<(), ApplicantError> {
        let request = self.by_thread(request_document_id, vetter)?;
        request.grant_status = Some(status);
        Ok(())
    }

    /// Read a pasted ticket link (what a vetter's QR code carries): the vetter
    /// to ask, and the ticket to present.
    ///
    /// # Errors
    ///
    /// Not a ticket link, or a ticket for vetting in another community — which
    /// the vetter would refuse, and which would tie this application's DID to
    /// that community if it were sent.
    pub fn ticket_from_uri(&self, input: &str) -> Result<TicketUri, TicketUriError> {
        let ticket = ticket_uri::decode(input).map_err(TicketUriError::Unreadable)?;
        if ticket.community != self.community {
            return Err(TicketUriError::OtherCommunity(ticket.community));
        }
        Ok(ticket)
    }

    /// What to do next.
    ///
    /// A waiting session comes first: it closes in minutes. Then, in order, the
    /// requirements have to be known, the application may already be enough,
    /// the first card needs a face, and a request that needs more statements
    /// needs a vetter working on one.
    #[must_use]
    pub fn next_step(&self, now: DateTime<Utc>) -> NextStep {
        if let Some(session_id) = self.requests.iter().find_map(|r| match &r.state {
            RequestState::Session {
                session,
                card: None,
                ..
            } if session.expires_at > now => Some(session.id.clone()),
            _ => None,
        }) {
            return NextStep::SendCard { session_id };
        }
        let Some(evaluation) = self.checklist(now) else {
            return NextStep::LearnRequirements;
        };
        if evaluation.satisfied() {
            return NextStep::Join;
        }
        // The claims are read from the face with the *first card*, so
        // `identity_claims` stays empty until a vetter has been asked — which
        // is why choosing a face has to be recorded in its own right. Without
        // `face`, the step still read "choose a face" immediately after one had
        // been chosen, and the screen contradicted itself.
        if self.face.is_none() && self.identity_claims.is_empty() && self.requests.is_empty() {
            return NextStep::ChooseFace;
        }
        let in_progress = self.requests.iter().any(|r| {
            matches!(
                r.state,
                RequestState::Sent | RequestState::Accepted { .. } | RequestState::Session { .. }
            )
        });
        if in_progress {
            NextStep::WaitForVetters
        } else {
            NextStep::AskVetter
        }
    }

    /// The vetter refused the request (`trust-task-error`, threaded on it).
    ///
    /// # Errors
    ///
    /// No matching request, or one that was already answered.
    pub fn on_refused(
        &mut self,
        thread: &str,
        vetter: &str,
        code: String,
        message: Option<String>,
        now: DateTime<Utc>,
    ) -> Result<(), ApplicantError> {
        let request = self.by_thread(thread, vetter)?;
        if request.state != RequestState::Sent {
            return Err(ApplicantError::WrongState("be refused"));
        }
        request.state = RequestState::Refused { code, message };
        request.updated_at = now;
        Ok(())
    }

    /// The vetter opened a session (`vetting/session`). Returns it, with the
    /// match code the two people read to each other.
    ///
    /// # Errors
    ///
    /// A malformed or expired session, one for another community, or one for
    /// a request this vetter never accepted.
    ///
    /// `document` is the signed session document exactly as received; it is
    /// kept, because the statement that closes the session cites its digest.
    pub fn on_session(
        &mut self,
        session_document_id: &str,
        document: &Value,
        vetter: &str,
        body: session::v0_1::Payload,
        now: DateTime<Utc>,
    ) -> Result<OpenSession, ApplicantError> {
        body.check_shape()?;
        if body.domain.as_str() != self.community {
            return Err(ApplicantError::WrongCommunity);
        }
        if body.expires_at <= now {
            return Err(ApplicantError::SessionExpired);
        }
        let request = self.by_request_id(body.request_id.as_str(), vetter)?;
        if matches!(request.state, RequestState::Attested { .. }) {
            return Err(ApplicantError::WrongState("open another session"));
        }
        // The session task has its own copy of the method vocabulary.
        let method = super::same_token(&body.method).map_err(
            |e: <VettingMethod as std::str::FromStr>::Err| {
                ApplicantError::Shape(ShapeError::Schema(e.to_string()))
            },
        )?;
        let session = OpenSession {
            id: session_document_id.to_string(),
            challenge: body.challenge.as_str().to_string(),
            domain: body.domain.as_str().to_string(),
            method,
            required_claims: body
                .required_claims
                .iter()
                .map(|c| c.as_str().to_string())
                .collect(),
            optional_claims: body
                .optional_claims
                .iter()
                .flatten()
                .map(|c| c.as_str().to_string())
                .collect(),
            expires_at: body.expires_at,
            match_code: vetting_match_code(session_document_id),
            document: Some(Box::new(document.clone())),
        };
        request.state = RequestState::Session {
            request_id: body.request_id.as_str().to_string(),
            session: Box::new(session.clone()),
            card: None,
        };
        request.updated_at = now;
        Ok(session)
    }

    /// The open session `session_id` and the vetter it is with.
    #[must_use]
    pub fn session(&self, session_id: &str) -> Option<(&str, &OpenSession)> {
        self.requests.iter().find_map(|r| match &r.state {
            RequestState::Session { session, .. } if session.id == session_id => {
                Some((r.vetter.as_str(), &**session))
            }
            _ => None,
        })
    }

    /// The claim types a card for `session_id` asks the face for: required,
    /// then optional.
    #[must_use]
    pub fn requested_claims(&self, session_id: &str) -> Vec<String> {
        self.session(session_id)
            .map(|(_, s)| {
                s.required_claims
                    .iter()
                    .chain(&s.optional_claims)
                    .cloned()
                    .collect()
            })
            .unwrap_or_default()
    }

    /// The card claims for `session_id` from what the face released (or would
    /// release — a preview has the same shape).
    ///
    /// Only the session's claim types are kept. Each needs a readable, current
    /// value, and a value vetters were already shown must not have changed.
    ///
    /// # Errors
    ///
    /// No such session, a required claim missing, a value withheld or stale, or
    /// an identity that differs from the cards already sent.
    pub fn card_claims(
        &self,
        session_id: &str,
        released: &[ReleasedClaim],
    ) -> Result<Vec<session::v0_1::VettingCardClaim>, ApplicantError> {
        let (_, session) = self
            .session(session_id)
            .ok_or(ApplicantError::NoMatchingRequest)?;
        let wanted = |t: &str| {
            session.required_claims.iter().any(|r| r == t)
                || session.optional_claims.iter().any(|o| o == t)
        };
        let mut claims = Vec::new();
        for claim in released.iter().filter(|c| wanted(&c.claim_type)) {
            if claim.stale {
                return Err(ApplicantError::StaleClaim(claim.claim_type.clone()));
            }
            let Some(value) = claim.value.clone() else {
                return Err(ApplicantError::ValueWithheld(claim.claim_type.clone()));
            };
            if self
                .identity_claims
                .iter()
                .any(|shown| shown.type_.as_str() == claim.claim_type && shown.value != value)
            {
                return Err(ApplicantError::IdentityChanged(claim.claim_type.clone()));
            }
            claims.push(
                session::v0_1::VettingCardClaim::try_from(
                    session::v0_1::VettingCardClaim::builder()
                        .type_(claim.claim_type.as_str())
                        .value(value)
                        .provenance(
                            claim
                                .provenance
                                .clone()
                                .unwrap_or_else(|| "unstated".to_string()),
                        ),
                )
                .map_err(|e| ApplicantError::Shape(ShapeError::Schema(e.to_string())))?,
            );
        }
        if let Some(missing) = session
            .required_claims
            .iter()
            .find(|t| !claims.iter().any(|c| c.type_.as_str() == t.as_str()))
        {
            return Err(ApplicantError::MissingClaim(missing.clone()));
        }
        Ok(claims)
    }

    /// Record a card that has been sent into `session_id`, and remember the
    /// identity it showed so later cards show the same.
    ///
    /// # Errors
    ///
    /// No such session, or claims that differ from those already shown.
    pub fn record_sent_card(
        &mut self,
        session_id: &str,
        card: SentCard,
        claims: &[session::v0_1::VettingCardClaim],
        now: DateTime<Utc>,
    ) -> Result<(), ApplicantError> {
        if let Some(changed) = claims.iter().find(|c| {
            self.identity_claims
                .iter()
                .any(|shown| shown.type_.as_str() == c.type_.as_str() && shown.value != c.value)
        }) {
            return Err(ApplicantError::IdentityChanged(
                changed.type_.as_str().to_string(),
            ));
        }
        let request = self
            .requests
            .iter_mut()
            .find(|r| matches!(&r.state, RequestState::Session { session, .. } if session.id == session_id))
            .ok_or(ApplicantError::NoMatchingRequest)?;
        if let RequestState::Session { card: sent, .. } = &mut request.state {
            *sent = Some(card);
        }
        request.updated_at = now;
        for claim in claims {
            if !self
                .identity_claims
                .iter()
                .any(|shown| shown.type_.as_str() == claim.type_.as_str())
            {
                self.identity_claims.push(claim.clone());
            }
        }
        Ok(())
    }

    /// The card to sign for `session_id`, from the claims the applicant chose
    /// to disclose. Only the session's required and optional claim types are
    /// kept; the identity commitment covers the required ones.
    ///
    /// # Errors
    ///
    /// No such session, an expired one, or a required claim missing.
    pub fn card_draft(
        &self,
        session_id: &str,
        claims: Vec<session::v0_1::VettingCardClaim>,
        now: DateTime<Utc>,
    ) -> Result<CardDraft, ApplicantError> {
        let (vetter, session) = self
            .session(session_id)
            .ok_or(ApplicantError::NoMatchingRequest)?;
        if session.expires_at <= now {
            return Err(ApplicantError::SessionExpired);
        }
        let claims: Vec<session::v0_1::VettingCardClaim> = claims
            .into_iter()
            .filter(|c| {
                let wanted = |t: &String| t.as_str() == c.type_.as_str();
                session.required_claims.iter().any(wanted)
                    || session.optional_claims.iter().any(wanted)
            })
            .collect();
        if let Some(missing) = session
            .required_claims
            .iter()
            .find(|t| !claims.iter().any(|c| c.type_.as_str() == t.as_str()))
        {
            return Err(ApplicantError::MissingClaim(missing.clone()));
        }
        Ok(CardDraft {
            id: format!("urn:uuid:{}", Uuid::new_v4()),
            publisher: self.join_did.clone(),
            audience: vetter.to_string(),
            community: self.community.clone(),
            challenge: session.challenge.clone(),
            domain: session.domain.clone(),
            issued_at: now,
            validity: MAX_CARD_VALIDITY.min(session.expires_at - now),
            claims,
            identity_types: session.required_claims.clone(),
            salt: self.commitment_salt.clone(),
        })
    }

    /// Record the signed card we are sending into `session_id`. Verifies it the
    /// way the vetter will, so a card that would be refused never leaves.
    /// Returns what was recorded.
    ///
    /// # Errors
    ///
    /// No such session, or a card that does not verify.
    pub async fn record_card(
        &mut self,
        session_id: &str,
        card: &Value,
        resolver: &TrustTaskVmResolver,
        now: DateTime<Utc>,
    ) -> Result<SentCard, ApplicantError> {
        let join_did = self.join_did.clone();
        let community = self.community.clone();
        let request = self
            .requests
            .iter_mut()
            .find(|r| matches!(&r.state, RequestState::Session { session, .. } if session.id == session_id))
            .ok_or(ApplicantError::NoMatchingRequest)?;
        let RequestState::Session {
            session,
            card: sent,
            ..
        } = &mut request.state
        else {
            unreachable!("matched a session above");
        };
        let verified = verify_card(
            card,
            &CardExpectations {
                audience: &request.vetter,
                publisher: &join_did,
                community: &community,
                challenge: &session.challenge,
                domain: &session.domain,
                required_claims: &session.required_claims,
                now,
            },
            resolver,
        )
        .await?;
        let recorded = SentCard {
            id: verified.card().id.as_str().to_string(),
            digest_multibase: verified.digest_multibase().to_string(),
            identity_commitment: verified.card().identity_commitment.as_str().to_string(),
            sent_at: now,
        };
        *sent = Some(recorded.clone());
        request.updated_at = now;
        Ok(recorded)
    }

    /// A statement arrived from `vetter`. Verified and bound to this
    /// application — our join DID, this community, and the card we sent that
    /// vetter — before it is kept.
    ///
    /// # Errors
    ///
    /// A statement that does not verify, is about someone or something else,
    /// or answers no card of ours.
    pub async fn on_statement(
        &mut self,
        vetter: &str,
        credential: &Value,
        resolver: &TrustTaskVmResolver,
        now: DateTime<Utc>,
    ) -> Result<HeldStatement, ApplicantError> {
        let verified = verify_statement(credential, now, resolver).await?;
        if verified.issuer() != vetter {
            return Err(ApplicantError::Binding("issuer"));
        }
        if verified.subject() != self.join_did {
            return Err(ApplicantError::Binding("subject"));
        }
        let endorsement = verified.value();
        if endorsement.community != self.community {
            return Err(ApplicantError::Binding("community"));
        }
        if let Some(held) = self.statements.iter().find(|s| s.id == verified.id()) {
            return Ok(held.clone());
        }
        let request = self
            .requests
            .iter_mut()
            .find(|r| {
                r.vetter == vetter
                    && matches!(&r.state, RequestState::Session { session, .. }
                        if session.id == verified.task_context())
            })
            .ok_or(ApplicantError::NoMatchingRequest)?;
        let RequestState::Session {
            request_id,
            card,
            session,
        } = &request.state
        else {
            unreachable!("matched a session above");
        };
        // `vetted/1` REQUIRES the statement to cite the session by digest as
        // well as by id: an `id` locates the exchange, only the digest binds
        // the statement to the document we were actually shown.
        let document = session
            .document
            .as_ref()
            .ok_or(ApplicantError::Binding("taskDigestMultibase"))?;
        verified.check_against_session(document)?;
        let card = card
            .as_ref()
            .ok_or(ApplicantError::WrongState("take a statement before a card"))?;
        // A vetter's statement carries all three vetter-only members; one
        // without them (the community's own check) answers no request of ours.
        let members = endorsement
            .vetter_members()
            .ok_or(ApplicantError::Binding("identityCommitment"))?;
        if members.card_digest_multibase != card.digest_multibase {
            return Err(ApplicantError::Binding("cardDigestMultibase"));
        }
        if members.identity_commitment != card.identity_commitment {
            return Err(ApplicantError::Binding("identityCommitment"));
        }
        let held = HeldStatement {
            id: verified.id().to_string(),
            vetter: vetter.to_string(),
            method: endorsement.method,
            declared_relationship: members.declared_relationship,
            document_classes: endorsement
                .document_classes
                .iter()
                .map(|d| d.as_str().to_string())
                .collect(),
            claims_verified: endorsement
                .claims_verified
                .iter()
                .map(|c| c.as_str().to_string())
                .collect(),
            identity_commitment: members.identity_commitment.to_string(),
            valid_from: verified.valid_from(),
            valid_until: verified.valid_until(),
            received_at: now,
            credential: credential.clone(),
        };
        request.state = RequestState::Attested {
            request_id: request_id.clone(),
            statement_id: held.id.clone(),
        };
        request.updated_at = now;
        self.statements.push(held.clone());
        Ok(held)
    }

    /// The vetter declined (`vetting/decline`).
    ///
    /// # Errors
    ///
    /// A malformed decline, or one for a request this vetter never accepted.
    pub fn on_decline(
        &mut self,
        vetter: &str,
        body: decline::v0_1::Payload,
        now: DateTime<Utc>,
    ) -> Result<(), ApplicantError> {
        body.check_shape()?;
        let request = self.by_request_id(body.request_id.as_str(), vetter)?;
        if matches!(request.state, RequestState::Attested { .. }) {
            return Err(ApplicantError::WrongState("be declined after attesting"));
        }
        request.state = RequestState::Declined {
            code: body.code,
            message: body.message.map(|m| m.as_str().to_string()),
        };
        request.updated_at = now;
        Ok(())
    }

    /// Progress against the published requirements, as far as this client can
    /// tell. `None` until the requirements are known.
    #[must_use]
    pub fn checklist(&self, now: DateTime<Utc>) -> Option<Evaluation> {
        let requirements = self.requirements.as_ref()?;
        let facts: Vec<StatementFacts> = self
            .statements
            .iter()
            .filter(|s| s.valid_until > now)
            .map(|s| StatementFacts {
                statement_id: s.id.clone(),
                vetter: s.vetter.clone(),
                method: s.method,
                claims_verified: s.claims_verified.clone(),
                document_classes: s.document_classes.clone(),
                declared_relationship: s.declared_relationship,
                identity_commitment: s.identity_commitment.clone(),
                valid_from: s.valid_from,
                community_matches: true,
                // Only the community can say; see the module docs.
                eligible: true,
                revoked: false,
            })
            .collect();
        // Under a hidden criterion there are no named statements to count, and counting zero
        // would tell an applicant it had gathered nothing while it held three attestations.
        // The facts come from what those attestations bind instead.
        //
        // Each held attestation counts as one vetter. The applicant cannot check that for
        // itself — two attestations from the same vetter carry the same tag, and the tag is
        // inside the proof, deliberately out of reach here — so this is the applicant's own
        // estimate of its progress, and the community's count at submit is the authority. An
        // applicant that asked three different people will find the two agree.
        let facts = if facts.is_empty() && self.hidden_state.is_some() {
            self.hidden_facts(now)
        } else {
            facts
        };
        Some(evaluate(requirements, &facts, now))
    }

    /// The facts a hidden application's held attestations bind, for its own checklist.
    fn hidden_facts(&self, now: DateTime<Utc>) -> Vec<StatementFacts> {
        let Some(state) = self.hidden_state.as_ref() else {
            return Vec::new();
        };
        state
            .held
            .iter()
            .enumerate()
            .filter(|(_, held)| held.meta.valid_until >= now.date_naive())
            .map(|(i, held)| StatementFacts {
                statement_id: format!("hidden-{i}"),
                // An ordinal, never an identifier: the applicant holds no name for the vetter
                // here, and inventing a stable one is how a store becomes the link the
                // exchange removes.
                vetter: format!("hidden-vetter-{i}"),
                method: held.meta.method,
                claims_verified: held.meta.claims_verified.clone(),
                document_classes: Vec::new(),
                declared_relationship: held.meta.declared_relationship,
                identity_commitment: held.meta.identity_commitment.clone(),
                valid_from: held
                    .meta
                    .valid_from
                    .and_hms_opt(0, 0, 0)
                    .map_or(now, |d| d.and_utc()),
                community_matches: true,
                eligible: true,
                revoked: false,
            })
            .collect()
    }

    /// The statements to present with the join request.
    #[must_use]
    pub fn presentable_statements(&self, now: DateTime<Utc>) -> Vec<Value> {
        self.statements
            .iter()
            .filter(|s| s.valid_until > now)
            .map(|s| s.credential.clone())
            .collect()
    }

    /// The join submission's `extensions`: the digest of the requirements the
    /// statements were gathered against, so the community applies the same
    /// criterion, and — under a hidden-vetting criterion — the proof that `k`
    /// distinct vetters vetted this applicant.
    #[must_use]
    pub fn join_extensions(&self, protocol: super::protocol::JoinProtocol) -> Value {
        let mut members = serde_json::Map::new();
        // 0.2 names the criterion here. 0.3 names it in the submit's own
        // `criterion` member and no longer reads this one.
        if protocol == super::protocol::JoinProtocol::V0_2
            && let Some(digest) = &self.requirements_digest
        {
            members.insert(REQUIREMENTS_DIGEST_MEMBER.into(), json!(digest));
        }
        if let Some(hidden) = &self.hidden_submission {
            members.insert(super::hidden::EXTENSIONS_MEMBER.into(), hidden.clone());
        }
        if members.is_empty() {
            Value::Null
        } else {
            Value::Object(members)
        }
    }

    /// Record the proof this application will submit, built by
    /// [`super::hidden::prove`] against the attestations it holds.
    pub fn set_hidden_submission(&mut self, submission: Value) {
        self.hidden_submission = Some(submission);
    }

    /// Build the proof this application submits, from the attestations it holds.
    ///
    /// `Ok(false)` when this is not a hidden-vetting application, which is every application
    /// today. The proof is bound to `challenge`; the community rebuilds the same binding and
    /// refuses a proof built for another one.
    ///
    /// # Errors
    ///
    /// [`super::hidden::HiddenError`] when the application holds no usable attestation, or the
    /// community's published parameters cannot be read.
    pub fn prepare_hidden_submission(
        &mut self,
        challenge: &str,
    ) -> Result<bool, super::hidden::HiddenError> {
        let (Some(params), Some(state)) = (&self.hidden, &self.hidden_state) else {
            return Ok(false);
        };
        let digest = self.requirements_digest.clone().unwrap_or_default();
        let submission = super::hidden::prove(
            &self.community,
            params,
            &digest,
            state,
            challenge,
            &mut rand::rngs::OsRng,
        )?;
        self.hidden_submission = Some(submission);
        Ok(true)
    }

    /// Take an attestation a vetter sent under a hidden-vetting criterion.
    ///
    /// # Errors
    ///
    /// [`super::hidden::HiddenError`] if this is not a hidden-vetting application, or the
    /// attestation does not verify under the community's published parameters.
    pub fn receive_hidden_attestation(
        &mut self,
        attestation: &Value,
    ) -> Result<(), super::hidden::HiddenError> {
        let params = self.hidden.clone().ok_or_else(|| {
            super::hidden::HiddenError::Unreadable(
                "this application is not under a hidden-vetting criterion".into(),
            )
        })?;
        let state = self.hidden_state.as_mut().ok_or_else(|| {
            super::hidden::HiddenError::Unreadable("the application has no key yet".into())
        })?;
        super::hidden::receive(&self.community, &params, state, attestation)
    }

    /// The applicant's PCS identifier, which is what a vetter attests. `None` on the named
    /// path.
    #[must_use]
    pub fn hidden_id(&self) -> Option<&str> {
        self.hidden_state.as_ref().map(|s| s.id.as_str())
    }

    /// How many hidden attestations this application holds. Zero on the named path, where the
    /// count that matters is [`Self::presentable_statements`].
    #[must_use]
    pub fn hidden_held(&self) -> usize {
        self.hidden_state.as_ref().map_or(0, |s| s.held.len())
    }
}