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
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
// 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.

//! Renderer that produces a JSON Schema document from a `SchemaGraph`/
//! `SchemaType`.

use crate::schema::graph::SchemaGraph;
use crate::schema::metadata::{MetadataEnvelope, TypeId};
use crate::schema::schema_type::{
    BinaryRestrictions, DiscriminatorRule, NumericBound, NumericRestrictions, PathSpec,
    PermissionCardSpec, QuantitySpec, QuantityValue, QuotaTokenSpec, ResultSpec, SchemaType,
    SecretSpec, TextRestrictions, UnionBranch, UnionSpec, UrlRestrictions, VariantCaseType,
};
use serde_json::{Map, Number, Value};
use std::collections::{HashMap, HashSet};

const JSON_SCHEMA_DRAFT: &str = "https://json-schema.org/draft/2020-12/schema";
const MIME_TYPE_PATTERN: &str = "^[A-Za-z0-9!#$&^_.+\\-]+\\/[A-Za-z0-9!#$&^_.+\\-]+$";
const BASE64URL_PATTERN: &str =
    "^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-][AQgw]|[A-Za-z0-9_-]{2}[AEIMQUYcgkosw048])?$";

/// Configuration for the JSON Schema renderer.
///
/// The public constants select the trusted canonical representation; boundary
/// renderers additionally select their host-managed capability policy.
#[derive(Clone, Copy, Debug)]
pub struct JsonSchemaConfig {
    /// Emit the `$schema` JSON Schema draft marker at the document root.
    pub include_draft_marker: bool,
    host_managed: HostManagedSchemaPolicy,
    unsupported: UnsupportedLeafSchemaPolicy,
}

#[derive(Clone, Copy, Debug)]
enum HostManagedSchemaPolicy {
    TrustedSnapshot,
    Reject,
    Redact,
}

#[derive(Clone, Copy, Debug)]
enum UnsupportedLeafSchemaPolicy {
    Placeholder,
    Reject,
}

impl JsonSchemaConfig {
    /// Canonical standalone JSON Schema document (includes the `$schema`
    /// draft marker).
    pub const CANONICAL: Self = Self {
        include_draft_marker: true,
        host_managed: HostManagedSchemaPolicy::TrustedSnapshot,
        unsupported: UnsupportedLeafSchemaPolicy::Placeholder,
    };

    /// Canonical JSON Schema document without the `$schema` draft marker, for
    /// consumers that embed the schema elsewhere (e.g. tool/resource schemas).
    pub const WITHOUT_DRAFT_MARKER: Self = Self {
        include_draft_marker: false,
        host_managed: HostManagedSchemaPolicy::TrustedSnapshot,
        unsupported: UnsupportedLeafSchemaPolicy::Placeholder,
    };

    pub(crate) const EXTERNAL_INPUT: Self = Self {
        include_draft_marker: false,
        host_managed: HostManagedSchemaPolicy::Reject,
        unsupported: UnsupportedLeafSchemaPolicy::Placeholder,
    };

    pub(crate) const EXTERNAL_OUTPUT: Self = Self {
        include_draft_marker: false,
        host_managed: HostManagedSchemaPolicy::Redact,
        unsupported: UnsupportedLeafSchemaPolicy::Placeholder,
    };

    /// Reflection JSON adapters cannot pack or unpack capabilities, futures,
    /// or streams, so their projected schemas must reject every JSON value.
    pub const REFLECTION: Self = Self {
        include_draft_marker: true,
        host_managed: HostManagedSchemaPolicy::Reject,
        unsupported: UnsupportedLeafSchemaPolicy::Reject,
    };
}

/// Render `(graph, ty)` to a canonical JSON Schema document (includes the
/// `$schema` draft marker). See [`to_json_schema_with_config`] for the
/// configurable form.
pub fn to_json_schema(graph: &SchemaGraph, ty: &SchemaType) -> Value {
    to_json_schema_with_config(graph, ty, JsonSchemaConfig::CANONICAL)
}

/// Render `(graph, ty)` to a JSON Schema document. When `ty` is a
/// `Ref(TypeId)` the document is `{ "$defs": {…}, "$ref": "#/$defs/<id>" }`;
/// otherwise the root schema is emitted inline with `$defs` carrying every
/// named definition from the graph plus any union per-branch synthesised
/// schemas under tag-derived keys (see [`BranchNameTable`]).
///
/// `config.include_draft_marker` controls whether the `$schema` draft marker
/// is added at the document root.
pub fn to_json_schema_with_config(
    graph: &SchemaGraph,
    ty: &SchemaType,
    config: JsonSchemaConfig,
) -> Value {
    let table = build_branch_name_table(graph, ty);
    let mut root = render_type(graph, ty, true, &table, config);
    let mut defs = render_defs(graph, &table, config);
    add_union_branch_defs(graph, ty, &mut defs, &table, config);
    if !defs.is_empty() {
        if let Some(obj) = root.as_object_mut() {
            obj.insert("$defs".to_string(), Value::Object(defs));
        } else {
            let mut wrapper = Map::new();
            wrapper.insert("$defs".to_string(), Value::Object(defs));
            wrapper.insert("allOf".to_string(), Value::Array(vec![root.clone()]));
            root = Value::Object(wrapper);
        }
    }
    if config.include_draft_marker
        && let Some(obj) = root.as_object_mut()
    {
        // Insert the JSON Schema draft marker at the top of the produced
        // root schema. OpenAPI removes this; see `super::openapi`.
        let mut with_schema = Map::with_capacity(obj.len() + 1);
        with_schema.insert(
            "$schema".to_string(),
            Value::String(JSON_SCHEMA_DRAFT.to_string()),
        );
        for (k, v) in obj.iter() {
            with_schema.insert(k.clone(), v.clone());
        }
        return Value::Object(with_schema);
    }
    root
}

/// Render a JSON Schema for untrusted external input. Host-managed capability
/// leaves cannot be constructed by callers.
pub fn to_external_input_json_schema(
    graph: &SchemaGraph,
    ty: &SchemaType,
    include_draft_marker: bool,
) -> Value {
    to_json_schema_with_config(
        graph,
        ty,
        JsonSchemaConfig {
            include_draft_marker,
            ..JsonSchemaConfig::EXTERNAL_INPUT
        },
    )
}

/// Render a JSON Schema for externally visible output. Host-managed capability
/// leaves expose only their redacted placeholders.
pub fn to_external_output_json_schema(
    graph: &SchemaGraph,
    ty: &SchemaType,
    include_draft_marker: bool,
) -> Value {
    to_json_schema_with_config(
        graph,
        ty,
        JsonSchemaConfig {
            include_draft_marker,
            ..JsonSchemaConfig::EXTERNAL_OUTPUT
        },
    )
}

/// Render the JSON domain accepted by reflection `pack_json`/`unpack_json`.
/// Capability, future, and stream leaves are unsatisfiable because those
/// adapters have no JSON representation for them.
pub fn to_reflection_json_schema(
    graph: &SchemaGraph,
    ty: &SchemaType,
    include_draft_marker: bool,
) -> Value {
    to_json_schema_with_config(
        graph,
        ty,
        JsonSchemaConfig {
            include_draft_marker,
            ..JsonSchemaConfig::REFLECTION
        },
    )
}

/// Whether `ty`, after following any `Ref` chain against `graph`, is an
/// `option<…>`. Used to decide whether an input parameter is required.
fn resolves_to_option(graph: &SchemaGraph, ty: &SchemaType) -> bool {
    let mut current = ty;
    let mut visited: HashSet<TypeId> = HashSet::new();
    loop {
        match current {
            SchemaType::Option { .. } => return true,
            SchemaType::Ref { id, .. } => {
                if !visited.insert(id.clone()) {
                    return false;
                }
                match graph.lookup(id) {
                    Some(def) => current = &def.body,
                    None => return false,
                }
            }
            _ => return false,
        }
    }
}

/// Build a `$defs` object covering every named definition in the graph.
///
/// Per RFC 6901 §4, JSON Pointer escaping (`~0`/`~1`) applies to the
/// *pointer string*, not to the resolved object member name. The map key
/// is therefore the **raw** `TypeId.0` string; the escaped form is only
/// used inside `$ref` pointers (see [`ref_pointer`]).
pub(super) fn render_defs(
    graph: &SchemaGraph,
    table: &BranchNameTable,
    config: JsonSchemaConfig,
) -> Map<String, Value> {
    let mut defs = Map::new();
    for def in &graph.defs {
        // The def's metadata now lives on `def.body` directly; `render_type`
        // already attaches inline-node metadata, so no extra `attach_metadata`
        // call is required here.
        let mut body = render_type(graph, &def.body, false, table, config);
        if let Some(name) = &def.name
            && let Some(obj) = body.as_object_mut()
        {
            obj.entry("title").or_insert(Value::String(name.clone()));
        }
        defs.insert(def.id.0.clone(), body);
    }
    defs
}

/// Walk every union under the graph and synthesize per-branch `$defs`
/// entries so discriminator-mapping pointers always resolve.
pub(super) fn add_union_branch_defs(
    graph: &SchemaGraph,
    root_ty: &SchemaType,
    defs: &mut Map<String, Value>,
    table: &BranchNameTable,
    config: JsonSchemaConfig,
) {
    let mut emitted = HashSet::new();
    collect_union_branch_defs(graph, root_ty, defs, &mut emitted, table, config);
    for def in &graph.defs {
        collect_union_branch_defs(graph, &def.body, defs, &mut emitted, table, config);
    }
}

fn collect_union_branch_defs(
    graph: &SchemaGraph,
    ty: &SchemaType,
    defs: &mut Map<String, Value>,
    emitted: &mut HashSet<String>,
    table: &BranchNameTable,
    config: JsonSchemaConfig,
) {
    match ty {
        SchemaType::Union { spec, .. } => {
            for branch in spec.branches.iter() {
                let key = table.name_for(branch).to_string();
                if emitted.insert(key.clone()) {
                    let mut body = render_type(graph, &branch.body, false, table, config);
                    attach_metadata(&mut body, &branch.metadata);
                    defs.insert(
                        key,
                        obj_inline([(
                            "allOf",
                            Value::Array(vec![
                                body,
                                discriminator_constraint(&branch.discriminator),
                            ]),
                        )]),
                    );
                }
                collect_union_branch_defs(graph, &branch.body, defs, emitted, table, config);
            }
        }
        SchemaType::Record { fields, .. } => {
            for f in fields {
                collect_union_branch_defs(graph, &f.body, defs, emitted, table, config);
            }
        }
        SchemaType::Variant { cases, .. } => {
            for case in cases {
                if let Some(p) = &case.payload {
                    collect_union_branch_defs(graph, p, defs, emitted, table, config);
                }
            }
        }
        SchemaType::Tuple { elements, .. } => {
            for e in elements {
                collect_union_branch_defs(graph, e, defs, emitted, table, config);
            }
        }
        SchemaType::List { element, .. }
        | SchemaType::FixedList { element, .. }
        | SchemaType::Option { inner: element, .. } => {
            collect_union_branch_defs(graph, element, defs, emitted, table, config);
        }
        SchemaType::Map { key, value, .. } => {
            collect_union_branch_defs(graph, key, defs, emitted, table, config);
            collect_union_branch_defs(graph, value, defs, emitted, table, config);
        }
        SchemaType::Result { spec, .. } => {
            if let Some(t) = &spec.ok {
                collect_union_branch_defs(graph, t, defs, emitted, table, config);
            }
            if let Some(t) = &spec.err {
                collect_union_branch_defs(graph, t, defs, emitted, table, config);
            }
        }
        SchemaType::Future { inner, .. } | SchemaType::Stream { inner, .. } => {
            if let Some(t) = inner {
                collect_union_branch_defs(graph, t, defs, emitted, table, config);
            }
        }
        _ => {}
    }
}

/// Stable, tag-preserving `$defs` / `components.schemas` keys for every
/// union branch reachable from a render root.
///
/// Built once per render via [`build_branch_name_table`]. The names are
/// derived primarily from each branch's `tag` (sanitised to
/// `UpperCamelCase`) so that types in a generated OpenAPI client carry
/// human-meaningful names rather than opaque content hashes.
///
/// Collisions (two structurally distinct branches sharing a tag) are
/// resolved by progressively prepending segments from the schema-graph
/// path that reached each branch, mirroring the algorithm used by
/// `bridge_gen::type_naming`. As a last resort — when no contextual
/// disambiguation works — a short hash suffix is appended.
///
/// Determinism: the walk visits branches in source order; collision
/// resolution iterates the resulting group deterministically. The
/// canonical structural key used internally is a `blake3` hash of the
/// branch's deterministic JSON serialisation.
pub(super) struct BranchNameTable {
    names: HashMap<String, String>,
}

impl BranchNameTable {
    pub(super) fn name_for(&self, branch: &UnionBranch) -> &str {
        let key = canonical_branch_key(branch);
        self.names.get(&key).map(String::as_str).expect(
            "BranchNameTable must contain every union branch reachable from the render root \
                 — `build_branch_name_table` is the source of truth for this invariant",
        )
    }
}

pub(super) fn build_branch_name_table(
    graph: &SchemaGraph,
    root_ty: &SchemaType,
) -> BranchNameTable {
    let mut collector = BranchCollector::default();
    collector.walk_type(root_ty);
    for def in &graph.defs {
        // Each named def starts a fresh path rooted at its name (or
        // TypeId fallback); this lets disambiguation lift names through
        // the named-def boundary when needed.
        collector.path.clear();
        let seg = def.name.clone().unwrap_or_else(|| def.id.0.clone());
        collector.path.push(seg);
        collector.walk_type(&def.body);
    }
    collector.path.clear();
    // Pre-seed `taken` with every named def's TypeId so branch names
    // never silently overwrite a real graph def in `$defs`.
    let taken: HashSet<String> = graph.defs.iter().map(|d| d.id.0.clone()).collect();
    collector.into_table(taken)
}

/// Deterministic structural key for a `UnionBranch`. Internal only;
/// never appears in rendered output.
fn canonical_branch_key(branch: &UnionBranch) -> String {
    let bytes = serde_json::to_vec(branch).expect("UnionBranch serializes deterministically");
    let hex = blake3::hash(&bytes).to_hex();
    // 128 bits of hash output — sufficient to uniquely identify a branch
    // body within any practical schema document.
    hex.as_str()[..32].to_string()
}

#[derive(Default)]
struct BranchCollector {
    /// Canonical key for every encountered branch, in walk order, with no
    /// duplicates. Used both for membership and for deterministic iteration
    /// during name resolution.
    keys: Vec<String>,
    occurrences: HashMap<String, Occurrence>,
    /// Path of segments describing the current position in the schema
    /// graph (record-field names, variant-case names, "key"/"value",
    /// "ok"/"err", outer branch tags, …).
    path: Vec<String>,
}

struct Occurrence {
    tag: String,
    /// First path at which this branch was reached. Used to disambiguate
    /// colliding preferred names.
    path: Vec<String>,
}

impl BranchCollector {
    fn record(&mut self, branch: &UnionBranch) {
        let key = canonical_branch_key(branch);
        if let std::collections::hash_map::Entry::Vacant(slot) = self.occurrences.entry(key.clone())
        {
            slot.insert(Occurrence {
                tag: branch.tag.clone(),
                path: self.path.clone(),
            });
            self.keys.push(key);
        }
    }

    /// Walk a `SchemaType` subtree, pushing/popping path segments and
    /// recording every encountered `UnionBranch`.
    ///
    /// `Ref(TypeId)` nodes are not followed: the named def they point
    /// at is walked separately from `build_branch_name_table` with its
    /// own fresh path, so following refs here would record duplicate
    /// occurrences and pollute the disambiguation path.
    fn walk_type(&mut self, ty: &SchemaType) {
        match ty {
            SchemaType::Union { spec, .. } => {
                for branch in &spec.branches {
                    self.record(branch);
                    self.path.push(branch.tag.clone());
                    self.walk_type(&branch.body);
                    self.path.pop();
                }
            }
            SchemaType::Record { fields, .. } => {
                for f in fields {
                    self.path.push(f.name.clone());
                    self.walk_type(&f.body);
                    self.path.pop();
                }
            }
            SchemaType::Variant { cases, .. } => {
                for case in cases {
                    if let Some(p) = &case.payload {
                        self.path.push(case.name.clone());
                        self.walk_type(p);
                        self.path.pop();
                    }
                }
            }
            SchemaType::Tuple { elements, .. } => {
                for (i, e) in elements.iter().enumerate() {
                    self.path.push(format!("item{i}"));
                    self.walk_type(e);
                    self.path.pop();
                }
            }
            SchemaType::List { element, .. } | SchemaType::FixedList { element, .. } => {
                self.path.push("item".to_string());
                self.walk_type(element);
                self.path.pop();
            }
            SchemaType::Option { inner, .. } => {
                self.path.push("inner".to_string());
                self.walk_type(inner);
                self.path.pop();
            }
            SchemaType::Map { key, value, .. } => {
                self.path.push("key".to_string());
                self.walk_type(key);
                self.path.pop();
                self.path.push("value".to_string());
                self.walk_type(value);
                self.path.pop();
            }
            SchemaType::Result { spec, .. } => {
                if let Some(t) = &spec.ok {
                    self.path.push("ok".to_string());
                    self.walk_type(t);
                    self.path.pop();
                }
                if let Some(t) = &spec.err {
                    self.path.push("err".to_string());
                    self.walk_type(t);
                    self.path.pop();
                }
            }
            SchemaType::Future { inner, .. } | SchemaType::Stream { inner, .. } => {
                if let Some(t) = inner {
                    self.path.push("inner".to_string());
                    self.walk_type(t);
                    self.path.pop();
                }
            }
            _ => {}
        }
    }

    fn into_table(self, mut taken: HashSet<String>) -> BranchNameTable {
        // Compute each occurrence's preferred name (from its `tag`) and
        // group by it.
        let mut groups: Vec<(String, Vec<String>)> = Vec::new();
        for key in &self.keys {
            let occ = &self.occurrences[key];
            let preferred = sanitise_to_upper_camel(&occ.tag);
            match groups.iter_mut().find(|(name, _)| name == &preferred) {
                Some((_, members)) => members.push(key.clone()),
                None => groups.push((preferred, vec![key.clone()])),
            }
        }

        let mut names = HashMap::<String, String>::new();
        for (preferred, members) in groups {
            if members.len() == 1 && !taken.contains(&preferred) {
                // Unique preferred name and not colliding with a graph
                // def TypeId — use it verbatim.
                let only = members.into_iter().next().unwrap();
                taken.insert(preferred.clone());
                names.insert(only, preferred);
            } else {
                // Real collision (or shadows a graph def): every member
                // is forced through location-based disambiguation so the
                // assigned names are symmetric.
                for key in members {
                    let occ = &self.occurrences[&key];
                    let assigned = disambiguate(&preferred, &occ.path, &taken, &key);
                    taken.insert(assigned.clone());
                    names.insert(key, assigned);
                }
            }
        }

        BranchNameTable { names }
    }
}

/// Find a unique name by progressively prepending sanitised path
/// segments (innermost → outermost) to `base`. Falls back to a short
/// canonical-key suffix if no contextual disambiguation works.
fn disambiguate(base: &str, path: &[String], taken: &HashSet<String>, canonical: &str) -> String {
    let mut candidate = base.to_string();
    for seg in path.iter().rev() {
        let seg_camel = sanitise_to_upper_camel(seg);
        if seg_camel.is_empty() {
            continue;
        }
        candidate = format!("{seg_camel}{candidate}");
        if !taken.contains(&candidate) {
            return candidate;
        }
    }
    let suffix_len = 6.min(canonical.len());
    format!("{base}_{}", &canonical[..suffix_len])
}

/// Sanitise an arbitrary string to a non-empty UpperCamelCase identifier
/// suitable for both JSON Pointer member names and OpenAPI schema names
/// (alphabet `[A-Za-z0-9]`). Non-alphanumerics are dropped and treated
/// as word separators; a leading digit is prefixed with `_`.
fn sanitise_to_upper_camel(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut upper_next = true;
    for ch in s.chars() {
        if ch.is_ascii_alphanumeric() {
            if upper_next {
                for u in ch.to_uppercase() {
                    out.push(u);
                }
                upper_next = false;
            } else {
                out.push(ch);
            }
        } else {
            upper_next = true;
        }
    }
    if out.is_empty() {
        return "Branch".to_string();
    }
    if out.starts_with(|c: char| c.is_ascii_digit()) {
        format!("_{out}")
    } else {
        out
    }
}

fn discriminator_constraint(rule: &DiscriminatorRule) -> Value {
    let mut obj = Map::new();
    match rule {
        DiscriminatorRule::Prefix { prefix } => {
            obj.insert(
                "pattern".to_string(),
                Value::String(format!("^{}", regex_escape(prefix))),
            );
        }
        DiscriminatorRule::Suffix { suffix } => {
            obj.insert(
                "pattern".to_string(),
                Value::String(format!("{}$", regex_escape(suffix))),
            );
        }
        DiscriminatorRule::Contains { substring } => {
            obj.insert(
                "pattern".to_string(),
                Value::String(regex_escape(substring)),
            );
        }
        DiscriminatorRule::Regex { regex } => {
            obj.insert("pattern".to_string(), Value::String(regex.clone()));
        }
        DiscriminatorRule::FieldEquals(disc) => {
            // Constrain the field's value with `const` if a literal is set;
            // otherwise just require the field to be present.
            obj.insert(
                "required".to_string(),
                Value::Array(vec![Value::String(disc.field_name.clone())]),
            );
            if let Some(lit) = &disc.literal {
                let props = obj
                    .entry("properties")
                    .or_insert_with(|| Value::Object(Map::new()))
                    .as_object_mut()
                    .expect("properties is object");
                let field = props
                    .entry(disc.field_name.clone())
                    .or_insert_with(|| obj_inline([("type", Value::String("string".to_string()))]));
                if let Some(field_obj) = field.as_object_mut() {
                    field_obj.insert("const".to_string(), Value::String(lit.clone()));
                }
            }
        }
        DiscriminatorRule::FieldAbsent { field_name } => {
            // Express absence via `not: { required: [field] }`.
            let not = obj_inline([(
                "required",
                Value::Array(vec![Value::String(field_name.clone())]),
            )]);
            obj.insert("not".to_string(), not);
        }
    }
    Value::Object(obj)
}

pub(super) fn render_type(
    graph: &SchemaGraph,
    ty: &SchemaType,
    root: bool,
    table: &BranchNameTable,
    config: JsonSchemaConfig,
) -> Value {
    let mut rendered = match ty {
        SchemaType::Ref { id, .. } => obj([("$ref", Value::String(ref_pointer(id, root)))]),

        SchemaType::Bool { .. } => obj([("type", Value::String("boolean".to_string()))]),
        SchemaType::S8 { restrictions, .. } => {
            signed_integer_schema(i8::MIN as i64, i8::MAX as i64, restrictions.as_ref())
        }
        SchemaType::S16 { restrictions, .. } => {
            signed_integer_schema(i16::MIN as i64, i16::MAX as i64, restrictions.as_ref())
        }
        SchemaType::S32 { restrictions, .. } => {
            signed_integer_schema(i32::MIN as i64, i32::MAX as i64, restrictions.as_ref())
        }
        SchemaType::S64 { restrictions, .. } => signed_64_schema(restrictions.as_ref()),
        SchemaType::U8 { restrictions, .. } => {
            unsigned_integer_schema(0, u8::MAX as u64, restrictions.as_ref())
        }
        SchemaType::U16 { restrictions, .. } => {
            unsigned_integer_schema(0, u16::MAX as u64, restrictions.as_ref())
        }
        SchemaType::U32 { restrictions, .. } => {
            unsigned_integer_schema(0, u32::MAX as u64, restrictions.as_ref())
        }
        SchemaType::U64 { restrictions, .. } => unsigned_64_schema(restrictions.as_ref()),
        SchemaType::F32 { restrictions, .. } => {
            float_schema(-(f32::MAX as f64), f32::MAX as f64, restrictions.as_ref())
        }
        SchemaType::F64 { restrictions, .. } => {
            float_schema(-f64::MAX, f64::MAX, restrictions.as_ref())
        }
        SchemaType::Char { .. } => obj([
            ("type", Value::String("string".to_string())),
            ("minLength", Value::Number(1.into())),
            ("maxLength", Value::Number(1.into())),
        ]),
        SchemaType::String { .. } => obj([("type", Value::String("string".to_string()))]),

        SchemaType::Record { fields, .. } => {
            let mut props = Map::new();
            let mut required = Vec::with_capacity(fields.len());
            for field in fields {
                let mut field_schema = render_type(graph, &field.body, false, table, config);
                attach_metadata(&mut field_schema, &field.metadata);
                props.insert(field.name.clone(), field_schema);
                // `option<…>` fields are not required: the field may be omitted
                // entirely, and an explicit `null` is still accepted by the
                // option's `oneOf [null, T]` schema.
                if !resolves_to_option(graph, &field.body) {
                    required.push(Value::String(field.name.clone()));
                }
            }
            obj([
                ("type", Value::String("object".to_string())),
                ("properties", Value::Object(props)),
                ("required", Value::Array(required)),
                ("additionalProperties", Value::Bool(false)),
            ])
        }

        SchemaType::Variant { cases, .. } => {
            Value::Object(variant_schema(graph, cases, table, config))
        }

        SchemaType::Enum { cases, .. } => obj([
            ("type", Value::String("string".to_string())),
            (
                "enum",
                Value::Array(cases.iter().cloned().map(Value::String).collect()),
            ),
        ]),

        SchemaType::Flags { flags, .. } => obj([
            ("type", Value::String("array".to_string())),
            (
                "items",
                obj([
                    ("type", Value::String("string".to_string())),
                    (
                        "enum",
                        Value::Array(flags.iter().cloned().map(Value::String).collect()),
                    ),
                ]),
            ),
            ("uniqueItems", Value::Bool(true)),
        ]),

        SchemaType::Tuple { elements, .. } => {
            if elements.is_empty() {
                // JSON Schema 2020-12 requires `prefixItems` to be a
                // non-empty array, so the empty-tuple shape uses
                // `maxItems`/`minItems` only.
                obj([
                    ("type", Value::String("array".to_string())),
                    ("minItems", Value::Number(0u64.into())),
                    ("maxItems", Value::Number(0u64.into())),
                ])
            } else {
                obj([
                    ("type", Value::String("array".to_string())),
                    (
                        "prefixItems",
                        Value::Array(
                            elements
                                .iter()
                                .map(|e| render_type(graph, e, false, table, config))
                                .collect(),
                        ),
                    ),
                    ("items", Value::Bool(false)),
                    ("minItems", Value::Number((elements.len() as u64).into())),
                ])
            }
        }

        SchemaType::List { element, .. } => obj([
            ("type", Value::String("array".to_string())),
            ("items", render_type(graph, element, false, table, config)),
        ]),

        SchemaType::FixedList {
            element, length, ..
        } => obj([
            ("type", Value::String("array".to_string())),
            ("items", render_type(graph, element, false, table, config)),
            ("minItems", Value::Number((*length).into())),
            ("maxItems", Value::Number((*length).into())),
        ]),

        SchemaType::Map { key, value, .. } => {
            let pair = obj([
                ("type", Value::String("array".to_string())),
                (
                    "prefixItems",
                    Value::Array(vec![
                        render_type(graph, key, false, table, config),
                        render_type(graph, value, false, table, config),
                    ]),
                ),
                ("items", Value::Bool(false)),
                ("minItems", Value::Number(2.into())),
                ("maxItems", Value::Number(2.into())),
            ]);
            obj([
                ("type", Value::String("array".to_string())),
                ("items", pair),
            ])
        }

        SchemaType::Option { inner, .. } => obj([(
            "oneOf",
            Value::Array(vec![
                obj([("type", Value::String("null".to_string()))]),
                render_type(graph, inner, false, table, config),
            ]),
        )]),

        SchemaType::Result { spec, .. } => Value::Object(result_schema(graph, spec, table, config)),

        SchemaType::Text { restrictions, .. } => Value::Object(text_schema(restrictions)),
        SchemaType::Binary { restrictions, .. } => Value::Object(binary_schema(restrictions)),
        SchemaType::Path { spec, .. } => Value::Object(path_schema(spec)),
        SchemaType::Url { restrictions, .. } => Value::Object(url_schema(restrictions)),
        SchemaType::Uuid { .. } => obj([
            ("type", Value::String("string".to_string())),
            ("format", Value::String("uuid".to_string())),
        ]),
        SchemaType::Datetime { .. } => obj([
            ("type", Value::String("string".to_string())),
            ("format", Value::String("date-time".to_string())),
        ]),
        SchemaType::Duration { .. } => obj([
            ("type", Value::String("object".to_string())),
            ("properties", obj([("nanoseconds", signed_64_schema(None))])),
            (
                "required",
                Value::Array(vec![Value::String("nanoseconds".to_string())]),
            ),
            ("additionalProperties", Value::Bool(false)),
            (
                "title",
                Value::String("Duration in nanoseconds".to_string()),
            ),
        ]),
        SchemaType::Quantity { spec, .. } => Value::Object(quantity_schema(spec)),

        SchemaType::Union { spec, .. } => Value::Object(union_schema(graph, spec, table, config)),

        SchemaType::Secret { spec, .. } => {
            host_managed_schema(config.host_managed, "secret", || {
                Value::Object(secret_schema(spec))
            })
        }
        SchemaType::QuotaToken { spec, .. } => {
            host_managed_schema(config.host_managed, "quota-token", || {
                Value::Object(quota_token_schema(spec))
            })
        }
        SchemaType::PermissionCard { spec, .. } => {
            host_managed_schema(config.host_managed, "permission-card", || {
                Value::Object(permission_card_schema(spec))
            })
        }

        SchemaType::Future { .. } | SchemaType::Stream { .. } => match config.unsupported {
            UnsupportedLeafSchemaPolicy::Placeholder => obj([
                ("type", Value::String("null".to_string())),
                (
                    "description",
                    Value::String("WASI P3 placeholder".to_string()),
                ),
            ]),
            UnsupportedLeafSchemaPolicy::Reject => obj([("not", Value::Object(Map::new()))]),
        },
    };

    // Per-node metadata: attach docs / examples / deprecated for every
    // SchemaType node so inline-typed positions (record fields, list
    // elements, etc.) propagate their metadata into the generated JSON
    // Schema, not only named definitions.
    attach_metadata(&mut rendered, ty.metadata());
    rendered
}

fn host_managed_schema(
    policy: HostManagedSchemaPolicy,
    kind: &str,
    trusted: impl FnOnce() -> Value,
) -> Value {
    match policy {
        HostManagedSchemaPolicy::TrustedSnapshot => trusted(),
        HostManagedSchemaPolicy::Reject => obj([
            ("not", Value::Object(Map::new())),
            (
                "description",
                Value::String(format!(
                    "Host-managed {kind} capabilities cannot be supplied externally"
                )),
            ),
        ]),
        HostManagedSchemaPolicy::Redact => obj([
            ("type", Value::String("string".to_string())),
            ("const", Value::String(format!("<redacted: {kind}>"))),
            (
                "description",
                Value::String(format!(
                    "Host-managed {kind} capability values are redacted"
                )),
            ),
        ]),
    }
}

fn ref_pointer(id: &TypeId, _root: bool) -> String {
    ref_to_def_key(&id.0)
}

/// Build the `$ref` pointer string for a raw `$defs` member key.
///
/// `key` is the raw (un-escaped) member name; this helper applies
/// RFC 6901 JSON Pointer escaping when embedding it in the pointer path.
pub(super) fn ref_to_def_key(key: &str) -> String {
    format!("#/$defs/{}", escape_pointer_token(key))
}

fn signed_integer_schema(min: i64, max: i64, restrictions: Option<&NumericRestrictions>) -> Value {
    let minimum = restrictions
        .and_then(|value| value.min)
        .and_then(|bound| match bound {
            NumericBound::Signed(value) => Some(value),
            _ => None,
        })
        .unwrap_or(min)
        .max(min);
    let maximum = restrictions
        .and_then(|value| value.max)
        .and_then(|bound| match bound {
            NumericBound::Signed(value) => Some(value),
            _ => None,
        })
        .unwrap_or(max)
        .min(max);
    obj([
        ("type", Value::String("integer".to_string())),
        ("minimum", Value::Number(Number::from(minimum))),
        ("maximum", Value::Number(Number::from(maximum))),
    ])
}

fn unsigned_integer_schema(
    min: u64,
    max: u64,
    restrictions: Option<&NumericRestrictions>,
) -> Value {
    let minimum = restrictions
        .and_then(|value| value.min)
        .and_then(|bound| match bound {
            NumericBound::Unsigned(value) => Some(value),
            _ => None,
        })
        .unwrap_or(min)
        .max(min);
    let maximum = restrictions
        .and_then(|value| value.max)
        .and_then(|bound| match bound {
            NumericBound::Unsigned(value) => Some(value),
            _ => None,
        })
        .unwrap_or(max)
        .min(max);
    obj([
        ("type", Value::String("integer".to_string())),
        ("minimum", Value::Number(Number::from(minimum))),
        ("maximum", Value::Number(Number::from(maximum))),
    ])
}

fn float_schema(min: f64, max: f64, restrictions: Option<&NumericRestrictions>) -> Value {
    let mut schema = Map::new();
    schema.insert("type".to_string(), Value::String("number".to_string()));
    if let Some(NumericBound::FloatBits(bits)) = restrictions.and_then(|value| value.min)
        && let Some(value) = Number::from_f64(f64::from_bits(bits).max(min))
    {
        schema.insert("minimum".to_string(), Value::Number(value));
    }
    if let Some(NumericBound::FloatBits(bits)) = restrictions.and_then(|value| value.max)
        && let Some(value) = Number::from_f64(f64::from_bits(bits).min(max))
    {
        schema.insert("maximum".to_string(), Value::Number(value));
    }
    Value::Object(schema)
}

fn unsigned_64_schema(restrictions: Option<&NumericRestrictions>) -> Value {
    let minimum = restrictions
        .and_then(|value| value.min)
        .and_then(|bound| match bound {
            NumericBound::Unsigned(value) => Some(value),
            _ => None,
        })
        .unwrap_or(0);
    let maximum = restrictions
        .and_then(|value| value.max)
        .and_then(|bound| match bound {
            NumericBound::Unsigned(value) => Some(value),
            _ => None,
        })
        .unwrap_or(u64::MAX);
    obj([
        ("type", Value::String("string".to_string())),
        ("format", Value::String("uint64".to_string())),
        ("pattern", Value::String("^(?:0|[1-9][0-9]*)$".to_string())),
        ("x-golem-minimum", Value::String(minimum.to_string())),
        ("x-golem-maximum", Value::String(maximum.to_string())),
    ])
}

fn signed_64_schema(restrictions: Option<&NumericRestrictions>) -> Value {
    let minimum = restrictions
        .and_then(|value| value.min)
        .and_then(|bound| match bound {
            NumericBound::Signed(value) => Some(value),
            _ => None,
        })
        .unwrap_or(i64::MIN);
    let maximum = restrictions
        .and_then(|value| value.max)
        .and_then(|bound| match bound {
            NumericBound::Signed(value) => Some(value),
            _ => None,
        })
        .unwrap_or(i64::MAX);
    obj([
        ("type", Value::String("string".to_string())),
        ("format", Value::String("int64".to_string())),
        (
            "pattern",
            Value::String("^(?:0|-[1-9][0-9]*|[1-9][0-9]*)$".to_string()),
        ),
        ("x-golem-minimum", Value::String(minimum.to_string())),
        ("x-golem-maximum", Value::String(maximum.to_string())),
    ])
}

fn variant_schema(
    graph: &SchemaGraph,
    cases: &[VariantCaseType],
    table: &BranchNameTable,
    config: JsonSchemaConfig,
) -> Map<String, Value> {
    let one_of: Vec<Value> = cases
        .iter()
        .map(|case| match &case.payload {
            None => obj([("const", Value::String(case.name.clone()))]),
            Some(payload_ty) => {
                let mut props = Map::new();
                props.insert(
                    case.name.clone(),
                    render_type(graph, payload_ty, false, table, config),
                );
                obj([
                    ("type", Value::String("object".to_string())),
                    ("properties", Value::Object(props)),
                    (
                        "required",
                        Value::Array(vec![Value::String(case.name.clone())]),
                    ),
                    ("additionalProperties", Value::Bool(false)),
                ])
            }
        })
        .collect();
    let mut out = Map::new();
    out.insert("oneOf".to_string(), Value::Array(one_of));
    out
}

fn result_schema(
    graph: &SchemaGraph,
    spec: &ResultSpec,
    table: &BranchNameTable,
    config: JsonSchemaConfig,
) -> Map<String, Value> {
    let ok_inner = spec
        .ok
        .as_deref()
        .map(|t| render_type(graph, t, false, table, config))
        .unwrap_or_else(|| obj([("type", Value::String("null".to_string()))]));
    let err_inner = spec
        .err
        .as_deref()
        .map(|t| render_type(graph, t, false, table, config))
        .unwrap_or_else(|| obj([("type", Value::String("null".to_string()))]));
    let one_of = vec![
        obj([
            ("type", Value::String("object".to_string())),
            (
                "properties",
                Value::Object({
                    let mut m = Map::new();
                    m.insert("ok".to_string(), ok_inner);
                    m
                }),
            ),
            ("required", Value::Array(vec![Value::String("ok".into())])),
            ("additionalProperties", Value::Bool(false)),
        ]),
        obj([
            ("type", Value::String("object".to_string())),
            (
                "properties",
                Value::Object({
                    let mut m = Map::new();
                    m.insert("err".to_string(), err_inner);
                    m
                }),
            ),
            ("required", Value::Array(vec![Value::String("err".into())])),
            ("additionalProperties", Value::Bool(false)),
        ]),
    ];
    let mut out = Map::new();
    out.insert("oneOf".to_string(), Value::Array(one_of));
    out
}

fn text_schema(restrictions: &TextRestrictions) -> Map<String, Value> {
    // Canonical Text JSON shape: `{ text: string, language?: string }` with
    // length / pattern constraints lifted into the `text` field.
    let mut text_field = Map::new();
    text_field.insert("type".to_string(), Value::String("string".to_string()));
    if let Some(min) = restrictions.min_length {
        text_field.insert("minLength".to_string(), Value::Number(min.into()));
    }
    if let Some(max) = restrictions.max_length {
        text_field.insert("maxLength".to_string(), Value::Number(max.into()));
    }
    if let Some(regex) = &restrictions.regex {
        text_field.insert("pattern".to_string(), Value::String(regex.clone()));
    }
    let mut properties = Map::new();
    properties.insert("text".to_string(), Value::Object(text_field));
    let mut language_field = Map::new();
    language_field.insert("type".to_string(), Value::String("string".to_string()));
    if let Some(langs) = &restrictions.languages {
        language_field.insert(
            "enum".to_string(),
            Value::Array(langs.iter().cloned().map(Value::String).collect()),
        );
    }
    properties.insert("language".to_string(), Value::Object(language_field));
    let mut m = Map::new();
    m.insert("type".to_string(), Value::String("object".to_string()));
    m.insert("properties".to_string(), Value::Object(properties));
    m.insert(
        "required".to_string(),
        Value::Array(vec![Value::String("text".to_string())]),
    );
    m.insert("additionalProperties".to_string(), Value::Bool(false));
    m
}

fn binary_schema(restrictions: &BinaryRestrictions) -> Map<String, Value> {
    // Canonical Binary JSON shape: `{ bytes: base64url-string, mimeType?: string }`.
    // `min_bytes` / `max_bytes` count *raw* bytes; the JSON field is
    // base64url-no-pad-encoded, so the on-wire string length is
    // `base64url_no_pad_len(n) = 4*(n/3) + match n%3 { 0=>0, 1=>2, 2=>3 }`.
    let mut bytes_field = Map::new();
    bytes_field.insert("type".to_string(), Value::String("string".to_string()));
    bytes_field.insert(
        "contentEncoding".to_string(),
        Value::String("base64url".to_string()),
    );
    bytes_field.insert(
        "pattern".to_string(),
        Value::String(BASE64URL_PATTERN.to_string()),
    );
    if let Some(min) = restrictions.min_bytes {
        bytes_field.insert(
            "minLength".to_string(),
            Value::Number(base64url_no_pad_len(min).into()),
        );
    }
    if let Some(max) = restrictions.max_bytes {
        bytes_field.insert(
            "maxLength".to_string(),
            Value::Number(base64url_no_pad_len(max).into()),
        );
    }
    let mut mime_field = Map::new();
    mime_field.insert("type".to_string(), Value::String("string".to_string()));
    mime_field.insert(
        "pattern".to_string(),
        Value::String(MIME_TYPE_PATTERN.to_string()),
    );
    if let Some(mimes) = &restrictions.mime_types {
        mime_field.insert(
            "enum".to_string(),
            Value::Array(mimes.iter().cloned().map(Value::String).collect()),
        );
    }
    let mut properties = Map::new();
    properties.insert("bytes".to_string(), Value::Object(bytes_field));
    properties.insert("mimeType".to_string(), Value::Object(mime_field));
    let mut m = Map::new();
    m.insert("type".to_string(), Value::String("object".to_string()));
    m.insert("properties".to_string(), Value::Object(properties));
    m.insert(
        "required".to_string(),
        Value::Array(vec![Value::String("bytes".to_string())]),
    );
    m.insert("additionalProperties".to_string(), Value::Bool(false));
    m
}

fn path_schema(spec: &PathSpec) -> Map<String, Value> {
    let mut m = Map::new();
    m.insert("type".to_string(), Value::String("string".to_string()));
    m.insert("format".to_string(), Value::String("file-path".to_string()));
    let kind = match spec.kind {
        crate::schema::schema_type::PathKind::File => "file",
        crate::schema::schema_type::PathKind::Directory => "directory",
        crate::schema::schema_type::PathKind::Any => "any",
    };
    let direction = match spec.direction {
        crate::schema::schema_type::PathDirection::Input => "input",
        crate::schema::schema_type::PathDirection::Output => "output",
        crate::schema::schema_type::PathDirection::InOut => "inout",
    };
    m.insert(
        "title".to_string(),
        Value::String(format!("{direction} {kind} path")),
    );
    let mut description = Vec::new();
    if let Some(exts) = &spec.allowed_extensions {
        description.push(format!("Allowed extensions: {}", exts.join(", ")));
    }
    if let Some(mimes) = &spec.allowed_mime_types {
        description.push(format!("Allowed MIME types: {}", mimes.join(", ")));
    }
    if !description.is_empty() {
        m.insert(
            "description".to_string(),
            Value::String(description.join("; ")),
        );
    }
    m
}

fn url_schema(restrictions: &UrlRestrictions) -> Map<String, Value> {
    let mut m = Map::new();
    m.insert("type".to_string(), Value::String("string".to_string()));
    m.insert("format".to_string(), Value::String("uri".to_string()));
    m.insert("title".to_string(), Value::String("URL".to_string()));
    let mut description = Vec::new();
    if let Some(schemes) = &restrictions.allowed_schemes {
        description.push(format!("Allowed schemes: {}", schemes.join(", ")));
    }
    if let Some(hosts) = &restrictions.allowed_hosts {
        description.push(format!("Allowed hosts: {}", hosts.join(", ")));
    }
    if !description.is_empty() {
        m.insert(
            "description".to_string(),
            Value::String(description.join("; ")),
        );
    }
    m
}

fn quantity_schema(spec: &QuantitySpec) -> Map<String, Value> {
    let mut props = Map::new();
    props.insert("mantissa".to_string(), signed_64_schema(None));
    props.insert(
        "scale".to_string(),
        obj([("type", Value::String("integer".to_string()))]),
    );
    props.insert(
        "unit".to_string(),
        obj([("type", Value::String("string".to_string()))]),
    );
    let mut m = Map::new();
    m.insert("type".to_string(), Value::String("object".to_string()));
    m.insert("properties".to_string(), Value::Object(props));
    m.insert(
        "required".to_string(),
        Value::Array(vec![
            Value::String("mantissa".to_string()),
            Value::String("scale".to_string()),
            Value::String("unit".to_string()),
        ]),
    );
    m.insert("additionalProperties".to_string(), Value::Bool(false));
    m.insert(
        "title".to_string(),
        Value::String(format!("Quantity ({})", spec.base_unit)),
    );
    let mut description = Vec::new();
    if let Some(min) = &spec.min {
        description.push(format!("min: {}", render_quantity(min)));
    }
    if let Some(max) = &spec.max {
        description.push(format!("max: {}", render_quantity(max)));
    }
    if !description.is_empty() {
        m.insert(
            "description".to_string(),
            Value::String(description.join("; ")),
        );
    }
    m
}

fn render_quantity(q: &QuantityValue) -> String {
    format!("{}e-{} {}", q.mantissa, q.scale, q.unit)
}

fn secret_schema(_spec: &SecretSpec) -> Map<String, Value> {
    // Canonical Secret JSON shape: see canonical/secret.rs.
    let secret_id = obj_inline([
        ("type", Value::String("string".to_string())),
        ("format", Value::String("uuid".to_string())),
    ]);
    let config_key = obj_inline([
        ("type", Value::String("array".to_string())),
        (
            "items",
            obj_inline([("type", Value::String("string".to_string()))]),
        ),
    ]);
    let version = obj_inline([
        ("type", Value::String("integer".to_string())),
        ("minimum", Value::Number(0.into())),
    ]);
    let resolved_at = obj_inline([
        ("type", Value::String("string".to_string())),
        ("format", Value::String("date-time".to_string())),
    ]);
    let category = obj_inline([("type", Value::String("string".to_string()))]);
    let mut properties = Map::new();
    properties.insert("secretId".to_string(), secret_id);
    properties.insert("configKey".to_string(), config_key);
    properties.insert("version".to_string(), version);
    properties.insert("resolvedAt".to_string(), resolved_at);
    properties.insert("category".to_string(), category);
    let mut m = Map::new();
    m.insert("type".to_string(), Value::String("object".to_string()));
    m.insert("properties".to_string(), Value::Object(properties));
    m.insert(
        "required".to_string(),
        Value::Array(vec![
            Value::String("secretId".to_string()),
            Value::String("version".to_string()),
            Value::String("resolvedAt".to_string()),
        ]),
    );
    m.insert("additionalProperties".to_string(), Value::Bool(false));
    m
}

fn quota_token_schema(_spec: &QuotaTokenSpec) -> Map<String, Value> {
    // Canonical QuotaToken JSON shape: see canonical/quota_token.rs.
    let env_id = obj_inline([
        ("type", Value::String("string".to_string())),
        ("format", Value::String("uuid".to_string())),
    ]);
    let resource_name = obj_inline([("type", Value::String("string".to_string()))]);
    let expected_use = obj_inline([(
        "oneOf",
        Value::Array(vec![
            obj_inline([
                ("type", Value::String("string".to_string())),
                ("pattern", Value::String("^[0-9]+$".to_string())),
            ]),
            obj_inline([
                ("type", Value::String("integer".to_string())),
                ("minimum", Value::Number(0u64.into())),
            ]),
        ]),
    )]);
    let last_credit = obj_inline([(
        "oneOf",
        Value::Array(vec![
            obj_inline([
                ("type", Value::String("string".to_string())),
                ("pattern", Value::String("^-?[0-9]+$".to_string())),
            ]),
            obj_inline([("type", Value::String("integer".to_string()))]),
        ]),
    )]);
    let last_credit_at = obj_inline([
        ("type", Value::String("string".to_string())),
        ("format", Value::String("date-time".to_string())),
    ]);
    let mut properties = Map::new();
    properties.insert("environmentId".to_string(), env_id);
    properties.insert("resourceName".to_string(), resource_name);
    properties.insert("expectedUse".to_string(), expected_use);
    properties.insert("lastCredit".to_string(), last_credit);
    properties.insert("lastCreditAt".to_string(), last_credit_at);
    let mut m = Map::new();
    m.insert("type".to_string(), Value::String("object".to_string()));
    m.insert("properties".to_string(), Value::Object(properties));
    m.insert(
        "required".to_string(),
        Value::Array(vec![
            Value::String("environmentId".to_string()),
            Value::String("resourceName".to_string()),
            Value::String("expectedUse".to_string()),
            Value::String("lastCredit".to_string()),
            Value::String("lastCreditAt".to_string()),
        ]),
    );
    m.insert("additionalProperties".to_string(), Value::Bool(false));
    m
}

fn permission_card_schema(_spec: &PermissionCardSpec) -> Map<String, Value> {
    // Permission-card values are opaque capability handles. The transported
    // snapshot carries card_id (authoritative), parent_ids, expires_at, and
    // polymorphic as trusted cache. See canonical/permission_card.rs.
    let card_id = obj_inline([
        ("type", Value::String("string".to_string())),
        ("format", Value::String("uuid".to_string())),
    ]);
    let parent_ids = obj_inline([
        ("type", Value::String("array".to_string())),
        (
            "items",
            obj_inline([
                ("type", Value::String("string".to_string())),
                ("format", Value::String("uuid".to_string())),
            ]),
        ),
    ]);
    let expires_at = obj_inline([
        ("type", Value::String("string".to_string())),
        ("format", Value::String("date-time".to_string())),
    ]);
    let polymorphic = obj_inline([("type", Value::String("boolean".to_string()))]);
    let mut properties = Map::new();
    properties.insert("cardId".to_string(), card_id);
    properties.insert("parentIds".to_string(), parent_ids);
    properties.insert("expiresAt".to_string(), expires_at);
    properties.insert("polymorphic".to_string(), polymorphic);
    let mut m = Map::new();
    m.insert("type".to_string(), Value::String("object".to_string()));
    m.insert("properties".to_string(), Value::Object(properties));
    m.insert(
        "required".to_string(),
        Value::Array(vec![
            Value::String("cardId".to_string()),
            Value::String("polymorphic".to_string()),
        ]),
    );
    m.insert("additionalProperties".to_string(), Value::Bool(false));
    m
}

fn union_schema(
    graph: &SchemaGraph,
    spec: &UnionSpec,
    table: &BranchNameTable,
    config: JsonSchemaConfig,
) -> Map<String, Value> {
    // Each branch gets a per-branch reference into `$defs` (synthesised
    // by `add_union_branch_defs`), so the `oneOf` and any discriminator
    // mapping resolves against schemas the renderer actually emits. The
    // branch key is resolved through `BranchNameTable` so two unrelated
    // unions sharing a tag get disambiguated names.
    let one_of: Vec<Value> = spec
        .branches
        .iter()
        .map(|b| obj([("$ref", Value::String(ref_to_def_key(table.name_for(b))))]))
        .collect();
    let mut m = Map::new();
    m.insert("oneOf".to_string(), Value::Array(one_of));
    if let Some(disc_field) = openapi_discriminator(spec) {
        let mut mapping = Map::new();
        for branch in spec.branches.iter() {
            let literal = match &branch.discriminator {
                DiscriminatorRule::FieldEquals(disc) => disc.literal.clone(),
                _ => None,
            };
            if let Some(lit) = literal {
                mapping.insert(lit, Value::String(ref_to_def_key(table.name_for(branch))));
            }
        }
        let mut d = Map::new();
        d.insert("propertyName".to_string(), Value::String(disc_field));
        if !mapping.is_empty() {
            d.insert("mapping".to_string(), Value::Object(mapping));
        }
        m.insert("discriminator".to_string(), Value::Object(d));
    }
    let _ = graph;
    let _ = config;
    m
}

fn openapi_discriminator(spec: &UnionSpec) -> Option<String> {
    let mut field: Option<String> = None;
    for branch in spec.branches.iter() {
        match &branch.discriminator {
            DiscriminatorRule::FieldEquals(disc) => {
                let _ = disc.literal.as_ref()?;
                match &field {
                    Some(prev) if prev != &disc.field_name => return None,
                    Some(_) => {}
                    None => field = Some(disc.field_name.clone()),
                }
            }
            _ => return None,
        }
    }
    field
}

fn attach_metadata(target: &mut Value, metadata: &MetadataEnvelope) {
    if metadata.is_empty() {
        return;
    }
    let Some(obj) = target.as_object_mut() else {
        return;
    };
    if let Some(doc) = &metadata.doc {
        obj.entry("description")
            .or_insert(Value::String(doc.clone()));
    }
    if !metadata.examples.is_empty() {
        obj.entry("examples").or_insert_with(|| {
            Value::Array(
                metadata
                    .examples
                    .iter()
                    .map(|e| Value::String(e.clone()))
                    .collect(),
            )
        });
    }
    if let Some(dep) = &metadata.deprecated {
        obj.entry("deprecated").or_insert(Value::Bool(true));
        obj.entry("x-golem-deprecation-note")
            .or_insert(Value::String(dep.clone()));
    }
}

/// Number of base64url-no-pad characters required to encode `n` raw bytes.
/// Matches the alphabet used by [`crate::schema::canonical::binary`] which
/// uses `base64::engine::general_purpose::URL_SAFE_NO_PAD`.
fn base64url_no_pad_len(n: u32) -> u64 {
    let n = n as u64;
    4 * (n / 3)
        + match n % 3 {
            0 => 0,
            1 => 2,
            2 => 3,
            _ => unreachable!(),
        }
}

/// Escape a string for use as a single JSON-Pointer token: `~` becomes `~0`
/// and `/` becomes `~1` per RFC 6901.
fn escape_pointer_token(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '~' => out.push_str("~0"),
            '/' => out.push_str("~1"),
            other => out.push(other),
        }
    }
    out
}

/// Escape a string for inclusion as a literal in a basic regex pattern.
fn regex_escape(s: &str) -> String {
    let specials: &[char] = &[
        '\\', '^', '$', '.', '|', '?', '*', '+', '(', ')', '[', ']', '{', '}',
    ];
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        if specials.contains(&ch) {
            out.push('\\');
        }
        out.push(ch);
    }
    out
}

fn obj<I: IntoIterator<Item = (&'static str, Value)>>(entries: I) -> Value {
    let mut map = Map::new();
    for (k, v) in entries {
        map.insert(k.to_string(), v);
    }
    Value::Object(map)
}

fn obj_inline<I: IntoIterator<Item = (&'static str, Value)>>(entries: I) -> Value {
    obj(entries)
}