golem-schema 1.6.1

Golem schema and value model
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
// Copyright 2024-2026 Golem Cloud
//
// Licensed under the Golem Source License v1.1 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://license.golem.cloud/LICENSE
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! JSON value renderer: convert a `(SchemaGraph, SchemaType, SchemaValue)`
//! to and from a `serde_json::Value`.
//!
//! Rich scalars route through [`crate::schema::canonical`]; the renderer
//! never re-implements their text/JSON forms.

use crate::schema::canonical;
use crate::schema::graph::SchemaGraph;
use crate::schema::host_managed::HostManagedKind;
use crate::schema::metadata::TypeId;
use crate::schema::render::error::RenderError;
use crate::schema::render::walker::{SchemaWalker, WalkerError, resolve_ref, walk};
use crate::schema::schema_type::{
    DiscriminatorRule, ResultSpec, SchemaType, UnionBranch, UnionSpec, VariantCaseType,
};
use crate::schema::schema_value::{
    ResultValuePayload, SchemaValue, UnionValuePayload, VariantValuePayload,
};
use serde_json::{Map, Number, Value};
use std::collections::HashSet;

/// Render a value tree to a `serde_json::Value`.
pub fn to_json_value(
    graph: &SchemaGraph,
    ty: &SchemaType,
    value: &SchemaValue,
) -> Result<Value, RenderError> {
    let mut renderer = ToJsonRenderer {
        path: PathStack::new(),
        redact: false,
    };
    drive(walk(&mut renderer, graph, ty, value))
}

/// Render a value tree to a `serde_json::Value`, redacting every
/// host-managed capability node (see [`HostManagedKind`]).
///
/// Each `Secret` / `QuotaToken` value — including those nested inside
/// records, variants, lists, maps, options, results and unions — is
/// replaced with the JSON string `"<redacted: kind>"`. Non-capability
/// material is encoded exactly as in [`to_json_value`].
///
/// Use this on external-facing surfaces (MCP tool/resource responses,
/// custom HTTP API responses) that would otherwise forward raw
/// capability references to clients. Internal, trusted callers that
/// need the lossless round-trippable form — registry storage,
/// cross-worker RPC, oplog/grpc, config storage — should keep using
/// [`to_json_value`]. Unlike [`to_json_value`], the output of this
/// function is **not** guaranteed to round-trip through
/// [`from_json_value`]; the redacted placeholder is a one-way sink.
pub fn to_json_value_redacted(
    graph: &SchemaGraph,
    ty: &SchemaType,
    value: &SchemaValue,
) -> Result<Value, RenderError> {
    let mut renderer = ToJsonRenderer {
        path: PathStack::new(),
        redact: true,
    };
    drive(walk(&mut renderer, graph, ty, value))
}

/// Decode a `serde_json::Value` into a value tree typed by `ty` in `graph`.
pub fn from_json_value(
    graph: &SchemaGraph,
    ty: &SchemaType,
    json: &Value,
) -> Result<SchemaValue, RenderError> {
    from_json_value_with_policy(graph, ty, json, JsonDecodePolicy::Trusted)
}

/// Decode externally supplied JSON without allowing it to construct
/// host-managed capabilities. Rejection happens when the selected value path
/// reaches a capability leaf, so absent options and unselected sum-type arms
/// remain valid.
pub fn from_untrusted_json_value(
    graph: &SchemaGraph,
    ty: &SchemaType,
    json: &Value,
) -> Result<SchemaValue, RenderError> {
    from_json_value_with_policy(graph, ty, json, JsonDecodePolicy::Untrusted)
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum JsonDecodePolicy {
    Trusted,
    Untrusted,
}

fn from_json_value_with_policy(
    graph: &SchemaGraph,
    ty: &SchemaType,
    json: &Value,
    policy: JsonDecodePolicy,
) -> Result<SchemaValue, RenderError> {
    let mut path = PathStack::new();
    let mut visited: HashSet<TypeId> = HashSet::new();
    from_json_inner(graph, ty, json, &mut path, &mut visited, policy)
}

// --------------------------------------------------------------------- to

struct ToJsonRenderer {
    path: PathStack,
    redact: bool,
}

impl SchemaWalker for ToJsonRenderer {
    type Output = Value;
    type Error = RenderError;

    fn walk(
        &mut self,
        graph: &SchemaGraph,
        ty: &SchemaType,
        value: &SchemaValue,
    ) -> Result<Value, RenderError> {
        encode(self, graph, ty, value)
    }
}

fn drive<T>(res: Result<T, WalkerError<RenderError>>) -> Result<T, RenderError> {
    match res {
        Ok(v) => Ok(v),
        Err(WalkerError::Walker(e)) => Err(e),
        Err(WalkerError::RefCycle(id)) => Err(RenderError::ValueMismatch {
            path: String::new(),
            reason: format!("reference cycle through `{id}`"),
        }),
        Err(WalkerError::DanglingRef(id)) => Err(RenderError::ValueMismatch {
            path: String::new(),
            reason: format!("dangling reference `{id}`"),
        }),
    }
}

fn encode(
    r: &mut ToJsonRenderer,
    graph: &SchemaGraph,
    ty: &SchemaType,
    value: &SchemaValue,
) -> Result<Value, RenderError> {
    if r.redact
        && let (Some(type_kind), Some(value_kind)) = (
            HostManagedKind::from_type(ty),
            HostManagedKind::from_value(value),
        )
        && type_kind == value_kind
    {
        return Ok(Value::String(type_kind.redacted_placeholder().to_string()));
    }

    match (ty, value) {
        (SchemaType::Ref { .. }, _) => unreachable!("walker resolves refs"),

        (SchemaType::Bool { .. }, SchemaValue::Bool(b)) => Ok(Value::Bool(*b)),
        (SchemaType::S8 { .. }, SchemaValue::S8(i)) => Ok(json_number_i64(*i as i64)),
        (SchemaType::S16 { .. }, SchemaValue::S16(i)) => Ok(json_number_i64(*i as i64)),
        (SchemaType::S32 { .. }, SchemaValue::S32(i)) => Ok(json_number_i64(*i as i64)),
        (SchemaType::S64 { .. }, SchemaValue::S64(i)) => Ok(Value::String(i.to_string())),
        (SchemaType::U8 { .. }, SchemaValue::U8(u)) => Ok(json_number_u64(*u as u64)),
        (SchemaType::U16 { .. }, SchemaValue::U16(u)) => Ok(json_number_u64(*u as u64)),
        (SchemaType::U32 { .. }, SchemaValue::U32(u)) => Ok(json_number_u64(*u as u64)),
        (SchemaType::U64 { .. }, SchemaValue::U64(u)) => Ok(Value::String(u.to_string())),
        (SchemaType::F32 { .. }, SchemaValue::F32(f)) => json_number_f64(*f as f64, &r.path),
        (SchemaType::F64 { .. }, SchemaValue::F64(f)) => json_number_f64(*f, &r.path),
        (SchemaType::Char { .. }, SchemaValue::Char(c)) => Ok(Value::String(c.to_string())),
        (SchemaType::String { .. }, SchemaValue::String(s)) => Ok(Value::String(s.clone())),

        (SchemaType::Text { .. }, SchemaValue::Text(p)) => Ok(canonical::text::to_json(p)),
        (SchemaType::Binary { .. }, SchemaValue::Binary(p)) => {
            canonical::binary::to_json(p).map_err(RenderError::from)
        }
        (SchemaType::Path { .. }, SchemaValue::Path { path }) => {
            canonical::path::to_json(path).map_err(RenderError::from)
        }
        (SchemaType::Url { .. }, SchemaValue::Url { url }) => {
            canonical::url::to_json(url).map_err(RenderError::from)
        }
        (SchemaType::Uuid { .. }, SchemaValue::Uuid(value)) => Ok(canonical::uuid::to_json(value)),
        (SchemaType::Datetime { .. }, SchemaValue::Datetime { value }) => {
            canonical::datetime::to_json(value).map_err(RenderError::from)
        }
        (SchemaType::Duration { .. }, SchemaValue::Duration(p)) => {
            Ok(canonical::duration::to_json(p))
        }
        (SchemaType::Quantity { .. }, SchemaValue::Quantity(q)) => {
            Ok(canonical::quantity::to_json(q))
        }
        #[cfg(not(all(feature = "guest", not(feature = "host"))))]
        (SchemaType::Secret { .. }, SchemaValue::Secret(p)) => {
            canonical::secret::to_json(p).map_err(RenderError::from)
        }
        #[cfg(not(all(feature = "guest", not(feature = "host"))))]
        (SchemaType::QuotaToken { .. }, SchemaValue::QuotaToken(p)) => {
            canonical::quota_token::to_json(p).map_err(RenderError::from)
        }
        #[cfg(not(all(feature = "guest", not(feature = "host"))))]
        (SchemaType::PermissionCard { .. }, SchemaValue::PermissionCard(p)) => {
            canonical::permission_card::to_json(p).map_err(RenderError::from)
        }
        #[cfg(all(feature = "guest", not(feature = "host")))]
        (
            SchemaType::Secret { .. }
            | SchemaType::QuotaToken { .. }
            | SchemaType::PermissionCard { .. },
            SchemaValue::Secret(_) | SchemaValue::QuotaToken(_) | SchemaValue::PermissionCard(_),
        ) => Err(RenderError::Unsupported(
            "opaque host-managed capabilities cannot be rendered by a guest",
        )),

        (SchemaType::Record { fields, .. }, SchemaValue::Record { fields: vs }) => {
            if fields.len() != vs.len() {
                return Err(r.mismatch(format!(
                    "record arity: expected {}, found {}",
                    fields.len(),
                    vs.len()
                )));
            }
            let mut obj = Map::new();
            for (field, value) in fields.iter().zip(vs.iter()) {
                r.path.push(PathSegment::Field(field.name.clone()));
                let rendered = drive(walk(r, graph, &field.body, value))?;
                r.path.pop();
                obj.insert(field.name.clone(), rendered);
            }
            Ok(Value::Object(obj))
        }

        (SchemaType::Variant { cases, .. }, SchemaValue::Variant(vp)) => {
            let case_index = vp.case as usize;
            if case_index >= cases.len() {
                return Err(r.mismatch(format!(
                    "variant case index {} out of range (count {})",
                    vp.case,
                    cases.len()
                )));
            }
            let case: &VariantCaseType = &cases[case_index];
            match (&case.payload, &vp.payload) {
                (None, None) => Ok(Value::String(case.name.clone())),
                (Some(case_ty), Some(payload)) => {
                    r.path.push(PathSegment::Variant(case.name.clone()));
                    let rendered = drive(walk(r, graph, case_ty, payload))?;
                    r.path.pop();
                    let mut obj = Map::new();
                    obj.insert(case.name.clone(), rendered);
                    Ok(Value::Object(obj))
                }
                _ => Err(r.mismatch(format!(
                    "variant payload presence mismatch on case `{}`",
                    case.name
                ))),
            }
        }

        (SchemaType::Enum { cases, .. }, SchemaValue::Enum { case }) => {
            let idx = *case as usize;
            if idx >= cases.len() {
                return Err(r.mismatch(format!(
                    "enum case index {} out of range (count {})",
                    case,
                    cases.len()
                )));
            }
            Ok(Value::String(cases[idx].clone()))
        }

        (SchemaType::Flags { flags, .. }, SchemaValue::Flags { bits }) => {
            if flags.len() != bits.len() {
                return Err(r.mismatch(format!(
                    "flags arity: expected {}, found {}",
                    flags.len(),
                    bits.len()
                )));
            }
            let selected: Vec<Value> = flags
                .iter()
                .zip(bits.iter())
                .filter(|(_, on)| **on)
                .map(|(name, _)| Value::String(name.clone()))
                .collect();
            Ok(Value::Array(selected))
        }

        (SchemaType::Tuple { elements, .. }, SchemaValue::Tuple { elements: vs }) => {
            if elements.len() != vs.len() {
                return Err(r.mismatch(format!(
                    "tuple arity: expected {}, found {}",
                    elements.len(),
                    vs.len()
                )));
            }
            let mut out = Vec::with_capacity(vs.len());
            for (i, (et, ev)) in elements.iter().zip(vs.iter()).enumerate() {
                r.path.push(PathSegment::Index(i));
                let rendered = drive(walk(r, graph, et, ev))?;
                r.path.pop();
                out.push(rendered);
            }
            Ok(Value::Array(out))
        }

        (SchemaType::List { element, .. }, SchemaValue::List { elements }) => {
            let mut out = Vec::with_capacity(elements.len());
            for (i, ev) in elements.iter().enumerate() {
                r.path.push(PathSegment::Index(i));
                let rendered = drive(walk(r, graph, element, ev))?;
                r.path.pop();
                out.push(rendered);
            }
            Ok(Value::Array(out))
        }

        (
            SchemaType::FixedList {
                element, length, ..
            },
            SchemaValue::FixedList { elements },
        ) => {
            if elements.len() as u32 != *length {
                return Err(r.mismatch(format!(
                    "fixed list length: expected {}, found {}",
                    length,
                    elements.len()
                )));
            }
            let mut out = Vec::with_capacity(elements.len());
            for (i, ev) in elements.iter().enumerate() {
                r.path.push(PathSegment::Index(i));
                let rendered = drive(walk(r, graph, element, ev))?;
                r.path.pop();
                out.push(rendered);
            }
            Ok(Value::Array(out))
        }

        (SchemaType::Map { key, value, .. }, SchemaValue::Map { entries }) => {
            let mut out = Vec::with_capacity(entries.len());
            for (i, (k, v)) in entries.iter().enumerate() {
                r.path.push(PathSegment::MapKey(i));
                let rk = drive(walk(r, graph, key, k))?;
                r.path.pop();
                r.path.push(PathSegment::MapValue(i));
                let rv = drive(walk(r, graph, value, v))?;
                r.path.pop();
                out.push(Value::Array(vec![rk, rv]));
            }
            Ok(Value::Array(out))
        }

        (SchemaType::Option { inner, .. }, SchemaValue::Option { inner: v }) => match v {
            None => Ok(Value::Null),
            Some(inner_value) => {
                r.path.push(PathSegment::OptionInner);
                let rendered = drive(walk(r, graph, inner, inner_value))?;
                r.path.pop();
                Ok(rendered)
            }
        },

        (SchemaType::Result { spec, .. }, SchemaValue::Result(payload)) => {
            encode_result(r, graph, spec, payload)
        }

        (SchemaType::Union { spec, .. }, SchemaValue::Union(payload)) => {
            encode_union(r, graph, spec, payload)
        }

        (SchemaType::Future { .. }, _) | (SchemaType::Stream { .. }, _) => Err(
            RenderError::Unsupported("future/stream values have no JSON representation"),
        ),

        (ty, value) => Err(r.mismatch(format!(
            "shape mismatch: expected {}, found {}",
            type_name(ty),
            value_name(value)
        ))),
    }
}

fn encode_result(
    r: &mut ToJsonRenderer,
    graph: &SchemaGraph,
    spec: &ResultSpec,
    payload: &ResultValuePayload,
) -> Result<Value, RenderError> {
    let mut obj = Map::new();
    match payload {
        ResultValuePayload::Ok {
            value: payload_value,
        } => {
            let v = match (spec.ok.as_deref(), payload_value.as_deref()) {
                (None, None) => Value::Null,
                (Some(ok_ty), Some(inner)) => {
                    r.path.push(PathSegment::Ok);
                    let v = drive(walk(r, graph, ok_ty, inner))?;
                    r.path.pop();
                    v
                }
                _ => {
                    return Err(r.mismatch("result ok payload presence mismatch".to_string()));
                }
            };
            obj.insert("ok".to_string(), v);
        }
        ResultValuePayload::Err {
            value: payload_value,
        } => {
            let v = match (spec.err.as_deref(), payload_value.as_deref()) {
                (None, None) => Value::Null,
                (Some(err_ty), Some(inner)) => {
                    r.path.push(PathSegment::Err);
                    let v = drive(walk(r, graph, err_ty, inner))?;
                    r.path.pop();
                    v
                }
                _ => {
                    return Err(r.mismatch("result err payload presence mismatch".to_string()));
                }
            };
            obj.insert("err".to_string(), v);
        }
    }
    Ok(Value::Object(obj))
}

fn encode_union(
    r: &mut ToJsonRenderer,
    graph: &SchemaGraph,
    spec: &UnionSpec,
    payload: &UnionValuePayload,
) -> Result<Value, RenderError> {
    let branch = find_branch(spec, &payload.tag)
        .ok_or_else(|| r.mismatch(format!("unknown union branch tag `{}`", payload.tag)))?;
    // Encode the body first; the on-wire union form is the body's JSON.
    r.path.push(PathSegment::Union(payload.tag.clone()));
    let rendered = drive(walk(r, graph, &branch.body, &payload.body))?;
    r.path.pop();
    // Sanity check: the produced JSON should match the branch's
    // discriminator rule. Validation should have caught a tag/body
    // disagreement at construction time; this is the runtime safety net.
    if !rule_matches(&branch.discriminator, &rendered)? {
        return Err(RenderError::UnionTagMismatch {
            tag: payload.tag.clone(),
            reason: format!(
                "encoded body does not satisfy discriminator {}",
                rule_label(&branch.discriminator)
            ),
        });
    }
    Ok(rendered)
}

fn find_branch<'a>(spec: &'a UnionSpec, tag: &str) -> Option<&'a UnionBranch> {
    spec.branches.iter().find(|b| b.tag == tag)
}

impl ToJsonRenderer {
    fn mismatch(&self, reason: String) -> RenderError {
        RenderError::ValueMismatch {
            path: self.path.render(),
            reason,
        }
    }
}

// --------------------------------------------------------------------- from

fn from_json_inner(
    graph: &SchemaGraph,
    ty: &SchemaType,
    json: &Value,
    path: &mut PathStack,
    visited: &mut HashSet<TypeId>,
    policy: JsonDecodePolicy,
) -> Result<SchemaValue, RenderError> {
    // Route through the shared ref-resolution helper so the decoder uses
    // the same cycle protection as the walker-based encoder.
    let res = resolve_ref::<_, SchemaValue, RenderError>(graph, ty, visited, |graph, body| {
        match from_json_body(graph, body, json, path, &mut HashSet::new(), policy) {
            Ok(v) => Ok(v),
            Err(e) => Err(WalkerError::Walker(e)),
        }
    });
    drive_with_path(res, path)
}

fn drive_with_path(
    res: Result<SchemaValue, WalkerError<RenderError>>,
    path: &PathStack,
) -> Result<SchemaValue, RenderError> {
    match res {
        Ok(v) => Ok(v),
        Err(WalkerError::Walker(e)) => Err(e),
        Err(WalkerError::RefCycle(id)) => Err(RenderError::ValueMismatch {
            path: path.render(),
            reason: format!("reference cycle through `{id}`"),
        }),
        Err(WalkerError::DanglingRef(id)) => Err(RenderError::ValueMismatch {
            path: path.render(),
            reason: format!("dangling reference `{id}`"),
        }),
    }
}

fn from_json_body(
    graph: &SchemaGraph,
    ty: &SchemaType,
    json: &Value,
    path: &mut PathStack,
    _local_visited: &mut HashSet<TypeId>,
    policy: JsonDecodePolicy,
) -> Result<SchemaValue, RenderError> {
    // The `visited` HashSet for nested references is provided by the caller
    // through `resolve_ref`. For sub-recursions we re-enter `from_json_inner`
    // with a fresh set per sibling traversal because ref protection is
    // scoped to the active stack of references, not the entire walk.
    let mut visited: HashSet<TypeId> = HashSet::new();
    if policy == JsonDecodePolicy::Untrusted
        && let Some(kind) = HostManagedKind::from_type(ty)
    {
        return Err(mismatch(
            path,
            format!(
                "host-managed capability `{}` cannot be constructed from external JSON",
                kind.kind_name()
            ),
        ));
    }

    match ty {
        SchemaType::Ref { .. } => unreachable!("ref resolved by resolve_ref"),
        SchemaType::Bool { .. } => match json.as_bool() {
            Some(b) => Ok(SchemaValue::Bool(b)),
            None => Err(mismatch(path, "expected JSON boolean".to_string())),
        },
        SchemaType::S8 { .. } => {
            check_int_range::<i8>(json, path)?;
            Ok(SchemaValue::S8(json_i64(json, path)? as i8))
        }
        SchemaType::S16 { .. } => {
            check_int_range::<i16>(json, path)?;
            Ok(SchemaValue::S16(json_i64(json, path)? as i16))
        }
        SchemaType::S32 { .. } => {
            check_int_range::<i32>(json, path)?;
            Ok(SchemaValue::S32(json_i64(json, path)? as i32))
        }
        SchemaType::S64 { .. } => Ok(SchemaValue::S64(json_i64_string(json, path)?)),
        SchemaType::U8 { .. } => {
            check_int_range::<u8>(json, path)?;
            Ok(SchemaValue::U8(json_u64(json, path)? as u8))
        }
        SchemaType::U16 { .. } => {
            check_int_range::<u16>(json, path)?;
            Ok(SchemaValue::U16(json_u64(json, path)? as u16))
        }
        SchemaType::U32 { .. } => {
            check_int_range::<u32>(json, path)?;
            Ok(SchemaValue::U32(json_u64(json, path)? as u32))
        }
        SchemaType::U64 { .. } => Ok(SchemaValue::U64(json_u64_string(json, path)?)),
        SchemaType::F32 { .. } => {
            let value = json_f64(json, path)?;
            check_f32_in_range(value, path)?;
            Ok(SchemaValue::F32(value as f32))
        }
        SchemaType::F64 { .. } => {
            // `serde_json::Number` only stores finite floats, but assert
            // it here as a defensive insurance so round-tripping never
            // emits a non-finite number.
            let value = json_f64(json, path)?;
            if !value.is_finite() {
                return Err(mismatch(path, "f64 must be finite".to_string()));
            }
            Ok(SchemaValue::F64(value))
        }
        SchemaType::Char { .. } => match json.as_str() {
            Some(s) => {
                let mut chars = s.chars();
                match (chars.next(), chars.next()) {
                    (Some(c), None) => Ok(SchemaValue::Char(c)),
                    _ => Err(mismatch(
                        path,
                        "expected JSON string with exactly one char".to_string(),
                    )),
                }
            }
            None => Err(mismatch(path, "expected JSON string".to_string())),
        },
        SchemaType::String { .. } => match json.as_str() {
            Some(s) => Ok(SchemaValue::String(s.to_string())),
            None => Err(mismatch(path, "expected JSON string".to_string())),
        },

        SchemaType::Text { .. } => {
            let p = canonical::text::from_json(json)?;
            Ok(SchemaValue::Text(p))
        }
        SchemaType::Binary { .. } => {
            let p = canonical::binary::from_json(json)?;
            Ok(SchemaValue::Binary(p))
        }
        SchemaType::Path { .. } => {
            let s = canonical::path::from_json(json)?;
            Ok(SchemaValue::Path { path: s })
        }
        SchemaType::Url { .. } => {
            let s = canonical::url::from_json(json)?;
            Ok(SchemaValue::Url { url: s })
        }
        SchemaType::Uuid { .. } => {
            let value = canonical::uuid::from_json(json)?;
            Ok(SchemaValue::Uuid(value))
        }
        SchemaType::Datetime { .. } => {
            let dt = canonical::datetime::from_json(json)?;
            Ok(SchemaValue::Datetime { value: dt })
        }
        SchemaType::Duration { .. } => {
            let p = canonical::duration::from_json(json)?;
            Ok(SchemaValue::Duration(p))
        }
        SchemaType::Quantity { .. } => {
            let q = canonical::quantity::from_json(json)?;
            Ok(SchemaValue::Quantity(q))
        }
        #[cfg(not(all(feature = "guest", not(feature = "host"))))]
        SchemaType::Secret { .. } => {
            let p = canonical::secret::from_json(json)?;
            Ok(SchemaValue::Secret(p))
        }
        #[cfg(not(all(feature = "guest", not(feature = "host"))))]
        SchemaType::QuotaToken { .. } => {
            let p = canonical::quota_token::from_json(json)?;
            Ok(SchemaValue::QuotaToken(p))
        }
        #[cfg(not(all(feature = "guest", not(feature = "host"))))]
        SchemaType::PermissionCard { .. } => {
            let p = canonical::permission_card::from_json(json)?;
            Ok(SchemaValue::PermissionCard(p))
        }
        #[cfg(all(feature = "guest", not(feature = "host")))]
        SchemaType::Secret { .. }
        | SchemaType::QuotaToken { .. }
        | SchemaType::PermissionCard { .. } => Err(RenderError::Unsupported(
            "opaque host-managed capabilities cannot be constructed by a guest",
        )),

        SchemaType::Record { fields, .. } => {
            let obj = json
                .as_object()
                .ok_or_else(|| mismatch(path, "expected JSON object for record".to_string()))?;
            // Strict boundary check: every JSON field must be declared by
            // the schema record.
            let known: HashSet<&str> = fields.iter().map(|f| f.name.as_str()).collect();
            for key in obj.keys() {
                if !known.contains(key.as_str()) {
                    return Err(RenderError::UnexpectedField {
                        record: "anonymous".to_string(),
                        field: key.clone(),
                    });
                }
            }
            let mut out = Vec::with_capacity(fields.len());
            for field in fields.iter() {
                match obj.get(&field.name) {
                    Some(value) => {
                        path.push(PathSegment::Field(field.name.clone()));
                        let v =
                            from_json_inner(graph, &field.body, value, path, &mut visited, policy)?;
                        path.pop();
                        out.push(v);
                    }
                    None if resolves_to_option(graph, &field.body) => {
                        out.push(SchemaValue::Option { inner: None });
                    }
                    None => {
                        return Err(mismatch(
                            path,
                            format!("missing record field `{}`", field.name),
                        ));
                    }
                }
            }
            Ok(SchemaValue::Record { fields: out })
        }

        SchemaType::Variant { cases, .. } => match json {
            Value::String(name) => {
                let (idx, case) = find_variant_case(cases, name)
                    .ok_or_else(|| mismatch(path, format!("unknown variant case `{name}`")))?;
                if case.payload.is_some() {
                    return Err(mismatch(
                        path,
                        format!("variant case `{name}` requires a payload"),
                    ));
                }
                Ok(SchemaValue::Variant(VariantValuePayload {
                    case: idx as u32,
                    payload: None,
                }))
            }
            Value::Object(obj) if obj.len() == 1 => {
                let (name, payload_json) = obj.iter().next().unwrap();
                let (idx, case) = find_variant_case(cases, name)
                    .ok_or_else(|| mismatch(path, format!("unknown variant case `{name}`")))?;
                let payload_ty = case.payload.as_ref().ok_or_else(|| {
                    mismatch(
                        path,
                        format!("variant case `{name}` does not accept a payload"),
                    )
                })?;
                path.push(PathSegment::Variant(name.clone()));
                let inner =
                    from_json_inner(graph, payload_ty, payload_json, path, &mut visited, policy)?;
                path.pop();
                Ok(SchemaValue::Variant(VariantValuePayload {
                    case: idx as u32,
                    payload: Some(Box::new(inner)),
                }))
            }
            _ => Err(mismatch(
                path,
                "expected JSON string or single-entry object for variant".to_string(),
            )),
        },

        SchemaType::Enum { cases, .. } => {
            let name = json
                .as_str()
                .ok_or_else(|| mismatch(path, "expected JSON string for enum".to_string()))?;
            let idx = cases
                .iter()
                .position(|c| c == name)
                .ok_or_else(|| mismatch(path, format!("unknown enum case `{name}`")))?;
            Ok(SchemaValue::Enum { case: idx as u32 })
        }

        SchemaType::Flags { flags, .. } => {
            let arr = json
                .as_array()
                .ok_or_else(|| mismatch(path, "expected JSON array for flags".to_string()))?;
            let mut selected: HashSet<&str> = HashSet::new();
            for item in arr {
                let name = item.as_str().ok_or_else(|| {
                    mismatch(path, "expected JSON string in flags array".to_string())
                })?;
                if !flags.iter().any(|f| f == name) {
                    return Err(mismatch(path, format!("unknown flag `{name}`")));
                }
                if !selected.insert(name) {
                    return Err(RenderError::DuplicateFlag {
                        flag: name.to_string(),
                    });
                }
            }
            let bits: Vec<bool> = flags
                .iter()
                .map(|f| selected.contains(f.as_str()))
                .collect();
            Ok(SchemaValue::Flags { bits })
        }

        SchemaType::Tuple { elements, .. } => {
            let arr = json
                .as_array()
                .ok_or_else(|| mismatch(path, "expected JSON array for tuple".to_string()))?;
            if arr.len() != elements.len() {
                return Err(mismatch(
                    path,
                    format!(
                        "tuple arity: expected {}, found {}",
                        elements.len(),
                        arr.len()
                    ),
                ));
            }
            let mut out = Vec::with_capacity(arr.len());
            for (i, (et, ev)) in elements.iter().zip(arr.iter()).enumerate() {
                path.push(PathSegment::Index(i));
                let v = from_json_inner(graph, et, ev, path, &mut visited, policy)?;
                path.pop();
                out.push(v);
            }
            Ok(SchemaValue::Tuple { elements: out })
        }

        SchemaType::List { element, .. } => {
            let arr = json
                .as_array()
                .ok_or_else(|| mismatch(path, "expected JSON array for list".to_string()))?;
            let mut out = Vec::with_capacity(arr.len());
            for (i, ev) in arr.iter().enumerate() {
                path.push(PathSegment::Index(i));
                let v = from_json_inner(graph, element, ev, path, &mut visited, policy)?;
                path.pop();
                out.push(v);
            }
            Ok(SchemaValue::List { elements: out })
        }

        SchemaType::FixedList {
            element, length, ..
        } => {
            let arr = json
                .as_array()
                .ok_or_else(|| mismatch(path, "expected JSON array for fixed list".to_string()))?;
            if arr.len() as u32 != *length {
                return Err(mismatch(
                    path,
                    format!(
                        "fixed list length: expected {}, found {}",
                        length,
                        arr.len()
                    ),
                ));
            }
            let mut out = Vec::with_capacity(arr.len());
            for (i, ev) in arr.iter().enumerate() {
                path.push(PathSegment::Index(i));
                let v = from_json_inner(graph, element, ev, path, &mut visited, policy)?;
                path.pop();
                out.push(v);
            }
            Ok(SchemaValue::FixedList { elements: out })
        }

        SchemaType::Map { key, value, .. } => {
            let arr = json
                .as_array()
                .ok_or_else(|| mismatch(path, "expected JSON array for map".to_string()))?;
            let mut out: Vec<(SchemaValue, SchemaValue)> = Vec::with_capacity(arr.len());
            for (i, item) in arr.iter().enumerate() {
                let pair = item.as_array().ok_or_else(|| {
                    mismatch(path, "expected `[k, v]` array for map entry".to_string())
                })?;
                if pair.len() != 2 {
                    return Err(mismatch(
                        path,
                        format!(
                            "map entry must have exactly 2 elements, found {}",
                            pair.len()
                        ),
                    ));
                }
                path.push(PathSegment::MapKey(i));
                let k = from_json_inner(graph, key, &pair[0], path, &mut visited, policy)?;
                path.pop();
                path.push(PathSegment::MapValue(i));
                let v = from_json_inner(graph, value, &pair[1], path, &mut visited, policy)?;
                path.pop();
                out.push((k, v));
            }
            Ok(SchemaValue::Map { entries: out })
        }

        SchemaType::Option { inner, .. } => match json {
            Value::Null => Ok(SchemaValue::Option { inner: None }),
            other => {
                path.push(PathSegment::OptionInner);
                let v = from_json_inner(graph, inner, other, path, &mut visited, policy)?;
                path.pop();
                Ok(SchemaValue::Option {
                    inner: Some(Box::new(v)),
                })
            }
        },

        SchemaType::Result { spec, .. } => {
            decode_result(graph, spec, json, path, &mut visited, policy)
        }

        SchemaType::Union { spec, .. } => decode_union(graph, spec, json, path, policy),

        SchemaType::Future { .. } | SchemaType::Stream { .. } => Err(RenderError::Unsupported(
            "future/stream values have no JSON representation",
        )),
    }
}

fn resolves_to_option(graph: &SchemaGraph, ty: &SchemaType) -> bool {
    let mut current = ty;
    let mut visited = HashSet::new();
    loop {
        match current {
            SchemaType::Option { .. } => return true,
            SchemaType::Ref { id, .. } if visited.insert(id.clone()) => match graph.lookup(id) {
                Some(definition) => current = &definition.body,
                None => return false,
            },
            _ => return false,
        }
    }
}

fn decode_result(
    graph: &SchemaGraph,
    spec: &ResultSpec,
    json: &Value,
    path: &mut PathStack,
    visited: &mut HashSet<TypeId>,
    policy: JsonDecodePolicy,
) -> Result<SchemaValue, RenderError> {
    let obj = json
        .as_object()
        .ok_or_else(|| mismatch(path, "expected JSON object for result".to_string()))?;
    if obj.len() != 1 {
        return Err(mismatch(
            path,
            "result object must have exactly one key `ok` or `err`".to_string(),
        ));
    }
    let (key, payload_json) = obj.iter().next().unwrap();
    match key.as_str() {
        "ok" => {
            let value = match (spec.ok.as_deref(), payload_json) {
                (None, Value::Null) => None,
                (Some(ok_ty), other) => {
                    path.push(PathSegment::Ok);
                    let v = from_json_inner(graph, ok_ty, other, path, visited, policy)?;
                    path.pop();
                    Some(Box::new(v))
                }
                _ => {
                    return Err(mismatch(
                        path,
                        "result ok payload presence mismatch".to_string(),
                    ));
                }
            };
            Ok(SchemaValue::Result(ResultValuePayload::Ok { value }))
        }
        "err" => {
            let value = match (spec.err.as_deref(), payload_json) {
                (None, Value::Null) => None,
                (Some(err_ty), other) => {
                    path.push(PathSegment::Err);
                    let v = from_json_inner(graph, err_ty, other, path, visited, policy)?;
                    path.pop();
                    Some(Box::new(v))
                }
                _ => {
                    return Err(mismatch(
                        path,
                        "result err payload presence mismatch".to_string(),
                    ));
                }
            };
            Ok(SchemaValue::Result(ResultValuePayload::Err { value }))
        }
        other => Err(mismatch(path, format!("unexpected result key `{other}`"))),
    }
}

fn decode_union(
    graph: &SchemaGraph,
    spec: &UnionSpec,
    json: &Value,
    path: &mut PathStack,
    policy: JsonDecodePolicy,
) -> Result<SchemaValue, RenderError> {
    // First: find every branch whose discriminator rule matches the
    // incoming JSON value. Validation rules out multi-match at construction
    // time; a runtime safety net catches the case where the value is bad.
    let mut matched: Vec<&UnionBranch> = Vec::new();
    for branch in spec.branches.iter() {
        if rule_matches(&branch.discriminator, json)? {
            matched.push(branch);
        }
    }
    match matched.as_slice() {
        [] => Err(RenderError::UnionNoMatch),
        [branch] => {
            // Then: decode the body against the matched branch.
            path.push(PathSegment::Union(branch.tag.clone()));
            let body =
                from_json_inner(graph, &branch.body, json, path, &mut HashSet::new(), policy)?;
            path.pop();
            Ok(SchemaValue::Union(UnionValuePayload {
                tag: branch.tag.clone(),
                body: Box::new(body),
            }))
        }
        multiple => Err(RenderError::UnionAmbiguous {
            matched: multiple.iter().map(|b| b.tag.clone()).collect(),
        }),
    }
}

// ----------------------------------------------------------- discriminators

/// Whether a [`DiscriminatorRule`] matches a raw JSON value.
fn rule_matches(rule: &DiscriminatorRule, json: &Value) -> Result<bool, RenderError> {
    Ok(match rule {
        DiscriminatorRule::Prefix { prefix } => json
            .as_str()
            .map(|s| s.starts_with(prefix.as_str()))
            .unwrap_or(false),
        DiscriminatorRule::Suffix { suffix } => json
            .as_str()
            .map(|s| s.ends_with(suffix.as_str()))
            .unwrap_or(false),
        DiscriminatorRule::Contains { substring } => json
            .as_str()
            .map(|s| s.contains(substring.as_str()))
            .unwrap_or(false),
        #[cfg(not(feature = "regex"))]
        DiscriminatorRule::Regex { .. } => return Err(RenderError::Unsupported("feature `regex`")),
        #[cfg(feature = "regex")]
        DiscriminatorRule::Regex { regex } => match (json.as_str(), regex::Regex::new(regex)) {
            (Some(s), Ok(re)) => re.is_match(s),
            _ => false,
        },
        DiscriminatorRule::FieldEquals(disc) => json
            .as_object()
            .and_then(|obj| obj.get(disc.field_name.as_str()))
            .map(|v| match &disc.literal {
                None => true,
                Some(lit) => v.as_str().map(|s| s == lit.as_str()).unwrap_or(false),
            })
            .unwrap_or(false),
        DiscriminatorRule::FieldAbsent { field_name } => json
            .as_object()
            .map(|obj| !obj.contains_key(field_name.as_str()))
            .unwrap_or(false),
    })
}

fn rule_label(rule: &DiscriminatorRule) -> String {
    match rule {
        DiscriminatorRule::Prefix { prefix } => format!("prefix `{prefix}`"),
        DiscriminatorRule::Suffix { suffix } => format!("suffix `{suffix}`"),
        DiscriminatorRule::Contains { substring } => format!("contains `{substring}`"),
        DiscriminatorRule::Regex { regex } => format!("regex `{regex}`"),
        DiscriminatorRule::FieldEquals(disc) => match &disc.literal {
            None => format!("field `{}` present", disc.field_name),
            Some(lit) => format!("field `{}` == `{lit}`", disc.field_name),
        },
        DiscriminatorRule::FieldAbsent { field_name } => format!("field `{field_name}` absent"),
    }
}

// -------------------------------------------------------------- small bits

fn find_variant_case<'a>(
    cases: &'a [VariantCaseType],
    name: &str,
) -> Option<(usize, &'a VariantCaseType)> {
    cases.iter().enumerate().find(|(_, c)| c.name == name)
}

fn json_i64(json: &Value, path: &mut PathStack) -> Result<i64, RenderError> {
    json.as_i64()
        .ok_or_else(|| mismatch(path, "expected JSON integer".to_string()))
}

fn json_u64(json: &Value, path: &mut PathStack) -> Result<u64, RenderError> {
    json.as_u64()
        .ok_or_else(|| mismatch(path, "expected JSON non-negative integer".to_string()))
}

fn json_i64_string(json: &Value, path: &mut PathStack) -> Result<i64, RenderError> {
    let value = json
        .as_str()
        .ok_or_else(|| mismatch(path, "expected canonical signed integer string".to_string()))?;
    if !is_canonical_signed_integer(value) {
        return Err(mismatch(
            path,
            "expected canonical signed integer string".to_string(),
        ));
    }
    value
        .parse()
        .map_err(|_| mismatch(path, "signed 64-bit integer out of range".to_string()))
}

fn json_u64_string(json: &Value, path: &mut PathStack) -> Result<u64, RenderError> {
    let value = json.as_str().ok_or_else(|| {
        mismatch(
            path,
            "expected canonical unsigned integer string".to_string(),
        )
    })?;
    if value != "0" && !canonical_nonzero_digits(value) {
        return Err(mismatch(
            path,
            "expected canonical unsigned integer string".to_string(),
        ));
    }
    value
        .parse()
        .map_err(|_| mismatch(path, "unsigned 64-bit integer out of range".to_string()))
}

fn is_canonical_signed_integer(value: &str) -> bool {
    value == "0"
        || value
            .strip_prefix('-')
            .is_some_and(canonical_nonzero_digits)
        || canonical_nonzero_digits(value)
}

fn canonical_nonzero_digits(value: &str) -> bool {
    value
        .as_bytes()
        .first()
        .is_some_and(|digit| matches!(digit, b'1'..=b'9'))
        && value.bytes().all(|digit| digit.is_ascii_digit())
}

fn json_f64(json: &Value, path: &mut PathStack) -> Result<f64, RenderError> {
    json.as_f64()
        .ok_or_else(|| mismatch(path, "expected JSON number".to_string()))
}

fn json_number_i64(value: i64) -> Value {
    Value::Number(Number::from(value))
}

fn json_number_u64(value: u64) -> Value {
    Value::Number(Number::from(value))
}

fn json_number_f64(value: f64, path: &PathStack) -> Result<Value, RenderError> {
    Number::from_f64(value)
        .map(Value::Number)
        .ok_or_else(|| RenderError::Json(format!("non-finite float at {}", path.render())))
}

/// Reject f64 inputs whose magnitude exceeds the f32 range, where `value as
/// f32` would silently saturate to `±inf`. NaN is rejected because the JSON
/// number type cannot represent it on round-trip.
fn check_f32_in_range(value: f64, path: &mut PathStack) -> Result<(), RenderError> {
    if !value.is_finite() {
        return Err(mismatch(path, "f32 must be finite".to_string()));
    }
    if value.abs() > f32::MAX as f64 {
        return Err(mismatch(path, "f32 out of range".to_string()));
    }
    Ok(())
}

fn check_int_range<T: TryFrom<i128>>(
    json: &Value,
    path: &mut PathStack,
) -> Result<(), RenderError> {
    let n = json
        .as_i64()
        .map(i128::from)
        .or_else(|| json.as_u64().map(i128::from))
        .ok_or_else(|| mismatch(path, "expected JSON integer".to_string()))?;
    T::try_from(n)
        .map(|_| ())
        .map_err(|_| mismatch(path, "integer out of range".to_string()))
}

fn mismatch(path: &PathStack, reason: String) -> RenderError {
    RenderError::ValueMismatch {
        path: path.render(),
        reason,
    }
}

fn type_name(ty: &SchemaType) -> &'static str {
    match ty {
        SchemaType::Ref { .. } => "ref",
        SchemaType::Bool { .. } => "bool",
        SchemaType::S8 { .. } => "s8",
        SchemaType::S16 { .. } => "s16",
        SchemaType::S32 { .. } => "s32",
        SchemaType::S64 { .. } => "s64",
        SchemaType::U8 { .. } => "u8",
        SchemaType::U16 { .. } => "u16",
        SchemaType::U32 { .. } => "u32",
        SchemaType::U64 { .. } => "u64",
        SchemaType::F32 { .. } => "f32",
        SchemaType::F64 { .. } => "f64",
        SchemaType::Char { .. } => "char",
        SchemaType::String { .. } => "string",
        SchemaType::Record { .. } => "record",
        SchemaType::Variant { .. } => "variant",
        SchemaType::Enum { .. } => "enum",
        SchemaType::Flags { .. } => "flags",
        SchemaType::Tuple { .. } => "tuple",
        SchemaType::List { .. } => "list",
        SchemaType::FixedList { .. } => "fixed-list",
        SchemaType::Map { .. } => "map",
        SchemaType::Option { .. } => "option",
        SchemaType::Result { .. } => "result",
        SchemaType::Text { .. } => "text",
        SchemaType::Binary { .. } => "binary",
        SchemaType::Path { .. } => "path",
        SchemaType::Url { .. } => "url",
        SchemaType::Uuid { .. } => "uuid",
        SchemaType::Datetime { .. } => "datetime",
        SchemaType::Duration { .. } => "duration",
        SchemaType::Quantity { .. } => "quantity",
        SchemaType::Union { .. } => "union",
        SchemaType::Secret { .. } => "secret",
        SchemaType::QuotaToken { .. } => "quota-token",
        SchemaType::PermissionCard { .. } => "permission-card",
        SchemaType::Future { .. } => "future",
        SchemaType::Stream { .. } => "stream",
    }
}

fn value_name(value: &SchemaValue) -> &'static str {
    match value {
        SchemaValue::Bool(_) => "bool",
        SchemaValue::S8(_) => "s8",
        SchemaValue::S16(_) => "s16",
        SchemaValue::S32(_) => "s32",
        SchemaValue::S64(_) => "s64",
        SchemaValue::U8(_) => "u8",
        SchemaValue::U16(_) => "u16",
        SchemaValue::U32(_) => "u32",
        SchemaValue::U64(_) => "u64",
        SchemaValue::F32(_) => "f32",
        SchemaValue::F64(_) => "f64",
        SchemaValue::Char(_) => "char",
        SchemaValue::String(_) => "string",
        SchemaValue::Record { .. } => "record",
        SchemaValue::Variant(_) => "variant",
        SchemaValue::Enum { .. } => "enum",
        SchemaValue::Flags { .. } => "flags",
        SchemaValue::Tuple { .. } => "tuple",
        SchemaValue::List { .. } => "list",
        SchemaValue::FixedList { .. } => "fixed-list",
        SchemaValue::Map { .. } => "map",
        SchemaValue::Option { .. } => "option",
        SchemaValue::Result(_) => "result",
        SchemaValue::Text(_) => "text",
        SchemaValue::Binary(_) => "binary",
        SchemaValue::Path { .. } => "path",
        SchemaValue::Url { .. } => "url",
        SchemaValue::Uuid(_) => "uuid",
        SchemaValue::Datetime { .. } => "datetime",
        SchemaValue::Duration(_) => "duration",
        SchemaValue::Quantity(_) => "quantity",
        SchemaValue::Union(_) => "union",
        SchemaValue::Secret(_) => "secret",
        SchemaValue::QuotaToken(_) => "quota-token",
        SchemaValue::Stream(_) => "stream",
        SchemaValue::PermissionCard(_) => "permission-card",
    }
}

// ---------------------------------------------------------------- path stack

#[derive(Clone, Debug)]
enum PathSegment {
    Field(String),
    Variant(String),
    Index(usize),
    OptionInner,
    Ok,
    Err,
    Union(String),
    MapKey(usize),
    MapValue(usize),
}

struct PathStack {
    segments: Vec<PathSegment>,
}

impl PathStack {
    fn new() -> Self {
        Self {
            segments: Vec::new(),
        }
    }

    fn push(&mut self, segment: PathSegment) {
        self.segments.push(segment);
    }

    fn pop(&mut self) {
        self.segments.pop();
    }

    fn render(&self) -> String {
        let mut s = String::new();
        for seg in &self.segments {
            match seg {
                PathSegment::Field(n) => {
                    s.push('.');
                    s.push_str(n);
                }
                PathSegment::Variant(n) => {
                    s.push('.');
                    s.push_str(n);
                }
                PathSegment::Index(i) => {
                    s.push('[');
                    s.push_str(&i.to_string());
                    s.push(']');
                }
                PathSegment::OptionInner => s.push_str(".some"),
                PathSegment::Ok => s.push_str(".ok"),
                PathSegment::Err => s.push_str(".err"),
                PathSegment::Union(n) => {
                    s.push('.');
                    s.push_str(n);
                }
                PathSegment::MapKey(i) => {
                    s.push_str(".key[");
                    s.push_str(&i.to_string());
                    s.push(']');
                }
                PathSegment::MapValue(i) => {
                    s.push_str(".value[");
                    s.push_str(&i.to_string());
                    s.push(']');
                }
            }
        }
        if s.is_empty() { "$".to_string() } else { s }
    }
}