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
// 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.

//! Runtime trait surface for converting Rust values to and from the
//! recursive schema model.
//!
//! The two core traits are:
//!
//! - [`IntoSchema`] — emits a self-contained [`SchemaGraph`] for a type and
//!   converts a Rust value of that type into a matching [`SchemaValue`].
//! - [`FromSchema`] — decodes a [`SchemaValue`] back into a Rust value.
//!
//! Hand-written impls for the standard primitive set live below. Derived
//! impls are generated by the `golem-schema-derive` crate, but the traits
//! themselves can be implemented by hand for any type that needs a custom
//! mapping.

use crate::schema::graph::{SchemaGraph, SchemaTypeDef, TypedSchemaValue};
use crate::schema::metadata::{MetadataEnvelope, TypeId};
use crate::schema::schema_type::{SchemaType, VariantCaseType};
use crate::schema::schema_value::{
    BinaryValuePayload, DurationValuePayload, SchemaValue, TextValuePayload, VariantValuePayload,
};
use crate::schema::validation::{SchemaError, validate_graph};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt::{self, Display, Formatter};

#[cfg(feature = "bigdecimal")]
mod bigdecimal;
#[cfg(feature = "bit_vec")]
mod bit_vec;
#[cfg(feature = "bytes")]
mod bytes;
#[cfg(feature = "chrono")]
mod chrono;
#[cfg(feature = "mac_address")]
mod mac_address;
#[cfg(feature = "nonempty_collections")]
mod nonempty_collections;
#[cfg(feature = "num_bigint")]
mod num_bigint;
#[cfg(feature = "rust_decimal")]
mod rust_decimal;
#[cfg(feature = "serde_json_types")]
mod serde_json_types;
#[cfg(feature = "url")]
mod url;

mod quantity;

pub use quantity::{Quantity, QuantityUnit};

// =====================================================================
// Trait surface
// =====================================================================

/// Convert a Rust type into a self-contained schema graph and a
/// [`SchemaValue`] tree.
///
/// The Rust-SDK default `type_id()` is derived from
/// [`core::any::type_name`] by replacing `::` with `.` so the identifier
/// matches the language-independent dotted-FQN form (`a.b.c.Xyz`, see
/// §4.20 of the value-type spec). Generic instantiations keep the angle
/// brackets and normalize their contents the same way:
/// `my_crate::Container<my_crate::user::Profile>` becomes
/// `my_crate.Container<my_crate.user.Profile>`.
///
/// `#[schema(named = "shared.foo")]` overrides the base name. For a
/// generic type the derive auto-suffixes the explicit name with the
/// resolved arguments so each instantiation gets its own definition.
pub trait IntoSchema {
    fn type_id() -> TypeId;
    fn register_in(builder: &mut SchemaBuilder) -> SchemaType;
    fn to_value(&self) -> SchemaValue;
}

/// Decode a [`SchemaValue`] back into a Rust value.
pub trait FromSchema: Sized {
    fn from_value(value: &SchemaValue) -> Result<Self, FromSchemaError>;
}

/// Build a self-contained graph for `T` and run well-formedness
/// validation on the result. Returns the first reported [`SchemaError`]
/// if the graph is malformed.
pub fn try_into_schema_graph<T: IntoSchema + ?Sized>() -> Result<SchemaGraph, SchemaError> {
    let mut builder = SchemaBuilder::new();
    let root = T::register_in(&mut builder);
    let graph = SchemaGraph {
        defs: builder.finish(),
        root,
    };
    match validate_graph(&graph) {
        Ok(()) => Ok(graph),
        Err(mut errors) => Err(errors.remove(0)),
    }
}

/// Build a [`TypedSchemaValue`] — a self-contained [`SchemaGraph`] paired with
/// the encoded [`SchemaValue`] tree — from a value whose type implements
/// [`IntoSchema`].
///
/// This produces a `TypedSchemaValue` (a `SchemaGraph` + `SchemaValue`) for a
/// Rust value carrying its own type. It is the bridge used
/// at boundaries that still need a value carrying its own type (e.g. the public
/// oplog / oplog-processor surface).
pub fn try_into_typed_schema_value<T: IntoSchema + ?Sized>(
    value: &T,
) -> Result<TypedSchemaValue, SchemaError> {
    let graph = try_into_schema_graph::<T>()?;
    Ok(TypedSchemaValue::new(graph, value.to_value()))
}

/// Ergonomic `value.into_typed_schema_value()?` form of
/// [`try_into_typed_schema_value`], mirroring the legacy
/// `IntoValueAndType::into_value_and_type` method shape.
pub trait IntoTypedSchemaValue: IntoSchema {
    #[allow(clippy::wrong_self_convention)]
    fn into_typed_schema_value(&self) -> Result<TypedSchemaValue, SchemaError>;
}

impl<T: IntoSchema + ?Sized> IntoTypedSchemaValue for T {
    fn into_typed_schema_value(&self) -> Result<TypedSchemaValue, SchemaError> {
        try_into_typed_schema_value(self)
    }
}

/// Errors produced by [`merge_agent_graphs`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MergeError {
    /// Two input graphs declare the same [`TypeId`] with divergent
    /// definition bodies. The agent's shared name pool requires every
    /// `TypeId` to resolve to exactly one body; same id with the same
    /// body is fine, same id with different bodies is rejected.
    ConflictingDefinitions {
        id: TypeId,
        first_name: Option<String>,
        second_name: Option<String>,
    },
}

impl Display for MergeError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            MergeError::ConflictingDefinitions {
                id,
                first_name,
                second_name,
            } => write!(
                f,
                "conflicting definitions for TypeId `{id}` while merging agent graphs \
                 (first name = {first_name:?}, second name = {second_name:?})"
            ),
        }
    }
}

impl std::error::Error for MergeError {}

/// Merge the named definitions from any number of per-root
/// [`SchemaGraph`]s into a single agent-level graph.
///
/// Intended for SDK / derive-crate codegen that produces one
/// [`crate::schema::agent::AgentTypeSchema`] per agent: each constructor
/// input, method input, and method output type is converted via
/// [`try_into_schema_graph`] or [`IntoSchema::register_in`], then all
/// resulting graphs are merged here to produce the agent's shared
/// [`crate::schema::agent::AgentTypeSchema::schema`] field (see §4.22).
///
/// Behaviour:
///
/// - The merged graph carries a sentinel root via
///   [`SchemaGraph::empty`]; only its `defs` are meaningful.
///   **Input graph roots are ignored.** Callers must retain the
///   original [`SchemaType`] roots themselves and install them into
///   the agent's constructor/method input/output slots.
/// - Definitions are deduplicated by [`TypeId`]: identical bodies under
///   the same id are merged into a single entry.
/// - Same id with **divergent** bodies fails with
///   [`MergeError::ConflictingDefinitions`]. Conflict detection uses
///   exact [`SchemaType`] equality (including metadata).
///   [`SchemaTypeDef::name`] is display-only and does not participate
///   in conflict detection; when duplicates have identical bodies, the
///   first-seen definition (including its `name`) is retained.
/// - The order of definitions in the result follows first-seen
///   insertion order across the input iterator.
///
/// Call this **once per carrier**: separately for the parent
/// [`crate::schema::agent::AgentTypeSchema::schema`] and separately for
/// each [`crate::schema::agent::AgentDependencySchema::schema`].
/// Dependencies own independent graphs (§4.22) — do not merge their
/// definitions into the parent agent's graph.
pub fn merge_agent_graphs(
    graphs: impl IntoIterator<Item = SchemaGraph>,
) -> Result<SchemaGraph, MergeError> {
    let mut merged: Vec<SchemaTypeDef> = Vec::new();

    for graph in graphs {
        for def in graph.defs {
            if let Some(existing) = merged.iter().find(|d| d.id == def.id) {
                if existing.body != def.body {
                    return Err(MergeError::ConflictingDefinitions {
                        id: def.id,
                        first_name: existing.name.clone(),
                        second_name: def.name,
                    });
                }
                // identical body — skip, first-seen wins
            } else {
                merged.push(def);
            }
        }
    }

    Ok(SchemaGraph {
        defs: merged,
        root: SchemaGraph::empty().root,
    })
}

// =====================================================================
// Builder
// =====================================================================

/// Mutable working set used while a graph is being built up.
///
/// Derived `register_in` bodies call [`SchemaBuilder::reserve`] before
/// recursing into inner fields so back-references through
/// [`SchemaType::Ref`] can close without infinite recursion. Once the
/// body is fully constructed they call [`SchemaBuilder::commit`] to
/// promote the reservation to a real definition.
#[derive(Default)]
pub struct SchemaBuilder {
    defs: Vec<SchemaTypeDef>,
    reserved: HashSet<TypeId>,
}

impl SchemaBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// `true` when `id` is already reserved or committed in this builder.
    pub fn is_registered(&self, id: &TypeId) -> bool {
        self.reserved.contains(id) || self.defs.iter().any(|d| &d.id == id)
    }

    /// Reserve a slot for `id` so recursive references close without
    /// infinite recursion. Must be followed by a matching
    /// [`Self::commit`] call once the body is built.
    pub fn reserve(&mut self, id: TypeId) {
        self.reserved.insert(id);
    }

    /// Promote a reservation to a real definition.
    ///
    /// `metadata` is attached to the body's [`MetadataEnvelope`] (every
    /// [`SchemaType`] node carries metadata directly; the def no longer has
    /// a separate slot for it).
    pub fn commit(
        &mut self,
        id: TypeId,
        name: Option<String>,
        metadata: MetadataEnvelope,
        body: SchemaType,
    ) {
        self.reserved.remove(&id);
        let body = body.with_metadata(metadata);
        // De-duplicate: if a definition with this id already exists
        // (because of a parallel registration in a sibling subtree) the
        // first one wins; later registrations are idempotent overwrites.
        if let Some(existing) = self.defs.iter_mut().find(|d| d.id == id) {
            *existing = SchemaTypeDef { id, name, body };
        } else {
            self.defs.push(SchemaTypeDef { id, name, body });
        }
    }

    /// Consume the builder and return the accumulated definitions.
    pub fn finish(self) -> Vec<SchemaTypeDef> {
        self.defs
    }

    /// Build a [`SchemaGraph`] using `root` as the entry point.
    pub fn into_graph(self, root: SchemaType) -> SchemaGraph {
        SchemaGraph {
            defs: self.finish(),
            root,
        }
    }
}

// =====================================================================
// TypeId helpers — used by generated code
// =====================================================================

/// Normalize a Rust path-form name into the dotted FQN used by [`TypeId`].
///
/// Every `::` becomes `.`; the inside of any `<…>` argument list is
/// normalized recursively by the same rule (because `::` only occurs in
/// path-like positions, a plain string replacement suffices). See §4.20.
pub fn normalize_type_path(raw: &str) -> String {
    raw.replace("::", ".")
}

/// Build a [`TypeId`] for a generic instantiation. `base` is the
/// already-normalized base name (e.g., `"my_crate.Container"`) and
/// `args` are the resolved argument [`TypeId`]s in declaration order.
///
/// `Container<u32>` → `my_crate.Container<u32>`.
/// `Container<u32, String>` → `my_crate.Container<u32, alloc.string.String>`.
pub fn type_id_with_args(base: &str, args: &[TypeId]) -> TypeId {
    if args.is_empty() {
        TypeId::new(base.to_string())
    } else {
        let mut s = String::with_capacity(base.len() + 16);
        s.push_str(base);
        s.push('<');
        for (i, a) in args.iter().enumerate() {
            if i > 0 {
                s.push_str(", ");
            }
            s.push_str(a.as_str());
        }
        s.push('>');
        TypeId::new(s)
    }
}

/// Default [`TypeId`] derivation from a `core::any::type_name::<Self>()`
/// output. Equivalent to `normalize_type_path` but exposed under a
/// generated-code-friendly name.
pub fn default_type_id_from(raw: &str) -> TypeId {
    TypeId::new(normalize_type_path(raw))
}

// =====================================================================
// Errors
// =====================================================================

/// Errors produced by [`FromSchema::from_value`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FromSchemaError {
    /// The expected value shape does not match what was provided.
    ShapeMismatch {
        expected: String,
        actual: String,
        context: String,
    },
    /// A variant or enum case index is out of range.
    OutOfRange {
        index: u32,
        len: u32,
        context: String,
    },
    /// A union tag was not matched by any branch.
    UnknownUnionTag(String),
    /// Free-form error message produced by generated decoders.
    Custom(String),
}

/// Backwards-compatible alias kept for codegen and consumers.
pub type DecodeError = FromSchemaError;

impl FromSchemaError {
    pub fn shape_mismatch(
        expected: impl Into<String>,
        actual: impl Into<String>,
        context: impl Into<String>,
    ) -> Self {
        Self::ShapeMismatch {
            expected: expected.into(),
            actual: actual.into(),
            context: context.into(),
        }
    }

    pub fn out_of_range(index: u32, len: u32, context: impl Into<String>) -> Self {
        Self::OutOfRange {
            index,
            len,
            context: context.into(),
        }
    }

    pub fn custom(msg: impl Into<String>) -> Self {
        Self::Custom(msg.into())
    }
}

impl Display for FromSchemaError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            FromSchemaError::ShapeMismatch {
                expected,
                actual,
                context,
            } => write!(
                f,
                "shape mismatch in {context}: expected {expected}, got {actual}"
            ),
            FromSchemaError::OutOfRange {
                index,
                len,
                context,
            } => write!(f, "index {index} out of range (len {len}) in {context}"),
            FromSchemaError::UnknownUnionTag(tag) => write!(f, "unknown union tag `{tag}`"),
            FromSchemaError::Custom(msg) => f.write_str(msg),
        }
    }
}

impl std::error::Error for FromSchemaError {}

/// Stringify the kind of a [`SchemaValue`] for error messages.
pub fn value_kind(v: &SchemaValue) -> &'static str {
    match v {
        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",
    }
}

// =====================================================================
// Rich-scalar codec helpers (used by codegen for #[schema(text(...))]
// etc.)
// =====================================================================

pub fn text_to_value(body: String, language: Option<String>) -> SchemaValue {
    SchemaValue::Text(TextValuePayload {
        text: body,
        language,
    })
}

pub fn text_from_value(v: &SchemaValue, context: &'static str) -> Result<String, FromSchemaError> {
    match v {
        SchemaValue::Text(p) => Ok(p.text.clone()),
        other => Err(FromSchemaError::shape_mismatch(
            "text",
            value_kind(other),
            context,
        )),
    }
}

pub fn binary_to_value(bytes: Vec<u8>, mime_type: Option<String>) -> SchemaValue {
    SchemaValue::Binary(BinaryValuePayload { bytes, mime_type })
}

pub fn binary_from_value(
    v: &SchemaValue,
    context: &'static str,
) -> Result<Vec<u8>, FromSchemaError> {
    match v {
        SchemaValue::Binary(p) => Ok(p.bytes.clone()),
        other => Err(FromSchemaError::shape_mismatch(
            "binary",
            value_kind(other),
            context,
        )),
    }
}

pub fn path_to_value(path: String) -> SchemaValue {
    SchemaValue::Path { path }
}

pub fn path_from_value(v: &SchemaValue, context: &'static str) -> Result<String, FromSchemaError> {
    match v {
        SchemaValue::Path { path } => Ok(path.clone()),
        other => Err(FromSchemaError::shape_mismatch(
            "path",
            value_kind(other),
            context,
        )),
    }
}

pub fn url_to_value(url: String) -> SchemaValue {
    SchemaValue::Url { url }
}

pub fn url_from_value(v: &SchemaValue, context: &'static str) -> Result<String, FromSchemaError> {
    match v {
        SchemaValue::Url { url } => Ok(url.clone()),
        other => Err(FromSchemaError::shape_mismatch(
            "url",
            value_kind(other),
            context,
        )),
    }
}

// =====================================================================
// Primitive impls
// =====================================================================

macro_rules! impl_primitive {
    ($ty:ty, $type_id:literal, $schema_ty:expr, $variant:ident) => {
        impl IntoSchema for $ty {
            fn type_id() -> TypeId {
                TypeId::new($type_id)
            }
            fn register_in(_b: &mut SchemaBuilder) -> SchemaType {
                $schema_ty
            }
            fn to_value(&self) -> SchemaValue {
                SchemaValue::$variant(*self)
            }
        }
        impl FromSchema for $ty {
            fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
                match v {
                    SchemaValue::$variant(x) => Ok(*x),
                    other => Err(FromSchemaError::shape_mismatch(
                        stringify!($variant),
                        value_kind(other),
                        stringify!($ty),
                    )),
                }
            }
        }
    };
}

impl_primitive!(bool, "bool", SchemaType::bool(), Bool);
impl_primitive!(i8, "i8", SchemaType::s8(), S8);
impl_primitive!(i16, "i16", SchemaType::s16(), S16);
impl_primitive!(i32, "i32", SchemaType::s32(), S32);
impl_primitive!(i64, "i64", SchemaType::s64(), S64);
impl_primitive!(u8, "u8", SchemaType::u8(), U8);
impl_primitive!(u16, "u16", SchemaType::u16(), U16);
impl_primitive!(u32, "u32", SchemaType::u32(), U32);
impl_primitive!(u64, "u64", SchemaType::u64(), U64);
impl_primitive!(f32, "f32", SchemaType::f32(), F32);
impl_primitive!(f64, "f64", SchemaType::f64(), F64);
impl_primitive!(char, "char", SchemaType::char(), Char);

impl IntoSchema for String {
    fn type_id() -> TypeId {
        TypeId::new("alloc.string.String")
    }
    fn register_in(_b: &mut SchemaBuilder) -> SchemaType {
        SchemaType::string()
    }
    fn to_value(&self) -> SchemaValue {
        SchemaValue::String(self.clone())
    }
}

impl FromSchema for String {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        match v {
            SchemaValue::String(s) => Ok(s.clone()),
            other => Err(FromSchemaError::shape_mismatch(
                "string",
                value_kind(other),
                "String",
            )),
        }
    }
}

/// `str` schema is identical to [`String`], so a `&str` produces the same
/// schema graph and value as an owned `String`. This makes string literals
/// usable directly as agent parameters without an explicit `.to_string()`.
impl IntoSchema for str {
    fn type_id() -> TypeId {
        TypeId::new("alloc.string.String")
    }
    fn register_in(_b: &mut SchemaBuilder) -> SchemaType {
        SchemaType::string()
    }
    fn to_value(&self) -> SchemaValue {
        SchemaValue::String(self.to_string())
    }
}

/// Forward [`IntoSchema`] through shared references so that `&T` values (most
/// commonly `&str` string literals) can be used wherever an `IntoSchema` value
/// is expected.
impl<T: IntoSchema + ?Sized> IntoSchema for &T {
    fn type_id() -> TypeId {
        T::type_id()
    }
    fn register_in(b: &mut SchemaBuilder) -> SchemaType {
        T::register_in(b)
    }
    fn to_value(&self) -> SchemaValue {
        (**self).to_value()
    }
}

// =====================================================================
// Option / Vec / Map / Result / Box / Rc / Arc / tuples
// =====================================================================

impl<T: IntoSchema + ?Sized> IntoSchema for Box<T> {
    fn type_id() -> TypeId {
        T::type_id()
    }
    fn register_in(b: &mut SchemaBuilder) -> SchemaType {
        T::register_in(b)
    }
    fn to_value(&self) -> SchemaValue {
        (**self).to_value()
    }
}

impl<T: FromSchema> FromSchema for Box<T> {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        Ok(Box::new(T::from_value(v)?))
    }
}

impl<T: IntoSchema + ?Sized> IntoSchema for std::rc::Rc<T> {
    fn type_id() -> TypeId {
        T::type_id()
    }
    fn register_in(b: &mut SchemaBuilder) -> SchemaType {
        T::register_in(b)
    }
    fn to_value(&self) -> SchemaValue {
        (**self).to_value()
    }
}

impl<T: FromSchema> FromSchema for std::rc::Rc<T> {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        Ok(std::rc::Rc::new(T::from_value(v)?))
    }
}

impl<T: IntoSchema + ?Sized> IntoSchema for std::sync::Arc<T> {
    fn type_id() -> TypeId {
        T::type_id()
    }
    fn register_in(b: &mut SchemaBuilder) -> SchemaType {
        T::register_in(b)
    }
    fn to_value(&self) -> SchemaValue {
        (**self).to_value()
    }
}

impl<T: FromSchema> FromSchema for std::sync::Arc<T> {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        Ok(std::sync::Arc::new(T::from_value(v)?))
    }
}

impl<T: IntoSchema> IntoSchema for Option<T> {
    fn type_id() -> TypeId {
        type_id_with_args("core.option.Option", &[T::type_id()])
    }
    fn register_in(b: &mut SchemaBuilder) -> SchemaType {
        SchemaType::option(T::register_in(b))
    }
    fn to_value(&self) -> SchemaValue {
        SchemaValue::Option {
            inner: self.as_ref().map(|x| Box::new(x.to_value())),
        }
    }
}

impl<T: FromSchema> FromSchema for Option<T> {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        match v {
            SchemaValue::Option { inner: Some(x) } => Ok(Some(T::from_value(x)?)),
            SchemaValue::Option { inner: None } => Ok(None),
            other => Err(FromSchemaError::shape_mismatch(
                "option",
                value_kind(other),
                "Option",
            )),
        }
    }
}

impl<T: IntoSchema> IntoSchema for Vec<T> {
    fn type_id() -> TypeId {
        type_id_with_args("alloc.vec.Vec", &[T::type_id()])
    }
    fn register_in(b: &mut SchemaBuilder) -> SchemaType {
        SchemaType::list(T::register_in(b))
    }
    fn to_value(&self) -> SchemaValue {
        SchemaValue::List {
            elements: self.iter().map(|x| x.to_value()).collect(),
        }
    }
}

impl<T: FromSchema> FromSchema for Vec<T> {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        match v {
            SchemaValue::List { elements } => elements.iter().map(T::from_value).collect(),
            other => Err(FromSchemaError::shape_mismatch(
                "list",
                value_kind(other),
                "Vec",
            )),
        }
    }
}

impl<T: IntoSchema> IntoSchema for HashSet<T> {
    fn type_id() -> TypeId {
        type_id_with_args("std.collections.HashSet", &[T::type_id()])
    }
    fn register_in(b: &mut SchemaBuilder) -> SchemaType {
        SchemaType::list(T::register_in(b))
    }
    fn to_value(&self) -> SchemaValue {
        SchemaValue::List {
            elements: self.iter().map(|x| x.to_value()).collect(),
        }
    }
}

impl<T: FromSchema + Eq + std::hash::Hash> FromSchema for HashSet<T> {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        match v {
            SchemaValue::List { elements } => elements.iter().map(T::from_value).collect(),
            other => Err(FromSchemaError::shape_mismatch(
                "list",
                value_kind(other),
                "HashSet",
            )),
        }
    }
}

impl<K: IntoSchema, V: IntoSchema> IntoSchema for HashMap<K, V> {
    fn type_id() -> TypeId {
        type_id_with_args("std.collections.HashMap", &[K::type_id(), V::type_id()])
    }
    fn register_in(b: &mut SchemaBuilder) -> SchemaType {
        SchemaType::map(K::register_in(b), V::register_in(b))
    }
    fn to_value(&self) -> SchemaValue {
        SchemaValue::Map {
            entries: self
                .iter()
                .map(|(k, v)| (k.to_value(), v.to_value()))
                .collect(),
        }
    }
}

impl<K, V> FromSchema for HashMap<K, V>
where
    K: FromSchema + std::hash::Hash + Eq,
    V: FromSchema,
{
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        match v {
            SchemaValue::Map { entries } => entries
                .iter()
                .map(|(k, v)| Ok((K::from_value(k)?, V::from_value(v)?)))
                .collect(),
            other => Err(FromSchemaError::shape_mismatch(
                "map",
                value_kind(other),
                "HashMap",
            )),
        }
    }
}

impl<K: IntoSchema, V: IntoSchema> IntoSchema for BTreeMap<K, V> {
    fn type_id() -> TypeId {
        type_id_with_args("alloc.collections.BTreeMap", &[K::type_id(), V::type_id()])
    }
    fn register_in(b: &mut SchemaBuilder) -> SchemaType {
        SchemaType::map(K::register_in(b), V::register_in(b))
    }
    fn to_value(&self) -> SchemaValue {
        SchemaValue::Map {
            entries: self
                .iter()
                .map(|(k, v)| (k.to_value(), v.to_value()))
                .collect(),
        }
    }
}

impl<K, V> FromSchema for BTreeMap<K, V>
where
    K: FromSchema + Ord,
    V: FromSchema,
{
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        match v {
            SchemaValue::Map { entries } => entries
                .iter()
                .map(|(k, v)| Ok((K::from_value(k)?, V::from_value(v)?)))
                .collect(),
            other => Err(FromSchemaError::shape_mismatch(
                "map",
                value_kind(other),
                "BTreeMap",
            )),
        }
    }
}

// =====================================================================
// Tuples (1..12)
// =====================================================================

macro_rules! impl_tuple {
    ( $name:literal => $( $idx:tt : $t:ident ),+ ) => {
        impl< $( $t : IntoSchema ),+ > IntoSchema for ( $( $t, )+ ) {
            fn type_id() -> TypeId {
                type_id_with_args($name, &[ $( <$t as IntoSchema>::type_id() ),+ ])
            }
            fn register_in(b: &mut SchemaBuilder) -> SchemaType {
                SchemaType::tuple(vec![ $( <$t as IntoSchema>::register_in(b) ),+ ])
            }
            fn to_value(&self) -> SchemaValue {
                SchemaValue::Tuple {
                    elements: vec![ $( IntoSchema::to_value(&self.$idx) ),+ ],
                }
            }
        }
        impl< $( $t : FromSchema ),+ > FromSchema for ( $( $t, )+ ) {
            fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
                match v {
                    SchemaValue::Tuple { elements } => {
                        let expected = [ $( stringify!($t) ),+ ].len();
                        if elements.len() != expected {
                            return Err(FromSchemaError::custom(format!(
                                "tuple length mismatch: expected {expected}, got {}",
                                elements.len()
                            )));
                        }
                        Ok(( $( <$t as FromSchema>::from_value(&elements[$idx])? , )+ ))
                    }
                    other => Err(FromSchemaError::shape_mismatch(
                        "tuple",
                        value_kind(other),
                        "tuple",
                    )),
                }
            }
        }
    };
}

impl_tuple!("core.tuple.Tuple1" => 0: T0);
impl_tuple!("core.tuple.Tuple2" => 0: T0, 1: T1);
impl_tuple!("core.tuple.Tuple3" => 0: T0, 1: T1, 2: T2);
impl_tuple!("core.tuple.Tuple4" => 0: T0, 1: T1, 2: T2, 3: T3);
impl_tuple!("core.tuple.Tuple5" => 0: T0, 1: T1, 2: T2, 3: T3, 4: T4);
impl_tuple!("core.tuple.Tuple6" => 0: T0, 1: T1, 2: T2, 3: T3, 4: T4, 5: T5);
impl_tuple!("core.tuple.Tuple7" => 0: T0, 1: T1, 2: T2, 3: T3, 4: T4, 5: T5, 6: T6);
impl_tuple!("core.tuple.Tuple8" => 0: T0, 1: T1, 2: T2, 3: T3, 4: T4, 5: T5, 6: T6, 7: T7);

impl IntoSchema for () {
    fn type_id() -> TypeId {
        TypeId::new("core.tuple.Unit")
    }
    fn register_in(_b: &mut SchemaBuilder) -> SchemaType {
        SchemaType::tuple(vec![])
    }
    fn to_value(&self) -> SchemaValue {
        SchemaValue::Tuple { elements: vec![] }
    }
}

impl FromSchema for () {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        match v {
            SchemaValue::Tuple { elements } if elements.is_empty() => Ok(()),
            other => Err(FromSchemaError::shape_mismatch(
                "unit tuple",
                value_kind(other),
                "()",
            )),
        }
    }
}

// =====================================================================
// Result<T, E>
// =====================================================================

/// `true` if `T` is the unit type `()`, whose ok/err branch carries no payload
/// (`result<_, _>`) and is represented by `None` in the schema and value model.
fn is_unit_type<T: IntoSchema>() -> bool {
    T::type_id() == <() as IntoSchema>::type_id()
}

impl<T: IntoSchema, E: IntoSchema> IntoSchema for Result<T, E> {
    fn type_id() -> TypeId {
        type_id_with_args("core.result.Result", &[T::type_id(), E::type_id()])
    }
    fn register_in(b: &mut SchemaBuilder) -> SchemaType {
        let ok = if is_unit_type::<T>() {
            None
        } else {
            Some(Box::new(T::register_in(b)))
        };
        let err = if is_unit_type::<E>() {
            None
        } else {
            Some(Box::new(E::register_in(b)))
        };
        SchemaType::result(crate::schema::schema_type::ResultSpec { ok, err })
    }
    fn to_value(&self) -> SchemaValue {
        use crate::schema::schema_value::ResultValuePayload;
        match self {
            Ok(x) => SchemaValue::Result(ResultValuePayload::Ok {
                value: if is_unit_type::<T>() {
                    None
                } else {
                    Some(Box::new(x.to_value()))
                },
            }),
            Err(e) => SchemaValue::Result(ResultValuePayload::Err {
                value: if is_unit_type::<E>() {
                    None
                } else {
                    Some(Box::new(e.to_value()))
                },
            }),
        }
    }
}

impl<T: FromSchema, E: FromSchema> FromSchema for Result<T, E> {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        use crate::schema::schema_value::ResultValuePayload;
        let unit = SchemaValue::Tuple { elements: vec![] };
        match v {
            SchemaValue::Result(ResultValuePayload::Ok { value }) => {
                let inner = value.as_deref().unwrap_or(&unit);
                Ok(Ok(T::from_value(inner)?))
            }
            SchemaValue::Result(ResultValuePayload::Err { value }) => {
                let inner = value.as_deref().unwrap_or(&unit);
                Ok(Err(E::from_value(inner)?))
            }
            other => Err(FromSchemaError::shape_mismatch(
                "result",
                value_kind(other),
                "Result",
            )),
        }
    }
}

// =====================================================================
// chrono::DateTime / std::time
// =====================================================================

impl IntoSchema for ::chrono::DateTime<::chrono::Utc> {
    fn type_id() -> TypeId {
        TypeId::new("chrono.DateTime<chrono.Utc>")
    }
    fn register_in(_b: &mut SchemaBuilder) -> SchemaType {
        SchemaType::datetime()
    }
    fn to_value(&self) -> SchemaValue {
        SchemaValue::Datetime { value: *self }
    }
}

impl FromSchema for ::chrono::DateTime<::chrono::Utc> {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        match v {
            SchemaValue::Datetime { value } => Ok(*value),
            other => Err(FromSchemaError::shape_mismatch(
                "datetime",
                value_kind(other),
                "DateTime<Utc>",
            )),
        }
    }
}

impl IntoSchema for std::time::Duration {
    fn type_id() -> TypeId {
        TypeId::new("core.time.Duration")
    }
    fn register_in(_b: &mut SchemaBuilder) -> SchemaType {
        SchemaType::duration()
    }
    fn to_value(&self) -> SchemaValue {
        let nanos = self.as_nanos();
        let clamped: i64 = if nanos > i64::MAX as u128 {
            i64::MAX
        } else {
            nanos as i64
        };
        SchemaValue::Duration(DurationValuePayload {
            nanoseconds: clamped,
        })
    }
}

impl FromSchema for std::time::Duration {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        match v {
            SchemaValue::Duration(p) => {
                if p.nanoseconds < 0 {
                    Err(FromSchemaError::custom(
                        "std::time::Duration cannot decode a negative duration",
                    ))
                } else {
                    Ok(std::time::Duration::from_nanos(p.nanoseconds as u64))
                }
            }
            other => Err(FromSchemaError::shape_mismatch(
                "duration",
                value_kind(other),
                "Duration",
            )),
        }
    }
}

// A `std::path::PathBuf` is modelled as the rich `Path` schema type. Only
// UTF-8 paths are supported because `SchemaValue::Path` is string-backed.
impl IntoSchema for std::path::PathBuf {
    fn type_id() -> TypeId {
        TypeId::new("std.path.PathBuf")
    }
    fn register_in(_b: &mut SchemaBuilder) -> SchemaType {
        use crate::schema::schema_type::{PathDirection, PathKind, PathSpec};
        SchemaType::path(PathSpec {
            direction: PathDirection::InOut,
            kind: PathKind::Any,
            allowed_mime_types: None,
            allowed_extensions: None,
        })
    }
    fn to_value(&self) -> SchemaValue {
        match self.to_str() {
            Some(s) => path_to_value(s.to_string()),
            None => path_to_value(self.to_string_lossy().into_owned()),
        }
    }
}

impl FromSchema for std::path::PathBuf {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        Ok(std::path::PathBuf::from(path_from_value(v, "PathBuf")?))
    }
}

impl IntoSchema for uuid::Uuid {
    fn type_id() -> TypeId {
        TypeId::new("uuid.Uuid")
    }
    fn register_in(_builder: &mut SchemaBuilder) -> SchemaType {
        SchemaType::uuid()
    }
    fn to_value(&self) -> SchemaValue {
        SchemaValue::Uuid(*self)
    }
}

impl FromSchema for uuid::Uuid {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        match v {
            SchemaValue::Uuid(value) => Ok(*value),
            other => Err(FromSchemaError::shape_mismatch(
                "uuid",
                value_kind(other),
                "Uuid",
            )),
        }
    }
}

// `usize` is modelled as a `u64` (the schema model has no platform-width
// integer; oplog payloads never need values above `u64::MAX`).
impl IntoSchema for usize {
    fn type_id() -> TypeId {
        TypeId::new("usize")
    }
    fn register_in(_b: &mut SchemaBuilder) -> SchemaType {
        SchemaType::u64()
    }
    fn to_value(&self) -> SchemaValue {
        SchemaValue::U64(*self as u64)
    }
}

impl FromSchema for usize {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        match v {
            SchemaValue::U64(x) => Ok(*x as usize),
            other => Err(FromSchemaError::shape_mismatch(
                "u64",
                value_kind(other),
                "usize",
            )),
        }
    }
}

// `std::ops::Bound<T>` is modelled as a 3-case variant
// `included(T) | excluded(T) | unbounded`.
impl<T: IntoSchema> IntoSchema for std::ops::Bound<T> {
    fn type_id() -> TypeId {
        type_id_with_args("core.ops.range.Bound", &[T::type_id()])
    }
    fn register_in(b: &mut SchemaBuilder) -> SchemaType {
        let inner = T::register_in(b);
        SchemaType::variant(vec![
            VariantCaseType {
                name: "included".to_string(),
                payload: Some(inner.clone()),
                metadata: MetadataEnvelope::default(),
            },
            VariantCaseType {
                name: "excluded".to_string(),
                payload: Some(inner),
                metadata: MetadataEnvelope::default(),
            },
            VariantCaseType {
                name: "unbounded".to_string(),
                payload: None,
                metadata: MetadataEnvelope::default(),
            },
        ])
    }
    fn to_value(&self) -> SchemaValue {
        match self {
            std::ops::Bound::Included(t) => SchemaValue::Variant(VariantValuePayload {
                case: 0,
                payload: Some(Box::new(t.to_value())),
            }),
            std::ops::Bound::Excluded(t) => SchemaValue::Variant(VariantValuePayload {
                case: 1,
                payload: Some(Box::new(t.to_value())),
            }),
            std::ops::Bound::Unbounded => SchemaValue::Variant(VariantValuePayload {
                case: 2,
                payload: None,
            }),
        }
    }
}

impl<T: FromSchema> FromSchema for std::ops::Bound<T> {
    fn from_value(v: &SchemaValue) -> Result<Self, FromSchemaError> {
        match v {
            SchemaValue::Variant(VariantValuePayload { case, payload }) => match case {
                0 => {
                    let p = payload.as_ref().ok_or_else(|| {
                        FromSchemaError::custom("Bound::Included requires a payload")
                    })?;
                    Ok(std::ops::Bound::Included(T::from_value(p)?))
                }
                1 => {
                    let p = payload.as_ref().ok_or_else(|| {
                        FromSchemaError::custom("Bound::Excluded requires a payload")
                    })?;
                    Ok(std::ops::Bound::Excluded(T::from_value(p)?))
                }
                2 => Ok(std::ops::Bound::Unbounded),
                other => Err(FromSchemaError::out_of_range(*other, 3, "Bound")),
            },
            other => Err(FromSchemaError::shape_mismatch(
                "variant",
                value_kind(other),
                "Bound",
            )),
        }
    }
}

// =====================================================================
// Tests
// =====================================================================

#[cfg(test)]
mod result_unit_tests {
    use super::*;
    use crate::schema::schema_value::ResultValuePayload;
    use test_r::test;

    #[test]
    fn ok_unit_encodes_as_none() {
        let v: Result<(), String> = Ok(());
        assert_eq!(
            v.to_value(),
            SchemaValue::Result(ResultValuePayload::Ok { value: None })
        );
    }

    #[test]
    fn err_unit_encodes_as_none() {
        let v: Result<u32, ()> = Err(());
        assert_eq!(
            v.to_value(),
            SchemaValue::Result(ResultValuePayload::Err { value: None })
        );
    }

    #[test]
    fn non_unit_branches_still_carry_payload() {
        let ok: Result<u32, String> = Ok(7);
        assert_eq!(
            ok.to_value(),
            SchemaValue::Result(ResultValuePayload::Ok {
                value: Some(Box::new(7u32.to_value()))
            })
        );
        let err: Result<u32, String> = Err("boom".to_string());
        assert_eq!(
            err.to_value(),
            SchemaValue::Result(ResultValuePayload::Err {
                value: Some(Box::new("boom".to_string().to_value()))
            })
        );
    }

    #[test]
    fn unit_branch_schema_is_none() {
        let mut b = SchemaBuilder::new();
        let ty = <Result<(), String> as IntoSchema>::register_in(&mut b);
        match ty {
            SchemaType::Result { spec, .. } => {
                assert!(spec.ok.is_none(), "ok branch should be None for unit");
                assert!(spec.err.is_some(), "err branch should carry string");
            }
            other => panic!("expected result schema, got {other:?}"),
        }
    }

    #[test]
    fn ok_unit_roundtrips() {
        let v: Result<(), String> = Ok(());
        let decoded = <Result<(), String> as FromSchema>::from_value(&v.to_value()).unwrap();
        assert_eq!(decoded, Ok(()));
    }

    #[test]
    fn err_unit_roundtrips() {
        let v: Result<u32, ()> = Err(());
        let decoded = <Result<u32, ()> as FromSchema>::from_value(&v.to_value()).unwrap();
        assert_eq!(decoded, Err(()));
    }
}

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

    fn def(id: &str, body: SchemaType) -> SchemaTypeDef {
        SchemaTypeDef {
            id: TypeId::new(id),
            name: None,
            body,
        }
    }

    #[test]
    fn empty_input_produces_empty_merged_graph() {
        let merged = merge_agent_graphs(std::iter::empty()).unwrap();
        assert!(merged.defs.is_empty());
        // root is the sentinel from SchemaGraph::empty()
        assert_eq!(merged.root, SchemaGraph::empty().root);
    }

    #[test]
    fn defs_are_deduplicated_by_type_id_when_bodies_match() {
        let g1 = SchemaGraph {
            defs: vec![def("a.Foo", SchemaType::s32())],
            root: SchemaType::ref_to(TypeId::new("a.Foo")),
        };
        let g2 = SchemaGraph {
            defs: vec![def("a.Foo", SchemaType::s32())],
            root: SchemaType::ref_to(TypeId::new("a.Foo")),
        };
        let merged = merge_agent_graphs([g1, g2]).unwrap();
        assert_eq!(merged.defs.len(), 1);
        assert_eq!(merged.defs[0].id, TypeId::new("a.Foo"));
    }

    #[test]
    fn defs_with_same_id_but_divergent_bodies_are_rejected() {
        let g1 = SchemaGraph {
            defs: vec![def("a.Foo", SchemaType::s32())],
            root: SchemaType::ref_to(TypeId::new("a.Foo")),
        };
        let g2 = SchemaGraph {
            defs: vec![def("a.Foo", SchemaType::string())],
            root: SchemaType::ref_to(TypeId::new("a.Foo")),
        };
        let err = merge_agent_graphs([g1, g2]).unwrap_err();
        assert!(matches!(
            err,
            MergeError::ConflictingDefinitions { ref id, .. } if id == &TypeId::new("a.Foo")
        ));
    }

    #[test]
    fn first_seen_insertion_order_is_preserved() {
        let g1 = SchemaGraph {
            defs: vec![
                def("a.Alpha", SchemaType::bool()),
                def("a.Beta", SchemaType::s64()),
            ],
            root: SchemaType::ref_to(TypeId::new("a.Alpha")),
        };
        let g2 = SchemaGraph {
            defs: vec![
                def("a.Gamma", SchemaType::u32()),
                def("a.Alpha", SchemaType::bool()), // dup, identical
            ],
            root: SchemaType::ref_to(TypeId::new("a.Gamma")),
        };
        let merged = merge_agent_graphs([g1, g2]).unwrap();
        let ids: Vec<_> = merged
            .defs
            .iter()
            .map(|d| d.id.as_str().to_string())
            .collect();
        assert_eq!(ids, vec!["a.Alpha", "a.Beta", "a.Gamma"]);
    }

    #[test]
    fn duplicate_id_with_same_body_keeps_first_seen_name() {
        // `SchemaTypeDef::name` is display-only and does not affect
        // dedup. When the same id appears twice with the same body but
        // different display names, the first-seen name is retained.
        let g1 = SchemaGraph {
            defs: vec![SchemaTypeDef {
                id: TypeId::new("a.Foo"),
                name: Some("FooFirst".into()),
                body: SchemaType::s32(),
            }],
            root: SchemaType::ref_to(TypeId::new("a.Foo")),
        };
        let g2 = SchemaGraph {
            defs: vec![SchemaTypeDef {
                id: TypeId::new("a.Foo"),
                name: Some("FooSecond".into()),
                body: SchemaType::s32(),
            }],
            root: SchemaType::ref_to(TypeId::new("a.Foo")),
        };
        let merged = merge_agent_graphs([g1, g2]).unwrap();
        assert_eq!(merged.defs.len(), 1);
        assert_eq!(merged.defs[0].name.as_deref(), Some("FooFirst"));
    }

    #[test]
    fn merged_graph_uses_sentinel_root() {
        // Even when input graphs have non-trivial roots (which would
        // happen in practice — each one is a per-type try_into_schema_graph
        // result), the merged carrier's root is always the sentinel,
        // because the agent layer is a multi-root carrier.
        let g = SchemaGraph::anonymous(SchemaType::s32());
        let merged = merge_agent_graphs([g]).unwrap();
        assert_eq!(merged.root, SchemaGraph::empty().root);
    }
}