datumesh-core 0.3.10

Datumesh protocol core: strict JSON and JCS, canonical forms, cell URIs, receipts, keys, envelopes and offline verification.
Documentation
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
//! Envelopes of `spec-0.4.2` (5.5-5.7): every outcome and trust label, the `fn_hash` echo, slice
//! pages and batches, checked and built.

use std::collections::BTreeMap;

use crate::descriptor::cmp_lexical;
use crate::envelope::{
    check_job_and_poll_for, env_err, integer_member, quote, EnvelopeExtras, Fault, ForeignDetail, Outcome, Overrides,
    Pending, Quote, Request, Resolution, ResolutionKind, Resolved, Shadows, Trust, BAD_REQUEST_CODES,
};
use crate::error::{Error, ErrorCode, Result};
use crate::json::{self, Value};
use crate::keys::Keys;
use crate::lexical::{self, limits};
use crate::model::{scalar_canonical, Arg, Cell, Scalar, Type};
use crate::receipt::Receipt;
use crate::schema;
use crate::slice::Slice;
use crate::Envelope;

/// The nine outcomes of SPEC 5.5 (`spec-0.4.2`), `pending` included.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum AnswerOutcome {
    /// 200.
    Ok,
    /// 200.
    Stale,
    /// 404.
    NotCovered,
    /// 403.
    Unlicensed,
    /// 402.
    PaymentRequired,
    /// 429.
    RateLimited,
    /// 400.
    BadRequest,
    /// 500-599.
    Error,
    /// 202.
    Pending,
    /// 200 (since `spec-0.6.0`): the answer to a `whatif` request, a scenario (5.9). Never a fact.
    Scenario,
}

impl AnswerOutcome {
    /// The outcome as written in JSON.
    pub const fn as_str(self) -> &'static str {
        match self {
            AnswerOutcome::Ok => "ok",
            AnswerOutcome::Stale => "stale",
            AnswerOutcome::NotCovered => "not_covered",
            AnswerOutcome::Unlicensed => "unlicensed",
            AnswerOutcome::PaymentRequired => "payment_required",
            AnswerOutcome::RateLimited => "rate_limited",
            AnswerOutcome::BadRequest => "bad_request",
            AnswerOutcome::Error => "error",
            AnswerOutcome::Pending => "pending",
            AnswerOutcome::Scenario => "scenario",
        }
    }

    /// The outcome of its JSON name.
    pub fn from_name(s: &str) -> Option<AnswerOutcome> {
        Some(match s {
            "ok" => AnswerOutcome::Ok,
            "stale" => AnswerOutcome::Stale,
            "not_covered" => AnswerOutcome::NotCovered,
            "unlicensed" => AnswerOutcome::Unlicensed,
            "payment_required" => AnswerOutcome::PaymentRequired,
            "rate_limited" => AnswerOutcome::RateLimited,
            "bad_request" => AnswerOutcome::BadRequest,
            "error" => AnswerOutcome::Error,
            "pending" => AnswerOutcome::Pending,
            "scenario" => AnswerOutcome::Scenario,
            _ => return None,
        })
    }

    /// The HTTP status a mesh sends with it (500 for `error`, whose exact 5xx is the mesh's).
    pub const fn status(self) -> u16 {
        match self {
            AnswerOutcome::Ok | AnswerOutcome::Stale => 200,
            AnswerOutcome::NotCovered => 404,
            AnswerOutcome::Unlicensed => 403,
            AnswerOutcome::PaymentRequired => 402,
            AnswerOutcome::RateLimited => 429,
            AnswerOutcome::BadRequest => 400,
            AnswerOutcome::Error => 500,
            AnswerOutcome::Pending => 202,
            AnswerOutcome::Scenario => 200,
        }
    }

    fn status_ok(self, status: u16) -> bool {
        match self {
            AnswerOutcome::Error => (500..=599).contains(&status),
            other => other.status() == status,
        }
    }

    fn members(self) -> (&'static [&'static str], &'static [&'static str]) {
        match self {
            AnswerOutcome::Ok => {
                (&["receipt", "trust"], &["superseded_by", "reason", "fn_hash", "resolved", "shadows"])
            }
            AnswerOutcome::Stale => {
                (&["receipt", "trust", "age_seconds"], &["superseded_by", "reason", "fn_hash", "resolved", "shadows"])
            }
            AnswerOutcome::NotCovered => (&[], &["fault", "error", "fn_hash", "resolved", "shadows"]),
            AnswerOutcome::Unlicensed => (&[], &["fn_hash", "resolved", "shadows"]),
            AnswerOutcome::PaymentRequired => (&["quote"], &["fn_hash", "resolved", "shadows"]),
            AnswerOutcome::RateLimited => (&["retry_after_seconds"], &["fn_hash"]),
            AnswerOutcome::BadRequest => (&["error"], &["fn_hash"]),
            // spec-0.4.3: detail, with E_FOREIGN_UNAVAILABLE only.
            // spec-0.6.0: cycle, with E_EVAL_UNAVAILABLE only.
            AnswerOutcome::Error => (&["error"], &["cycle", "detail", "fn_hash", "resolved", "shadows"]),
            AnswerOutcome::Pending => (&["estimate_seconds", "job", "poll", "request"], &[]),
            AnswerOutcome::Scenario => (&["scenario"], &["fn_hash", "resolved"]),
        }
    }
}

/// The four trust labels of SPEC 5.5 (`spec-0.4.2`), `computed` included.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum TrustLabel {
    /// The publisher answered from its own records.
    Primary,
    /// Not primary; the mesh asked evaluated the cell and signed the receipt itself.
    Computed,
    /// Not primary, signed by another host, and the mesh recomputed it.
    Verified,
    /// Not primary, signed by another host, not recomputed.
    Unverified,
    /// The publisher's host signed a stored receipt that has a `source` (5.5, `spec-0.6.0`): a
    /// value the publisher took from another party. Not `computed`, never `primary`.
    Relayed,
}

impl TrustLabel {
    /// The label as written in JSON.
    pub const fn as_str(self) -> &'static str {
        match self {
            TrustLabel::Primary => "primary",
            TrustLabel::Computed => "computed",
            TrustLabel::Verified => "verified",
            TrustLabel::Unverified => "unverified",
            TrustLabel::Relayed => "relayed",
        }
    }

    fn from_name(s: &str) -> Option<TrustLabel> {
        Some(match s {
            "primary" => TrustLabel::Primary,
            "computed" => TrustLabel::Computed,
            "verified" => TrustLabel::Verified,
            "unverified" => TrustLabel::Unverified,
            "relayed" => TrustLabel::Relayed,
            _ => return None,
        })
    }
}

/// A slice page (5.6): the `ok` answer of the slice endpoint.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct SlicePage {
    /// The slice object requested, with the function hash its name resolved to (or the pin).
    pub slice: Slice,
    /// The member envelopes, `ok` or `stale`, in ascending key order.
    pub members: Vec<Answer>,
    /// The URL of the following page; `None` on the last.
    pub next: Option<String>,
}

impl SlicePage {
    /// A page of `members` of `slice`, with `next` when there is a following page. Not checked
    /// until written and checked back.
    pub fn new(slice: Slice, members: Vec<Answer>, next: Option<String>) -> SlicePage {
        SlicePage { slice, members, next }
    }
}

/// An envelope of `spec-0.4.2` (5.5), checked or to be written: every outcome, trust label and
/// member, with a slice page (5.6) for the `ok` answer of the slice endpoint; since 0.3.7
/// (`spec-0.4.3`) also `E_FOREIGN_UNAVAILABLE` with its `detail` ([`Answer::foreign_unavailable`]). As a builder: one
/// constructor per outcome, `with_*` for the optional members, [`Answer::to_json`] for the body
/// and [`Answer::status`] for the HTTP status; check the body back with [`check_answer`] (or
/// [`check_slice_answer`]) to hold it to every rule.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Answer {
    /// The outcome.
    pub outcome: AnswerOutcome,
    /// The receipt (`ok`, `stale`; not a slice page's).
    pub receipt: Option<Receipt>,
    /// The trust label (`ok`, `stale`).
    pub trust: Option<TrustLabel>,
    /// Seconds since the mesh last confirmed the receipt (`stale`).
    pub age_seconds: Option<u64>,
    /// Hash of a newer receipt for the same cell.
    pub superseded_by: Option<String>,
    /// Why the receipt was superseded.
    pub reason: Option<String>,
    /// The quote (`payment_required`).
    pub quote: Option<Quote>,
    /// Seconds to wait (`rate_limited`).
    pub retry_after_seconds: Option<u64>,
    /// The code (`bad_request`, `error`, and `E_NAME_UNBOUND` in `not_covered`).
    pub error: Option<ErrorCode>,
    /// The formula evaluation fault (`not_covered`).
    pub fault: Option<Fault>,
    /// What failed in reaching a foreign mesh: with `E_FOREIGN_UNAVAILABLE` only, and always
    /// with it (`error`, 502; `spec-0.4.3`).
    pub detail: Option<ForeignDetail>,
    /// The function the answer is of: a pin's echo, or the hash the name resolved to.
    pub fn_hash: Option<String>,
    /// The `pending` envelope's members.
    pub pending: Option<Pending>,
    /// The slice page (`ok` at the slice endpoint).
    pub page: Option<SlicePage>,
    /// What a short call resolved (`ok`, `stale`, `not_covered`, `unlicensed`,
    /// `payment_required`, `error`; 5.5, `spec-0.5.0`).
    pub resolved: Option<Resolved>,
    /// The class this mesh binds to another hash than its reference class (the same outcomes as
    /// `resolved`; 5.5, 16.9, `spec-0.5.0`).
    pub shadows: Option<Shadows>,
    /// The scenario of a `whatif` request (`scenario`, 5.9, `spec-0.6.0`).
    pub scenario: Option<Scenario>,
    /// The path of an evaluation cycle (`error` with `E_EVAL_UNAVAILABLE`, 5.5, `spec-0.6.0`).
    pub cycle: Option<Cycle>,
    /// The HTTP status to send (`error`'s exact 5xx); checked answers carry the one received.
    status: u16,
}

fn bare(outcome: AnswerOutcome) -> Answer {
    Answer {
        outcome,
        receipt: None,
        trust: None,
        age_seconds: None,
        superseded_by: None,
        reason: None,
        quote: None,
        retry_after_seconds: None,
        error: None,
        fault: None,
        detail: None,
        fn_hash: None,
        pending: None,
        page: None,
        resolved: None,
        shadows: None,
        scenario: None,
        cycle: None,
        status: outcome.status(),
    }
}

fn code_allowed(outcome: AnswerOutcome, code: ErrorCode, job_url: bool) -> bool {
    match outcome {
        AnswerOutcome::BadRequest => {
            BAD_REQUEST_CODES.contains(&code)
                || matches!(
                    code,
                    ErrorCode::CanonHex
                        | ErrorCode::SliceAtCell
                        | ErrorCode::ShortIdAmbiguous
                        | ErrorCode::KeyNormalisation
                        | ErrorCode::KeyEncoding
                )
                || (code == ErrorCode::JobUnknown && job_url)
                // spec-0.6.0: the whatif codes, in a whatif request only (checked by the caller).
                || matches!(code, ErrorCode::WhatifUnsupported | ErrorCode::SliceMember)
        }
        AnswerOutcome::NotCovered => matches!(code, ErrorCode::NameUnbound | ErrorCode::NamespaceSuspended),
        // 5.5 (spec-0.5.0): every code of 10.2 but exactly these. The define and write codes are
        // never in a read envelope; the class codes are define's, E_DESCRIBE a client's, and the
        // two key codes are `bad_request`'s when a call raises them.
        AnswerOutcome::Error => !matches!(
            code,
            ErrorCode::Envelope
                | ErrorCode::JobUnknown
                | ErrorCode::SliceAtCell
                | ErrorCode::NameUnbound
                | ErrorCode::KeyNormalisation
                | ErrorCode::KeyEncoding
                | ErrorCode::UnrootedInput
                | ErrorCode::NamespaceSuspended
                | ErrorCode::ClassMember
                | ErrorCode::ClassParent
                | ErrorCode::ClassInherit
                | ErrorCode::ClassOverride
                | ErrorCode::ClassFinal
                | ErrorCode::ClassMethod
                | ErrorCode::ClassInterface
                | ErrorCode::ClassOwner
                | ErrorCode::ShortIdAmbiguous
                | ErrorCode::Describe
                // spec-0.6.0: the two whatif codes are a bad_request's and a not_covered
                // fault's, never an error's (5.5; the 10.2 table's "whatif" codes).
                | ErrorCode::WhatifUnsupported
                | ErrorCode::WhatifNoSolution
        ),
        _ => false,
    }
}

impl Answer {
    /// `ok` (200): `receipt`, served with `trust`.
    pub fn ok(receipt: Receipt, trust: TrustLabel) -> Answer {
        Answer { receipt: Some(receipt), trust: Some(trust), ..bare(AnswerOutcome::Ok) }
    }

    /// `stale` (200): the last receipt known, last confirmed `age_seconds` ago.
    pub fn stale(receipt: Receipt, trust: TrustLabel, age_seconds: u64) -> Answer {
        Answer {
            receipt: Some(receipt),
            trust: Some(trust),
            age_seconds: Some(age_seconds),
            ..bare(AnswerOutcome::Stale)
        }
    }

    /// `not_covered` (404).
    pub fn not_covered() -> Answer {
        bare(AnswerOutcome::NotCovered)
    }

    /// `unlicensed` (403).
    pub fn unlicensed() -> Answer {
        bare(AnswerOutcome::Unlicensed)
    }

    /// `payment_required` (402) with its quote.
    pub fn payment_required(quote: Quote) -> Answer {
        Answer { quote: Some(quote), ..bare(AnswerOutcome::PaymentRequired) }
    }

    /// `rate_limited` (429): retry after this many seconds.
    pub fn rate_limited(retry_after_seconds: u64) -> Answer {
        Answer { retry_after_seconds: Some(retry_after_seconds), ..bare(AnswerOutcome::RateLimited) }
    }

    /// `bad_request` (400) with a code it can carry (5.5: a parse code, `E_CANON_HEX`,
    /// `E_SLICE_AT_CELL`, `E_SHORT_ID_AMBIGUOUS`, `E_KEY_NORMALISATION` or `E_KEY_ENCODING`
    /// (since `spec-0.5.0`), or `E_JOB_UNKNOWN` at a job URL); `E_ENVELOPE` otherwise.
    pub fn bad_request(code: ErrorCode) -> Result<Answer> {
        if !code_allowed(AnswerOutcome::BadRequest, code, true) {
            return env_err("$.error", format!("bad_request cannot carry {code}"));
        }
        Ok(Answer { error: Some(code), ..bare(AnswerOutcome::BadRequest) })
    }

    /// `error` (500; see [`Answer::with_status`]) with a code it can carry (any of 10.2 but
    /// the codes 5.5 refuses in an `error` envelope: `E_ENVELOPE`, `E_DESCRIBE`, the request
    /// codes, the define and write codes and the class codes, since `spec-0.5.0`).
    /// `E_FOREIGN_UNAVAILABLE` needs a `detail` and HTTP 502: build it with
    /// [`Answer::foreign_unavailable`] (here it is `E_ENVELOPE`).
    pub fn error(code: ErrorCode) -> Result<Answer> {
        if !code_allowed(AnswerOutcome::Error, code, false) {
            return env_err("$.error", format!("error cannot carry {code}"));
        }
        if code == ErrorCode::ForeignUnavailable {
            return env_err("$.detail", "E_FOREIGN_UNAVAILABLE needs a detail: Answer::foreign_unavailable");
        }
        Ok(Answer { error: Some(code), ..bare(AnswerOutcome::Error) })
    }

    /// `error` with `E_FOREIGN_UNAVAILABLE` and `detail` (5.5, `spec-0.4.3`), HTTP 502: the cell
    /// belongs to another mesh, which could not be reached. Answered by a resolver, or by a mesh
    /// fetching across meshes, when no HTTP response came back from the foreign host. Its
    /// status must stay 502 ([`Answer::with_status`] to another fails [`check_answer`]).
    pub fn foreign_unavailable(detail: ForeignDetail) -> Answer {
        Answer {
            error: Some(ErrorCode::ForeignUnavailable),
            detail: Some(detail),
            status: 502,
            ..bare(AnswerOutcome::Error)
        }
    }

    /// `pending` (202).
    pub fn pending(p: Pending) -> Answer {
        Answer { pending: Some(p), ..bare(AnswerOutcome::Pending) }
    }

    /// The `ok` answer of the slice endpoint (5.6).
    pub fn page(page: SlicePage) -> Answer {
        Answer { page: Some(page), ..bare(AnswerOutcome::Ok) }
    }

    /// `scenario` (200, 5.9, `spec-0.6.0`): the answer to a `whatif` request. It has no receipt
    /// and no trust; [`check_answer`] accepts it only for a request with overrides.
    pub fn scenario(scenario: Scenario) -> Answer {
        Answer { scenario: Some(scenario), ..bare(AnswerOutcome::Scenario) }
    }

    /// With the `cycle` member (5.5, `spec-0.6.0`): only on `error` with `E_EVAL_UNAVAILABLE`;
    /// `E_ENVELOPE` otherwise.
    pub fn with_cycle(self, cycle: Cycle) -> Result<Answer> {
        if self.outcome != AnswerOutcome::Error || self.error != Some(ErrorCode::EvalUnavailable) {
            return env_err("$.cycle", "cycle is carried by error with E_EVAL_UNAVAILABLE only");
        }
        Ok(Answer { cycle: Some(cycle), ..self })
    }

    /// With the `fn_hash` echo (64 lowercase hex digits; not on `pending`); `E_ENVELOPE`
    /// otherwise.
    pub fn with_fn_hash(self, fn_hash: &str) -> Result<Answer> {
        if self.outcome == AnswerOutcome::Pending || lexical::check_hex(fn_hash, 64, "").is_err() {
            return env_err("$.fn_hash", "fn_hash is 64 lowercase hex digits, not on pending");
        }
        Ok(Answer { fn_hash: Some(fn_hash.into()), ..self })
    }

    /// A `not_covered` answer with a formula evaluation fault. Not checked here: a fault with
    /// `error`, or on another outcome, fails [`check_answer`].
    pub fn with_fault(self, fault: Fault) -> Answer {
        Answer { fault: Some(fault), ..self }
    }

    /// A `not_covered` answer with `error` (only `E_NAME_UNBOUND`, and not with a fault);
    /// `E_ENVELOPE` otherwise.
    pub fn with_error(self, code: ErrorCode) -> Result<Answer> {
        if self.outcome != AnswerOutcome::NotCovered || self.fault.is_some() || !code_allowed(self.outcome, code, false)
        {
            return env_err("$.error", "not_covered carries E_NAME_UNBOUND or E_NAMESPACE_SUSPENDED, not with a fault");
        }
        Ok(Answer { error: Some(code), ..self })
    }

    /// With the `resolved` member (`spec-0.5.0`): allowed on `ok`, `stale`, `not_covered`,
    /// `unlicensed`, `payment_required` and `error`; `E_ENVELOPE` on `rate_limited`,
    /// `bad_request` and `pending`.
    pub fn with_resolved(self, resolved: Resolved) -> Result<Answer> {
        if !outcome_has_resolved(self.outcome) {
            return env_err("$.resolved", format!("{} carries no resolved", self.outcome.as_str()));
        }
        Ok(Answer { resolved: Some(resolved), ..self })
    }

    /// With the `shadows` member (`spec-0.5.0`), on the same outcomes as
    /// [`with_resolved`](Self::with_resolved); `E_ENVELOPE` otherwise.
    pub fn with_shadows(self, shadows: Shadows) -> Result<Answer> {
        if !outcome_has_resolved(self.outcome) {
            return env_err("$.shadows", format!("{} carries no shadows", self.outcome.as_str()));
        }
        Ok(Answer { shadows: Some(shadows), ..self })
    }

    /// An `ok` or `stale` answer pointing to a newer receipt, with an optional reason.
    pub fn with_superseded(self, superseded_by: &str, reason: Option<&str>) -> Answer {
        Answer { superseded_by: Some(superseded_by.into()), reason: reason.map(String::from), ..self }
    }

    /// The HTTP status to send, for an `error` within 500-599 (other outcomes have one status).
    pub fn with_status(self, status: u16) -> Answer {
        Answer { status, ..self }
    }

    /// The HTTP status: the outcome's, or for a checked answer the one received.
    pub fn status(&self) -> u16 {
        self.status
    }

    /// The JSON form of the envelope.
    pub fn to_value(&self) -> Value {
        if let Some(p) = &self.pending {
            return p.to_value();
        }
        let mut m: Vec<(String, Value)> = vec![("outcome".into(), Value::String(self.outcome.as_str().into()))];
        let s = |x: &str| Value::String(x.into());
        let n = |x: u64| json::parse(x.to_string().as_bytes()).unwrap_or(Value::Null);
        if let Some(r) = &self.receipt {
            m.push(("receipt".into(), receipt_value(r)));
        }
        if let Some(t) = self.trust {
            m.push(("trust".into(), s(t.as_str())));
        }
        if let Some(a) = self.age_seconds {
            m.push(("age_seconds".into(), n(a)));
        }
        if let Some(x) = &self.superseded_by {
            m.push(("superseded_by".into(), s(x)));
        }
        if let Some(x) = &self.reason {
            m.push(("reason".into(), s(x)));
        }
        if let Some(q) = &self.quote {
            m.push((
                "quote".into(),
                Value::Object(vec![
                    ("amount".into(), s(&q.amount)),
                    ("authorise".into(), s(&q.authorise)),
                    ("currency".into(), s(&q.currency)),
                ]),
            ));
        }
        if let Some(a) = self.retry_after_seconds {
            m.push(("retry_after_seconds".into(), n(a)));
        }
        if let Some(e) = self.error {
            m.push(("error".into(), s(e.as_str())));
        }
        if let Some(f) = self.fault {
            m.push(("fault".into(), s(f.as_str())));
        }
        if let Some(d) = self.detail {
            m.push(("detail".into(), s(d.as_str())));
        }
        if let Some(h) = &self.fn_hash {
            m.push(("fn_hash".into(), s(h)));
        }
        if let Some(r) = &self.resolved {
            let mut rm = vec![
                ("call".to_string(), s(&r.call)),
                (
                    "resolutions".to_string(),
                    Value::Array(
                        r.resolutions
                            .iter()
                            .map(|x| {
                                let mut xm = vec![
                                    ("from".to_string(), s(&x.from)),
                                    ("kind".to_string(), s(x.kind.as_str())),
                                    ("to".to_string(), s(&x.to)),
                                ];
                                if let Some(a) = &x.asof {
                                    xm.push(("asof".into(), s(a)));
                                }
                                Value::Object(xm)
                            })
                            .collect(),
                    ),
                ),
            ];
            if let Some(t) = &r.aliases_tx {
                rm.push(("aliases_tx".into(), s(t)));
            }
            m.push(("resolved".into(), Value::Object(rm)));
        }
        if let Some(sh) = &self.shadows {
            m.push((
                "shadows".into(),
                Value::Object(vec![("class".into(), s(&sh.class)), ("reference".into(), s(&sh.reference))]),
            ));
        }
        if let Some(sc) = &self.scenario {
            m.push(("scenario".into(), sc.to_value()));
        }
        if let Some(c) = &self.cycle {
            m.push(("cycle".into(), c.to_value()));
        }
        if let Some(p) = &self.page {
            m.push(("slice".into(), p.slice.to_value()));
            m.push(("members".into(), Value::Array(p.members.iter().map(Answer::to_value).collect())));
            if let Some(x) = &p.next {
                m.push(("next".into(), s(x)));
            }
        }
        Value::Object(m)
    }

    /// The envelope's body: its canonical JSON text (JCS).
    pub fn to_json(&self) -> Vec<u8> {
        self.to_value().to_jcs()
    }

    /// The `spec-0.4.1` form, for the 0.3.x functions: not `pending`, not `computed`.
    pub(crate) fn into_envelope(self) -> Result<(Envelope, EnvelopeExtras)> {
        // spec-0.6.0 members are read by check_answer only: the 0.3.x envelope refuses them.
        if self.cycle.is_some() {
            return env_err("$.cycle", "cycle is read by check_answer");
        }
        let outcome = match self.outcome {
            AnswerOutcome::Ok => Outcome::Ok,
            AnswerOutcome::Stale => Outcome::Stale,
            AnswerOutcome::NotCovered => Outcome::NotCovered,
            AnswerOutcome::Unlicensed => Outcome::Unlicensed,
            AnswerOutcome::PaymentRequired => Outcome::PaymentRequired,
            AnswerOutcome::RateLimited => Outcome::RateLimited,
            AnswerOutcome::BadRequest => Outcome::BadRequest,
            AnswerOutcome::Error => Outcome::Error,
            AnswerOutcome::Pending => return env_err("$.outcome", "unknown outcome \"pending\""),
            AnswerOutcome::Scenario => return env_err("$.outcome", "unknown outcome \"scenario\""),
        };
        let trust = match self.trust {
            None => None,
            Some(TrustLabel::Primary) => Some(Trust::Primary),
            Some(TrustLabel::Verified) => Some(Trust::Verified),
            Some(TrustLabel::Unverified) => Some(Trust::Unverified),
            Some(_) => return env_err("$.trust", "trust is primary, verified or unverified"),
        };
        let env = Envelope {
            outcome,
            receipt: self.receipt,
            trust,
            age_seconds: self.age_seconds,
            superseded_by: self.superseded_by,
            reason: self.reason,
            quote: self.quote,
            retry_after_seconds: self.retry_after_seconds,
            error: self.error,
        };
        Ok((env, EnvelopeExtras { fault: self.fault, fn_hash: self.fn_hash, detail: self.detail }))
    }
}

fn receipt_value(r: &Receipt) -> Value {
    let mut members = json::parse(r.payload()).ok().and_then(|v| v.as_object().map(<[_]>::to_vec)).unwrap_or_default();
    members.push(("sig".into(), Value::String(r.sig().into())));
    Value::Object(members)
}

/// What an envelope is checked against: a cell request, the slice endpoint's request, or
/// nothing (a batch's refusal).
enum Ctx<'a> {
    Cell(&'a Request),
    Slice(&'a SliceRequest),
    None,
}

impl Ctx<'_> {
    fn pin(&self) -> Option<&str> {
        match self {
            Ctx::Cell(r) => r.pin.as_deref(),
            Ctx::Slice(s) => s.pin.as_deref(),
            Ctx::None => None,
        }
    }

    fn mesh(&self) -> Option<&str> {
        match self {
            Ctx::Cell(r) => r.mesh.as_deref(),
            Ctx::Slice(s) => s.mesh.as_deref(),
            Ctx::None => None,
        }
    }

    fn job_url(&self) -> bool {
        matches!(self, Ctx::Cell(r) if r.job.is_some())
    }

    /// A `whatif` request: one with overrides (5.9, `spec-0.6.0`).
    fn whatif(&self) -> bool {
        matches!(self, Ctx::Cell(r) if r.overrides.is_some())
    }

    fn solve(&self) -> Option<&str> {
        match self {
            Ctx::Cell(r) => r.solve.as_deref(),
            _ => None,
        }
    }
}

/// The whatif codes a `bad_request` carries only in a whatif request (5.5, 5.9): with
/// `E_WHATIF_UNSUPPORTED`, a request with `solve`; with `E_SLICE_MEMBER`, one with overrides.
fn whatif_code_ok(outcome: AnswerOutcome, code: ErrorCode, ctx: &Ctx<'_>) -> bool {
    match (outcome, code) {
        (AnswerOutcome::BadRequest, ErrorCode::WhatifUnsupported) => ctx.solve().is_some(),
        (AnswerOutcome::BadRequest, ErrorCode::SliceMember) => ctx.whatif(),
        _ => true,
    }
}

/// Checks an envelope (5.5) answering a `/cell` request or a job URL, of any outcome and trust
/// label, in the order of 5.5: strict JSON, members, HTTP status, the receipt through step 6 of
/// 10.1, the binding to `request` (cell id, `asof`, the pin and its echo, the echoed request
/// and job of `pending`), then `trust` (with `computed` against the signer and `poll` against
/// the host when `request` names the mesh asked) and `superseded_by`. Never touches the
/// network.
pub fn check_answer(status: u16, body: &[u8], keys: &Keys, request: &Request) -> Result<Answer> {
    let v = json::parse(body)?;
    check_value(status, &v, keys, &Ctx::Cell(request), "$")
}

/// A slice request (5.6): the slice id asked for, the `asof`, the pin, the host asked, and for
/// a following page the key of the last member received (`after`).
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct SliceRequest {
    slice_id: String,
    asof: Option<String>,
    pin: Option<String>,
    mesh: Option<String>,
    after: Option<BTreeMap<String, Scalar>>,
}

impl SliceRequest {
    /// A request for the slice with id `slice_id` (64 lowercase hex digits) as of `asof` (an
    /// instant) or now; anything else is [`crate::InvalidRequest`].
    pub fn new(slice_id: &str, asof: Option<&str>) -> core::result::Result<SliceRequest, crate::InvalidRequest> {
        let r = Request::new(slice_id, asof)?;
        Ok(SliceRequest { slice_id: r.cell_id, asof: r.asof, pin: None, mesh: None, after: None })
    }

    /// Pinned to `fn_hash` (64 lowercase hex digits).
    pub fn with_pin(self, fn_hash: &str) -> core::result::Result<SliceRequest, crate::InvalidRequest> {
        let r = Request::new(&self.slice_id, None)?.with_pin(fn_hash)?;
        Ok(SliceRequest { pin: r.pin, ..self })
    }

    /// Naming the host asked (a DNS name): `next` and `computed` are then checked against it.
    pub fn with_mesh(self, host: &str) -> core::result::Result<SliceRequest, crate::InvalidRequest> {
        let r = Request::new(&self.slice_id, None)?.with_mesh(host)?;
        Ok(SliceRequest { mesh: r.mesh, ..self })
    }

    /// For a following page: the key of the last member received, from each open argument's
    /// name to its value. Other names are ignored; a cursor lacking an open argument, or whose
    /// value has another type than the members' key, cannot be ordered against (`E_ENVELOPE`
    /// from [`check_slice_answer`]).
    pub fn with_after(self, after: BTreeMap<String, Scalar>) -> SliceRequest {
        SliceRequest { after: Some(after), ..self }
    }

    /// The slice id asked for.
    pub fn slice_id(&self) -> &str {
        &self.slice_id
    }

    /// The `asof` asked for.
    pub fn asof(&self) -> Option<&str> {
        self.asof.as_deref()
    }

    /// The pin.
    pub fn fn_hash(&self) -> Option<&str> {
        self.pin.as_deref()
    }

    /// The host asked.
    pub fn mesh(&self) -> Option<&str> {
        self.mesh.as_deref()
    }

    /// The key after which this page's members come.
    pub fn after(&self) -> Option<&BTreeMap<String, Scalar>> {
        self.after.as_ref()
    }
}

/// Checks an answer of the slice endpoint (5.6) against `request`: `stale` and `pending` are
/// not answers there; `ok` is a page, checked as 5.6 says (its members, the slice id, `next`,
/// then each member's receipt through step 6 of 10.1, membership, `asof`, trust and key order
/// after `after`); every other outcome as in 5.5.
pub fn check_slice_answer(status: u16, body: &[u8], keys: &Keys, request: &SliceRequest) -> Result<Answer> {
    let v = json::parse(body)?;
    check_value(status, &v, keys, &Ctx::Slice(request), "$")
}

/// The answer to a batch (5.7).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Batch {
    /// 200: one result per request, in request order; a failing item is its error, in place.
    Items(Vec<Result<Answer>>),
    /// The whole batch refused: one envelope (`unlicensed`, `payment_required`, `rate_limited`,
    /// `bad_request` or `error`).
    Refused(Box<Answer>),
}

/// Checks the answer to a batch (5.7) of `requests`: for 200, an array with one
/// `{envelope, status}` per request (`status` an integer 100-599), else `E_ENVELOPE` for the
/// whole; then each item as an envelope (5.5) with its status against its own request, a
/// failing item reported in its place. Any other status is one envelope of a refusal outcome,
/// with nothing to bind.
pub fn check_batch(status: u16, body: &[u8], keys: &Keys, requests: &[Request]) -> Result<Batch> {
    let v = json::parse(body)?;
    if status != 200 {
        if !matches!(v, Value::Object(_)) {
            return env_err("$", "a refused batch is one envelope");
        }
        let a = check_value(status, &v, keys, &Ctx::None, "$")?;
        if !matches!(
            a.outcome,
            AnswerOutcome::Unlicensed
                | AnswerOutcome::PaymentRequired
                | AnswerOutcome::RateLimited
                | AnswerOutcome::BadRequest
                | AnswerOutcome::Error
        ) {
            return env_err(
                "$.outcome",
                "a batch is refused with unlicensed, payment_required, rate_limited, bad_request or error",
            );
        }
        return Ok(Batch::Refused(Box::new(a)));
    }
    let Value::Array(items) = &v else { return env_err("$", "a batch answer is an array") };
    if items.len() != requests.len() {
        return env_err("$", format!("{} items for {} requests", items.len(), requests.len()));
    }
    let mut parts = Vec::with_capacity(items.len());
    for (i, item) in items.iter().enumerate() {
        let p = format!("$[{i}]");
        let m = schema::object_or(item, &p, ErrorCode::Envelope, "an item")?;
        schema::exact(m, &["envelope", "status"], &[], &p, ErrorCode::Envelope)?;
        let st = integer_member(schema::get(m, "status"), &format!("{p}.status"))?;
        if !(100..=599).contains(&st) {
            return env_err(&format!("{p}.status"), "an item's status is 100-599");
        }
        parts.push((schema::get(m, "envelope"), st as u16));
    }
    Ok(Batch::Items(
        parts
            .into_iter()
            .zip(requests)
            .enumerate()
            .map(|(i, ((env, st), req))| check_value(st, env, keys, &Ctx::Cell(req), &format!("$[{i}].envelope")))
            .collect(),
    ))
}

/// A batch answer's body (5.7): one `{envelope, status}` per answer, in order.
pub fn batch_body(items: &[(u16, Answer)]) -> Vec<u8> {
    let n = |x: u16| json::parse(x.to_string().as_bytes()).unwrap_or(Value::Null);
    Value::Array(
        items
            .iter()
            .map(|(st, a)| Value::Object(vec![("envelope".into(), a.to_value()), ("status".into(), n(*st))]))
            .collect(),
    )
    .to_jcs()
}

fn nested(e: Error, prefix: &str) -> Error {
    if prefix == "$" {
        return e;
    }
    let inner = e.path().strip_prefix('$').unwrap_or(e.path());
    Error::new(e.code(), format!("{prefix}{inner}"), e.detail())
}

fn check_value(status: u16, v: &Value, keys: &Keys, ctx: &Ctx<'_>, at: &str) -> Result<Answer> {
    check_inner(status, v, keys, ctx).map_err(|e| nested(e, at))
}

/// A URL `https://<DNS name>/<path>` of printable ASCII, at most 512 characters.
fn url_host(u: &str) -> Option<&str> {
    let rest = u.strip_prefix("https://")?;
    if u.len() > limits::LICENCE_URL || !rest.bytes().all(|c| (0x21..=0x7E).contains(&c)) {
        return None;
    }
    let (host, _) = rest.split_once('/')?;
    lexical::check_dns_name(host, "").ok().map(|()| host)
}

fn check_inner(status: u16, v: &Value, keys: &Keys, ctx: &Ctx<'_>) -> Result<Answer> {
    // 2.
    let m = match v {
        Value::Object(m) if matches!(schema::opt(m, "outcome"), Some(Value::String(_))) => m,
        _ => return env_err("$", "an envelope is an object with a string outcome"),
    };
    let oname = schema::get(m, "outcome").as_str().unwrap_or("");
    let Some(outcome) = AnswerOutcome::from_name(oname) else {
        return env_err("$.outcome", format!("unknown outcome {oname:?}"));
    };
    let slice_ctx = matches!(ctx, Ctx::Slice(_));
    if slice_ctx && matches!(outcome, AnswerOutcome::Stale | AnswerOutcome::Pending) {
        return env_err("$.outcome", "stale and pending are not answers of the slice endpoint");
    }
    // 5.9 (spec-0.6.0): with overrides, ok, stale and pending are not answers; scenario is only
    // an answer to a request with overrides.
    let whatif = ctx.whatif();
    if whatif && matches!(outcome, AnswerOutcome::Ok | AnswerOutcome::Stale | AnswerOutcome::Pending) {
        return env_err("$.outcome", format!("{oname} is not an answer to a whatif request"));
    }
    if outcome == AnswerOutcome::Scenario && !whatif {
        return env_err("$.outcome", "scenario is the answer to a request with overrides");
    }
    if outcome == AnswerOutcome::Pending {
        return check_pending(status, m, ctx);
    }
    let is_page = slice_ctx && outcome == AnswerOutcome::Ok;
    let mut a = check_members(m, outcome, ctx, is_page)?;
    // 3.
    if !outcome.status_ok(status) {
        return env_err("$.outcome", format!("status {status} does not match outcome {oname}"));
    }
    // spec-0.4.3: E_FOREIGN_UNAVAILABLE is answered with 502 exactly.
    if a.error == Some(ErrorCode::ForeignUnavailable) && status != 502 {
        return env_err("$.outcome", format!("E_FOREIGN_UNAVAILABLE is answered with 502, not {status}"));
    }
    a.status = status;
    // 3a. What the request decides without the receipt: the pin echo (E_JOB_UNKNOWN only at
    // a job URL was checked with the members; pending is checked apart).
    pin_echo(&a, ctx.pin(), "$.fn_hash")?;
    if is_page {
        let Ctx::Slice(req) = ctx else { return env_err("$", "a page answers a slice request") };
        return check_page(m, a, keys, req);
    }
    // 5 for a scenario (5.9): the scenario binds to the request, and holds no receipt.
    if outcome == AnswerOutcome::Scenario {
        if let Ctx::Cell(req) = ctx {
            bind_scenario(&a, req)?;
        }
        return Ok(a);
    }
    // 4.
    if let Some(rv) = schema::opt(m, "receipt") {
        a.receipt = Some(member_receipt(rv, keys, "$.receipt")?);
    }
    // 5.
    if let Ctx::Cell(req) = ctx {
        bind_cell(&a, req)?;
    }
    // 6.
    if let Some(r) = &a.receipt {
        trust_check(&a, r, ctx.mesh(), "$")?;
    }
    Ok(a)
}

fn member_receipt(rv: &Value, keys: &Keys, path: &str) -> Result<Receipt> {
    crate::verify::signature_valid_value(rv, keys).map_err(|(e, _)| {
        let inner = e.path().strip_prefix('$').unwrap_or(e.path());
        Error::new(e.code(), format!("{path}{inner}"), e.detail())
    })
}

/// 5.5 step 2 for every outcome but `pending`; for a page, its own members.
/// The outcomes that carry `resolved` and `shadows` (5.5 table, `spec-0.5.0`).
fn outcome_has_resolved(outcome: AnswerOutcome) -> bool {
    matches!(
        outcome,
        AnswerOutcome::Ok
            | AnswerOutcome::Stale
            | AnswerOutcome::NotCovered
            | AnswerOutcome::Unlicensed
            | AnswerOutcome::PaymentRequired
            | AnswerOutcome::Error
            | AnswerOutcome::Scenario
    )
}

/// The `resolved` member (5.5, 16.7): exactly `call` (a non-empty string), `resolutions` and
/// optionally `aliases_tx` (an instant); each resolution exactly `from`, `kind` and `to`, plus
/// `asof` (an instant) exactly when its kind is `lookup`.
fn resolved_of(v: &Value) -> Result<Resolved> {
    let m = schema::object_or(v, "$.resolved", ErrorCode::Envelope, "resolved")?;
    schema::exact(m, &["call", "resolutions"], &["aliases_tx"], "$.resolved", ErrorCode::Envelope)?;
    let call = schema::string_or(m, "call", "$.resolved", ErrorCode::Envelope)?;
    let Value::Array(items) = schema::get(m, "resolutions") else {
        return env_err("$.resolved.resolutions", "resolutions is an array");
    };
    let mut resolutions = Vec::with_capacity(items.len());
    for (i, item) in items.iter().enumerate() {
        let p = format!("$.resolved.resolutions[{i}]");
        let rm = schema::object_or(item, &p, ErrorCode::Envelope, "a resolution")?;
        let (required, optional): (&[&str], &[&str]) = match schema::opt(rm, "kind").and_then(Value::as_str) {
            Some("lookup") => (&["from", "kind", "to", "asof"], &[]),
            _ => (&["from", "kind", "to"], &[]),
        };
        schema::exact(rm, required, optional, &p, ErrorCode::Envelope)?;
        let from = schema::string_or(rm, "from", &p, ErrorCode::Envelope)?;
        let kind_text = schema::string_or(rm, "kind", &p, ErrorCode::Envelope)?;
        let to = schema::string_or(rm, "to", &p, ErrorCode::Envelope)?;
        let Some(kind) = ResolutionKind::from_name(kind_text) else {
            return env_err(&p, format!("kind {kind_text:?} is not a resolution kind"));
        };
        let resolution = match kind {
            ResolutionKind::Lookup => {
                let asof = schema::string_or(rm, "asof", &p, ErrorCode::Envelope)?;
                Resolution::lookup(from, to, asof)
            }
            _ => Resolution::new(from, kind, to),
        };
        resolutions.push(resolution.map_err(|e| e.recode(ErrorCode::Envelope))?);
    }
    let mut out = Resolved::new(call, resolutions).map_err(|e| e.recode(ErrorCode::Envelope))?;
    if let Some(t) = schema::opt(m, "aliases_tx") {
        let t = t.as_str().unwrap_or("");
        out = out.with_aliases_tx(t).map_err(|e| e.recode(ErrorCode::Envelope))?;
    }
    Ok(out)
}

fn check_members(m: &[(String, Value)], outcome: AnswerOutcome, ctx: &Ctx<'_>, is_page: bool) -> Result<Answer> {
    let (req, opt): (&[&str], &[&str]) =
        if is_page { (&["members", "slice"], &["next", "fn_hash"]) } else { outcome.members() };
    let mut allowed: Vec<&str> = vec!["outcome"];
    allowed.extend_from_slice(req);
    schema::exact(m, &allowed, opt, "$", ErrorCode::Envelope)?;
    let mut a = bare(outcome);
    if let Some(r) = schema::opt(m, "receipt") {
        if !matches!(r, Value::Object(_)) {
            return env_err("$.receipt", "receipt is a receipt object");
        }
    }
    if let Some(t) = schema::opt(m, "trust") {
        a.trust = match t.as_str().and_then(TrustLabel::from_name) {
            Some(t) => Some(t),
            None => return env_err("$.trust", "trust is primary, computed, verified or unverified"),
        };
    }
    if let Some(x) = schema::opt(m, "age_seconds") {
        a.age_seconds = Some(integer_member(x, "$.age_seconds")?);
    }
    if let Some(x) = schema::opt(m, "retry_after_seconds") {
        a.retry_after_seconds = Some(integer_member(x, "$.retry_after_seconds")?);
    }
    if let Some(s) = schema::opt(m, "superseded_by") {
        let s = s.as_str().unwrap_or("");
        lexical::check_hex(s, 64, "$.superseded_by").map_err(|e| e.recode(ErrorCode::Envelope))?;
        a.superseded_by = Some(s.into());
    }
    if let Some(r) = schema::opt(m, "reason") {
        let Some(r) = r.as_str() else { return env_err("$.reason", "reason must be a string") };
        if schema::opt(m, "superseded_by").is_none() {
            return env_err("$.reason", "reason is only present with superseded_by");
        }
        lexical::check_text(r, limits::SUMMARY, false, "$.reason").map_err(|e| e.recode(ErrorCode::Envelope))?;
        if r.is_empty() {
            return env_err("$.reason", "reason must not be empty");
        }
        a.reason = Some(r.into());
    }
    if let Some(q) = schema::opt(m, "quote") {
        a.quote = Some(quote(q)?);
    }
    if let Some(e) = schema::opt(m, "error") {
        let code = e.as_str().and_then(ErrorCode::from_code);
        match code {
            Some(c) if code_allowed(outcome, c, ctx.job_url()) && whatif_code_ok(outcome, c, ctx) => a.error = Some(c),
            _ => return env_err("$.error", format!("{e:?} is not a code this outcome can carry")),
        }
    }
    if let Some(sc) = schema::opt(m, "scenario") {
        a.scenario = Some(scenario_of(sc)?);
    }
    if let Some(c) = schema::opt(m, "cycle") {
        let cycle = cycle_of(c)?;
        a = a.with_cycle(cycle)?;
    }
    // spec-0.4.3: detail, one of the closed list, present exactly with E_FOREIGN_UNAVAILABLE.
    if let Some(r) = schema::opt(m, "resolved") {
        a.resolved = Some(resolved_of(r)?);
    }
    if let Some(sh) = schema::opt(m, "shadows") {
        let sm = schema::object_or(sh, "$.shadows", ErrorCode::Envelope, "shadows")?;
        schema::exact(sm, &["class", "reference"], &[], "$.shadows", ErrorCode::Envelope)?;
        let class = schema::string_or(sm, "class", "$.shadows", ErrorCode::Envelope)?;
        let reference = schema::string_or(sm, "reference", "$.shadows", ErrorCode::Envelope)?;
        a.shadows = Some(Shadows::new(class, reference).map_err(|e| e.recode(ErrorCode::Envelope))?);
    }
    if let Some(d) = schema::opt(m, "detail") {
        let Some(detail) = d.as_str().and_then(ForeignDetail::from_name) else {
            return env_err("$.detail", format!("{d:?} is not a detail of E_FOREIGN_UNAVAILABLE"));
        };
        a.detail = Some(detail);
    }
    if (a.error == Some(ErrorCode::ForeignUnavailable)) != a.detail.is_some() {
        return env_err("$.detail", "detail is present exactly when error is E_FOREIGN_UNAVAILABLE");
    }
    if let Some(f) = schema::opt(m, "fault") {
        let Some(fault) = f.as_str().and_then(Fault::from_code) else {
            return env_err("$.fault", format!("{f:?} is not a formula evaluation fault"));
        };
        if a.error.is_some() {
            return env_err("$.fault", "not_covered carries a fault or an error, not both");
        }
        // 5.9: E_WHATIF_NO_SOLUTION is the fault of a whatif request with solve, and no other.
        if fault == Fault::WhatifNoSolution && ctx.solve().is_none() {
            return env_err("$.fault", "E_WHATIF_NO_SOLUTION answers a whatif request with solve");
        }
        a.fault = Some(fault);
    }
    if let Some(h) = schema::opt(m, "fn_hash") {
        let h = h.as_str().unwrap_or("");
        lexical::check_hex(h, 64, "$.fn_hash").map_err(|e| e.recode(ErrorCode::Envelope))?;
        a.fn_hash = Some(h.into());
    }
    if let Some(n) = schema::opt(m, "next") {
        let shape = n.as_str().is_some_and(|u| url_host(u).is_some() || lexical::loopback_origin(u).is_some());
        if !shape {
            return env_err(
                "$.next",
                "next is https://, a DNS name, then a path, or a loopback URL, at most 512 characters",
            );
        }
    }
    Ok(a)
}

/// The receipt answers the request (5.5 step 5).
fn bind_cell(a: &Answer, req: &Request) -> Result<()> {
    let Some(r) = &a.receipt else { return Ok(()) };
    if r.cell().id() != req.cell_id {
        return env_err("$.receipt.cell", "the receipt is for another cell than the one requested");
    }
    if let Some(asked) = &req.asof {
        if r.asof() > asked.as_str() {
            return env_err("$.receipt.asof", "the receipt's asof is after the requested asof");
        }
    }
    Ok(())
}

/// The pin echo (5.5 step 3a): with a pin, `fn_hash` required (but on `rate_limited` and
/// `bad_request`) and equal to it.
fn pin_echo(a: &Answer, pin: Option<&str>, path: &str) -> Result<()> {
    if let Some(p) = pin {
        match &a.fn_hash {
            Some(h) if h != p => return env_err(path, "the fn_hash echo is not the pin"),
            None if !matches!(a.outcome, AnswerOutcome::RateLimited | AnswerOutcome::BadRequest) => {
                return env_err(path, "an answer to a pinned request echoes the pin");
            }
            _ => {}
        }
    }
    Ok(())
}

/// 5.5 step 6: trust against the receipt (and the host asked, when known), then `fn_hash`
/// against the receipt's `cell.fn_hash`, then `superseded_by`.
fn trust_check(a: &Answer, r: &Receipt, mesh: Option<&str>, at: &str) -> Result<()> {
    let p = |m: &str| format!("{at}.{m}");
    // 5.5 step 6 (spec-0.6.0): primary and relayed are the publisher's own, with no inputs; the
    // receipt's source tells them apart.
    let own = r.signer_host() == lexical::host_of(&r.cell().ns) && r.inputs().is_empty();
    let primary = own && r.source().is_none();
    let relayed = own && r.source().is_some();
    let t = a.trust.unwrap_or(TrustLabel::Unverified);
    if (t == TrustLabel::Primary) != primary {
        return env_err(
            &p("trust"),
            if primary { "a primary receipt is labelled primary" } else { "the receipt is not primary" },
        );
    }
    if (t == TrustLabel::Relayed) != relayed {
        return env_err(
            &p("trust"),
            if relayed { "a relayed receipt is labelled relayed" } else { "the receipt is not relayed" },
        );
    }
    if let Some(host) = mesh {
        match t {
            TrustLabel::Computed if r.signer_host() != host => {
                return env_err(&p("trust"), "computed: the receipt is signed by another host than the one asked");
            }
            TrustLabel::Verified | TrustLabel::Unverified if r.signer_host() == host => {
                return env_err(&p("trust"), "the mesh asked signed this receipt: its trust is computed");
            }
            _ => {}
        }
    }
    if a.fn_hash.as_deref().is_some_and(|h| h != r.cell().fn_hash) {
        return env_err(&p("fn_hash"), "fn_hash differs from the receipt's cell.fn_hash");
    }
    if a.superseded_by.as_deref() == Some(r.hash()) {
        return env_err(&p("superseded_by"), "a receipt cannot supersede itself");
    }
    Ok(())
}

fn check_pending(status: u16, m: &[(String, Value)], ctx: &Ctx<'_>) -> Result<Answer> {
    // 2.
    schema::exact(m, &["estimate_seconds", "job", "outcome", "poll", "request"], &[], "$", ErrorCode::Envelope)?;
    let estimate = integer_member(schema::get(m, "estimate_seconds"), "$.estimate_seconds")?;
    let Some(job) = schema::get(m, "job").as_str() else { return env_err("$.job", "job must be a string") };
    let Some(poll) = schema::get(m, "poll").as_str() else { return env_err("$.poll", "poll must be a string") };
    check_job_and_poll_for(job, poll, ctx.mesh())?;
    let rm = schema::object_or(schema::get(m, "request"), "$.request", ErrorCode::Envelope, "request")?;
    schema::exact(rm, &["cell_id"], &["asof", "fn_hash"], "$.request", ErrorCode::Envelope)?;
    let cell_id = schema::string_or(rm, "cell_id", "$.request", ErrorCode::Envelope)?;
    let opt = |name: &str| -> Result<Option<&str>> {
        match schema::opt(rm, name) {
            None => Ok(None),
            Some(_) => schema::string_or(rm, name, "$.request", ErrorCode::Envelope).map(Some),
        }
    };
    let invalid = |e: crate::InvalidRequest| Error::new(ErrorCode::Envelope, "$.request", e.to_string());
    let mut echoed = Request::new(cell_id, opt("asof")?).map_err(invalid)?;
    if let Some(p) = opt("fn_hash")? {
        echoed = echoed.with_pin(p).map_err(invalid)?;
    }
    // 3.
    if status != Pending::STATUS {
        return env_err("$.outcome", format!("status {status} does not match outcome pending"));
    }
    // 5.
    let Ctx::Cell(request) = ctx else { return env_err("$.outcome", "pending answers a cell request") };
    if echoed.cell_id != request.cell_id || echoed.asof != request.asof || echoed.pin != request.pin {
        return env_err("$.request", "the echoed request is not the request made");
    }
    if let Some(polled) = &request.job {
        if job != polled {
            return env_err("$.job", "the envelope is for another job than the one polled");
        }
    }
    // 6. poll on the host asked (a loopback poll was checked with the unrooted mesh asked).
    if let (Some(host), false) = (&request.mesh, poll.starts_with("http://")) {
        if url_host(poll) != Some(host.as_str()) {
            return env_err("$.poll", "poll is on another host than the one asked");
        }
    }
    // The mesh asked is named to Pending::new, which checks the poll (a loopback one only for it);
    // the echoed request does not carry it.
    let with_mesh = Request { mesh: request.mesh.clone(), ..echoed };
    let p = Pending::new(job, estimate, poll, with_mesh)?;
    Ok(Answer { pending: Some(p), ..bare(AnswerOutcome::Pending) })
}

/// The key of a member: its values of the slice's open (and ranged) arguments, by name.
fn key_of(r: &Receipt, names: &[String]) -> Vec<Scalar> {
    names.iter().filter_map(|n| r.cell().args.get(n).and_then(Arg::scalar).cloned()).collect()
}

fn cmp_keys(a: &[Scalar], b: &[Scalar]) -> core::cmp::Ordering {
    for (x, y) in a.iter().zip(b) {
        let o = if x.ty() == y.ty() { cmp_lexical(x.ty(), x.lexical(), y.lexical()) } else { x.ty().cmp(&y.ty()) };
        if o != core::cmp::Ordering::Equal {
            return o;
        }
    }
    a.len().cmp(&b.len())
}

/// 5.6: a page bound to its request, the page first, then each member completely.
fn check_page(m: &[(String, Value)], mut a: Answer, keys: &Keys, req: &SliceRequest) -> Result<Answer> {
    let Value::Array(items) = schema::get(m, "members") else {
        return env_err("$.members", "members is an array of envelopes");
    };
    let slice = Slice::from_value(schema::get(m, "slice")).map_err(|e| e.recode(ErrorCode::Envelope))?;
    let next = schema::opt(m, "next").and_then(Value::as_str).map(String::from);
    // 2. The page: the slice, its fn_hash, next, the cursor.
    if slice.id() != req.slice_id {
        return env_err("$.slice", "the page is of another slice than the one requested");
    }
    if a.fn_hash.as_deref().is_some_and(|h| h != slice.fn_hash()) {
        return env_err("$.fn_hash", "fn_hash differs from the slice's");
    }
    if let Some(n) = &next {
        if n.starts_with("http://") {
            // A loopback next only when the request names the unrooted mesh asked (5.6, 9.6).
            if !req.mesh.as_deref().is_some_and(lexical::is_unrooted) {
                return env_err("$.next", "a loopback next is only for an unrooted mesh the request names");
            }
        } else if let Some(host) = &req.mesh {
            if url_host(n) != Some(host.as_str()) {
                return env_err("$.next", "next is on another host than the one asked");
            }
        }
    }
    // The cursor on the open arguments only; other names are ignored.
    let names = slice.key_names();
    let mut last: Option<Vec<Scalar>> = match &req.after {
        None => None,
        Some(after) => {
            let key: Vec<Scalar> = names.iter().filter_map(|n| after.get(n).cloned()).collect();
            if key.len() != names.len() {
                return env_err("$", "the cursor lacks an open argument of the slice");
            }
            Some(key)
        }
    };
    // 3. Each member, completely, in order.
    let mut out = Vec::with_capacity(items.len());
    for (i, item) in items.iter().enumerate() {
        let p = format!("$.members[{i}]");
        let mm = match item {
            Value::Object(mm) => mm,
            _ => return env_err(&p, "a member is an envelope"),
        };
        let o = match schema::get(mm, "outcome").as_str().and_then(AnswerOutcome::from_name) {
            Some(o @ (AnswerOutcome::Ok | AnswerOutcome::Stale)) => o,
            _ => return env_err(&p, "a member is an ok or stale envelope"),
        };
        let mut ma = check_members(mm, o, &Ctx::None, false).map_err(|e| nested(e, &p))?;
        let r = member_receipt(schema::get(mm, "receipt"), keys, &format!("{p}.receipt"))?;
        if !slice.contains(&r) {
            return env_err(&p, "the member's cell is not a member of the slice");
        }
        if let Some(asked) = &req.asof {
            if r.asof() > asked.as_str() {
                return env_err(&format!("{p}.receipt.asof"), "the member's asof is after the requested asof");
            }
        }
        trust_check(&ma, &r, req.mesh.as_deref(), &p)?;
        let key = key_of(&r, &names);
        if let Some(prev) = &last {
            if key.len() != prev.len() || key.iter().zip(prev).any(|(x, y)| x.ty() != y.ty()) {
                return env_err(&p, "the member's key has other types than the previous key (or the cursor)");
            }
            if cmp_keys(&key, prev) != core::cmp::Ordering::Greater {
                return env_err(&p, "members are in strictly ascending key order, after the cursor");
            }
        }
        last = Some(key);
        ma.receipt = Some(r);
        out.push(ma);
    }
    a.page = Some(SlicePage { slice, members: out, next });
    Ok(a)
}

/// A fix a cycle admits (5.5, 15.12; `spec-0.6.0`), in the order 5.5 lists them.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[non_exhaustive]
pub enum CycleFix {
    /// `asof`: read the cell as of an earlier instant, `asof(c, T)`.
    Asof,
    /// `lag`: read the previous period.
    Lag,
    /// `step`: add an iteration argument.
    Step,
    /// `solver`: use `whatif` with `solve` (5.9).
    Solver,
}

impl CycleFix {
    /// Every fix, in the order of 5.5: `asof`, `lag`, `step`, `solver`.
    pub const ALL: &'static [CycleFix] = &[CycleFix::Asof, CycleFix::Lag, CycleFix::Step, CycleFix::Solver];

    /// The fix as written in JSON.
    pub const fn as_str(self) -> &'static str {
        match self {
            CycleFix::Asof => "asof",
            CycleFix::Lag => "lag",
            CycleFix::Step => "step",
            CycleFix::Solver => "solver",
        }
    }

    /// The fix of its JSON name; `None` for anything else (case included).
    pub fn from_name(s: &str) -> Option<CycleFix> {
        CycleFix::ALL.iter().copied().find(|f| f.as_str() == s)
    }
}

/// The `cycle` member of an `error` envelope (5.5, 15.12; `spec-0.6.0`): the path of calls
/// around the cycle, and the fixes it admits. Exactly `path` and `fixes`.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct Cycle {
    path: Vec<String>,
    fixes: Vec<CycleFix>,
}

impl Cycle {
    /// A cycle: `path` of at least two calls whose first and last are equal (`E_ENVELOPE`
    /// otherwise), and `fixes`, non-empty, distinct and in the order of [`CycleFix::ALL`].
    pub fn new(path: Vec<String>, fixes: Vec<CycleFix>) -> Result<Cycle> {
        if path.len() < 2 {
            return env_err("$.cycle.path", "a cycle's path has at least two calls");
        }
        if path.first() != path.last() {
            return env_err("$.cycle.path", "a cycle's path starts and ends with the same call");
        }
        if path.iter().any(String::is_empty) {
            return env_err("$.cycle.path", "a call is a non-empty string");
        }
        if fixes.is_empty() {
            return env_err("$.cycle.fixes", "a cycle names at least one fix");
        }
        if fixes.windows(2).any(|w| w[0] >= w[1]) {
            return env_err("$.cycle.fixes", "fixes are distinct and in the order asof, lag, step, solver");
        }
        Ok(Cycle { path, fixes })
    }

    /// The calls around the cycle, the first and last equal.
    pub fn path(&self) -> &[String] {
        &self.path
    }

    /// The fixes the cycle admits.
    pub fn fixes(&self) -> &[CycleFix] {
        &self.fixes
    }

    fn to_value(&self) -> Value {
        let strings = |xs: Vec<&str>| Value::Array(xs.into_iter().map(|x| Value::String(x.into())).collect());
        Value::Object(vec![
            ("path".into(), strings(self.path.iter().map(String::as_str).collect())),
            ("fixes".into(), strings(self.fixes.iter().map(|f| f.as_str()).collect())),
        ])
    }
}

/// The `solved` member of a scenario (5.9; `spec-0.6.0`): the value found for `vary`, and the
/// target's value under it.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Solved {
    vary: Cell,
    value: Scalar,
}

impl Solved {
    /// The cell varied.
    pub fn vary(&self) -> &Cell {
        &self.vary
    }

    /// The value found for it: a number.
    pub fn value(&self) -> &Scalar {
        &self.value
    }
}

/// A scenario (5.9; `spec-0.6.0`): the value a cell would have under overrides. It is a
/// statement of what-if, never a receipt: it has no signer, no trust and no hash, and cannot be
/// turned into one. Built with [`Scenario::new`] and checked back by [`check_answer`] against
/// the request.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Scenario {
    cell: Cell,
    value: Scalar,
    asof: String,
    overrides: Overrides,
    solved: Option<Solved>,
}

impl Scenario {
    /// A scenario of `cell` with `value`, as of `asof` (an instant), under `overrides` (the
    /// canonical array: value overrides and slice overrides, sorted by cell or slice id, at most
    /// 64). `E_ENVELOPE` for anything else.
    pub fn new(cell: Cell, value: Scalar, asof: &str, overrides: &Value) -> Result<Scenario> {
        lexical::check_instant(asof, "$.scenario.asof").map_err(|e| e.recode(ErrorCode::Envelope))?;
        check_overrides(overrides)?;
        Ok(Scenario { cell, value, asof: asof.into(), overrides: Overrides(overrides.clone()), solved: None })
    }

    /// With `solved`: the value found for `vary` (a cell, not a slice) and the target's value
    /// under it, a number. `E_ENVELOPE` otherwise.
    pub fn with_solved(self, vary: Cell, value: Scalar) -> Result<Scenario> {
        if vary.is_slice() {
            return env_err("$.scenario.solved.vary", "the varied cell is one cell, not a slice");
        }
        if value.ty() != Type::Number {
            return env_err("$.scenario.solved.value", "the value found is a number");
        }
        Ok(Scenario { solved: Some(Solved { vary, value }), ..self })
    }

    /// The cell answered.
    pub fn cell(&self) -> &Cell {
        &self.cell
    }

    /// The scenario's value.
    pub fn value(&self) -> &Scalar {
        &self.value
    }

    /// The value's type.
    pub fn ty(&self) -> Type {
        self.value.ty()
    }

    /// The instant evaluated as of.
    pub fn asof(&self) -> &str {
        &self.asof
    }

    /// The overrides, canonical.
    pub fn overrides(&self) -> &Value {
        &self.overrides.0
    }

    /// The value found by `solve`, when the request had one.
    pub fn solved(&self) -> Option<&Solved> {
        self.solved.as_ref()
    }

    fn to_value(&self) -> Value {
        let raw = match &self.value {
            Scalar::Boolean(b) => Value::Bool(*b),
            other => Value::String(other.lexical().to_string()),
        };
        let mut m = vec![
            ("asof".to_string(), Value::String(self.asof.clone())),
            ("cell".to_string(), self.cell.to_value()),
            ("overrides".to_string(), self.overrides.0.clone()),
            ("type".to_string(), Value::String(self.value.ty().as_str().into())),
            ("value".to_string(), raw),
        ];
        if let Some(x) = &self.solved {
            m.push((
                "solved".into(),
                Value::Object(vec![("vary".into(), x.vary.to_value()), ("value".into(), x.value.to_value())]),
            ));
        }
        Value::Object(m)
    }
}

fn cell_of(v: &Value, path: &str) -> Result<Cell> {
    let c = Cell::from_value(v).map_err(|e| e.recode(ErrorCode::Envelope))?;
    if c.is_slice() {
        return env_err(path, "a cell, not a slice");
    }
    Ok(c)
}

/// A value of a scenario, read in its declared type: a boolean or a lexical string.
fn typed_value(ty: Type, v: &Value, path: &str) -> Result<Scalar> {
    match (ty, v) {
        (Type::Boolean, Value::Bool(b)) => Ok(Scalar::Boolean(*b)),
        (Type::Boolean, _) => env_err(path, "a boolean value is true or false"),
        (t, Value::String(text)) => Scalar::from_lexical(t, text).map_err(|e| e.recode(ErrorCode::Envelope)),
        _ => env_err(path, "a value is a string in its type's lexical form"),
    }
}

/// Keeps `id` strictly after the previous id in `prev` (5.9: sorted, distinct).
fn ascending(prev: &mut Option<String>, id: String, path: &str) -> Result<()> {
    if prev.as_deref().is_some_and(|q| q >= id.as_str()) {
        return env_err(path, "entries are distinct and sorted by cell id");
    }
    *prev = Some(id);
    Ok(())
}

/// The id an override is sorted by, after its shape is checked (5.9): a value override's cell,
/// or a slice override's slice.
fn override_id(item: &Value, p: &str) -> Result<String> {
    let m = schema::object_or(item, p, ErrorCode::Envelope, "an override")?;
    if schema::opt(m, "slice").is_none() {
        schema::exact(m, &["cell", "value"], &[], p, ErrorCode::Envelope)?;
        let cell = cell_of(schema::get(m, "cell"), &format!("{p}.cell"))?;
        scalar_canonical(schema::get(m, "value"), &format!("{p}.value")).map_err(|e| e.recode(ErrorCode::Envelope))?;
        return Ok(cell.id());
    }
    schema::exact(m, &["add", "remove", "slice"], &[], p, ErrorCode::Envelope)?;
    let slice = Slice::from_value(schema::get(m, "slice")).map_err(|e| e.recode(ErrorCode::Envelope))?;
    let Value::Array(added) = schema::get(m, "add") else { return env_err(p, "add is an array of members") };
    let mut prev = None;
    for (i, a) in added.iter().enumerate() {
        let ap = format!("{p}.add[{i}]");
        let am = schema::object_or(a, &ap, ErrorCode::Envelope, "an added member")?;
        schema::exact(am, &["cell", "value"], &[], &ap, ErrorCode::Envelope)?;
        let cell = cell_of(schema::get(am, "cell"), &format!("{ap}.cell"))?;
        scalar_canonical(schema::get(am, "value"), &format!("{ap}.value"))
            .map_err(|e| e.recode(ErrorCode::Envelope))?;
        ascending(&mut prev, cell.id(), &ap)?;
    }
    let Value::Array(removed) = schema::get(m, "remove") else { return env_err(p, "remove is an array of cells") };
    let mut prev = None;
    for (i, r) in removed.iter().enumerate() {
        let rp = format!("{p}.remove[{i}]");
        let cell = cell_of(r, &rp)?;
        ascending(&mut prev, cell.id(), &rp)?;
    }
    Ok(slice.id().to_string())
}

/// The overrides of a scenario or a request (5.9): an array of at most 64 overrides, sorted by
/// their cell or slice id and distinct.
pub(crate) fn check_overrides(v: &Value) -> Result<()> {
    let Value::Array(items) = v else { return env_err("$.overrides", "overrides is an array") };
    if items.len() > 64 {
        return env_err("$.overrides", "at most 64 overrides");
    }
    let mut prev = None;
    for (i, item) in items.iter().enumerate() {
        let p = format!("$.overrides[{i}]");
        let id = override_id(item, &p)?;
        ascending(&mut prev, id, &p)?;
    }
    Ok(())
}

/// A `scenario` member, read and checked by [`Scenario::new`] and [`Scenario::with_solved`].
fn scenario_of(v: &Value) -> Result<Scenario> {
    let m = schema::object_or(v, "$.scenario", ErrorCode::Envelope, "scenario")?;
    schema::exact(m, &["asof", "cell", "overrides", "type", "value"], &["solved"], "$.scenario", ErrorCode::Envelope)?;
    let cell = cell_of(schema::get(m, "cell"), "$.scenario.cell")?;
    let ty_name = schema::string_or(m, "type", "$.scenario", ErrorCode::Envelope)?;
    let Some(ty) = Type::from_name(ty_name) else {
        return env_err("$.scenario.type", format!("{ty_name:?} is not a type"));
    };
    let value = typed_value(ty, schema::get(m, "value"), "$.scenario.value")?;
    let asof = schema::string_or(m, "asof", "$.scenario", ErrorCode::Envelope)?;
    let mut sc = Scenario::new(cell, value, asof, schema::get(m, "overrides"))?;
    if let Some(sv) = schema::opt(m, "solved") {
        let sm = schema::object_or(sv, "$.scenario.solved", ErrorCode::Envelope, "solved")?;
        schema::exact(sm, &["vary", "value"], &[], "$.scenario.solved", ErrorCode::Envelope)?;
        let vary = cell_of(schema::get(sm, "vary"), "$.scenario.solved.vary")?;
        let value = scalar_canonical(schema::get(sm, "value"), "$.scenario.solved.value")
            .map_err(|e| e.recode(ErrorCode::Envelope))?;
        sc = sc.with_solved(vary, value)?;
    }
    Ok(sc)
}

/// A `cycle` member, read and checked by [`Cycle::new`].
fn cycle_of(v: &Value) -> Result<Cycle> {
    let m = schema::object_or(v, "$.cycle", ErrorCode::Envelope, "cycle")?;
    schema::exact(m, &["fixes", "path"], &[], "$.cycle", ErrorCode::Envelope)?;
    let Value::Array(calls) = schema::get(m, "path") else { return env_err("$.cycle.path", "path is an array") };
    let mut path = Vec::with_capacity(calls.len());
    for (i, c) in calls.iter().enumerate() {
        let Some(t) = c.as_str() else { return env_err(&format!("$.cycle.path[{i}]"), "a call is a string") };
        path.push(t.to_string());
    }
    let Value::Array(names) = schema::get(m, "fixes") else { return env_err("$.cycle.fixes", "fixes is an array") };
    let mut fixes = Vec::with_capacity(names.len());
    for (i, f) in names.iter().enumerate() {
        match f.as_str().and_then(CycleFix::from_name) {
            Some(fix) => fixes.push(fix),
            None => return env_err(&format!("$.cycle.fixes[{i}]"), "a fix is asof, lag, step or solver"),
        }
    }
    Cycle::new(path, fixes)
}

/// 5.9 step 5 for a scenario: its cell is the one requested, its asof the requested one when
/// one was sent, its overrides the request's byte for byte after canonical JSON, and `solved`
/// present exactly when `solve` was sent, with `vary` the requested cell.
fn bind_scenario(a: &Answer, req: &Request) -> Result<()> {
    let Some(s) = &a.scenario else { return Ok(()) };
    if s.cell.id() != req.cell_id {
        return env_err("$.scenario.cell", "the scenario is for another cell than the one requested");
    }
    if req.asof.as_deref().is_some_and(|asked| asked != s.asof) {
        return env_err("$.scenario.asof", "the scenario's asof is not the requested asof");
    }
    let asked = req.overrides.as_ref().map(|o| o.0.to_jcs()).unwrap_or_default();
    if s.overrides.0.to_jcs() != asked {
        return env_err("$.scenario.overrides", "the scenario's overrides are not the request's");
    }
    match (&s.solved, req.solve.as_deref()) {
        (Some(x), Some(v)) if x.vary.id() == v => Ok(()),
        (None, None) => Ok(()),
        _ => env_err("$.scenario.solved", "solved is present exactly when solve was sent, for the vary cell"),
    }
}