tilo-resource 0.5.0

The Tilo resource layer: typed, hierarchical app resources.
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
//! JSON Schemas for the values actions carry, so a caller with no screen can
//! read what an operation takes instead of guessing it.
//!
//! [`JsonSchema`] describes a type's serde JSON form. `#[derive(JsonSchema)]`
//! implements it from the type's definition and its serde attributes, so the
//! schema is the type: a new variant or field is described the moment it is
//! written. [`Resource::action_schema`](crate::Resource::action_schema) is
//! what the generic [`APPLY`](crate::APPLY) operation publishes as its
//! parameter's schema, less what the named actions already publish.
//!
//! Schemas stay within the vocabulary `tilo-actions` validates and publishes
//! (`type`, `const`, `enum`, `properties`, `required`,
//! `additionalProperties: false`, `items`, `oneOf`, bounds, `description`):
//! everything is inline, with no references, so every surface that lists an
//! operation shows the whole shape and binding enforces it.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use tilo_sort::CompactSort as _;

use serde_json::{Map, Value, json};
use tilo_actions::{ActionParam, ParamType};

mod table;
pub use table::{Body, Bounds, Content, Field, Tagging, TypeSchema, Variant, build};

/// A type whose serde JSON form has a JSON Schema.
///
/// Derive it with `#[derive(JsonSchema)]` next to `Serialize` and
/// `Deserialize`. The derive follows the serde attributes that change the
/// JSON form (`rename`, `rename_all`, `tag`, `content`, `transparent`,
/// `default`, `skip`) and refuses the ones it cannot describe (`flatten`,
/// `untagged`, custom `with` functions), so a schema never silently differs
/// from what serde reads. Doc comments become descriptions.
pub trait JsonSchema {
    /// Whether serde reads an absent field of this type as its default, as it
    /// does for [`Option`]: such a field is not required.
    const OPTIONAL: bool = false;

    /// The schema of this type's JSON form.
    fn json_schema() -> Value;

    /// This type in the language-neutral vocabulary a surface publishes
    /// ([`FieldType`](crate::FieldType)), declaring the records and enums it
    /// names in `types`: what a verb's parameter of it is published as. The
    /// default describes no type: any value.
    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        let _ = types;
        crate::FieldType::Any
    }
}

macro_rules! primitive {
    ($($ty:ty => $schema:expr, $field:ident),* $(,)?) => {
        $(impl JsonSchema for $ty {
            fn json_schema() -> Value {
                $schema
            }
            fn field_type(_: &mut crate::TypeSet) -> crate::FieldType {
                crate::FieldType::$field
            }
        })*
    };
}

primitive! {
    bool => json!({"type": "boolean"}), Bool,
    String => json!({"type": "string"}), Text,
    str => json!({"type": "string"}), Text,
    char => json!({"type": "string", "minLength": 1, "maxLength": 1}), Text,
    f32 => json!({"type": "number"}), Float,
    f64 => json!({"type": "number"}), Float,
    i8 => json!({"type": "integer", "minimum": i8::MIN, "maximum": i8::MAX}), Int,
    i16 => json!({"type": "integer", "minimum": i16::MIN, "maximum": i16::MAX}), Int,
    i32 => json!({"type": "integer", "minimum": i32::MIN, "maximum": i32::MAX}), Int,
    i64 => json!({"type": "integer"}), Int,
    isize => json!({"type": "integer"}), Int,
    u8 => json!({"type": "integer", "minimum": 0, "maximum": u8::MAX}), Int,
    u16 => json!({"type": "integer", "minimum": 0, "maximum": u16::MAX}), Int,
    u32 => json!({"type": "integer", "minimum": 0, "maximum": u32::MAX}), Int,
    u64 => json!({"type": "integer", "minimum": 0}), Int,
    usize => json!({"type": "integer", "minimum": 0}), Int,
    serde_json::Value => json!({}), Any,
    crate::Id => json!({"type": "string"}), Text,
    crate::Counter => json!({"type": "integer"}), Int,
    uuid::Uuid => json!({"type": "string", "format": "uuid"}), Text,
}

/// A member as serde writes it: `{"person": "<id>"}`, `{"agent": "<id>"}` or
/// `{"bot": "<id>"}`.
impl JsonSchema for tilo_action_policy::MemberId {
    fn json_schema() -> Value {
        let kind = |name: &str| {
            json!({
                "type": "object",
                "properties": { name: {"type": "string"} },
                "required": [name],
                "additionalProperties": false,
            })
        };
        json!({"oneOf": [kind("person"), kind("agent"), kind("bot")]})
    }
}

/// Who made a change, as serde writes it: `{"member": {"person": "<id>"}}`
/// (or `agent` or `bot`), `{"automation": "<id>"}`, `{"app": "<id>"}` or
/// `{"visitor": "<key>"}`.
impl JsonSchema for tilo_actions::Actor {
    fn json_schema() -> Value {
        let kind = |name: &str, value: Value| {
            json!({
                "type": "object",
                "properties": { name: value },
                "required": [name],
                "additionalProperties": false,
            })
        };
        json!({"oneOf": [
            kind("member", <tilo_action_policy::MemberId as JsonSchema>::json_schema()),
            kind("automation", json!({"type": "string"})),
            kind("app", json!({"type": "string"})),
            kind("visitor", json!({"type": "string"})),
        ]})
    }
}

/// Where a message sent from a window goes, as serde writes it: one of
/// `new-agent`, `agent`, `person`, `conversation` or `feedback`.
impl JsonSchema for tilo_actions::RecipientKind {
    fn json_schema() -> Value {
        json!({
            "type": "string",
            "enum": ["new-agent", "agent", "person", "conversation", "feedback"],
        })
    }

    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        crate::surface::enum_type(
            types,
            "tilo_actions::RecipientKind",
            "RecipientKind",
            "Who a message sent from a window goes to.",
            &[
                ("new-agent", "New agent", &[]),
                ("agent", "Agent", &[]),
                ("person", "Person", &[]),
                ("conversation", "Conversation", &[]),
                ("feedback", "Feedback", &[]),
            ],
        )
    }
}

/// A recipient of a message sent from a window: who it goes to, and what the
/// person reads on its chip.
impl JsonSchema for tilo_actions::Recipient {
    fn json_schema() -> Value {
        json!({
            "type": "object",
            "additionalProperties": false,
            "properties": {
                "kind": <tilo_actions::RecipientKind as JsonSchema>::json_schema(),
                "id": {"type": "string"},
                "name": {"type": "string"},
                "detail": {"type": ["string", "null"]},
            },
            "required": ["kind", "name"],
        })
    }

    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        crate::surface::resource_of(
            types,
            "tilo_actions::Recipient",
            "Recipient",
            "One recipient of a message sent from a window.",
            &[
                (
                    "kind",
                    <tilo_actions::RecipientKind as JsonSchema>::field_type,
                ),
                ("id", |_| crate::FieldType::Text),
                ("name", |_| crate::FieldType::Text),
                ("detail", |_| {
                    crate::FieldType::Option(Box::new(crate::FieldType::Text))
                }),
            ],
        )
    }
}

impl<T: JsonSchema> JsonSchema for Option<T> {
    const OPTIONAL: bool = true;

    fn json_schema() -> Value {
        nullable(T::json_schema())
    }

    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        crate::FieldType::Option(Box::new(T::field_type(types)))
    }
}

impl<T: JsonSchema + ?Sized> JsonSchema for Box<T> {
    const OPTIONAL: bool = T::OPTIONAL;

    fn json_schema() -> Value {
        T::json_schema()
    }

    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        T::field_type(types)
    }
}

impl<T: JsonSchema + ?Sized> JsonSchema for std::sync::Arc<T> {
    const OPTIONAL: bool = T::OPTIONAL;

    fn json_schema() -> Value {
        T::json_schema()
    }

    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        T::field_type(types)
    }
}

impl<T: JsonSchema + ?Sized> JsonSchema for &T {
    const OPTIONAL: bool = T::OPTIONAL;

    fn json_schema() -> Value {
        T::json_schema()
    }

    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        T::field_type(types)
    }
}

impl<T: JsonSchema> JsonSchema for [T] {
    fn json_schema() -> Value {
        array(T::json_schema())
    }

    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        crate::FieldType::List(Box::new(T::field_type(types)))
    }
}

impl<T: JsonSchema> JsonSchema for Vec<T> {
    fn json_schema() -> Value {
        array(T::json_schema())
    }

    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        crate::FieldType::List(Box::new(T::field_type(types)))
    }
}

impl<T: JsonSchema, const N: usize> JsonSchema for [T; N] {
    fn json_schema() -> Value {
        let mut schema = array(T::json_schema());
        if let Some(object) = schema.as_object_mut() {
            object.insert("minItems".into(), N.into());
            object.insert("maxItems".into(), N.into());
        }
        schema
    }

    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        crate::FieldType::List(Box::new(T::field_type(types)))
    }
}

macro_rules! tuples {
    ($($len:literal => ($($name:ident),+)),* $(,)?) => {
        $(impl<$($name: JsonSchema),+> JsonSchema for ($($name,)+) {
            fn json_schema() -> Value {
                tuple($len)
            }
        })*
    };
}

tuples! {
    1 => (A),
    2 => (A, B),
    3 => (A, B, C),
    4 => (A, B, C, D),
}

// Serde reads a set from any array and keeps one of each value, so a
// repeated value is not an error the schema should assert.
impl<T: JsonSchema, S> JsonSchema for HashSet<T, S> {
    fn json_schema() -> Value {
        array(T::json_schema())
    }

    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        crate::FieldType::Set(Box::new(T::field_type(types)))
    }
}

impl<T: JsonSchema> JsonSchema for BTreeSet<T> {
    fn json_schema() -> Value {
        array(T::json_schema())
    }

    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        crate::FieldType::Set(Box::new(T::field_type(types)))
    }
}

// The published vocabulary has no schema for a map's values, so a map is
// described as an object and its values are checked by the action itself.
impl<K, V: JsonSchema, S> JsonSchema for HashMap<K, V, S> {
    fn json_schema() -> Value {
        json!({"type": "object"})
    }

    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        crate::FieldType::Map(Box::new(V::field_type(types)))
    }
}

impl<K, V: JsonSchema> JsonSchema for BTreeMap<K, V> {
    fn json_schema() -> Value {
        json!({"type": "object"})
    }

    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
        crate::FieldType::Map(Box::new(V::field_type(types)))
    }
}

/// An array of `items`.
pub fn array(items: Value) -> Value {
    let mut schema = Map::new();
    schema.insert("type".into(), "array".into());
    schema.insert("items".into(), items);
    Value::Object(schema)
}

/// An array of exactly `len` values. The published vocabulary has no
/// per-position item schema, so the positions are described in words.
pub fn tuple(len: usize) -> Value {
    json!({"type": "array", "minItems": len, "maxItems": len})
}

/// `schema`, or JSON `null`.
pub fn nullable(schema: Value) -> Value {
    let Value::Object(mut object) = schema else {
        return schema;
    };
    if object.is_empty() {
        return Value::Object(object);
    }
    let simple = !object.contains_key("oneOf")
        && !object.contains_key("const")
        && !object.contains_key("enum");
    match object.get_mut("type") {
        Some(Value::String(name)) if simple => {
            if name != "null" {
                let name = std::mem::take(name);
                object.insert("type".into(), json!([name, "null"]));
            }
            Value::Object(object)
        }
        Some(Value::Array(types)) if simple => {
            if !types.iter().any(|name| name == "null") {
                types.push("null".into());
            }
            Value::Object(object)
        }
        _ => {
            let description = object.remove("description");
            let mut wrapped = Map::new();
            wrapped.insert(
                "oneOf".into(),
                json!([{"type": "null"}, Value::Object(object)]),
            );
            if let Some(description) = description {
                wrapped.insert("description".into(), description);
            }
            Value::Object(wrapped)
        }
    }
}

/// `schema` with its bounds narrowed to `minimum` and `maximum`, those
/// given: `#[schema(range(min = 1, max = 100))]` on a field. A number's range
/// is its value's, a text's its length (`minLength`, `maxLength`) and a
/// list's its number of items. An optional field's bounds go on its value's
/// alternative.
pub fn range(schema: Value, minimum: Option<Value>, maximum: Option<Value>) -> Value {
    let Value::Object(mut object) = schema else {
        return schema;
    };
    if let Some(Value::Array(alternatives)) = object.get_mut("oneOf") {
        for alternative in alternatives.iter_mut() {
            if alternative.get("type") != Some(&json!("null")) {
                *alternative = range(alternative.take(), minimum.clone(), maximum.clone());
            }
        }
        return Value::Object(object);
    }
    // A text's range bounds its length, a list's its items, a number itself.
    let named = match object.get("type") {
        Some(Value::String(name)) => Some(name.as_str()),
        // A nullable value (`["string", "null"]`) is bounded as its value.
        Some(Value::Array(names)) => names
            .iter()
            .filter_map(Value::as_str)
            .find(|name| *name != "null"),
        _ => None,
    };
    let keys = match named {
        Some("string") => ("minLength", "maxLength"),
        Some("array") => ("minItems", "maxItems"),
        _ => ("minimum", "maximum"),
    };
    for (key, bound) in [(keys.0, minimum), (keys.1, maximum)] {
        if let Some(bound) = bound {
            object.insert(key.into(), bound);
        }
    }
    Value::Object(object)
}

/// `schema` narrowed to the texts `choices`: `#[model(choices = ..)]` on a
/// field. An optional field may still be absent (`null`).
pub fn choices(schema: Value, choices: &[&str]) -> Value {
    let Value::Object(mut object) = schema else {
        return schema;
    };
    if let Some(Value::Array(alternatives)) = object.get_mut("oneOf") {
        for alternative in alternatives.iter_mut() {
            if alternative.get("type") != Some(&json!("null")) {
                *alternative = self::choices(alternative.take(), choices);
            }
        }
        return Value::Object(object);
    }
    let mut values: Vec<Value> = choices.iter().map(|choice| json!(choice)).collect();
    if matches!(object.get("type"), Some(Value::Array(names)) if names.iter().any(|name| name == "null"))
    {
        values.push(Value::Null);
    }
    object.insert("enum".into(), Value::Array(values));
    Value::Object(object)
}

/// `schema` saying the value a field has until someone changes it:
/// `#[model(defaults)]` on a record.
pub fn with_default(schema: Value, default: Option<Value>) -> Value {
    match (schema, default) {
        (Value::Object(mut object), Some(default)) => {
            object.insert("default".into(), default);
            Value::Object(object)
        }
        (schema, _) => schema,
    }
}

/// `schema` with `description`, when there is one.
pub fn describe(schema: Value, description: &str) -> Value {
    if description.is_empty() {
        return schema;
    }
    match schema {
        Value::Object(mut object) => {
            object.insert("description".into(), description.into());
            Value::Object(object)
        }
        other => other,
    }
}

/// A closed object: `properties` as `(name, schema, required)`, nothing else.
pub fn object(properties: Vec<(&str, Value, bool)>) -> Value {
    let required: Vec<Value> = properties
        .iter()
        .filter(|(_, _, required)| *required)
        .map(|(name, _, _)| Value::from(*name))
        .collect();
    let properties: Map<String, Value> = properties
        .into_iter()
        .map(|(name, schema, _)| (name.to_owned(), schema))
        .collect();
    let mut schema = Map::new();
    schema.insert("type".into(), "object".into());
    if !required.is_empty() {
        schema.insert("required".into(), Value::Array(required));
    }
    schema.insert("properties".into(), Value::Object(properties));
    schema.insert("additionalProperties".into(), false.into());
    Value::Object(schema)
}

/// Exactly one of `alternatives`.
pub fn one_of(alternatives: Vec<Value>) -> Value {
    let mut schema = Map::new();
    schema.insert("oneOf".into(), Value::Array(alternatives));
    Value::Object(schema)
}

/// The string `value`.
pub fn constant(value: &str) -> Value {
    json!({"type": "string", "const": value})
}

/// One of `values`.
pub fn string_enum(values: &[&str]) -> Value {
    json!({"type": "string", "enum": values})
}

/// An externally tagged variant: `{ name: content }`.
pub fn external(name: &str, content: Value) -> Value {
    object(vec![(name, content, true)])
}

/// An adjacently tagged variant: `{ tag: name, content_key: content }`, or
/// only the tag for a unit variant.
pub fn adjacent(tag: &str, content_key: &str, name: &str, content: Option<Value>) -> Value {
    let mut properties = vec![(tag, constant(name), true)];
    if let Some(content) = content {
        properties.push((content_key, content, true));
    }
    object(properties)
}

/// An internally tagged variant: `content`'s fields with `tag` naming the
/// variant among them.
pub fn internal(tag: &str, name: &str, content: Value) -> Value {
    let Value::Object(mut schema) = content else {
        return object(vec![(tag, constant(name), true)]);
    };
    if let Some(Value::Object(properties)) = schema.get_mut("properties") {
        properties.insert(tag.to_owned(), constant(name));
    } else {
        schema.insert("type".into(), "object".into());
        schema.insert("properties".into(), json!({ tag: constant(name) }));
    }
    match schema.get_mut("required") {
        Some(Value::Array(required)) => required.insert(0, tag.into()),
        _ => {
            schema.insert("required".into(), json!([tag]));
        }
    }
    Value::Object(schema)
}

/// `schema` without its descriptions: the same shape, smaller, for a copy
/// nested where the documented original is published beside it.
pub fn undescribed(schema: &Value) -> Value {
    match schema {
        Value::Object(object) => Value::Object(
            object
                .iter()
                .filter(|(key, _)| key.as_str() != "description")
                .map(|(key, value)| {
                    let value = if key == "properties" {
                        match value {
                            Value::Object(properties) => Value::Object(
                                properties
                                    .iter()
                                    .map(|(name, child)| (name.clone(), undescribed(child)))
                                    .collect(),
                            ),
                            other => other.clone(),
                        }
                    } else {
                        undescribed(value)
                    };
                    (key.clone(), value)
                })
                .collect(),
        ),
        Value::Array(values) => Value::Array(values.iter().map(undescribed).collect()),
        other => other.clone(),
    }
}

/// The schema of one declared parameter's value as serde reads it: `null`
/// reads into an optional field.
pub(crate) fn param_schema(param: &ActionParam) -> Value {
    let base = match param.ty {
        ParamType::Text | ParamType::Secret | ParamType::Resource => json!({"type": "string"}),
        ParamType::DateTime => json!({"type": "string", "format": "date-time"}),
        ParamType::Integer => json!({"type": "integer"}),
        ParamType::Number => json!({"type": "number"}),
        ParamType::Boolean => json!({"type": "boolean"}),
        ParamType::Array => json!({"type": "array"}),
        // Serde reads whatever the field's type is, which a declaration
        // does not record.
        ParamType::Object => json!({}),
    };
    let mut schema = match (param.schema.as_deref(), base) {
        (Some(Value::Object(declared)), Value::Object(base)) => {
            let mut merged = declared.clone();
            for (key, value) in base {
                merged.entry(key).or_insert(value);
            }
            merged
        }
        (_, Value::Object(base)) => base,
        (_, _) => Map::new(),
    };
    if !param.choices.is_empty() && !schema.contains_key("enum") {
        let choices = param
            .choices
            .iter()
            .map(|choice| match param.ty {
                ParamType::Text | ParamType::Secret | ParamType::Resource | ParamType::DateTime => {
                    Value::String(choice.to_string())
                }
                _ => serde_json::from_str(choice).unwrap_or_else(|_| choice.to_string().into()),
            })
            .collect();
        schema.insert("enum".into(), Value::Array(choices));
    }
    let schema = describe(Value::Object(schema), &param.description);
    if param.nullable || !param.required {
        nullable(schema)
    } else {
        schema
    }
}

/// The arguments object of a declaration, as serde reads it.
///
/// This is the one projection of an action's parameters to a JSON Schema:
/// what its own typed call publishes, what a generic invoke takes, and what
/// every other caller reads to know the shape of a call (a model's function,
/// an MCP tool's `inputSchema`, a REST body).
pub fn args_schema(params: &[ActionParam]) -> Value {
    object(
        params
            .iter()
            .map(|param| (param.name.as_ref(), param_schema(param), param.required))
            .collect(),
    )
}

/// `schema` with every alternative that only restates a declared action
/// folded into one that names those actions, so `apply` does not publish a
/// second copy of what each named action already publishes. `declared` maps
/// an action id to its arguments object as serde reads it. An alternative
/// folds when it is `{"action": id, ..fields}` or `{"action": id, "args":
/// fields}` with exactly the declaration's fields; the folded alternative
/// is permissive, and [`declared_invocation`] checks the fields against
/// the declaration, so binding refuses nothing it refused before.
pub(crate) fn fold_declared(schema: &Value, declared: &BTreeMap<&str, Value>) -> Value {
    match schema {
        Value::Object(object) => {
            let mut out = Map::new();
            for (key, value) in object {
                let value = match (key.as_str(), value) {
                    ("oneOf", Value::Array(alternatives)) => {
                        Value::Array(fold_alternatives(alternatives, declared))
                    }
                    _ => fold_declared(value, declared),
                };
                out.insert(key.clone(), value);
            }
            Value::Object(out)
        }
        Value::Array(values) => Value::Array(
            values
                .iter()
                .map(|value| fold_declared(value, declared))
                .collect(),
        ),
        other => other.clone(),
    }
}

fn fold_alternatives(alternatives: &[Value], declared: &BTreeMap<&str, Value>) -> Vec<Value> {
    let (mut internal, mut adjacent, mut kept) = (Vec::new(), Vec::new(), Vec::new());
    for alternative in alternatives {
        match restated(alternative, declared) {
            Some((id, false)) => internal.push(id),
            Some((id, true)) => adjacent.push(id),
            None => kept.push(fold_declared(alternative, declared)),
        }
    }
    let names = |ids: &[&str]| json!({"type": "string", "enum": ids});
    if !internal.is_empty() {
        kept.push(json!({
            "type": "object",
            "required": ["action"],
            "properties": {"action": names(&internal)},
            "description": "A named action: `action` is its id, the other fields its parameters",
        }));
    }
    if !adjacent.is_empty() {
        kept.push(json!({
            "type": "object",
            "required": ["action", "args"],
            "properties": {"action": names(&adjacent), "args": {"type": "object"}},
            "additionalProperties": false,
            "description": "A named action: `action` is its id, `args` its parameters",
        }));
    }
    kept
}

/// The declared id an alternative restates, and whether its fields sit
/// under `args`.
fn restated<'a>(
    alternative: &Value,
    declared: &BTreeMap<&'a str, Value>,
) -> Option<(&'a str, bool)> {
    let properties = alternative.get("properties")?.as_object()?;
    let tag = properties.get("action")?.get("const")?.as_str()?;
    let (id, args) = declared.get_key_value(tag)?;
    let args = shape(args);
    if properties.len() == 2
        && let Some(nested) = properties.get("args")
        && shape(nested) == args
    {
        return Some((id, true));
    }
    let mut fields = undescribed(alternative);
    if let Some(Value::Object(properties)) = fields.get_mut("properties") {
        properties.remove("action");
    }
    if let Some(Value::Array(required)) = fields.get_mut("required") {
        required.retain(|name| name != "action");
        if required.is_empty() {
            fields.as_object_mut()?.remove("required");
        }
    }
    (shape(&fields) == args).then_some((id, false))
}

/// A schema as compared for sameness: no descriptions, `required` in order,
/// and no `null`: a declaration and serde may differ in whether a field
/// takes `null`, and serde still reads the folded value strictly.
fn shape(schema: &Value) -> Value {
    let mut schema = non_null(&undescribed(schema));
    sort_required(&mut schema);
    schema
}

fn non_null(schema: &Value) -> Value {
    let Value::Object(object) = schema else {
        return match schema {
            Value::Array(values) => Value::Array(values.iter().map(non_null).collect()),
            other => other.clone(),
        };
    };
    if let Some(Value::Array(alternatives)) = object.get("oneOf") {
        let rest: Vec<&Value> = alternatives
            .iter()
            .filter(|alternative| **alternative != json!({"type": "null"}))
            .collect();
        if object.len() == 1
            && let [only] = rest.as_slice()
        {
            return non_null(only);
        }
    }
    Value::Object(
        object
            .iter()
            .map(|(key, value)| {
                let value = match (key.as_str(), value) {
                    ("type", Value::Array(types)) => {
                        let types: Vec<&Value> =
                            types.iter().filter(|name| *name != "null").collect();
                        match types.as_slice() {
                            [only] => (*only).clone(),
                            _ => Value::Array(types.into_iter().cloned().collect()),
                        }
                    }
                    _ => non_null(value),
                };
                (key.clone(), value)
            })
            .collect(),
    )
}

fn sort_required(schema: &mut Value) {
    match schema {
        Value::Object(object) => {
            for (key, value) in object.iter_mut() {
                if key == "required"
                    && let Value::Array(names) = value
                {
                    names.compact_sort_by(|a, b| a.as_str().cmp(&b.as_str()));
                } else {
                    sort_required(value);
                }
            }
        }
        Value::Array(values) => values.iter_mut().for_each(sort_required),
        _ => {}
    }
}

/// The declared action a JSON action value names and its fields, in either
/// form [`fold_declared`] folds.
pub(crate) fn declared_invocation<'a>(
    value: &'a Value,
    declared: &[&str],
) -> Option<(&'a str, Map<String, Value>)> {
    let value = value.get("op").unwrap_or(value);
    let id = value.get("action")?.as_str()?;
    if !declared.contains(&id) {
        return None;
    }
    let fields = if let Some(Value::Object(args)) = value.get("args") {
        args.clone()
    } else {
        let mut fields = value.as_object()?.clone();
        fields.remove("action");
        fields
    };
    Some((id, fields))
}

/// One declared action as a member of a record's action schema.
fn declared_operation(id: &str, params: &[ActionParam], description: &str) -> Value {
    let variant = object(vec![
        ("action", constant(id), true),
        ("args", args_schema(params), true),
    ]);
    describe(variant, description)
}

/// The replayable action of a `#[resource]` record, as the generic
/// [`APPLY`](crate::APPLY) takes it: `{"op": {"action": id, "args": {..}},
/// "at": ms}`, one alternative per declaration.
pub fn resource_action_schema<R: crate::Resource>() -> Value {
    resource_action_schema_of(crate::vocabulary::<R>(), R::seed().is_some())
}

/// [`resource_action_schema`] of the resource `vocabulary`, which `seeds` its
/// first content or not.
fn resource_action_schema_of(vocabulary: &crate::Vocabulary, seeds: bool) -> Value {
    let mut operations: Vec<Value> = Vec::new();
    for decl in vocabulary.declarations().iter() {
        operations.push(declared_operation(
            decl.id,
            &decl.params,
            decl.description.as_deref().unwrap_or(&decl.label),
        ));
    }
    if vocabulary.edits {
        // Described in full by the field-edit action itself.
        operations.push(describe(
            object(vec![
                ("action", constant(crate::FIELD_EDIT), true),
                ("args", json!({"type": "object"}), true),
            ]),
            "A field edit, as the field-edit action takes it",
        ));
    }
    if seeds {
        operations.push(describe(
            object(vec![("action", constant("seed"), true)]),
            "Write the record's first content",
        ));
    }
    object(vec![
        ("op", one_of(operations), true),
        (
            "at",
            describe(
                json!({"type": "integer"}),
                "When the action was authored, in milliseconds since the Unix epoch: set by the host that applies it, which replaces a value given here. When content was first written elsewhere, the action that writes it takes that as its `origin`",
            ),
            false,
        ),
    ])
}

/// A vocabulary's schema in a line: each alternative of an enum by its name
/// and its arguments (`Name {a, b?}`; `?` marks an optional one), or by the
/// value it takes.
#[must_use]
pub fn summary(schema: &Value) -> String {
    let alternatives = schema
        .get("oneOf")
        .or_else(|| schema.get("anyOf"))
        .and_then(Value::as_array)
        .map_or_else(
            || vec![schema],
            |alternatives| alternatives.iter().collect(),
        );
    alternatives
        .into_iter()
        .filter_map(summarise_alternative)
        .collect::<Vec<_>>()
        .join("; ")
}

fn summarise_alternative(schema: &Value) -> Option<String> {
    if let Some(value) = schema.get("const") {
        return Some(
            value
                .as_str()
                .map_or_else(|| value.to_string(), str::to_owned),
        );
    }
    if let Some(values) = schema.get("enum").and_then(Value::as_array) {
        return Some(
            values
                .iter()
                .map(|value| {
                    value
                        .as_str()
                        .map_or_else(|| value.to_string(), str::to_owned)
                })
                .collect::<Vec<_>>()
                .join(" | "),
        );
    }
    let properties = schema.get("properties")?.as_object()?;
    // An externally tagged variant: one property, its name, holding its
    // arguments.
    if let [(name, inner)] = properties.iter().collect::<Vec<_>>().as_slice() {
        let arguments = arguments_of(inner);
        return Some(if arguments.is_empty() {
            (*name).clone()
        } else {
            format!("{name} {{{arguments}}}")
        });
    }
    Some(format!("{{{}}}", arguments_of(schema)))
}

fn arguments_of(schema: &Value) -> String {
    let required: Vec<&str> = schema
        .get("required")
        .and_then(Value::as_array)
        .map(|names| names.iter().filter_map(Value::as_str).collect())
        .unwrap_or_default();
    schema
        .get("properties")
        .and_then(Value::as_object)
        .map(|properties| {
            properties
                .keys()
                .map(|name| {
                    if required.contains(&name.as_str()) {
                        name.clone()
                    } else {
                        format!("{name}?")
                    }
                })
                .collect::<Vec<_>>()
                .join(", ")
        })
        .unwrap_or_default()
}

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

    tilo_test_env::scenario! {
        fn schemas_keep_nulls_tags_and_fields_named_description;

        phase optional_values_accept_null_and_keep_their_shape;
        {
            assert_eq!(
                <Option<String>>::json_schema(),
                json!({"type": ["string", "null"]})
            );
            let choice = nullable(one_of(vec![constant("a"), constant("b")]));
            assert!(tilo_actions::validate_json_schema(&Value::Null, &choice).is_ok());
            assert!(tilo_actions::validate_json_schema(&json!("a"), &choice).is_ok());
            assert!(tilo_actions::validate_json_schema(&json!("c"), &choice).is_err());
            const { assert!(<Option<u8>>::OPTIONAL) };
            const { assert!(!<Vec<u8>>::OPTIONAL) };
        }

        phase internal_tags_join_the_variant_fields;
        {
            let schema = internal(
                "kind",
                "Circle",
                object(vec![("radius", f64::json_schema(), true)]),
            );
            assert!(
                tilo_actions::validate_json_schema(&json!({"kind": "Circle", "radius": 1.5}), &schema)
                    .is_ok()
            );
            assert!(tilo_actions::validate_json_schema(&json!({"radius": 1.5}), &schema).is_err());
        }

        phase a_copy_without_descriptions_keeps_fields_named_description;
        {
            let schema = describe(
                object(vec![(
                    "description",
                    describe(String::json_schema(), "Text"),
                    true,
                )]),
                "A note",
            );
            let copy = undescribed(&schema);
            assert!(copy.get("description").is_none());
            assert_eq!(copy["properties"]["description"], json!({"type": "string"}));
        }
    }
}