wyrd-spec 0.4.1

Wyrd foundation types: Card envelope, SpecKinds, and pure data contracts.
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
//! Generic Verifier execution wire contracts.
//!
//! One request shape serves `POST /v1/verification/execute` (inline, `200`
//! with a [`VerificationResult`]) and `POST /v1/verification/enqueue` (`202`
//! with an [`EnqueueVerificationResponse`]). Files are declared by digest
//! through `POST /v1/verification/evidence` before either call, and
//! `GET /v1/verification/executions/{execution_id}` reports
//! [`VerificationExecutionState`]. Execution status stays separate from the
//! verdict: a failed requirement is a normal result, never a transport error.

use std::collections::{BTreeMap, BTreeSet};

use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use skald_spec::{MediaFormat, NamedResponseFormat, SkaldError, check_output_schema};

use super::{
    DriftReport, DriftWindow, GroupSnapshot, OperatorDispatchState, VerificationError,
    VerificationExecutionStatus, VerificationVerdict,
};
use crate::auth::Sha256Hex;
use crate::card::agent::{BuiltinTool, ExecutionRoute};
use crate::card::verifier::{Check, CodeRuntime};
use crate::error::WyrdError;
use crate::ids::{CardUid, ExecutionId, GroupId, SlotName};
use crate::reference::CardRef;
use crate::storage::ids::UploadId;
use crate::storage::upload::UploadPlan;
use crate::vala::ids::{RunId, TraceId};
use crate::verification::TaskId;

/// `POST /v1/verification/execute` and `POST /v1/verification/enqueue`
/// request body: the exact Verifier and subject plus one declaration per
/// named input slot. Tenant and principal come from authentication, never
/// from the body.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct VerificationRequest {
    /// Exact Verifier Card version to execute.
    pub verifier_card_uid: CardUid,
    /// Exact Card the judgment is about.
    pub card_uid: CardUid,
    /// The caller's application Run, when the execution belongs to one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub run_id: Option<RunId>,
    /// Caller-chosen group this execution belongs to, scoped to the tenant
    /// and authenticated owner Service. Grouped Verifier bindings discover
    /// executions sharing it; omitting it keeps the invocation ungrouped.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group_id: Option<GroupId>,
    /// Input declarations keyed by the Verifier's slot names.
    #[serde(default)]
    pub inputs: BTreeMap<SlotName, InputDeclaration>,
    /// Whole execution-route replacements keyed by Agent block ID.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub execution_route_overrides: BTreeMap<TaskId, ExecutionRoute>,
    /// The invoking workload's deployment environment: an optional,
    /// non-empty correlation tag copied onto the accepted execution and its
    /// result. It never selects, filters, or changes the execution and is
    /// never permission.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deployment_environment: Option<String>,
}

/// What a caller supplies for one input slot. Execution results echo the
/// pinned declarations as the original evidence identities.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum InputDeclaration {
    /// Bounded inline JSON for a `json` slot.
    Json {
        /// The supplied value.
        value: Value,
    },
    /// A file uploaded by digest through the evidence plan.
    File {
        /// SHA-256 of the file bytes.
        #[cfg_attr(feature = "server", schema(value_type = String))]
        sha256: Sha256Hex,
        /// File length in bytes.
        size_bytes: u64,
        /// Declared canonical format.
        #[cfg_attr(feature = "server", schema(value_type = String))]
        format: MediaFormat,
        /// Original filename, for display only.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        filename: Option<String>,
    },
    /// A registered Artifact Card's file.
    Artifact {
        /// Exact Artifact Card reference.
        artifact: CardRef,
        /// File path inside the Artifact; required when it holds several.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        path: Option<String>,
    },
    /// A recorded trace for a `trace` slot.
    Trace {
        /// The trace to judge.
        trace_id: TraceId,
    },
}

/// One file the caller intends to reference by digest.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct EvidenceFile {
    /// SHA-256 of the file bytes.
    #[cfg_attr(feature = "server", schema(value_type = String))]
    pub sha256: Sha256Hex,
    /// File length in bytes.
    pub size_bytes: u64,
}

/// `POST /v1/verification/evidence` request body.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct EvidencePlanRequest {
    /// Files the caller is about to declare.
    pub files: Vec<EvidenceFile>,
}

/// `POST /v1/verification/evidence` response: upload plans only for files
/// the server does not already hold as completed File uploads.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct EvidencePlanResponse {
    /// One upload per missing file; completed files are omitted.
    pub uploads: Vec<EvidenceUpload>,
}

/// How to upload one missing file through the shared storage lifecycle.
///
/// Transfer the bytes by `plan`, then finish with
/// `POST /v1/cards/upload/{upload_id}/complete`; multipart part URLs come
/// from `POST /v1/cards/upload/{upload_id}/part-url`. Completion succeeds
/// once the File's inventory record is acknowledged.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct EvidenceUpload {
    /// Digest of the file this plan uploads.
    #[cfg_attr(feature = "server", schema(value_type = String))]
    pub sha256: Sha256Hex,
    /// Upload session to transfer into and complete.
    pub upload_id: UploadId,
    /// The upload plan.
    pub plan: UploadPlan,
}

/// `202 Accepted` body of `POST /v1/verification/enqueue`. It confirms
/// staging only; replay or conflict is decided when the queue accepts it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct EnqueueVerificationResponse {
    /// Identity to poll.
    pub execution_id: ExecutionId,
}

/// `GET /v1/verification/executions/{execution_id}` response.
///
/// A conflicting idempotent replay settles as `errored` with the
/// idempotency-conflict code and never carries a result. `completed` may
/// briefly lack a visible result.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[schemars(rename = "VerificationExecutionState")]
#[cfg_attr(feature = "server", schema(bound = ""))]
pub struct VerificationExecutionState<T = Map<String, Value>> {
    /// The execution.
    pub execution_id: ExecutionId,
    /// Lifecycle status, independent of the verdict.
    pub status: VerificationExecutionStatus,
    /// Terminal error of an `errored`, `cancelled`, or `timed_out` execution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<VerificationError>,
    /// The result once completed and visible.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[schemars(default)]
    #[cfg_attr(feature = "server", schema(value_type = Option<VerificationResult>))]
    pub result: Option<VerificationResult<T>>,
    /// Every Operator dispatch of a failed background binding execution or a
    /// changed group verdict, in identity order; empty otherwise. Delivery
    /// completes independently of the execution and never changes its verdict.
    #[serde(default)]
    pub dispatches: Vec<OperatorDispatchState>,
    /// Caller group the execution belongs to, or the group a group execution
    /// judges.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group_id: Option<GroupId>,
    /// Binding owner of a background execution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub owner_card_uid: Option<CardUid>,
    /// The source snapshot a group execution judges.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group: Option<GroupSnapshot>,
}

/// The attributable result of one Verifier execution.
///
/// `T` is the type of each requirement's custom `data`: JSON objects on the
/// wire, or a caller's type after a typed SDK read.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[schemars(rename = "VerificationResult")]
#[cfg_attr(feature = "server", schema(bound = ""))]
pub struct VerificationResult<T = Map<String, Value>> {
    /// Server-issued execution identity.
    pub execution_id: ExecutionId,
    /// The caller's application Run, when there is one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub run_id: Option<RunId>,
    /// The exact Verifier executed.
    pub verifier: CardRef,
    /// The exact subject judged.
    pub subject: CardRef,
    /// The deployment environment tag the execution was invoked with, or
    /// absent when the invocation carried none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub deployment_environment: Option<String>,
    /// Verdict, breakdown, and evidence.
    #[cfg_attr(feature = "server", schema(value_type = VerificationOutcome))]
    pub outcome: VerificationOutcome<T>,
}

/// Overall verdict with its requirement and step breakdown.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[schemars(rename = "VerificationOutcome")]
#[cfg_attr(feature = "server", schema(bound = ""))]
pub struct VerificationOutcome<T = Map<String, Value>> {
    /// The `decide` rule applied to every applicable requirement.
    pub verdict: VerificationVerdict,
    /// Every requirement, step requirements included.
    #[cfg_attr(feature = "server", schema(value_type = Vec<RequirementResult>))]
    pub requirements: Vec<RequirementResult<T>>,
    /// Every step in plan order.
    pub steps: Vec<StepResult>,
    /// The pinned original evidence, by slot.
    pub evidence: BTreeMap<SlotName, InputDeclaration>,
}

/// The judgment of one requirement.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[schemars(rename = "RequirementResult")]
#[cfg_attr(feature = "server", schema(bound = ""))]
pub struct RequirementResult<T = Map<String, Value>> {
    /// Requirement ID.
    pub id: TaskId,
    /// Owning step of a step requirement.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub step: Option<TaskId>,
    /// The requirement statement.
    pub statement: String,
    /// The outcome.
    pub outcome: RequirementOutcome,
    /// Why the outcome holds.
    pub reason: String,
    /// The compared actual value, when capture permits it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub actual: Option<Value>,
    /// Validated original-evidence citations.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub citations: Vec<Citation>,
    /// Custom data an Agent or code check returned under its declared
    /// `verdict` format; absent when none was declared or the output was
    /// rejected.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[schemars(
        default,
        schema_with = "crate::schema::skipped_option::<Map<String, Value>>"
    )]
    #[cfg_attr(feature = "server", schema(value_type = Option<Object>))]
    pub data: Option<T>,
    /// Check-specific detail.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detail: Option<RequirementDetail>,
    /// The exact check configuration that ran.
    pub check: Check,
    /// What executed the check, for Agent, code, and drift checks.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provenance: Option<CallProvenance>,
}

/// One requirement's outcome. Only `not_applicable` leaves the `decide`
/// denominator.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum RequirementOutcome {
    /// The requirement held.
    Passed,
    /// The requirement was violated.
    Failed,
    /// No judgment could be made; never a pass.
    Inconclusive,
    /// The requirement did not apply because its step was intentionally
    /// skipped.
    NotApplicable,
}

/// Check-specific requirement detail.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum RequirementDetail {
    /// Full per-feature statistics of a drift check.
    Drift(DriftReport),
}

/// What executed one Agent, code, extract, or drift block.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum CallProvenance {
    /// An Agent call.
    Agent {
        /// Exact Agent Card; absent when declared inline in the Verifier.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        agent: Option<CardRef>,
        /// Exact Prompt Card; absent when declared inline.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        prompt: Option<CardRef>,
        /// The effective route after overrides.
        route: ExecutionRoute,
    },
    /// A sandboxed code call.
    Code {
        /// SHA-256 of the executed source.
        #[cfg_attr(feature = "server", schema(value_type = String))]
        sha256: Sha256Hex,
        /// The runtime.
        runtime: CodeRuntime,
    },
    /// An extraction.
    Extract {
        /// Extractor version that produced the output.
        version: String,
    },
    /// A drift check.
    Drift {
        /// The scored sample window, for scheduled evidence.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        window: Option<DriftWindow>,
    },
}

/// The execution record of one step.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct StepResult {
    /// Step ID.
    pub id: TaskId,
    /// Final status, as `steps.<id>.status` reads it.
    pub status: StepStatus,
    /// The action output, when capture permits it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output: Option<Value>,
    /// Attempts made, retries included; zero when skipped.
    pub attempts: u32,
    /// Wall-clock duration across attempts.
    pub duration_ms: u64,
    /// Why the step failed or was skipped.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
    /// What executed the action.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub provenance: Option<CallProvenance>,
    /// Tools an Agent action called, in call order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub tool_calls: Vec<ToolCallRecord>,
}

/// Final status of one step.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum StepStatus {
    /// The action produced output.
    Succeeded,
    /// The action failed or timed out after its retries.
    Failed,
    /// The step did not run: its `when` was false or a dependency did not
    /// succeed.
    Skipped,
}

/// One tool call an Agent action made.
///
/// Records what the model received, never the raw tool output: the digest
/// and size describe the bounded output actually returned. A call that
/// returned no output, such as one that failed, has no digest and zero
/// returned bytes rather than a digest of nothing.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
pub struct ToolCallRecord {
    /// The built-in called.
    pub tool: BuiltinTool,
    /// Call arguments.
    pub arguments: Value,
    /// SHA-256 of the bounded output returned to the model; absent when the
    /// call returned none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "server", schema(value_type = Option<String>))]
    pub output_sha256: Option<Sha256Hex>,
    /// Bytes of output returned to the model; zero when it returned none.
    pub returned_bytes: u64,
    /// Error the tool returned, when it failed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

/// Most bytes of compact UTF-8 JSON one Verdict's custom `data` may take.
pub const MAX_VERDICT_DATA_BYTES: usize = 65_536;

/// Most nested containers one Verdict's custom `data` may hold; the root
/// object counts as one.
pub const MAX_VERDICT_DATA_DEPTH: usize = 16;

/// The name of the generated Verdict response format.
pub const VERDICT_FORMAT: &str = "verdict";

/// The `$id` that makes a declared `data` schema its own resource inside the
/// Verdict envelope, relative to the envelope's base: the data's `#` then
/// names the data schema, not the envelope.
const DATA_RESOURCE: &str = "verdict-data";

/// The closed schema every Agent and code check returns.
///
/// `data` is present exactly when the check declares a custom-data schema
/// through the `verdict` response format; the server validates the whole
/// response against that declaration before decoding it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct Verdict {
    /// The judgment.
    pub outcome: VerificationVerdict,
    /// Why it holds.
    pub reason: String,
    /// Original-evidence locations supporting it; a pass without a valid
    /// citation becomes inconclusive.
    pub citations: Vec<Citation>,
    /// Custom data the check's declared format requires.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    #[schemars(schema_with = "crate::schema::skipped_option::<Map<String, Value>>")]
    pub data: Option<Map<String, Value>>,
}

impl VerificationExecutionState {
    /// This state with its result's custom data decoded as `T`; a state
    /// without a result converts unchanged.
    ///
    /// # Errors
    /// Returns the [`VerificationResult::decode_data`] error.
    pub fn decode_data<T: DeserializeOwned>(
        self,
    ) -> Result<VerificationExecutionState<T>, WyrdError> {
        let Self {
            execution_id,
            status,
            error,
            result,
            dispatches,
            group_id,
            owner_card_uid,
            group,
        } = self;
        Ok(VerificationExecutionState {
            execution_id,
            status,
            error,
            result: result.map(VerificationResult::decode_data).transpose()?,
            dispatches,
            group_id,
            owner_card_uid,
            group,
        })
    }
}

impl VerificationResult {
    /// This result with every present requirement `data` decoded as `T`.
    ///
    /// The SDKs' typed reads use it after the ordinary read: absent data
    /// stays absent, failed requirements decode too, and the stored result is
    /// never changed or re-executed. One mismatch fails the whole
    /// conversion, so no partially typed result is returned.
    ///
    /// # Errors
    /// Returns `WYRD_SDK_422_VERIFICATION_DATA_INVALID` naming the first
    /// requirement whose data does not decode, with the empty `path` of the
    /// data root and never the data itself: a decoder cannot tell a declared
    /// field name from a returned dictionary key, so no deeper path is safe.
    pub fn decode_data<T: DeserializeOwned>(self) -> Result<VerificationResult<T>, WyrdError> {
        let Self {
            execution_id,
            run_id,
            verifier,
            subject,
            deployment_environment,
            outcome,
        } = self;
        let requirements = outcome
            .requirements
            .into_iter()
            .map(RequirementResult::decode_data)
            .collect::<Result<_, _>>()?;
        Ok(VerificationResult {
            execution_id,
            run_id,
            verifier,
            subject,
            deployment_environment,
            outcome: VerificationOutcome {
                verdict: outcome.verdict,
                requirements,
                steps: outcome.steps,
                evidence: outcome.evidence,
            },
        })
    }
}

impl RequirementResult {
    /// This requirement with its present `data` decoded as `T`.
    ///
    /// # Errors
    /// Returns `WYRD_SDK_422_VERIFICATION_DATA_INVALID` with the requirement
    /// ID and the data root's empty path, never the data.
    fn decode_data<T: DeserializeOwned>(self) -> Result<RequirementResult<T>, WyrdError> {
        let data = match self.data {
            None => None,
            Some(data) => Some(serde_json::from_value(Value::Object(data)).map_err(|_| {
                WyrdError::SdkVerificationDataInvalid {
                    message: format!(
                        "requirement `{}` data does not match the requested type",
                        self.id.as_str()
                    ),
                    details: serde_json::json!({"requirement": self.id, "path": ""}),
                }
            })?),
        };
        Ok(RequirementResult {
            id: self.id,
            step: self.step,
            statement: self.statement,
            outcome: self.outcome,
            reason: self.reason,
            actual: self.actual,
            citations: self.citations,
            data,
            detail: self.detail,
            check: self.check,
            provenance: self.provenance,
        })
    }
}

impl Verdict {
    /// Resolves a `verdict` response format to the schema its responses
    /// must satisfy.
    ///
    /// The plain form is the generated closed Verdict without `data`; an
    /// expanded `data` schema becomes the required `data` member, embedded
    /// as its own JSON Schema 2020-12 resource under a private `$id` so its
    /// local `$ref`s resolve exactly as they do standalone. Data schemas are
    /// 2020-12 only and carry no root `$id`: an older draft or an authored
    /// identity could leave those references bound to the envelope. This is
    /// the resolver Prompt compilation and code-check validation share.
    ///
    /// # Errors
    ///
    /// Returns [`SkaldError::PromptInvalid`] at `response_format` for a name
    /// other than `verdict`; at `response_format.data.$schema` for a data
    /// schema declaring a draft other than 2020-12; at
    /// `response_format.data.$id` for one with a root `$id`; and at
    /// `response_format.data...` for one that is not a valid object JSON
    /// Schema.
    ///
    /// # Panics
    ///
    /// Panics if the generated Verdict schema has no `properties` object, an
    /// invariant of the derived schema.
    pub fn response_format(format: &NamedResponseFormat) -> Result<Map<String, Value>, SkaldError> {
        let invalid = |field: &str, message: &str| SkaldError::PromptInvalid {
            field: field.to_owned(),
            message: message.to_owned(),
        };
        if format.name() != VERDICT_FORMAT {
            return Err(invalid(
                "response_format",
                &format!(
                    "unknown response format `{}`; the named format is `verdict`",
                    format.name()
                ),
            ));
        }
        let Ok(mut generated) = serde_json::to_value(crate::schema::schema_for::<Self>()) else {
            unreachable!("a generated root schema serializes to a JSON object");
        };
        portable(&mut generated);
        let Value::Object(mut schema) = generated else {
            unreachable!("a generated root schema serializes to a JSON object");
        };
        let required = |schema: &mut Map<String, Value>| {
            schema
                .get_mut("required")
                .and_then(Value::as_array_mut)
                .map(|required| required.retain(|name| name != "data"))
        };
        required(&mut schema);
        let properties = schema
            .get_mut("properties")
            .and_then(Value::as_object_mut)
            .expect("the generated Verdict schema declares properties");
        properties.remove("data");
        let Some(data) = format.data() else {
            return Ok(schema);
        };
        if let Some(dialect) = data.get("$schema")
            && !matches!(
                dialect.as_str(),
                Some(
                    "https://json-schema.org/draft/2020-12/schema"
                        | "https://json-schema.org/draft/2020-12/schema#"
                )
            )
        {
            return Err(invalid(
                "response_format.data.$schema",
                "a Verdict data schema is JSON Schema 2020-12; omit `$schema` or declare https://json-schema.org/draft/2020-12/schema",
            ));
        }
        if data.contains_key("$id") {
            return Err(invalid(
                "response_format.data.$id",
                "a Verdict data schema is embedded as its own resource; remove the root `$id`",
            ));
        }
        check_output_schema(&Value::Object(data.clone()), "response_format.data", true)?;
        let mut data = data.clone();
        data.insert("$id".to_owned(), Value::from(DATA_RESOURCE));
        schema["properties"]["data"] = Value::Object(data);
        schema
            .get_mut("required")
            .and_then(Value::as_array_mut)
            .expect("the generated Verdict schema requires fields")
            .push(Value::from("data"));
        Ok(schema)
    }

    /// Narrows a resolved Verdict schema's citation slots to `slots`, the
    /// bare slot names one check invocation can reach.
    ///
    /// Hosts apply it to a per-call copy before the model runs, so the
    /// provider request and local validation admit the same slots and a
    /// wrong slot is repaired rather than judged. An empty set, or a schema
    /// without the generated `SlotName` definition, is left unchanged;
    /// final evidence validation still decides every citation.
    pub fn restrict_slots(schema: &mut Value, slots: &BTreeSet<SlotName>) {
        if slots.is_empty() {
            return;
        }
        if let Some(slot) = schema.pointer_mut("/$defs/SlotName") {
            *slot = serde_json::json!({
                "type": "string",
                "enum": slots.iter().map(SlotName::as_str).collect::<Vec<_>>(),
            });
        }
    }

    /// Refuses custom `data` beyond the fixed size and depth bounds.
    ///
    /// Size is the compact UTF-8 JSON encoding of `data` alone, with only
    /// the escapes JSON requires; depth counts every object and array, the
    /// root included. The message names the violated limit, never the data.
    ///
    /// # Errors
    ///
    /// Returns the violated bound as a message when `data` exceeds
    /// [`MAX_VERDICT_DATA_BYTES`] or [`MAX_VERDICT_DATA_DEPTH`].
    pub fn check_data_bounds(&self) -> Result<(), String> {
        /// Containers in the deepest path through `value`.
        fn depth(value: &Value) -> usize {
            match value {
                Value::Object(map) => 1 + map.values().map(depth).max().unwrap_or(0),
                Value::Array(items) => 1 + items.iter().map(depth).max().unwrap_or(0),
                _ => 0,
            }
        }
        let Some(data) = &self.data else {
            return Ok(());
        };
        let bytes = serde_json::to_vec(data).map_or(usize::MAX, |encoded| encoded.len());
        if bytes > MAX_VERDICT_DATA_BYTES {
            return Err(format!(
                "verdict data is {bytes} bytes; the limit is {MAX_VERDICT_DATA_BYTES} bytes of compact JSON"
            ));
        }
        let nested = 1 + data.values().map(depth).max().unwrap_or(0);
        if nested > MAX_VERDICT_DATA_DEPTH {
            return Err(format!(
                "verdict data nests {nested} containers; the limit is {MAX_VERDICT_DATA_DEPTH}"
            ));
        }
        Ok(())
    }
}

/// Projects a generated schema onto the subset OpenAI strict mode,
/// Anthropic, and Gemini all accept, without changing what it admits beyond
/// numeric ranges.
///
/// `oneOf` becomes `anyOf`, which is equivalent for the disjoint closed
/// alternatives the generator emits, and an alternation of `const` values
/// becomes one `enum`. Siblings of `$ref`, `format`, and `minimum` are
/// dropped; typed decoding still enforces the numeric ranges they stated.
/// Keys of `properties` and `$defs` are names, never keywords. It runs on
/// the generated envelope only, before any authored `data` schema is
/// embedded.
fn portable(schema: &mut Value) {
    let Value::Object(node) = schema else {
        return;
    };
    if node.contains_key("$ref") {
        node.retain(|key, _| key == "$ref");
        return;
    }
    node.remove("format");
    node.remove("minimum");
    if let Some(Value::Array(alternatives)) = node.remove("oneOf") {
        let constants: Option<Vec<Value>> = alternatives
            .iter()
            .map(|alternative| alternative.get("const").cloned())
            .collect();
        let kind = alternatives
            .first()
            .and_then(|first| first.get("type"))
            .cloned();
        match constants {
            Some(values)
                if alternatives
                    .iter()
                    .all(|alternative| alternative.get("type") == kind.as_ref()) =>
            {
                if let Some(kind) = kind {
                    node.insert("type".to_owned(), kind);
                }
                node.insert("enum".to_owned(), Value::Array(values));
            }
            _ => {
                node.insert("anyOf".to_owned(), Value::Array(alternatives));
            }
        }
    }
    for (keyword, value) in node.iter_mut() {
        match (keyword.as_str(), value) {
            ("properties" | "$defs", Value::Object(named)) => named.values_mut().for_each(portable),
            (_, Value::Array(items)) => items.iter_mut().for_each(portable),
            (_, value) => portable(value),
        }
    }
}

/// A location in an original input slot, never in scratch space.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(deny_unknown_fields)]
pub struct Citation {
    /// The original input slot.
    pub slot: SlotName,
    /// Where in that slot.
    pub locator: Locator,
}

/// A typed location, serialized as a one-key object such as `{"page": 7}`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
#[cfg_attr(feature = "server", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum Locator {
    /// One-based PDF page.
    Page(u32),
    /// One-based PPTX slide.
    Slide(u32),
    /// One-based inclusive text line range.
    Lines {
        /// First line.
        start: u32,
        /// Last line.
        end: u32,
    },
    /// RFC 6901 pointer into JSON input or canonical extracted JSON.
    JsonPointer(String),
    /// A rectangle on a one-based page, in page coordinates.
    Region {
        /// Page.
        page: u32,
        /// Left edge.
        x: f32,
        /// Top edge.
        y: f32,
        /// Width.
        width: f32,
        /// Height.
        height: f32,
    },
}

impl From<&WyrdError> for VerificationError {
    /// Record a refusal as the secret-free stable code and message an
    /// execution status carries, such as a delayed idempotency conflict.
    fn from(error: &WyrdError) -> Self {
        Self {
            code: error.code().to_owned(),
            message: error.message_details().0.into_owned(),
        }
    }
}

#[cfg(test)]
mod tests {
    //! Wire round trips and refusals for the Verifier execution contracts.

    use serde_json::json;

    use super::*;

    /// Every input kind and route override round-trips, and malformed
    /// declarations are refused.
    ///
    /// # Panics
    /// Panics when a request does not round-trip or a malformed one parses.
    #[test]
    fn verification_request_round_trips_every_input_kind() {
        let digest = "a".repeat(64);
        let uid = || CardUid::from_uuid(uuid::Uuid::now_v7()).expect("v7 uid");
        let request = json!({
            "verifier_card_uid": uid(),
            "card_uid": uid(),
            "inputs": {
                "answer": {"kind": "json", "value": {"text": "yes"}},
                "policy": {"kind": "file", "sha256": digest, "size_bytes": 10, "format": "pdf", "filename": "p.pdf"},
                "deck": {"kind": "artifact", "artifact": {"kind": "Artifact", "name": "decks", "version": "1.0.0"}, "path": "q3.pptx"},
                "trace": {"kind": "trace", "trace_id": "0af7651916cd43dd8448eb211c80319c"}
            },
            "execution_route_overrides": {"judge": {"kind": "wyrd_gateway", "deployment": "eu-west"}}
        });
        let parsed: VerificationRequest =
            serde_json::from_value(request.clone()).expect("documented request");
        assert_eq!(serde_json::to_value(&parsed).expect("serialize"), request);
        for invalid in [
            json!({"kind": "file", "sha256": "A".repeat(64), "size_bytes": 1, "format": "pdf"}),
            json!({"kind": "file", "sha256": digest, "size_bytes": 1, "format": "exe"}),
            json!({"kind": "json", "value": 1, "extra": true}),
        ] {
            assert!(
                serde_json::from_value::<InputDeclaration>(invalid.clone()).is_err(),
                "{invalid}"
            );
        }
    }

    /// A result with every locator kind, drift detail, provenance, tool calls
    /// with and without returned output, and a skipped step keeps its
    /// documented wire form; records without a returned size, naming a
    /// non-built-in tool, or with a non-canonical digest are refused.
    ///
    /// # Panics
    /// Panics when the documented result does not round-trip.
    #[test]
    fn verification_result_round_trips_documented_outcome() {
        let result = json!({
            "execution_id": ExecutionId::new_v7(),
            "verifier": {"kind": "Verifier", "name": "msa-policy", "version": "1.0.0"},
            "subject": {"kind": "Agent", "name": "drafter", "version": "1.0.0"},
            "outcome": {
                "verdict": "failed",
                "requirements": [{
                    "id": "liability-cap", "statement": "Cap at 12 months",
                    "outcome": "failed", "reason": "cap is 24 months",
                    "citations": [
                        {"slot": "contract", "locator": {"page": 7}},
                        {"slot": "deck", "locator": {"slide": 2}},
                        {"slot": "notes", "locator": {"lines": {"start": 1, "end": 3}}},
                        {"slot": "workbook", "locator": {"json_pointer": "/sheets/0/cells/1/value"}},
                        {"slot": "contract", "locator": {"region": {"page": 7, "x": 0.5, "y": 1.0, "width": 2.0, "height": 0.25}}}
                    ],
                    "check": {"kind": "assert", "path": "inputs.contract", "operator": "is_not_null"},
                    "provenance": {"kind": "agent", "route": {"kind": "wyrd_gateway", "deployment": "eu-west"}}
                }, {
                    "id": "stable", "statement": "Inputs are stable",
                    "outcome": "not_applicable", "reason": "step skipped",
                    "detail": {"drift": {"method": "Psi", "features": {}, "verdict": "NoDrift"}},
                    "check": {"kind": "assert", "path": "inputs.contract", "operator": "is_not_null"},
                    "step": "structure"
                }],
                "steps": [{
                    "id": "structure", "status": "skipped", "attempts": 0, "duration_ms": 0,
                    "reason": "when was false",
                    "tool_calls": [
                        {"tool": "fs.read", "arguments": {"path": "/inputs/a.pdf"}, "output_sha256": "c".repeat(64), "returned_bytes": 512},
                        {"tool": "fs.search", "arguments": {"query": "cap"}, "returned_bytes": 0, "error": "workspace read timed out"}
                    ]
                }],
                "evidence": {"contract": {"kind": "file", "sha256": "b".repeat(64), "size_bytes": 4, "format": "pdf"}}
            }
        });
        let parsed: VerificationResult =
            serde_json::from_value(result.clone()).expect("documented result");
        assert_eq!(serde_json::to_value(&parsed).expect("serialize"), result);
        assert!(
            serde_json::from_value::<Verdict>(
                json!({"outcome": "passed", "reason": "ok", "citations": [], "score": 1})
            )
            .is_err()
        );
        for record in [
            json!({"tool": "fs.read", "arguments": {}}),
            json!({"tool": "http.fetch", "arguments": {}, "returned_bytes": 0}),
            json!({"tool": "fs.read", "arguments": {}, "output_sha256": "C".repeat(64), "returned_bytes": 1}),
        ] {
            assert!(
                serde_json::from_value::<ToolCallRecord>(record.clone()).is_err(),
                "{record}"
            );
        }
    }

    /// Typed decoding converts every present requirement `data`, leaves
    /// absent data absent, and refuses a mismatch with the requirement and
    /// field path but never the payload, returning no partial result.
    ///
    /// # Panics
    /// Panics when a conversion succeeds or fails on the wrong side.
    #[test]
    fn typed_data_decodes_whole_results() {
        /// The caller's model of a scoring check's custom data, the type
        /// the typed read decodes each requirement's `data` into.
        #[derive(Debug, PartialEq, Deserialize)]
        struct Judge {
            /// The judge's score; a string here is the mismatch under test.
            score: f64,
        }
        let requirement = |id: &str, data: Value| {
            let mut requirement = json!({
                "id": id, "statement": "s", "outcome": "failed", "reason": "r",
                "check": {"kind": "assert", "path": "inputs.answer", "operator": "is_not_null"}
            });
            if !data.is_null() {
                requirement["data"] = data;
            }
            requirement
        };
        let result = |requirements: Vec<Value>| -> VerificationResult {
            serde_json::from_value(json!({
                "execution_id": ExecutionId::new_v7(),
                "verifier": {"kind": "Verifier", "name": "judge", "version": "1.0.0"},
                "subject": {"kind": "Agent", "name": "drafter", "version": "1.0.0"},
                "outcome": {"verdict": "failed", "requirements": requirements, "steps": [], "evidence": {}}
            }))
            .expect("result")
        };
        let typed = result(vec![
            requirement("scored", json!({"score": 0.25})),
            requirement("plain", Value::Null),
        ])
        .decode_data::<Judge>()
        .expect("typed");
        assert_eq!(
            typed.outcome.requirements[0].data,
            Some(Judge { score: 0.25 })
        );
        assert_eq!(typed.outcome.requirements[1].data, None);
        let error = result(vec![
            requirement("scored", json!({"score": 0.25})),
            requirement("secretive", json!({"score": "hunter2"})),
        ])
        .decode_data::<Judge>()
        .expect_err("mismatch");
        assert_eq!(error.code(), "WYRD_SDK_422_VERIFICATION_DATA_INVALID");
        assert_eq!(
            error.problem().details,
            json!({"requirement": "secretive", "path": ""})
        );
        assert!(!error.to_string().contains("hunter2"), "{error}");
        let error = result(vec![requirement(
            "keyed",
            json!({"outer": {"customer-secret@example.test": "wrong"}}),
        )])
        .decode_data::<std::collections::BTreeMap<String, std::collections::BTreeMap<String, u8>>>()
        .expect_err("mismatch under a returned key");
        let problem = serde_json::to_string(&error.problem()).expect("problem");
        assert!(!problem.contains("customer-secret"), "{problem}");
        assert!(!error.to_string().contains("customer-secret"), "{error}");
    }

    /// Custom Verdict data obeys the inclusive size and depth bounds: exact
    /// boundaries pass and one more byte or container fails, counting UTF-8
    /// bytes, required JSON escapes, and wide arrays, with messages naming
    /// the limit and never the data.
    ///
    /// # Panics
    /// Panics when a boundary value is judged on the wrong side.
    #[test]
    fn custom_verdict_data_obeys_limits() {
        let verdict = |data: Value| Verdict {
            outcome: VerificationVerdict::Passed,
            reason: "ok".to_owned(),
            citations: Vec::new(),
            data: Some(data.as_object().expect("object data").clone()),
        };
        let text = |unit: &str, count: usize, tail: &str| json!({"s": format!("{}{tail}", unit.repeat(count))});
        let wide = |last: u32| {
            let mut items = vec![json!(0); 32_763];
            items.push(json!(last));
            json!({"a": items})
        };
        let nested = |containers: usize| {
            let mut value = json!(1);
            for level in 1..containers {
                value = if level % 2 == 0 {
                    json!({"o": value})
                } else {
                    json!([value])
                };
            }
            json!({"r": value})
        };
        for (data, fits) in [
            (text("x", 65_528, ""), true),
            (text("x", 65_529, ""), false),
            (text("é", 32_764, ""), true),
            (text("é", 32_764, "x"), false),
            (text("\n", 32_764, ""), true),
            (text("\n", 32_764, "x"), false),
            (text("\u{1}", 10_921, "xx"), true),
            (text("\u{1}", 10_921, "xxx"), false),
            (wide(9), true),
            (wide(10), true),
            (wide(100), false),
            (nested(16), true),
            (nested(17), false),
        ] {
            let bytes = serde_json::to_vec(&data).expect("json").len();
            match verdict(data).check_data_bounds() {
                Ok(()) => assert!(fits, "{bytes} bytes must fail"),
                Err(message) => {
                    assert!(!fits, "{bytes} bytes must pass: {message}");
                    assert!(
                        message.contains("65536") || message.contains("16"),
                        "{message}"
                    );
                    assert!(
                        !message.contains("xxx") && !message.contains('é'),
                        "{message}"
                    );
                }
            }
        }
        assert_eq!(
            serde_json::to_vec(&wide(10)).expect("json").len(),
            MAX_VERDICT_DATA_BYTES
        );
        let plain = Verdict {
            data: None,
            ..verdict(json!({}))
        };
        assert_eq!(plain.check_data_bounds(), Ok(()));
        assert!(
            serde_json::to_value(&plain)
                .expect("json")
                .get("data")
                .is_none(),
            "absent data is omitted"
        );
    }

    /// The plain Verdict schema is the portable structural target once
    /// titles and descriptions are removed: an outcome enum, closed citation
    /// objects, and five disjoint closed locator shapes under `anyOf`, with
    /// no `oneOf`, `const`, numeric annotations, or `$ref` siblings. The
    /// schema accepts every locator shape and refuses wrong outcomes,
    /// missing or extra fields, and several locator keys, while values the
    /// portable schema admits but `u32` cannot hold still fail decoding.
    ///
    /// # Panics
    /// Panics when the schema differs from the target or a value is judged
    /// on the wrong side.
    #[test]
    fn plain_verdict_schema_is_portable() {
        /// Refuses a non-portable keyword or a `$ref` sibling anywhere.
        ///
        /// # Panics
        /// Panics at the first node holding `oneOf`, `const`, `minimum`,
        /// `format`, or a `$ref` with siblings.
        fn portable(value: &Value) {
            match value {
                Value::Object(map) => {
                    assert!(!map.contains_key("$ref") || map.len() == 1, "{map:?}");
                    for keyword in ["oneOf", "const", "minimum", "format"] {
                        assert!(!map.contains_key(keyword), "{keyword} in {map:?}");
                    }
                    map.values().for_each(portable);
                }
                Value::Array(items) => items.iter().for_each(portable),
                _ => {}
            }
        }
        /// The schema with every `title` and `description` removed.
        fn structure(value: &Value) -> Value {
            match value {
                Value::Object(map) => Value::Object(
                    map.iter()
                        .filter(|(key, _)| !matches!(key.as_str(), "title" | "description"))
                        .map(|(key, value)| (key.clone(), structure(value)))
                        .collect(),
                ),
                Value::Array(items) => Value::Array(items.iter().map(structure).collect()),
                other => other.clone(),
            }
        }
        let schema = Value::Object(
            Verdict::response_format(&NamedResponseFormat::Name(VERDICT_FORMAT.to_owned()))
                .expect("resolves"),
        );
        let integer = || json!({"type": "integer"});
        let number = || json!({"type": "number"});
        let closed = |key: &str, value: Value| json!({"type": "object", "properties": {key: value}, "required": [key], "additionalProperties": false});
        let target = json!({
            "$schema": "https://json-schema.org/draft/2020-12/schema",
            "type": "object",
            "properties": {
                "outcome": {"$ref": "#/$defs/VerificationVerdict"},
                "reason": {"type": "string"},
                "citations": {"type": "array", "items": {"$ref": "#/$defs/Citation"}}
            },
            "additionalProperties": false,
            "required": ["outcome", "reason", "citations"],
            "$defs": {
                "VerificationVerdict": {"type": "string", "enum": ["passed", "failed", "inconclusive"]},
                "Citation": {
                    "type": "object",
                    "properties": {
                        "slot": {"$ref": "#/$defs/SlotName"},
                        "locator": {"$ref": "#/$defs/Locator"}
                    },
                    "additionalProperties": false,
                    "required": ["slot", "locator"]
                },
                "SlotName": {"type": "string"},
                "Locator": {"anyOf": [
                    closed("page", integer()),
                    closed("slide", integer()),
                    closed("lines", json!({
                        "type": "object",
                        "properties": {"start": integer(), "end": integer()},
                        "required": ["start", "end"],
                        "additionalProperties": false
                    })),
                    closed("json_pointer", json!({"type": "string"})),
                    closed("region", json!({
                        "type": "object",
                        "properties": {
                            "page": integer(), "x": number(), "y": number(),
                            "width": number(), "height": number()
                        },
                        "required": ["page", "x", "y", "width", "height"],
                        "additionalProperties": false
                    })),
                ]}
            }
        });
        assert_eq!(structure(&schema), target, "{schema:#}");
        portable(&schema);
        let validator = jsonschema::validator_for(&schema).expect("valid schema");
        let verdict = |outcome: Value, locator: Value| json!({"outcome": outcome, "reason": "r", "citations": [{"slot": "order", "locator": locator}]});
        for locator in [
            json!({"page": 1}),
            json!({"slide": 2}),
            json!({"lines": {"start": 1, "end": 3}}),
            json!({"json_pointer": "/a"}),
            json!({"region": {"page": 1, "x": 0.5, "y": 1, "width": 2, "height": 3}}),
        ] {
            let value = verdict(json!("failed"), locator);
            assert!(validator.is_valid(&value), "{value}");
            serde_json::from_value::<Verdict>(value.clone())
                .unwrap_or_else(|error| panic!("{value}: {error}"));
        }
        for value in [
            verdict(json!("FAIL"), json!({"page": 1})),
            verdict(json!("passed"), json!({"page": 1, "slide": 2})),
            verdict(json!("passed"), json!({"lines": {"start": 1}})),
            verdict(json!("passed"), json!({"page": 1, "extra": 1})),
            json!({"outcome": "passed", "reason": "r"}),
            json!({"outcome": "passed", "reason": "r", "citations": [], "extra": 1}),
            json!({"outcome": "passed", "reason": "r", "citations": [{"slot": "order"}]}),
        ] {
            assert!(!validator.is_valid(&value), "{value}");
        }
        for page in [json!(-1), json!(4_294_967_296_u64)] {
            let value = verdict(json!("passed"), json!({"page": page}));
            assert!(validator.is_valid(&value), "{value}");
            assert!(
                serde_json::from_value::<Verdict>(value.clone()).is_err(),
                "{value}"
            );
        }
    }

    /// An expanded format embeds the authored `data` schema with only the
    /// private `$id` added: its `oneOf`, `const`, numeric and `format`
    /// keywords, optional fields, and local references keep their meaning
    /// while the envelope around it is portable.
    ///
    /// # Panics
    /// Panics when an authored keyword changes or the data is not required.
    #[test]
    fn expanded_verdict_keeps_authored_data_schema() {
        let data = json!({
            "type": "object",
            "properties": {
                "score": {"type": "integer", "minimum": 1, "format": "int32", "description": "kept"},
                "kind": {"oneOf": [{"const": "a"}, {"const": "b"}]},
                "item": {"$ref": "#/$defs/item", "description": "kept"}
            },
            "required": ["score"],
            "$defs": {"item": {"type": "string", "minLength": 2}}
        });
        let format: NamedResponseFormat =
            serde_json::from_value(json!({"kind": "verdict", "data": data})).expect("format");
        let schema = Value::Object(Verdict::response_format(&format).expect("resolves"));
        let mut embedded = data.clone();
        embedded["$id"] = json!(DATA_RESOURCE);
        assert_eq!(schema["properties"]["data"], embedded);
        assert!(
            schema["required"]
                .as_array()
                .expect("required")
                .contains(&json!("data"))
        );
        assert!(schema["$defs"]["Locator"].get("anyOf").is_some());
        let validator = jsonschema::validator_for(&schema).expect("valid schema");
        let verdict = |data: Value| json!({"outcome": "passed", "reason": "r", "citations": [], "data": data});
        assert!(validator.is_valid(&verdict(json!({"score": 1, "kind": "a", "item": "ok"}))));
        for data in [
            json!({"score": 0}),
            json!({"score": 1, "kind": "c"}),
            json!({"score": 1, "item": "x"}),
            json!({}),
        ] {
            assert!(!validator.is_valid(&verdict(data.clone())), "{data}");
        }
    }

    /// Restriction admits exactly the reachable bare slots, and an empty set
    /// leaves the schema unchanged.
    ///
    /// # Panics
    /// Panics when a slot outside the set, or a prefixed slot, is admitted.
    #[test]
    fn restrict_slots_admits_only_reachable_slots() {
        let plain = Value::Object(
            Verdict::response_format(&NamedResponseFormat::Name(VERDICT_FORMAT.to_owned()))
                .expect("resolves"),
        );
        let mut unchanged = plain.clone();
        Verdict::restrict_slots(&mut unchanged, &BTreeSet::new());
        assert_eq!(unchanged, plain);
        let mut schema = plain;
        let slots = ["order", "receipt"].map(|slot| SlotName::new(slot).expect(slot));
        Verdict::restrict_slots(&mut schema, &slots.into_iter().collect());
        let slot = jsonschema::validator_for(&schema["$defs"]["SlotName"]).expect("valid");
        assert!(slot.is_valid(&json!("order")) && slot.is_valid(&json!("receipt")));
        for wrong in ["inputs.order", "other", ""] {
            assert!(!slot.is_valid(&json!(wrong)), "{wrong}");
        }
    }

    /// A delayed idempotency conflict is reported with the existing stable
    /// code on the execution status.
    ///
    /// # Panics
    /// Panics when the code or message is not carried over.
    #[test]
    fn verification_error_carries_idempotency_conflict() {
        let error = VerificationError::from(&WyrdError::RegistryIdempotencyConflict {
            message: "key reused with different content".to_owned(),
            details: json!({}),
        });
        assert_eq!(error.code, "WYRD_REGISTRY_409_IDEMPOTENCY_CONFLICT");
        assert_eq!(error.message, "key reused with different content");
    }
}