Skip to main content

tilo_resource/
schema.rs

1//! JSON Schemas for the values actions carry, so a caller with no screen can
2//! read what an operation takes instead of guessing it.
3//!
4//! [`JsonSchema`] describes a type's serde JSON form. `#[derive(JsonSchema)]`
5//! implements it from the type's definition and its serde attributes, so the
6//! schema is the type: a new variant or field is described the moment it is
7//! written. [`Resource::action_schema`](crate::Resource::action_schema) is
8//! what the generic [`APPLY`](crate::APPLY) operation publishes as its
9//! parameter's schema, less what the named actions already publish.
10//!
11//! Schemas stay within the vocabulary `tilo-actions` validates and publishes
12//! (`type`, `const`, `enum`, `properties`, `required`,
13//! `additionalProperties: false`, `items`, `oneOf`, bounds, `description`):
14//! everything is inline, with no references, so every surface that lists an
15//! operation shows the whole shape and binding enforces it.
16
17use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
18use tilo_sort::CompactSort as _;
19
20use serde_json::{Map, Value, json};
21use tilo_actions::{ActionParam, ParamType};
22
23mod table;
24pub use table::{Body, Bounds, Content, Field, Tagging, TypeSchema, Variant, build};
25
26/// A type whose serde JSON form has a JSON Schema.
27///
28/// Derive it with `#[derive(JsonSchema)]` next to `Serialize` and
29/// `Deserialize`. The derive follows the serde attributes that change the
30/// JSON form (`rename`, `rename_all`, `tag`, `content`, `transparent`,
31/// `default`, `skip`) and refuses the ones it cannot describe (`flatten`,
32/// `untagged`, custom `with` functions), so a schema never silently differs
33/// from what serde reads. Doc comments become descriptions.
34pub trait JsonSchema {
35    /// Whether serde reads an absent field of this type as its default, as it
36    /// does for [`Option`]: such a field is not required.
37    const OPTIONAL: bool = false;
38
39    /// The schema of this type's JSON form.
40    fn json_schema() -> Value;
41
42    /// This type in the language-neutral vocabulary a surface publishes
43    /// ([`FieldType`](crate::FieldType)), declaring the records and enums it
44    /// names in `types`: what a verb's parameter of it is published as. The
45    /// default describes no type: any value.
46    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
47        let _ = types;
48        crate::FieldType::Any
49    }
50}
51
52macro_rules! primitive {
53    ($($ty:ty => $schema:expr, $field:ident),* $(,)?) => {
54        $(impl JsonSchema for $ty {
55            fn json_schema() -> Value {
56                $schema
57            }
58            fn field_type(_: &mut crate::TypeSet) -> crate::FieldType {
59                crate::FieldType::$field
60            }
61        })*
62    };
63}
64
65primitive! {
66    bool => json!({"type": "boolean"}), Bool,
67    String => json!({"type": "string"}), Text,
68    str => json!({"type": "string"}), Text,
69    char => json!({"type": "string", "minLength": 1, "maxLength": 1}), Text,
70    f32 => json!({"type": "number"}), Float,
71    f64 => json!({"type": "number"}), Float,
72    i8 => json!({"type": "integer", "minimum": i8::MIN, "maximum": i8::MAX}), Int,
73    i16 => json!({"type": "integer", "minimum": i16::MIN, "maximum": i16::MAX}), Int,
74    i32 => json!({"type": "integer", "minimum": i32::MIN, "maximum": i32::MAX}), Int,
75    i64 => json!({"type": "integer"}), Int,
76    isize => json!({"type": "integer"}), Int,
77    u8 => json!({"type": "integer", "minimum": 0, "maximum": u8::MAX}), Int,
78    u16 => json!({"type": "integer", "minimum": 0, "maximum": u16::MAX}), Int,
79    u32 => json!({"type": "integer", "minimum": 0, "maximum": u32::MAX}), Int,
80    u64 => json!({"type": "integer", "minimum": 0}), Int,
81    usize => json!({"type": "integer", "minimum": 0}), Int,
82    serde_json::Value => json!({}), Any,
83    crate::Id => json!({"type": "string"}), Text,
84    crate::Counter => json!({"type": "integer"}), Int,
85    uuid::Uuid => json!({"type": "string", "format": "uuid"}), Text,
86}
87
88/// A member as serde writes it: `{"person": "<id>"}`, `{"agent": "<id>"}` or
89/// `{"bot": "<id>"}`.
90impl JsonSchema for tilo_action_policy::MemberId {
91    fn json_schema() -> Value {
92        let kind = |name: &str| {
93            json!({
94                "type": "object",
95                "properties": { name: {"type": "string"} },
96                "required": [name],
97                "additionalProperties": false,
98            })
99        };
100        json!({"oneOf": [kind("person"), kind("agent"), kind("bot")]})
101    }
102}
103
104/// Who made a change, as serde writes it: `{"member": {"person": "<id>"}}`
105/// (or `agent` or `bot`), `{"automation": "<id>"}`, `{"app": "<id>"}` or
106/// `{"visitor": "<key>"}`.
107impl JsonSchema for tilo_actions::Actor {
108    fn json_schema() -> Value {
109        let kind = |name: &str, value: Value| {
110            json!({
111                "type": "object",
112                "properties": { name: value },
113                "required": [name],
114                "additionalProperties": false,
115            })
116        };
117        json!({"oneOf": [
118            kind("member", <tilo_action_policy::MemberId as JsonSchema>::json_schema()),
119            kind("automation", json!({"type": "string"})),
120            kind("app", json!({"type": "string"})),
121            kind("visitor", json!({"type": "string"})),
122        ]})
123    }
124}
125
126/// Where a message sent from a window goes, as serde writes it: one of
127/// `new-agent`, `agent`, `person`, `conversation` or `feedback`.
128impl JsonSchema for tilo_actions::RecipientKind {
129    fn json_schema() -> Value {
130        json!({
131            "type": "string",
132            "enum": ["new-agent", "agent", "person", "conversation", "feedback"],
133        })
134    }
135
136    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
137        crate::surface::enum_type(
138            types,
139            "tilo_actions::RecipientKind",
140            "RecipientKind",
141            "Who a message sent from a window goes to.",
142            &[
143                ("new-agent", "New agent", &[]),
144                ("agent", "Agent", &[]),
145                ("person", "Person", &[]),
146                ("conversation", "Conversation", &[]),
147                ("feedback", "Feedback", &[]),
148            ],
149        )
150    }
151}
152
153/// A recipient of a message sent from a window: who it goes to, and what the
154/// person reads on its chip.
155impl JsonSchema for tilo_actions::Recipient {
156    fn json_schema() -> Value {
157        json!({
158            "type": "object",
159            "additionalProperties": false,
160            "properties": {
161                "kind": <tilo_actions::RecipientKind as JsonSchema>::json_schema(),
162                "id": {"type": "string"},
163                "name": {"type": "string"},
164                "detail": {"type": ["string", "null"]},
165            },
166            "required": ["kind", "name"],
167        })
168    }
169
170    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
171        crate::surface::resource_of(
172            types,
173            "tilo_actions::Recipient",
174            "Recipient",
175            "One recipient of a message sent from a window.",
176            &[
177                (
178                    "kind",
179                    <tilo_actions::RecipientKind as JsonSchema>::field_type,
180                ),
181                ("id", |_| crate::FieldType::Text),
182                ("name", |_| crate::FieldType::Text),
183                ("detail", |_| {
184                    crate::FieldType::Option(Box::new(crate::FieldType::Text))
185                }),
186            ],
187        )
188    }
189}
190
191impl<T: JsonSchema> JsonSchema for Option<T> {
192    const OPTIONAL: bool = true;
193
194    fn json_schema() -> Value {
195        nullable(T::json_schema())
196    }
197
198    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
199        crate::FieldType::Option(Box::new(T::field_type(types)))
200    }
201}
202
203impl<T: JsonSchema + ?Sized> JsonSchema for Box<T> {
204    const OPTIONAL: bool = T::OPTIONAL;
205
206    fn json_schema() -> Value {
207        T::json_schema()
208    }
209
210    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
211        T::field_type(types)
212    }
213}
214
215impl<T: JsonSchema + ?Sized> JsonSchema for std::sync::Arc<T> {
216    const OPTIONAL: bool = T::OPTIONAL;
217
218    fn json_schema() -> Value {
219        T::json_schema()
220    }
221
222    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
223        T::field_type(types)
224    }
225}
226
227impl<T: JsonSchema + ?Sized> JsonSchema for &T {
228    const OPTIONAL: bool = T::OPTIONAL;
229
230    fn json_schema() -> Value {
231        T::json_schema()
232    }
233
234    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
235        T::field_type(types)
236    }
237}
238
239impl<T: JsonSchema> JsonSchema for [T] {
240    fn json_schema() -> Value {
241        array(T::json_schema())
242    }
243
244    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
245        crate::FieldType::List(Box::new(T::field_type(types)))
246    }
247}
248
249impl<T: JsonSchema> JsonSchema for Vec<T> {
250    fn json_schema() -> Value {
251        array(T::json_schema())
252    }
253
254    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
255        crate::FieldType::List(Box::new(T::field_type(types)))
256    }
257}
258
259impl<T: JsonSchema, const N: usize> JsonSchema for [T; N] {
260    fn json_schema() -> Value {
261        let mut schema = array(T::json_schema());
262        if let Some(object) = schema.as_object_mut() {
263            object.insert("minItems".into(), N.into());
264            object.insert("maxItems".into(), N.into());
265        }
266        schema
267    }
268
269    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
270        crate::FieldType::List(Box::new(T::field_type(types)))
271    }
272}
273
274macro_rules! tuples {
275    ($($len:literal => ($($name:ident),+)),* $(,)?) => {
276        $(impl<$($name: JsonSchema),+> JsonSchema for ($($name,)+) {
277            fn json_schema() -> Value {
278                tuple($len)
279            }
280        })*
281    };
282}
283
284tuples! {
285    1 => (A),
286    2 => (A, B),
287    3 => (A, B, C),
288    4 => (A, B, C, D),
289}
290
291// Serde reads a set from any array and keeps one of each value, so a
292// repeated value is not an error the schema should assert.
293impl<T: JsonSchema, S> JsonSchema for HashSet<T, S> {
294    fn json_schema() -> Value {
295        array(T::json_schema())
296    }
297
298    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
299        crate::FieldType::Set(Box::new(T::field_type(types)))
300    }
301}
302
303impl<T: JsonSchema> JsonSchema for BTreeSet<T> {
304    fn json_schema() -> Value {
305        array(T::json_schema())
306    }
307
308    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
309        crate::FieldType::Set(Box::new(T::field_type(types)))
310    }
311}
312
313// The published vocabulary has no schema for a map's values, so a map is
314// described as an object and its values are checked by the action itself.
315impl<K, V: JsonSchema, S> JsonSchema for HashMap<K, V, S> {
316    fn json_schema() -> Value {
317        json!({"type": "object"})
318    }
319
320    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
321        crate::FieldType::Map(Box::new(V::field_type(types)))
322    }
323}
324
325impl<K, V: JsonSchema> JsonSchema for BTreeMap<K, V> {
326    fn json_schema() -> Value {
327        json!({"type": "object"})
328    }
329
330    fn field_type(types: &mut crate::TypeSet) -> crate::FieldType {
331        crate::FieldType::Map(Box::new(V::field_type(types)))
332    }
333}
334
335/// An array of `items`.
336pub fn array(items: Value) -> Value {
337    let mut schema = Map::new();
338    schema.insert("type".into(), "array".into());
339    schema.insert("items".into(), items);
340    Value::Object(schema)
341}
342
343/// An array of exactly `len` values. The published vocabulary has no
344/// per-position item schema, so the positions are described in words.
345pub fn tuple(len: usize) -> Value {
346    json!({"type": "array", "minItems": len, "maxItems": len})
347}
348
349/// `schema`, or JSON `null`.
350pub fn nullable(schema: Value) -> Value {
351    let Value::Object(mut object) = schema else {
352        return schema;
353    };
354    if object.is_empty() {
355        return Value::Object(object);
356    }
357    let simple = !object.contains_key("oneOf")
358        && !object.contains_key("const")
359        && !object.contains_key("enum");
360    match object.get_mut("type") {
361        Some(Value::String(name)) if simple => {
362            if name != "null" {
363                let name = std::mem::take(name);
364                object.insert("type".into(), json!([name, "null"]));
365            }
366            Value::Object(object)
367        }
368        Some(Value::Array(types)) if simple => {
369            if !types.iter().any(|name| name == "null") {
370                types.push("null".into());
371            }
372            Value::Object(object)
373        }
374        _ => {
375            let description = object.remove("description");
376            let mut wrapped = Map::new();
377            wrapped.insert(
378                "oneOf".into(),
379                json!([{"type": "null"}, Value::Object(object)]),
380            );
381            if let Some(description) = description {
382                wrapped.insert("description".into(), description);
383            }
384            Value::Object(wrapped)
385        }
386    }
387}
388
389/// `schema` with its bounds narrowed to `minimum` and `maximum`, those
390/// given: `#[schema(range(min = 1, max = 100))]` on a field. A number's range
391/// is its value's, a text's its length (`minLength`, `maxLength`) and a
392/// list's its number of items. An optional field's bounds go on its value's
393/// alternative.
394pub fn range(schema: Value, minimum: Option<Value>, maximum: Option<Value>) -> Value {
395    let Value::Object(mut object) = schema else {
396        return schema;
397    };
398    if let Some(Value::Array(alternatives)) = object.get_mut("oneOf") {
399        for alternative in alternatives.iter_mut() {
400            if alternative.get("type") != Some(&json!("null")) {
401                *alternative = range(alternative.take(), minimum.clone(), maximum.clone());
402            }
403        }
404        return Value::Object(object);
405    }
406    // A text's range bounds its length, a list's its items, a number itself.
407    let named = match object.get("type") {
408        Some(Value::String(name)) => Some(name.as_str()),
409        // A nullable value (`["string", "null"]`) is bounded as its value.
410        Some(Value::Array(names)) => names
411            .iter()
412            .filter_map(Value::as_str)
413            .find(|name| *name != "null"),
414        _ => None,
415    };
416    let keys = match named {
417        Some("string") => ("minLength", "maxLength"),
418        Some("array") => ("minItems", "maxItems"),
419        _ => ("minimum", "maximum"),
420    };
421    for (key, bound) in [(keys.0, minimum), (keys.1, maximum)] {
422        if let Some(bound) = bound {
423            object.insert(key.into(), bound);
424        }
425    }
426    Value::Object(object)
427}
428
429/// `schema` narrowed to the texts `choices`: `#[model(choices = ..)]` on a
430/// field. An optional field may still be absent (`null`).
431pub fn choices(schema: Value, choices: &[&str]) -> Value {
432    let Value::Object(mut object) = schema else {
433        return schema;
434    };
435    if let Some(Value::Array(alternatives)) = object.get_mut("oneOf") {
436        for alternative in alternatives.iter_mut() {
437            if alternative.get("type") != Some(&json!("null")) {
438                *alternative = self::choices(alternative.take(), choices);
439            }
440        }
441        return Value::Object(object);
442    }
443    let mut values: Vec<Value> = choices.iter().map(|choice| json!(choice)).collect();
444    if matches!(object.get("type"), Some(Value::Array(names)) if names.iter().any(|name| name == "null"))
445    {
446        values.push(Value::Null);
447    }
448    object.insert("enum".into(), Value::Array(values));
449    Value::Object(object)
450}
451
452/// `schema` saying the value a field has until someone changes it:
453/// `#[model(defaults)]` on a record.
454pub fn with_default(schema: Value, default: Option<Value>) -> Value {
455    match (schema, default) {
456        (Value::Object(mut object), Some(default)) => {
457            object.insert("default".into(), default);
458            Value::Object(object)
459        }
460        (schema, _) => schema,
461    }
462}
463
464/// `schema` with `description`, when there is one.
465pub fn describe(schema: Value, description: &str) -> Value {
466    if description.is_empty() {
467        return schema;
468    }
469    match schema {
470        Value::Object(mut object) => {
471            object.insert("description".into(), description.into());
472            Value::Object(object)
473        }
474        other => other,
475    }
476}
477
478/// A closed object: `properties` as `(name, schema, required)`, nothing else.
479pub fn object(properties: Vec<(&str, Value, bool)>) -> Value {
480    let required: Vec<Value> = properties
481        .iter()
482        .filter(|(_, _, required)| *required)
483        .map(|(name, _, _)| Value::from(*name))
484        .collect();
485    let properties: Map<String, Value> = properties
486        .into_iter()
487        .map(|(name, schema, _)| (name.to_owned(), schema))
488        .collect();
489    let mut schema = Map::new();
490    schema.insert("type".into(), "object".into());
491    if !required.is_empty() {
492        schema.insert("required".into(), Value::Array(required));
493    }
494    schema.insert("properties".into(), Value::Object(properties));
495    schema.insert("additionalProperties".into(), false.into());
496    Value::Object(schema)
497}
498
499/// Exactly one of `alternatives`.
500pub fn one_of(alternatives: Vec<Value>) -> Value {
501    let mut schema = Map::new();
502    schema.insert("oneOf".into(), Value::Array(alternatives));
503    Value::Object(schema)
504}
505
506/// The string `value`.
507pub fn constant(value: &str) -> Value {
508    json!({"type": "string", "const": value})
509}
510
511/// One of `values`.
512pub fn string_enum(values: &[&str]) -> Value {
513    json!({"type": "string", "enum": values})
514}
515
516/// An externally tagged variant: `{ name: content }`.
517pub fn external(name: &str, content: Value) -> Value {
518    object(vec![(name, content, true)])
519}
520
521/// An adjacently tagged variant: `{ tag: name, content_key: content }`, or
522/// only the tag for a unit variant.
523pub fn adjacent(tag: &str, content_key: &str, name: &str, content: Option<Value>) -> Value {
524    let mut properties = vec![(tag, constant(name), true)];
525    if let Some(content) = content {
526        properties.push((content_key, content, true));
527    }
528    object(properties)
529}
530
531/// An internally tagged variant: `content`'s fields with `tag` naming the
532/// variant among them.
533pub fn internal(tag: &str, name: &str, content: Value) -> Value {
534    let Value::Object(mut schema) = content else {
535        return object(vec![(tag, constant(name), true)]);
536    };
537    if let Some(Value::Object(properties)) = schema.get_mut("properties") {
538        properties.insert(tag.to_owned(), constant(name));
539    } else {
540        schema.insert("type".into(), "object".into());
541        schema.insert("properties".into(), json!({ tag: constant(name) }));
542    }
543    match schema.get_mut("required") {
544        Some(Value::Array(required)) => required.insert(0, tag.into()),
545        _ => {
546            schema.insert("required".into(), json!([tag]));
547        }
548    }
549    Value::Object(schema)
550}
551
552/// `schema` without its descriptions: the same shape, smaller, for a copy
553/// nested where the documented original is published beside it.
554pub fn undescribed(schema: &Value) -> Value {
555    match schema {
556        Value::Object(object) => Value::Object(
557            object
558                .iter()
559                .filter(|(key, _)| key.as_str() != "description")
560                .map(|(key, value)| {
561                    let value = if key == "properties" {
562                        match value {
563                            Value::Object(properties) => Value::Object(
564                                properties
565                                    .iter()
566                                    .map(|(name, child)| (name.clone(), undescribed(child)))
567                                    .collect(),
568                            ),
569                            other => other.clone(),
570                        }
571                    } else {
572                        undescribed(value)
573                    };
574                    (key.clone(), value)
575                })
576                .collect(),
577        ),
578        Value::Array(values) => Value::Array(values.iter().map(undescribed).collect()),
579        other => other.clone(),
580    }
581}
582
583/// The schema of one declared parameter's value as serde reads it: `null`
584/// reads into an optional field.
585pub(crate) fn param_schema(param: &ActionParam) -> Value {
586    let base = match param.ty {
587        ParamType::Text | ParamType::Secret | ParamType::Resource => json!({"type": "string"}),
588        ParamType::DateTime => json!({"type": "string", "format": "date-time"}),
589        ParamType::Integer => json!({"type": "integer"}),
590        ParamType::Number => json!({"type": "number"}),
591        ParamType::Boolean => json!({"type": "boolean"}),
592        ParamType::Array => json!({"type": "array"}),
593        // Serde reads whatever the field's type is, which a declaration
594        // does not record.
595        ParamType::Object => json!({}),
596    };
597    let mut schema = match (param.schema.as_deref(), base) {
598        (Some(Value::Object(declared)), Value::Object(base)) => {
599            let mut merged = declared.clone();
600            for (key, value) in base {
601                merged.entry(key).or_insert(value);
602            }
603            merged
604        }
605        (_, Value::Object(base)) => base,
606        (_, _) => Map::new(),
607    };
608    if !param.choices.is_empty() && !schema.contains_key("enum") {
609        let choices = param
610            .choices
611            .iter()
612            .map(|choice| match param.ty {
613                ParamType::Text | ParamType::Secret | ParamType::Resource | ParamType::DateTime => {
614                    Value::String(choice.to_string())
615                }
616                _ => serde_json::from_str(choice).unwrap_or_else(|_| choice.to_string().into()),
617            })
618            .collect();
619        schema.insert("enum".into(), Value::Array(choices));
620    }
621    let schema = describe(Value::Object(schema), &param.description);
622    if param.nullable || !param.required {
623        nullable(schema)
624    } else {
625        schema
626    }
627}
628
629/// The arguments object of a declaration, as serde reads it.
630///
631/// This is the one projection of an action's parameters to a JSON Schema:
632/// what its own typed call publishes, what a generic invoke takes, and what
633/// every other caller reads to know the shape of a call (a model's function,
634/// an MCP tool's `inputSchema`, a REST body).
635pub fn args_schema(params: &[ActionParam]) -> Value {
636    object(
637        params
638            .iter()
639            .map(|param| (param.name.as_ref(), param_schema(param), param.required))
640            .collect(),
641    )
642}
643
644/// `schema` with every alternative that only restates a declared action
645/// folded into one that names those actions, so `apply` does not publish a
646/// second copy of what each named action already publishes. `declared` maps
647/// an action id to its arguments object as serde reads it. An alternative
648/// folds when it is `{"action": id, ..fields}` or `{"action": id, "args":
649/// fields}` with exactly the declaration's fields; the folded alternative
650/// is permissive, and [`declared_invocation`] checks the fields against
651/// the declaration, so binding refuses nothing it refused before.
652pub(crate) fn fold_declared(schema: &Value, declared: &BTreeMap<&str, Value>) -> Value {
653    match schema {
654        Value::Object(object) => {
655            let mut out = Map::new();
656            for (key, value) in object {
657                let value = match (key.as_str(), value) {
658                    ("oneOf", Value::Array(alternatives)) => {
659                        Value::Array(fold_alternatives(alternatives, declared))
660                    }
661                    _ => fold_declared(value, declared),
662                };
663                out.insert(key.clone(), value);
664            }
665            Value::Object(out)
666        }
667        Value::Array(values) => Value::Array(
668            values
669                .iter()
670                .map(|value| fold_declared(value, declared))
671                .collect(),
672        ),
673        other => other.clone(),
674    }
675}
676
677fn fold_alternatives(alternatives: &[Value], declared: &BTreeMap<&str, Value>) -> Vec<Value> {
678    let (mut internal, mut adjacent, mut kept) = (Vec::new(), Vec::new(), Vec::new());
679    for alternative in alternatives {
680        match restated(alternative, declared) {
681            Some((id, false)) => internal.push(id),
682            Some((id, true)) => adjacent.push(id),
683            None => kept.push(fold_declared(alternative, declared)),
684        }
685    }
686    let names = |ids: &[&str]| json!({"type": "string", "enum": ids});
687    if !internal.is_empty() {
688        kept.push(json!({
689            "type": "object",
690            "required": ["action"],
691            "properties": {"action": names(&internal)},
692            "description": "A named action: `action` is its id, the other fields its parameters",
693        }));
694    }
695    if !adjacent.is_empty() {
696        kept.push(json!({
697            "type": "object",
698            "required": ["action", "args"],
699            "properties": {"action": names(&adjacent), "args": {"type": "object"}},
700            "additionalProperties": false,
701            "description": "A named action: `action` is its id, `args` its parameters",
702        }));
703    }
704    kept
705}
706
707/// The declared id an alternative restates, and whether its fields sit
708/// under `args`.
709fn restated<'a>(
710    alternative: &Value,
711    declared: &BTreeMap<&'a str, Value>,
712) -> Option<(&'a str, bool)> {
713    let properties = alternative.get("properties")?.as_object()?;
714    let tag = properties.get("action")?.get("const")?.as_str()?;
715    let (id, args) = declared.get_key_value(tag)?;
716    let args = shape(args);
717    if properties.len() == 2
718        && let Some(nested) = properties.get("args")
719        && shape(nested) == args
720    {
721        return Some((id, true));
722    }
723    let mut fields = undescribed(alternative);
724    if let Some(Value::Object(properties)) = fields.get_mut("properties") {
725        properties.remove("action");
726    }
727    if let Some(Value::Array(required)) = fields.get_mut("required") {
728        required.retain(|name| name != "action");
729        if required.is_empty() {
730            fields.as_object_mut()?.remove("required");
731        }
732    }
733    (shape(&fields) == args).then_some((id, false))
734}
735
736/// A schema as compared for sameness: no descriptions, `required` in order,
737/// and no `null`: a declaration and serde may differ in whether a field
738/// takes `null`, and serde still reads the folded value strictly.
739fn shape(schema: &Value) -> Value {
740    let mut schema = non_null(&undescribed(schema));
741    sort_required(&mut schema);
742    schema
743}
744
745fn non_null(schema: &Value) -> Value {
746    let Value::Object(object) = schema else {
747        return match schema {
748            Value::Array(values) => Value::Array(values.iter().map(non_null).collect()),
749            other => other.clone(),
750        };
751    };
752    if let Some(Value::Array(alternatives)) = object.get("oneOf") {
753        let rest: Vec<&Value> = alternatives
754            .iter()
755            .filter(|alternative| **alternative != json!({"type": "null"}))
756            .collect();
757        if object.len() == 1
758            && let [only] = rest.as_slice()
759        {
760            return non_null(only);
761        }
762    }
763    Value::Object(
764        object
765            .iter()
766            .map(|(key, value)| {
767                let value = match (key.as_str(), value) {
768                    ("type", Value::Array(types)) => {
769                        let types: Vec<&Value> =
770                            types.iter().filter(|name| *name != "null").collect();
771                        match types.as_slice() {
772                            [only] => (*only).clone(),
773                            _ => Value::Array(types.into_iter().cloned().collect()),
774                        }
775                    }
776                    _ => non_null(value),
777                };
778                (key.clone(), value)
779            })
780            .collect(),
781    )
782}
783
784fn sort_required(schema: &mut Value) {
785    match schema {
786        Value::Object(object) => {
787            for (key, value) in object.iter_mut() {
788                if key == "required"
789                    && let Value::Array(names) = value
790                {
791                    names.compact_sort_by(|a, b| a.as_str().cmp(&b.as_str()));
792                } else {
793                    sort_required(value);
794                }
795            }
796        }
797        Value::Array(values) => values.iter_mut().for_each(sort_required),
798        _ => {}
799    }
800}
801
802/// The declared action a JSON action value names and its fields, in either
803/// form [`fold_declared`] folds.
804pub(crate) fn declared_invocation<'a>(
805    value: &'a Value,
806    declared: &[&str],
807) -> Option<(&'a str, Map<String, Value>)> {
808    let value = value.get("op").unwrap_or(value);
809    let id = value.get("action")?.as_str()?;
810    if !declared.contains(&id) {
811        return None;
812    }
813    let fields = if let Some(Value::Object(args)) = value.get("args") {
814        args.clone()
815    } else {
816        let mut fields = value.as_object()?.clone();
817        fields.remove("action");
818        fields
819    };
820    Some((id, fields))
821}
822
823/// One declared action as a member of a record's action schema.
824fn declared_operation(id: &str, params: &[ActionParam], description: &str) -> Value {
825    let variant = object(vec![
826        ("action", constant(id), true),
827        ("args", args_schema(params), true),
828    ]);
829    describe(variant, description)
830}
831
832/// The replayable action of a `#[resource]` record, as the generic
833/// [`APPLY`](crate::APPLY) takes it: `{"op": {"action": id, "args": {..}},
834/// "at": ms}`, one alternative per declaration.
835pub fn resource_action_schema<R: crate::Resource>() -> Value {
836    resource_action_schema_of(crate::vocabulary::<R>(), R::seed().is_some())
837}
838
839/// [`resource_action_schema`] of the resource `vocabulary`, which `seeds` its
840/// first content or not.
841fn resource_action_schema_of(vocabulary: &crate::Vocabulary, seeds: bool) -> Value {
842    let mut operations: Vec<Value> = Vec::new();
843    for decl in vocabulary.declarations().iter() {
844        operations.push(declared_operation(
845            decl.id,
846            &decl.params,
847            decl.description.as_deref().unwrap_or(&decl.label),
848        ));
849    }
850    if vocabulary.edits {
851        // Described in full by the field-edit action itself.
852        operations.push(describe(
853            object(vec![
854                ("action", constant(crate::FIELD_EDIT), true),
855                ("args", json!({"type": "object"}), true),
856            ]),
857            "A field edit, as the field-edit action takes it",
858        ));
859    }
860    if seeds {
861        operations.push(describe(
862            object(vec![("action", constant("seed"), true)]),
863            "Write the record's first content",
864        ));
865    }
866    object(vec![
867        ("op", one_of(operations), true),
868        (
869            "at",
870            describe(
871                json!({"type": "integer"}),
872                "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`",
873            ),
874            false,
875        ),
876    ])
877}
878
879/// A vocabulary's schema in a line: each alternative of an enum by its name
880/// and its arguments (`Name {a, b?}`; `?` marks an optional one), or by the
881/// value it takes.
882#[must_use]
883pub fn summary(schema: &Value) -> String {
884    let alternatives = schema
885        .get("oneOf")
886        .or_else(|| schema.get("anyOf"))
887        .and_then(Value::as_array)
888        .map_or_else(
889            || vec![schema],
890            |alternatives| alternatives.iter().collect(),
891        );
892    alternatives
893        .into_iter()
894        .filter_map(summarise_alternative)
895        .collect::<Vec<_>>()
896        .join("; ")
897}
898
899fn summarise_alternative(schema: &Value) -> Option<String> {
900    if let Some(value) = schema.get("const") {
901        return Some(
902            value
903                .as_str()
904                .map_or_else(|| value.to_string(), str::to_owned),
905        );
906    }
907    if let Some(values) = schema.get("enum").and_then(Value::as_array) {
908        return Some(
909            values
910                .iter()
911                .map(|value| {
912                    value
913                        .as_str()
914                        .map_or_else(|| value.to_string(), str::to_owned)
915                })
916                .collect::<Vec<_>>()
917                .join(" | "),
918        );
919    }
920    let properties = schema.get("properties")?.as_object()?;
921    // An externally tagged variant: one property, its name, holding its
922    // arguments.
923    if let [(name, inner)] = properties.iter().collect::<Vec<_>>().as_slice() {
924        let arguments = arguments_of(inner);
925        return Some(if arguments.is_empty() {
926            (*name).clone()
927        } else {
928            format!("{name} {{{arguments}}}")
929        });
930    }
931    Some(format!("{{{}}}", arguments_of(schema)))
932}
933
934fn arguments_of(schema: &Value) -> String {
935    let required: Vec<&str> = schema
936        .get("required")
937        .and_then(Value::as_array)
938        .map(|names| names.iter().filter_map(Value::as_str).collect())
939        .unwrap_or_default();
940    schema
941        .get("properties")
942        .and_then(Value::as_object)
943        .map(|properties| {
944            properties
945                .keys()
946                .map(|name| {
947                    if required.contains(&name.as_str()) {
948                        name.clone()
949                    } else {
950                        format!("{name}?")
951                    }
952                })
953                .collect::<Vec<_>>()
954                .join(", ")
955        })
956        .unwrap_or_default()
957}
958
959#[cfg(test)]
960mod tests {
961    use super::*;
962
963    tilo_test_env::scenario! {
964        fn schemas_keep_nulls_tags_and_fields_named_description;
965
966        phase optional_values_accept_null_and_keep_their_shape;
967        {
968            assert_eq!(
969                <Option<String>>::json_schema(),
970                json!({"type": ["string", "null"]})
971            );
972            let choice = nullable(one_of(vec![constant("a"), constant("b")]));
973            assert!(tilo_actions::validate_json_schema(&Value::Null, &choice).is_ok());
974            assert!(tilo_actions::validate_json_schema(&json!("a"), &choice).is_ok());
975            assert!(tilo_actions::validate_json_schema(&json!("c"), &choice).is_err());
976            const { assert!(<Option<u8>>::OPTIONAL) };
977            const { assert!(!<Vec<u8>>::OPTIONAL) };
978        }
979
980        phase internal_tags_join_the_variant_fields;
981        {
982            let schema = internal(
983                "kind",
984                "Circle",
985                object(vec![("radius", f64::json_schema(), true)]),
986            );
987            assert!(
988                tilo_actions::validate_json_schema(&json!({"kind": "Circle", "radius": 1.5}), &schema)
989                    .is_ok()
990            );
991            assert!(tilo_actions::validate_json_schema(&json!({"radius": 1.5}), &schema).is_err());
992        }
993
994        phase a_copy_without_descriptions_keeps_fields_named_description;
995        {
996            let schema = describe(
997                object(vec![(
998                    "description",
999                    describe(String::json_schema(), "Text"),
1000                    true,
1001                )]),
1002                "A note",
1003            );
1004            let copy = undescribed(&schema);
1005            assert!(copy.get("description").is_none());
1006            assert_eq!(copy["properties"]["description"], json!({"type": "string"}));
1007        }
1008    }
1009}