spoke-operations 0.19.0

SPOKE lifecycle helpers — pure functions over spoke-schemas wire types
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
//! `spoke-judgment` envelope validation and canonical comparison (spoke-judgment
//! wire contract): `validate_judgment` is the pure wire-shape gate — required
//! fields, the closed `Judgment` / `JudgmentRef` / `verdict` envelopes, raw
//! `minLength: 1` strings, the interoperable integer domain,
//! `verdict.confidence` in `[0, 1]` and the reserved `verdict.detail`
//! `verdict.detail.target`) report `INVALID_INPUT` with `details.field`
//! instead of opaque decode errors. `validate_judgment_typed` runs the same
//! gate on the generated typed `Judgment`: the generated integer carriers
//! admit values above the `2^53-1` wire ceiling, so the typed value is
//! re-encoded to the wire form and checked there.
//!
//! `judgments_equal_canonical` is the RFC 8785 comparison helper on the wire
//! JSON itself: `verdict.detail` presence, `extensions` and the `created_at`
//! spelling stay comparison-significant — typed decodes never normalize them.
//!
//! TypeScript parity: `packages/spoke-operations/src/judgment.ts`.

use crate::result::{spoke_ok, spoke_ok_unit, spoke_reject, SpokeRejectCode, SpokeResult};
use serde_json::{Map, Value};
use spoke_schemas::timestamp::parse_strict;

// Closed-envelope property tables (judgment.schema.json, additionalProperties:
// false on Judgment, JudgmentRef and Verdict).
const JUDGMENT_KEYS: [&str; 9] = [
    "schema_version",
    "judgment_id",
    "judgment_kind",
    "target",
    "evidence",
    "verdict",
    "basis",
    "created_at",
    "extensions",
];

const JUDGMENT_REF_KEYS: [&str; 4] = ["kind", "id", "namespace", "revision"];

const VERDICT_KEYS: [&str; 3] = ["outcome", "confidence", "detail"];

// Reserved verdict.detail direct member names — they duplicate protocol-level
// envelope locations (contract §verdict core and detail).
const DETAIL_RESERVED_MEMBERS: [&str; 4] = ["target", "evidence", "judgment_kind", "outcome"];

// Raw `minLength: 1`: whitespace-only strings are valid non-empty wire
// values; the raw string is measured, never trimmed (wire-wide rule).
fn is_non_empty_string(value: &str) -> bool {
    !value.is_empty()
}

fn is_plain_object(value: &Value) -> bool {
    value.is_object()
}

// Interoperable integer domain [0, 2^53-1]: exact in u64 and IEEE-754
// binary64 alike. Integral spellings (`1.0`) decode as the integer they
// spell; non-integral or out-of-domain values are INVALID_INPUT.
const MAX_INTEROPERABLE_INTEGER: u64 = (1 << 53) - 1;

fn wire_integer(value: &Value) -> Option<u64> {
    if let Some(v) = value.as_u64() {
        return (v <= MAX_INTEROPERABLE_INTEGER).then_some(v);
    }
    match value.as_f64() {
        Some(v) if v.fract() == 0.0 && (0.0..=(MAX_INTEROPERABLE_INTEGER as f64)).contains(&v) => {
            Some(v as u64)
        }
        _ => None,
    }
}

fn is_positive_integer(value: &Value) -> bool {
    wire_integer(value).is_some_and(|v| v >= 1)
}

// One timestamp gate for the whole crate: the shared strict RFC 3339 parser
// (`spoke_schemas::timestamp`) — explicit offset required, `T`/`t` separator
// only, calendar-valid, leap second admitted (`spoke-data-model` §Shared wire
// scalars).
fn is_parseable_date_time(value: &str) -> bool {
    parse_strict(value).is_ok()
}

// Shared ExtensionMap grammar: namespace keys match `^[a-z][a-z0-9_-]*$`.
fn is_namespace(value: &str) -> bool {
    let mut chars = value.chars();
    match chars.next() {
        Some(c) if c.is_ascii_lowercase() => {}
        _ => return false,
    }
    value[1..]
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
}

/// Every shape violation rejects `INVALID_INPUT` with `details.field` set to
/// the logical field path (dotted members, bracketed array indices, e.g.
/// `target.revision`, `evidence[0].revision`, `verdict.detail.target`). `field`
/// is the only protocol-required member of `details`; the `message` carries no
/// stable machine semantics.
fn invalid(field: &str, message: &str) -> SpokeResult<()> {
    let mut details = Map::new();
    details.insert("field".into(), Value::String(field.into()));
    spoke_reject(SpokeRejectCode::InvalidInput, message, Some(details))
}

fn has_only_keys(value: &Map<String, Value>, allowed: &[&str]) -> bool {
    value.keys().all(|key| allowed.contains(&key.as_str()))
}

fn validate_judgment_ref(ref_: &Value, field: &str, require_revision: bool) -> SpokeResult<()> {
    let Some(ref_) = ref_.as_object() else {
        return invalid(field, &format!("{field} must be a JudgmentRef object"));
    };
    if !has_only_keys(ref_, &JUDGMENT_REF_KEYS) {
        return invalid(
            field,
            &format!("{field} carries a member outside the JudgmentRef shape"),
        );
    }
    let kind = ref_.get("kind").and_then(Value::as_str).unwrap_or("");
    if !is_non_empty_string(kind) {
        return invalid(
            &format!("{field}.kind"),
            &format!("{field}.kind must be a non-empty string"),
        );
    }
    let id = ref_.get("id").and_then(Value::as_str).unwrap_or("");
    if !is_non_empty_string(id) {
        return invalid(
            &format!("{field}.id"),
            &format!("{field}.id must be a non-empty string"),
        );
    }
    if let Some(namespace) = ref_.get("namespace") {
        let namespace = namespace.as_str().unwrap_or("");
        if !is_non_empty_string(namespace) {
            return invalid(
                &format!("{field}.namespace"),
                &format!("{field}.namespace must be a non-empty string when present"),
            );
        }
    }
    let revision = ref_.get("revision");
    if require_revision && revision.is_none() {
        return invalid(
            &format!("{field}.revision"),
            &format!("{field}.revision is required on evidence references"),
        );
    }
    if let Some(revision) = revision {
        if !is_positive_integer(revision) {
            return invalid(
                &format!("{field}.revision"),
                &format!("{field}.revision must be a positive integer"),
            );
        }
    }
    spoke_ok_unit()
}

/// Wire-shape gate for `Judgment` (optional capability spoke-judgment).
///
/// Checks required-field presence, the closed envelopes, raw `minLength: 1`
/// strings, `schema_version`/`revision` positive integers in the
/// interoperable `[0, 2^53-1]` domain, `verdict` shape and the reserved
/// `verdict.detail` members. Pure envelope validation only — verdict
/// truth, evidence existence or content correctness, and product-specific
/// `detail` shape stay product-owned. Deterministic, no I/O.
pub fn validate_judgment(judgment: &Value) -> SpokeResult<()> {
    let Some(judgment) = judgment.as_object() else {
        return invalid("judgment", "judgment must be an object");
    };
    if !has_only_keys(judgment, &JUDGMENT_KEYS) {
        return invalid(
            "judgment",
            "judgment carries a member outside the Judgment shape",
        );
    }
    let schema_version = judgment.get("schema_version").unwrap_or(&Value::Null);
    if !is_positive_integer(schema_version) {
        return invalid("schema_version", "schema_version must be an integer >= 1");
    }
    let judgment_id = judgment
        .get("judgment_id")
        .and_then(Value::as_str)
        .unwrap_or("");
    if !is_non_empty_string(judgment_id) {
        return invalid("judgment_id", "judgment_id must be a non-empty string");
    }
    let judgment_kind = judgment
        .get("judgment_kind")
        .and_then(Value::as_str)
        .unwrap_or("");
    if !is_non_empty_string(judgment_kind) {
        return invalid(
            "judgment_kind",
            "judgment_kind must be a non-empty string",
        );
    }

    let target = match judgment.get("target") {
        Some(target) => target,
        None => return invalid("target", "target must be a JudgmentRef object"),
    };
    let target_result = validate_judgment_ref(target, "target", false);
    if target_result.is_reject() {
        return target_result;
    }

    let Some(evidence) = judgment.get("evidence").and_then(Value::as_array) else {
        return invalid("evidence", "evidence must be an array (may be empty)");
    };
    for (index, item) in evidence.iter().enumerate() {
        let result = validate_judgment_ref(item, &format!("evidence[{index}]"), true);
        if result.is_reject() {
            return result;
        }
    }

    let verdict = match judgment.get("verdict") {
        Some(verdict) => verdict,
        None => return invalid("verdict", "verdict must be an object"),
    };
    let Some(verdict) = verdict.as_object() else {
        return invalid("verdict", "verdict must be an object");
    };
    if !has_only_keys(verdict, &VERDICT_KEYS) {
        return invalid(
            "verdict",
            "verdict carries a member outside the Verdict shape",
        );
    }
    let outcome = verdict
        .get("outcome")
        .and_then(Value::as_str)
        .unwrap_or("");
    if !is_non_empty_string(outcome) {
        return invalid(
            "verdict.outcome",
            "verdict.outcome must be a non-empty string",
        );
    }
    if let Some(confidence) = verdict.get("confidence") {
        if !confidence
            .as_f64()
            .is_some_and(|c| c.is_finite() && (0.0..=1.0).contains(&c))
        {
            return invalid(
                "verdict.confidence",
                "verdict.confidence must be a number in [0, 1]",
            );
        }
    }
    if let Some(detail) = verdict.get("detail") {
        let Some(detail) = detail.as_object() else {
            return invalid("verdict.detail", "verdict.detail must be an object");
        };
        // Fixed protocol probe order (contract §verdict core and detail):
        // bounded over the four reserved names, independent of wire member
        // order, so `details.field` is deterministic across stacks.
        for member in DETAIL_RESERVED_MEMBERS {
            if detail.contains_key(member) {
                return invalid(
                    &format!("verdict.detail.{member}"),
                    &format!(
                        "verdict.detail.{member} duplicates a protocol envelope location"
                    ),
                );
            }
        }
    }

    if let Some(basis) = judgment.get("basis") {
        if !basis.is_string() {
            return invalid("basis", "basis must be a string when present");
        }
    }
    if let Some(created_at) = judgment.get("created_at") {
        if !created_at.is_string()
            || !is_parseable_date_time(created_at.as_str().unwrap_or(""))
        {
            return invalid(
                "created_at",
                "created_at must be an RFC 3339 timestamp when present",
            );
        }
    }
    let Some(extensions) = judgment.get("extensions").and_then(Value::as_object) else {
        return invalid("extensions", "extensions must be a present object");
    };
    // Sorted-order probe: with several failing entries the first refusal
    // names the lexicographically-first offending member. Keys are sorted
    // explicitly by code point (`str::cmp` compares UTF-8 bytes, which is
    // code-point order) so the probe never depends on `serde_json::Map`
    // iteration order — it stays correct even under `serde_json/preserve_order`.
    let mut keys: Vec<&String> = extensions.keys().collect();
    keys.sort();
    for key in keys {
        let entry = &extensions[key];
        if !is_namespace(key) || !is_plain_object(entry) {
            return invalid(
                &format!("extensions.{key}"),
                "extensions entries need a namespace key and an object value",
            );
        }
    }

    spoke_ok_unit()
}

/// Wire-shape gate for the generated typed `Judgment`
/// (`spoke_schemas::Judgment`). The generated carrier admits values the wire
/// domain refuses — `schema_version` and `JudgmentRef.revision` are
/// `NonZeroU64` with no `2^53-1` ceiling — so the typed value is re-encoded
/// to the wire form and run through `validate_judgment`, which applies the
/// wire-integer domain to the typed value's fields. A typed `Judgment` that
/// fails to re-encode reports `INVALID_INPUT` at `judgment`.
pub fn validate_judgment_typed(
    judgment: &spoke_schemas::data::judgment::Judgment,
) -> SpokeResult<()> {
    match serde_json::to_value(judgment) {
        Ok(wire) => validate_judgment(&wire),
        Err(_) => invalid("judgment", "judgment failed to re-encode to the wire form"),
    }
}

/// Whether two `Judgment` wire values are byte-identical under RFC 8785
/// canonical JSON — the contract's producer-equality rule. Compares the
/// canonical serialization of the wire JSON, never a typed decode: member
/// presence (`verdict.detail: {}` ≠ absent) and the `created_at` spelling
/// stay comparison-significant.
///
/// Rejects with `INVALID_INPUT` when either judgment cannot be serialized to
/// canonical bytes.
pub fn judgments_equal_canonical(left: &Value, right: &Value) -> SpokeResult<bool> {
    let left = match serde_jcs::to_vec(left) {
        Ok(bytes) => bytes,
        Err(error) => {
            return spoke_reject(
                SpokeRejectCode::InvalidInput,
                format!("JCS canonicalization failed: {error}"),
                None,
            );
        }
    };
    let right = match serde_jcs::to_vec(right) {
        Ok(bytes) => bytes,
        Err(error) => {
            return spoke_reject(
                SpokeRejectCode::InvalidInput,
                format!("JCS canonicalization failed: {error}"),
                None,
            );
        }
    };
    spoke_ok(left == right)
}

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

    fn valid_judgment() -> Value {
        serde_json::json!({
            "schema_version": 1,
            "judgment_id": "j-1",
            "judgment_kind": "consistency",
            "target": {"kind": "knowledge_entry", "id": "ke-1"},
            "evidence": [
                {"kind": "knowledge_entry", "id": "ke-2", "revision": 3},
                {"kind": "rule", "id": "r-1", "namespace": "prod", "revision": 1},
            ],
            "verdict": {
                "outcome": "consistent",
                "confidence": 0.9,
                "detail": {"reason": "all agree"},
            },
            "basis": "human review",
            "created_at": "2026-11-22T10:00:00Z",
            "extensions": {},
        })
    }


    fn expect_invalid(result: SpokeResult<()>, field: &str) {
        let SpokeResult::Reject(reject) = result else {
            panic!("expected INVALID_INPUT reject for {field}");
        };
        assert_eq!(reject.code, SpokeRejectCode::InvalidInput);
        let details = reject.details.expect("reject carries details");
        assert_eq!(details.get("field").and_then(Value::as_str), Some(field));
    }

    #[test]
    fn validate_judgment_accepts_valid_record() {
        assert!(matches!(validate_judgment(&valid_judgment()), SpokeResult::Ok(())));
    }

    #[test]
    fn validate_judgment_rejects_missing_and_empty_required_fields() {
        let mut judgment = valid_judgment();
        judgment.as_object_mut().unwrap().remove("judgment_id");
        expect_invalid(validate_judgment(&judgment), "judgment_id");

        let mut judgment = valid_judgment();
        judgment["judgment_id"] = Value::String("".into());
        expect_invalid(validate_judgment(&judgment), "judgment_id");

        let mut judgment = valid_judgment();
        judgment["judgment_kind"] = Value::String("".into());
        expect_invalid(validate_judgment(&judgment), "judgment_kind");

        let mut judgment = valid_judgment();
        judgment["schema_version"] = Value::from(0);
        expect_invalid(validate_judgment(&judgment), "schema_version");

        let mut judgment = valid_judgment();
        judgment["schema_version"] = Value::from(1.5);
        expect_invalid(validate_judgment(&judgment), "schema_version");
    }

    #[test]
    fn validate_judgment_rejects_bad_target_and_evidence_refs() {
        let mut judgment = valid_judgment();
        judgment["target"] = serde_json::json!({"kind": "", "id": "ke-1"});
        expect_invalid(validate_judgment(&judgment), "target.kind");

        let mut judgment = valid_judgment();
        judgment["target"]["namespace"] = Value::String("".into());
        expect_invalid(validate_judgment(&judgment), "target.namespace");

        let mut judgment = valid_judgment();
        judgment["target"]["revision"] = Value::from(0);
        expect_invalid(validate_judgment(&judgment), "target.revision");

        let mut judgment = valid_judgment();
        judgment["target"]["extra"] = Value::Bool(true);
        expect_invalid(validate_judgment(&judgment), "target");

        let mut judgment = valid_judgment();
        judgment["evidence"] = serde_json::json!([{"kind": "rule", "id": "r-1"}]);
        expect_invalid(validate_judgment(&judgment), "evidence[0].revision");

        let mut judgment = valid_judgment();
        judgment["evidence"][0]["revision"] = Value::from(-1);
        expect_invalid(validate_judgment(&judgment), "evidence[0].revision");

        let mut judgment = valid_judgment();
        judgment["evidence"][1]["namespace"] = Value::String("".into());
        expect_invalid(validate_judgment(&judgment), "evidence[1].namespace");
    }

    #[test]
    fn validate_judgment_rejects_bad_verdict() {
        let mut judgment = valid_judgment();
        judgment["verdict"]["outcome"] = Value::String("".into());
        expect_invalid(validate_judgment(&judgment), "verdict.outcome");

        let mut judgment = valid_judgment();
        judgment["verdict"]["confidence"] = Value::from(1.5);
        expect_invalid(validate_judgment(&judgment), "verdict.confidence");

        let mut judgment = valid_judgment();
        judgment["verdict"]["confidence"] = Value::from(-0.1);
        expect_invalid(validate_judgment(&judgment), "verdict.confidence");

        let mut judgment = valid_judgment();
        judgment["verdict"]["confidence"] = Value::String("high".into());
        expect_invalid(validate_judgment(&judgment), "verdict.confidence");

        let mut judgment = valid_judgment();
        judgment["verdict"]["detail"] = serde_json::json!({"target": "x"});
        expect_invalid(validate_judgment(&judgment), "verdict.detail.target");

        let mut judgment = valid_judgment();
        judgment["verdict"]["extra"] = Value::Bool(true);
        expect_invalid(validate_judgment(&judgment), "verdict");
    }

    #[test]
    fn validate_judgment_rejects_envelope_and_optional_shape_errors() {
        expect_invalid(
            validate_judgment(&serde_json::json!(null)),
            "judgment",
        );
        expect_invalid(
            validate_judgment(&serde_json::json!([])),
            "judgment",
        );

        let mut judgment = valid_judgment();
        judgment["stray"] = Value::Bool(true);
        expect_invalid(validate_judgment(&judgment), "judgment");

        let mut judgment = valid_judgment();
        judgment.as_object_mut().unwrap().remove("extensions");
        expect_invalid(validate_judgment(&judgment), "extensions");

        let mut judgment = valid_judgment();
        judgment["extensions"] = serde_json::json!([]);
        expect_invalid(validate_judgment(&judgment), "extensions");

        let mut judgment = valid_judgment();
        judgment["evidence"] = Value::Null;
        expect_invalid(validate_judgment(&judgment), "evidence");

        let mut judgment = valid_judgment();
        judgment["basis"] = Value::from(7);
        expect_invalid(validate_judgment(&judgment), "basis");

        let mut judgment = valid_judgment();
        judgment["created_at"] = Value::String("not-a-date".into());
        expect_invalid(validate_judgment(&judgment), "created_at");
    }

    #[test]
    fn validate_judgment_accepts_boundary_confidence_and_empty_evidence() {
        let mut judgment = valid_judgment();
        judgment["verdict"]["confidence"] = Value::from(1.0);
        judgment["evidence"] = serde_json::json!([]);
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));
    }

    #[test]
    fn validate_judgment_uses_raw_min_length_one() {
        // Raw minLength: 1 — whitespace-only strings are valid non-empty
        // wire values (a lone space, U+FEFF); only the empty string fails.
        let mut judgment = valid_judgment();
        judgment["judgment_id"] = Value::String(" ".into());
        judgment["judgment_kind"] = Value::String("\u{FEFF}".into());
        judgment["target"]["kind"] = Value::String(" ".into());
        judgment["target"]["namespace"] = Value::String(" ".into());
        judgment["verdict"]["outcome"] = Value::String(" ".into());
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));
    }

    #[test]
    fn validate_judgment_enforces_the_interoperable_integer_domain() {
        // Integral spellings decode as the integer they spell.
        let mut judgment = valid_judgment();
        judgment["schema_version"] = Value::from(2.0);
        judgment["evidence"][0]["revision"] = Value::from(1.0);
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));

        // The top of [0, 2^53-1] is exact on both stacks.
        let mut judgment = valid_judgment();
        judgment["evidence"][0]["revision"] = Value::from(9_007_199_254_740_991_u64);
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));

        // 2^53 is out of domain even though it is u64-safe.
        let mut judgment = valid_judgment();
        judgment["evidence"][0]["revision"] = Value::from(9_007_199_254_740_992_u64);
        expect_invalid(validate_judgment(&judgment), "evidence[0].revision");

        let mut judgment = valid_judgment();
        judgment["target"]["revision"] = Value::from(2.5);
        expect_invalid(validate_judgment(&judgment), "target.revision");
    }

    #[test]
    fn validate_judgment_requires_a_created_at_offset() {
        let mut judgment = valid_judgment();
        judgment["created_at"] = Value::String("2026-11-22T10:00:00".into());
        expect_invalid(validate_judgment(&judgment), "created_at");

        // Leap-second spellings stay accepted.
        let mut judgment = valid_judgment();
        judgment["created_at"] = Value::String("2026-06-30T23:59:60Z".into());
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));

        // Explicit non-UTC offsets are accepted.
        let mut judgment = valid_judgment();
        judgment["created_at"] = Value::String("2026-11-22T18:00:00+08:00".into());
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));

        // Invalid calendar days stay refused.
        let mut judgment = valid_judgment();
        judgment["created_at"] = Value::String("2026-02-30T10:00:00Z".into());
        expect_invalid(validate_judgment(&judgment), "created_at");
    }

    #[test]
    fn validate_judgment_matches_created_at_against_the_raw_wire_string() {
        // The grammar is matched against the raw wire string exactly as
        // received: leading or trailing whitespace refuses even though the
        // inner spelling is a valid timestamp.
        let mut judgment = valid_judgment();
        judgment["created_at"] = Value::String(" 2026-06-30T15:59:59Z ".into());
        expect_invalid(validate_judgment(&judgment), "created_at");

        let mut judgment = valid_judgment();
        judgment["created_at"] = Value::String("\t2026-06-30T15:59:59Z".into());
        expect_invalid(validate_judgment(&judgment), "created_at");

        // A non-`T`/`t` date-time separator refuses — chrono's RFC 3339
        // parse alone would accept the space at index 10.
        let mut judgment = valid_judgment();
        judgment["created_at"] = Value::String("2026-06-30 15:59:59Z".into());
        expect_invalid(validate_judgment(&judgment), "created_at");

        // Lowercase `t` and `z` spellings stay accepted.
        let mut judgment = valid_judgment();
        judgment["created_at"] = Value::String("2026-06-30t15:59:59z".into());
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));
    }

    #[test]
    fn validate_judgment_refuses_non_ascii_created_at_spelling() {
        // Only ASCII offset signs are in contract: chrono's RFC 3339 parse
        // alone accepts U+2212 MINUS SIGN as an offset sign.
        let mut judgment = valid_judgment();
        judgment["created_at"] = Value::String("2026-06-30T23:59:59\u{2212}08:00".into());
        expect_invalid(validate_judgment(&judgment), "created_at");

        // Any non-ASCII byte refuses, not only offset signs.
        let mut judgment = valid_judgment();
        judgment["created_at"] = Value::String("2026-06-30T15:59:59\u{2212}".into());
        expect_invalid(validate_judgment(&judgment), "created_at");

        // ASCII `+` and `-` offsets stay accepted.
        let mut judgment = valid_judgment();
        judgment["created_at"] = Value::String("2026-06-30T15:59:59-08:00".into());
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));
        let mut judgment = valid_judgment();
        judgment["created_at"] = Value::String("2026-06-30T15:59:59+08:00".into());
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));
    }

    #[test]
    fn extensions_multi_violation_reports_the_lexicographically_first_key() {
        // Sorted-order probe: with several failing entries, details.field
        // names the first offending member in lexicographic key order —
        // derived from the map's keys alone, deterministic across stacks.
        let mut judgment = valid_judgment();
        judgment["extensions"] = serde_json::json!({"zeta_ns": 7, "Alpha": {}, "9lives": {}});
        expect_invalid(validate_judgment(&judgment), "extensions.9lives");

        let mut judgment = valid_judgment();
        judgment["extensions"] = serde_json::json!({"zeta_ns": 7, "acme_audit": 7});
        expect_invalid(validate_judgment(&judgment), "extensions.acme_audit");

        // A valid member ahead of an invalid one is skipped, not reported.
        let mut judgment = valid_judgment();
        judgment["extensions"] = serde_json::json!({"a_ok": {}, "bad key": {}});
        expect_invalid(validate_judgment(&judgment), "extensions.bad key");
    }

    #[test]
    fn validate_judgment_enforces_the_extension_map_grammar() {
        let mut judgment = valid_judgment();
        judgment["extensions"] = serde_json::json!({"Acme": {}});
        expect_invalid(validate_judgment(&judgment), "extensions.Acme");

        let mut judgment = valid_judgment();
        judgment["extensions"] = serde_json::json!({"acme": 7});
        expect_invalid(validate_judgment(&judgment), "extensions.acme");

        let mut judgment = valid_judgment();
        judgment["extensions"] = serde_json::json!({"acme-prod_1": {"flag": true}});
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));
    }

    #[test]
    fn detail_reserved_probe_follows_the_fixed_protocol_order() {
        // Probe order target, evidence, judgment_kind, outcome is independent
        // of wire member order, so details.field matches across stacks.
        let mut judgment = valid_judgment();
        judgment["verdict"]["detail"] =
            serde_json::json!({"outcome": 1, "judgment_kind": 1, "evidence": 1, "target": 1});
        expect_invalid(validate_judgment(&judgment), "verdict.detail.target");

        let mut judgment = valid_judgment();
        judgment["verdict"]["detail"] =
            serde_json::json!({"outcome": 1, "judgment_kind": 1});
        expect_invalid(validate_judgment(&judgment), "verdict.detail.judgment_kind");
    }

    #[test]
    fn validate_judgment_typed_enforces_the_wire_integer_ceiling() {
        // The generated integer carriers are NonZeroU64: a typed decode
        // accepts u64 values above the 2^53-1 interoperable domain. The
        // typed gate re-applies the wire-integer rule to those fields.
        let typed: spoke_schemas::data::judgment::Judgment =
            serde_json::from_value(valid_judgment()).expect("valid wire decodes");
        assert!(matches!(
            validate_judgment_typed(&typed),
            SpokeResult::Ok(())
        ));

        let mut typed: spoke_schemas::data::judgment::Judgment =
            serde_json::from_value(valid_judgment()).expect("valid wire decodes");
        typed.schema_version =
            std::num::NonZeroU64::new(MAX_INTEROPERABLE_INTEGER + 1).unwrap();
        expect_invalid(validate_judgment_typed(&typed), "schema_version");

        // The boundary value itself stays accepted.
        let mut typed: spoke_schemas::data::judgment::Judgment =
            serde_json::from_value(valid_judgment()).expect("valid wire decodes");
        typed.schema_version =
            std::num::NonZeroU64::new(MAX_INTEROPERABLE_INTEGER).unwrap();
        assert!(matches!(
            validate_judgment_typed(&typed),
            SpokeResult::Ok(())
        ));

        let mut typed: spoke_schemas::data::judgment::Judgment =
            serde_json::from_value(valid_judgment()).expect("valid wire decodes");
        typed.evidence[0].revision =
            std::num::NonZeroU64::new(MAX_INTEROPERABLE_INTEGER + 1).unwrap();
        expect_invalid(validate_judgment_typed(&typed), "evidence[0].revision");
    }

    #[test]
    fn validate_judgment_enforces_schema_version_and_revision_ceilings() {
        let mut judgment = valid_judgment();
        judgment["schema_version"] = Value::from(MAX_INTEROPERABLE_INTEGER);
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));
        judgment["schema_version"] = Value::from(MAX_INTEROPERABLE_INTEGER + 1);
        expect_invalid(validate_judgment(&judgment), "schema_version");

        // `target.revision` and `evidence[].revision` keep the narrowed
        // published domain [1, 2^53-1].
        let mut judgment = valid_judgment();
        judgment["target"]["revision"] = Value::from(MAX_INTEROPERABLE_INTEGER);
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));
        judgment["target"]["revision"] = Value::from(MAX_INTEROPERABLE_INTEGER + 1);
        expect_invalid(validate_judgment(&judgment), "target.revision");
        judgment["target"]["revision"] = Value::from(0);
        expect_invalid(validate_judgment(&judgment), "target.revision");

        let mut judgment = valid_judgment();
        judgment["evidence"][0]["revision"] = Value::from(MAX_INTEROPERABLE_INTEGER);
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));
        judgment["evidence"][0]["revision"] = Value::from(MAX_INTEROPERABLE_INTEGER + 1);
        expect_invalid(validate_judgment(&judgment), "evidence[0].revision");
        judgment["evidence"][0]["revision"] = Value::from(0);
        expect_invalid(validate_judgment(&judgment), "evidence[0].revision");
    }

    #[test]
    fn validate_judgment_uses_the_strict_timestamp_gate() {
        let mut judgment = valid_judgment();
        judgment["created_at"] = Value::String("2026-07-23T09:00:60Z".into());
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));

        for refused in [
            "2026-11-23T10:00:00",
            "2026-11-23 10:00:00Z",
            "2026-11-23T10:00:00 UTC",
        ] {
            let mut judgment = valid_judgment();
            judgment["created_at"] = Value::String(refused.into());
            expect_invalid(validate_judgment(&judgment), "created_at");
        }
    }

    #[test]
    fn identical_judgments_compare_equal() {
        assert!(matches!(
            judgments_equal_canonical(&valid_judgment(), &valid_judgment()),
            SpokeResult::Ok(true)
        ));
    }

    #[test]
    fn different_judgments_compare_unequal() {
        let mut right = valid_judgment();
        right["judgment_id"] = Value::String("j-2".into());
        assert!(matches!(
            judgments_equal_canonical(&valid_judgment(), &right),
            SpokeResult::Ok(false)
        ));
    }

    #[test]
    fn member_order_does_not_change_the_canonical_bytes() {
        let left = serde_json::json!({
            "judgment_id": "j-1",
            "judgment_kind": "review",
            "schema_version": 1,
            "target": {"id": "ke-1", "kind": "knowledge_entry"},
            "evidence": [],
            "verdict": {"outcome": "accepted", "detail": {"a": 1, "b": 2}},
            "extensions": {},
        });
        let right = serde_json::json!({
            "extensions": {},
            "verdict": {"detail": {"b": 2, "a": 1}, "outcome": "accepted"},
            "evidence": [],
            "target": {"kind": "knowledge_entry", "id": "ke-1"},
            "schema_version": 1,
            "judgment_kind": "review",
            "judgment_id": "j-1",
        });
        assert!(matches!(
            judgments_equal_canonical(&left, &right),
            SpokeResult::Ok(true)
        ));
    }

    #[test]
    fn detail_is_included_in_canonical_bytes() {
        let mut right = valid_judgment();
        right["verdict"]["detail"] = serde_json::json!({"reason": "changed"});
        assert!(matches!(
            judgments_equal_canonical(&valid_judgment(), &right),
            SpokeResult::Ok(false)
        ));
    }

    #[test]
    fn present_empty_detail_differs_from_absent_detail() {
        // Wire presence is comparison-significant: a present-and-empty
        // verdict.detail is a distinct member from an absent detail.
        let mut left = valid_judgment();
        left["verdict"].as_object_mut().unwrap().remove("detail");
        let mut right = left.clone();
        right["verdict"]["detail"] = serde_json::json!({});
        assert!(matches!(
            judgments_equal_canonical(&left, &right),
            SpokeResult::Ok(false)
        ));
    }

    /// In-memory detail payload nesting `levels` objects.
    fn deep_detail(levels: usize) -> Value {
        let mut deep = serde_json::json!({"note": "leaf"});
        for _ in 0..levels {
            let mut wrapper = Map::new();
            wrapper.insert("nested".into(), deep);
            deep = Value::Object(wrapper);
        }
        deep
    }

    #[test]
    fn wire_projection_accepts_conformance_depth() {
        // 100 levels sits inside every target engine's wire ceiling, so the
        // in-memory value validates. A 5000-level in-memory value is not
        // built here: recursive construction and drop abort the default
        // test-thread stack. The deserializer's own nesting ceiling is a
        // serde_json implementation fact, not a Spoke refusal contract, so
        // this suite does not pin it.
        let mut judgment = valid_judgment();
        judgment["verdict"]["detail"] = deep_detail(100);
        assert!(matches!(validate_judgment(&judgment), SpokeResult::Ok(())));
    }

    #[test]
    fn created_at_spelling_stays_comparison_significant() {
        // `created_at` compares by its exact wire spelling; the same instant
        // spelled with a non-UTC offset is a different canonical string.
        let mut right = valid_judgment();
        right["created_at"] = Value::String("2026-11-22T18:00:00+08:00".into());
        assert!(matches!(
            judgments_equal_canonical(&valid_judgment(), &right),
            SpokeResult::Ok(false)
        ));
    }
}