Skip to main content

tilo_actions/
params.rs

1//! Typed action parameters: what an invocation must carry, and the strict bind
2//! that checks it **before** anything runs.
3//!
4//! An [`ActionSpec`](crate::resource::ActionSpec) used to describe its argument
5//! in prose — `"Value 0–1"`, `"Rate, e.g. 0.5 / 1 / 2"`, `"grayscale / sepia /
6//! invert"` — and hand the raw string to a closure that parsed it leniently. A
7//! typo became a silent default. That is tolerable when a human is looking at a
8//! prompt and can see the result; it is not tolerable for a caller with no
9//! screen, whose only description of the surface is the enumeration it was
10//! handed.
11//!
12//! So a parameter is declared, not narrated: a [`name`](ActionParam::name), a
13//! [`ParamType`], whether it is [`required`](ActionParam::required), optional
14//! [`choices`](ActionParam::choices), and a description that explains *meaning*
15//! rather than syntax. [`ActionArgs::bind`] then refuses a missing, unknown,
16//! wrong-typed or out-of-choice argument up front, so a bad call is a refusal
17//! and never a half-applied edit.
18//!
19//! ## One vocabulary, both sides
20//!
21//! This is deliberately the *same* vocabulary the compositor's headless action
22//! API already speaks (`ParamType` / `ActionParam` / `ArgValue` / strict
23//! `ActionArgs::bind`), lifted here so the app-side action model and the
24//! shell-side one share a single definition instead of converging by accident.
25//! The `const` constructors keep `const PARAMS: &[ActionParam] = &[…]`
26//! compiling verbatim; the owned constructors are what an app needs, because an
27//! app builds its parameters at runtime out of document state.
28
29use std::borrow::Cow;
30use std::collections::BTreeMap;
31
32use serde::{Deserialize, Serialize};
33use tilo_lock::MutexRecover as _;
34
35mod carried;
36mod refused;
37
38pub(crate) use carried::without_named;
39
40/// Marks the legacy single-string invocation slot as carrying a canonical
41/// JSON argument object. The record-separator prefix cannot be produced by a
42/// normal palette text field, preserving unambiguous backward compatibility.
43pub const ARGUMENTS_JSON_PREFIX: &str = "\u{1e}tilo-args:";
44
45/// A string that is either a `&'static str` (so a parameter list can be a
46/// `const`) or owned (so an app can build one per frame from its document).
47pub type Str = Cow<'static, str>;
48
49/// The type of one action parameter. Deliberately small: these are values a
50/// caller with no screen can produce from a descriptor alone.
51///
52/// [`Text`](Self::Text), [`Integer`](Self::Integer) and
53/// [`Boolean`](Self::Boolean) carry the compositor's existing wire spellings
54/// unchanged. [`Number`](Self::Number) is the addition the app surface needs:
55/// the lossy parses this module replaces were overwhelmingly fractional
56/// (opacity, speed, volume), and rounding them to an integer would throw away
57/// exactly the values they exist to carry.
58#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
59#[serde(rename_all = "lowercase")]
60pub enum ParamType {
61    Text,
62    Integer,
63    /// A real number. JSON carries it as a number; an integer literal is
64    /// accepted and widened, because `1` and `1.0` are the same rate.
65    Number,
66    Boolean,
67    Object,
68    Array,
69    /// Stable address of another published Tilo resource.
70    Resource,
71    /// RFC 3339 timestamp.
72    DateTime,
73    /// Text that must be redacted from logs, history, and confirmation copy.
74    Secret,
75}
76
77/// The type of a parameter whose Rust type the macros cannot read
78/// (an app's own enum or struct): what its schema says it is written as.
79/// A unit enum is text, a struct an object; a value written in several
80/// shapes is an object, and one whose schema names the kind of resource it is the address of
81/// ([`RESOURCE_KIND_ANNOTATION`]) a resource.
82#[must_use]
83pub fn param_type_of(schema: &serde_json::Value) -> ParamType {
84    fn of(schema: &serde_json::Value) -> Option<ParamType> {
85        if schema
86            .get(RESOURCE_KIND_ANNOTATION)
87            .is_some_and(serde_json::Value::is_string)
88        {
89            return Some(ParamType::Resource);
90        }
91        // A nullable type: what it is when present.
92        let kind = match schema.get("type") {
93            Some(serde_json::Value::Array(kinds)) => kinds
94                .iter()
95                .filter_map(serde_json::Value::as_str)
96                .find(|kind| *kind != "null"),
97            Some(kind) => kind.as_str(),
98            None => None,
99        };
100        if let Some(kind) = kind {
101            return Some(match kind {
102                "string" => ParamType::Text,
103                "integer" => ParamType::Integer,
104                "number" => ParamType::Number,
105                "boolean" => ParamType::Boolean,
106                "array" => ParamType::Array,
107                _ => ParamType::Object,
108            });
109        }
110        if let Some(values) = schema.get("enum").and_then(serde_json::Value::as_array) {
111            return values
112                .iter()
113                .all(serde_json::Value::is_string)
114                .then_some(ParamType::Text);
115        }
116        let alternatives = schema
117            .get("oneOf")
118            .or_else(|| schema.get("anyOf"))
119            .and_then(serde_json::Value::as_array)?;
120        let mut kinds = alternatives
121            .iter()
122            .filter(|alternative| alternative.get("type") != Some(&serde_json::json!("null")))
123            .map(of);
124        let first = kinds.next()??;
125        kinds.all(|kind| kind == Some(first)).then_some(first)
126    }
127    of(schema).unwrap_or(ParamType::Object)
128}
129
130impl ParamType {
131    /// Wire spelling, and what an enumeration descriptor carries.
132    pub fn label(self) -> &'static str {
133        match self {
134            ParamType::Text => "text",
135            ParamType::Integer => "integer",
136            ParamType::Number => "number",
137            ParamType::Boolean => "boolean",
138            ParamType::Object => "object",
139            ParamType::Array => "array",
140            ParamType::Resource => "resource",
141            ParamType::DateTime => "datetime",
142            ParamType::Secret => "secret",
143        }
144    }
145}
146
147/// Schema annotation naming the kind of resource a [`ParamType::Resource`]
148/// parameter takes; see [`ActionParam::of_resource_kind`]. An annotation,
149/// not an assertion: binding does not check it.
150pub const RESOURCE_KIND_ANNOTATION: &str = "resource_kind";
151
152/// Schema annotation naming the kinds of resource a [`ParamType::Resource`]
153/// parameter takes when it takes one of several (a message, a thread or a direct
154/// conversation); see [`ActionParam::taking_resource_kinds`]. An annotation, not an
155/// assertion: binding does not check it.
156pub const RESOURCE_KINDS_ANNOTATION: &str = "resource_kinds";
157
158/// Schema annotation saying how each of a parameter's choices reads to a
159/// person: an object from choice to label; see
160/// [`ActionParam::with_labelled_choices`]. An identity is chosen by its name,
161/// never by its fingerprint.
162pub const CHOICE_LABELS_ANNOTATION: &str = "choice_labels";
163
164/// Schema annotation naming which of a parameter's choices are people
165/// (identities, members): a surface shows each with its avatar; see
166/// [`ActionParam::choosing_people`].
167pub const PEOPLE_ANNOTATION: &str = "people";
168
169/// Schema annotation marking a parameter as a place inside the resource the
170/// action is on (an item, a caret in it, a range of it); see
171/// [`ActionParam::as_place`].
172pub const PLACE_ANNOTATION: &str = "place";
173
174/// Schema annotation marking a text parameter as the address of content
175/// another action produced (a content hash), not words a caller can say;
176/// see [`ActionParam::as_content`].
177pub const CONTENT_ANNOTATION: &str = "content";
178
179/// Schema annotation naming what a parameter's value picks from the
180/// workspace; see [`ActionParam::picking`]. An annotation, not an
181/// assertion: binding takes any value of the parameter's type.
182pub const PICK_ANNOTATION: &str = "pick";
183
184/// Schema annotation of a parameter whose shape another argument of the same
185/// call decides: `{"argument": "<its name>", "shapes": {"<a value of it>":
186/// <schema>}}`. What a question keeps is its kind's: a secret keeps what is
187/// asked for and where it belongs. Where the other argument is text that
188/// names a shape, [`ActionArgs::bind`] holds this one against that shape, in
189/// the words every refused argument is told; any other value of it leaves
190/// this one to its own schema. A listing writes the shapes out
191/// ([`ActionParam::declared_shape`]). See [`ActionParam::shaped_by`].
192pub const SHAPED_BY_ANNOTATION: &str = "shaped_by";
193
194/// `schema` with the shapes the argument `argument` decides
195/// ([`SHAPED_BY_ANNOTATION`]): the schema a type publishes whose JSON form
196/// another argument of its action decides.
197#[must_use]
198pub fn shaped_by_schema<V: Into<String>>(
199    schema: serde_json::Value,
200    argument: &str,
201    shapes: impl IntoIterator<Item = (V, serde_json::Value)>,
202) -> serde_json::Value {
203    let mut schema = match schema {
204        serde_json::Value::Object(schema) => schema,
205        _ => serde_json::Map::new(),
206    };
207    schema.insert(
208        SHAPED_BY_ANNOTATION.into(),
209        shapes_decided_by(argument, shapes),
210    );
211    serde_json::Value::Object(schema)
212}
213
214/// What a [`SHAPED_BY_ANNOTATION`] holds.
215fn shapes_decided_by<V: Into<String>>(
216    argument: &str,
217    shapes: impl IntoIterator<Item = (V, serde_json::Value)>,
218) -> serde_json::Value {
219    let shapes: serde_json::Map<String, serde_json::Value> = shapes
220        .into_iter()
221        .map(|(value, schema)| (value.into(), schema))
222        .collect();
223    serde_json::json!({"argument": argument, "shapes": shapes})
224}
225
226/// What a parameter's value names in the workspace, so a person picks it
227/// from what is there instead of typing its encoding ([`PICK_ANNOTATION`]).
228#[derive(Clone, Debug, PartialEq, Eq)]
229pub enum Pick {
230    /// Who: a person, an agent or an app of the workspace, as a
231    /// `tilo_action_policy::Grantee`.
232    Grantee,
233    /// Where: a node of the workspace's tree, as its path below the workspace.
234    Node,
235    /// One of the workspace's grants, by its id.
236    Grant,
237    /// An existing resource of the workspace of kind `kind` (a note, a
238    /// file, an issue), found by the title its app publishes for it, as a
239    /// reference ([`resource_reference_schema`]). An agent passes the same
240    /// reference; nobody types an id.
241    Resource { kind: String },
242}
243
244impl Pick {
245    const TAGGED: [Self; 3] = [Self::Grantee, Self::Node, Self::Grant];
246    const RESOURCE_TAG: &str = "resource";
247
248    const fn tag(&self) -> &'static str {
249        match self {
250            Self::Grantee => "subject",
251            Self::Node => "node",
252            Self::Grant => "grant",
253            Self::Resource { .. } => Self::RESOURCE_TAG,
254        }
255    }
256}
257
258/// The schema of a reference to an existing resource of the workspace, as
259/// a parameter that picks one takes it ([`Pick::Resource`]): the app that
260/// keeps it, the record it keeps it in when not its record of the
261/// workspace, its kind, its id in that app and how it reads. The label is
262/// presentation only; the app, kind and id are the address.
263#[must_use]
264pub fn resource_reference_schema() -> serde_json::Value {
265    let text = || serde_json::json!({ "type": "string", "minLength": 1 });
266    serde_json::json!({
267        "type": "object",
268        "properties": {
269            "app": text(),
270            "record": text(),
271            "kind": text(),
272            "id": text(),
273            "label": { "type": "string" },
274        },
275        "required": ["app", "kind", "id", "label"],
276    })
277}
278
279/// The schema of a parameter that picks an existing resource of kind
280/// `kind` ([`Pick::Resource`]): a reference
281/// ([`resource_reference_schema`]), annotated with what it picks.
282#[must_use]
283pub fn picked_resource_schema(kind: &str) -> serde_json::Value {
284    let mut schema = resource_reference_schema();
285    if let serde_json::Value::Object(fields) = &mut schema {
286        fields.insert(PICK_ANNOTATION.into(), Pick::RESOURCE_TAG.into());
287        fields.insert(RESOURCE_KIND_ANNOTATION.into(), kind.into());
288    }
289    schema
290}
291
292/// The schema of a parameter that picks an existing resource of kind `kind` and names it by its
293/// address (`kind:id`) rather than a reference record: the address it stores, annotated with
294/// what it picks. What a verb whose parameter is a string of the item's address declares.
295#[must_use]
296pub fn picked_address_schema(kind: &str) -> serde_json::Value {
297    let mut schema = serde_json::json!({ "type": "string" });
298    if let serde_json::Value::Object(fields) = &mut schema {
299        fields.insert(RESOURCE_KIND_ANNOTATION.into(), kind.into());
300    }
301    schema
302}
303
304/// The schema of a place inside a resource ([`ActionParam::as_place`]).
305#[must_use]
306pub fn place_schema() -> serde_json::Value {
307    let offset = || serde_json::json!({ "type": "integer", "minimum": 0 });
308    serde_json::json!({
309        "type": "object",
310        PLACE_ANNOTATION: true,
311        "properties": {
312            "item": { "type": "string", "minLength": 1 },
313            "at": offset(),
314            "start": offset(),
315            "end": offset(),
316        },
317        "required": ["item"],
318        "additionalProperties": false,
319    })
320}
321
322/// One typed parameter an action declares.
323#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
324pub struct ActionParam {
325    pub name: Str,
326    pub ty: ParamType,
327    /// Whether an invocation must supply it. An optional parameter's default
328    /// belongs to the action and is stated in `description` — the surface does
329    /// not invent one.
330    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
331    pub required: bool,
332    /// Whether one line of typed text fills this parameter, and the others
333    /// the words it says (`title: Text (entry)`). An action with one is
334    /// offered as a capture: a person types "call landlord fri 10am" and the
335    /// action's own field types read the rest.
336    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
337    pub entry: bool,
338    pub description: Str,
339    /// When non-empty, the only values this parameter accepts.
340    ///
341    /// This is what turns a prose list (`"grayscale / sepia / invert"`) into
342    /// something a caller can *read* and something [`ActionArgs::bind`] can
343    /// *enforce*. A value outside the set is refused by name rather than
344    /// quietly falling through to a default.
345    #[serde(default, skip_serializing_if = "Vec::is_empty")]
346    pub choices: Vec<Str>,
347    /// JSON Schema fragment applied after the basic type check. This carries
348    /// ranges, lengths, patterns, formats, item/object schemas, and defaults
349    /// without growing a second incompatible validation vocabulary.
350    #[serde(default, skip_serializing_if = "Option::is_none")]
351    pub schema: Option<std::sync::Arc<serde_json::Value>>,
352    /// Explicitly permits JSON null. Optional means omitted; nullable means
353    /// present with no value, and callers need to distinguish the two.
354    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
355    pub nullable: bool,
356}
357
358impl ActionParam {
359    /// A required parameter with static strings — usable in a `const`.
360    pub const fn required(name: &'static str, ty: ParamType, description: &'static str) -> Self {
361        Self {
362            name: Cow::Borrowed(name),
363            ty,
364            required: true,
365            entry: false,
366            description: Cow::Borrowed(description),
367            choices: Vec::new(),
368            schema: None,
369            nullable: false,
370        }
371    }
372
373    /// An optional parameter with static strings — usable in a `const`.
374    pub const fn optional(name: &'static str, ty: ParamType, description: &'static str) -> Self {
375        Self {
376            name: Cow::Borrowed(name),
377            ty,
378            required: false,
379            entry: false,
380            description: Cow::Borrowed(description),
381            choices: Vec::new(),
382            schema: None,
383            nullable: false,
384        }
385    }
386
387    /// A required parameter whose strings are built at runtime — what an app
388    /// declaring parameters out of live document state needs.
389    pub fn required_owned(
390        name: impl Into<Str>,
391        ty: ParamType,
392        description: impl Into<Str>,
393    ) -> Self {
394        Self {
395            name: name.into(),
396            ty,
397            required: true,
398            entry: false,
399            description: description.into(),
400            choices: Vec::new(),
401            schema: None,
402            nullable: false,
403        }
404    }
405
406    /// An optional parameter whose strings are built at runtime.
407    pub fn optional_owned(
408        name: impl Into<Str>,
409        ty: ParamType,
410        description: impl Into<Str>,
411    ) -> Self {
412        Self {
413            name: name.into(),
414            ty,
415            required: false,
416            entry: false,
417            description: description.into(),
418            choices: Vec::new(),
419            schema: None,
420            nullable: false,
421        }
422    }
423
424    /// Have one line of typed text fill this parameter, and the parameters
425    /// the words say ([`ActionParam::entry`]).
426    #[must_use]
427    pub fn taking_entry(mut self) -> Self {
428        self.entry = true;
429        self
430    }
431
432    /// Restrict this parameter to `choices`. Binding refuses anything else.
433    #[must_use]
434    pub fn with_choices<S: Into<Str>>(mut self, choices: impl IntoIterator<Item = S>) -> Self {
435        self.choices = choices.into_iter().map(Into::into).collect();
436        self
437    }
438
439    #[must_use]
440    pub fn with_schema(mut self, schema: serde_json::Value) -> Self {
441        self.schema = Some(std::sync::Arc::new(schema));
442        self
443    }
444
445    /// Call this parameter `title` where people read it (a form's field, a
446    /// consent sheet's row): its schema's `title`, in the reader's language.
447    #[must_use]
448    pub fn titled(mut self, title: impl Into<String>) -> Self {
449        let mut schema = match self.schema.as_deref() {
450            Some(serde_json::Value::Object(schema)) => schema.clone(),
451            _ => serde_json::Map::new(),
452        };
453        schema.insert("title".to_owned(), serde_json::Value::String(title.into()));
454        self.schema = Some(std::sync::Arc::new(serde_json::Value::Object(schema)));
455        self
456    }
457
458    /// Call this parameter `title` where people read it *and* describe it so:
459    /// what a catalogue says of a parameter of a declared action or effect,
460    /// read in the reader's language.
461    #[must_use]
462    pub fn described(mut self, title: impl Into<String>) -> Self {
463        let title = title.into();
464        self.description = title.clone().into();
465        self.titled(title)
466    }
467
468    /// Offer `value` in this parameter's place: what the action's own state
469    /// knows it would be (a calendar's current colour), which a caller may
470    /// change. Its schema's `default`, so a surface fills the field without
471    /// binding anything.
472    #[must_use]
473    pub fn with_default(mut self, value: serde_json::Value) -> Self {
474        let mut schema = match self.schema.as_deref() {
475            Some(serde_json::Value::Object(schema)) => schema.clone(),
476            _ => serde_json::Map::new(),
477        };
478        schema.insert("default".to_owned(), value);
479        self.schema = Some(std::sync::Arc::new(serde_json::Value::Object(schema)));
480        self
481    }
482
483    /// Retain an immutable schema already shared by the current type generation.
484    /// Wire serialization and strict argument validation are unchanged.
485    #[must_use]
486    pub fn with_shared_schema(mut self, schema: std::sync::Arc<serde_json::Value>) -> Self {
487        self.schema = Some(schema);
488        self
489    }
490
491    /// Name the kinds of resource this [`ParamType::Resource`] parameter
492    /// takes, any one of them (a channel, a thread or a direct conversation), as the
493    /// [`RESOURCE_KINDS_ANNOTATION`] of its schema: what tells a grant that the step may reach
494    /// every one of them.
495    #[must_use]
496    pub fn taking_resource_kinds<I, S>(self, kinds: I) -> Self
497    where
498        I: IntoIterator<Item = S>,
499        S: Into<String>,
500    {
501        let kinds = kinds
502            .into_iter()
503            .map(|kind| serde_json::Value::String(kind.into()))
504            .collect();
505        self.annotate(RESOURCE_KINDS_ANNOTATION, serde_json::Value::Array(kinds))
506    }
507
508    /// The kinds of resource this parameter takes, when it names several
509    /// ([`Self::taking_resource_kinds`]).
510    #[must_use]
511    pub fn resource_kinds(&self) -> Vec<&str> {
512        self.schema
513            .as_deref()
514            .and_then(|schema| schema.get(RESOURCE_KINDS_ANNOTATION))
515            .and_then(serde_json::Value::as_array)
516            .map(|kinds| kinds.iter().filter_map(serde_json::Value::as_str).collect())
517            .unwrap_or_default()
518    }
519
520    /// Name the kind of resource this [`ParamType::Resource`] parameter
521    /// takes (e.g. `files.entry`), as the [`RESOURCE_KIND_ANNOTATION`] of its
522    /// schema. Surfaces use it to offer the action on resources of that kind
523    /// and its sub-kinds.
524    #[must_use]
525    pub fn of_resource_kind(mut self, kind: impl Into<String>) -> Self {
526        let mut schema = match self.schema.take() {
527            Some(schema) => match std::sync::Arc::unwrap_or_clone(schema) {
528                serde_json::Value::Object(schema) => schema,
529                _ => serde_json::Map::new(),
530            },
531            _ => serde_json::Map::new(),
532        };
533        schema.insert(
534            RESOURCE_KIND_ANNOTATION.into(),
535            serde_json::Value::String(kind.into()),
536        );
537        self.schema = Some(std::sync::Arc::new(serde_json::Value::Object(schema)));
538        self
539    }
540
541    /// Restrict this parameter to the first of each pair, each read as the
542    /// second ([`CHOICE_LABELS_ANNOTATION`]): binding still takes only the
543    /// values, and a surface offers the labels.
544    #[must_use]
545    pub fn with_labelled_choices<V: Into<Str>, L: Into<String>>(
546        mut self,
547        choices: impl IntoIterator<Item = (V, L)>,
548    ) -> Self {
549        let mut labels = serde_json::Map::new();
550        self.choices = choices
551            .into_iter()
552            .map(|(value, label)| {
553                let value: Str = value.into();
554                labels.insert(value.to_string(), serde_json::Value::String(label.into()));
555                value
556            })
557            .collect();
558        self.annotate(CHOICE_LABELS_ANNOTATION, serde_json::Value::Object(labels))
559    }
560
561    /// Mark which choices are people ([`PEOPLE_ANNOTATION`]): each is shown
562    /// with the avatar of its label, keyed by its value. Choices not named
563    /// (a "Create new" beside the identities) read as text alone.
564    #[must_use]
565    pub fn choosing_people<S: Into<String>>(self, people: impl IntoIterator<Item = S>) -> Self {
566        let people = people
567            .into_iter()
568            .map(|person| serde_json::Value::String(person.into()))
569            .collect();
570        self.annotate(PEOPLE_ANNOTATION, serde_json::Value::Array(people))
571    }
572
573    /// Have a person pick this parameter's value from the workspace's
574    /// `pick`s ([`PICK_ANNOTATION`]); callers that know the value still give
575    /// it as the parameter's type says. A resource is picked as a reference
576    /// ([`resource_reference_schema`]), whatever schema the parameter had.
577    #[must_use]
578    pub fn picking(self, pick: Pick) -> Self {
579        match pick {
580            Pick::Resource { kind } => self.with_schema(picked_resource_schema(&kind)),
581            tagged => self.annotate(
582                PICK_ANNOTATION,
583                serde_json::Value::String(tagged.tag().into()),
584            ),
585        }
586    }
587
588    /// What this parameter's value picks from the workspace
589    /// ([`Self::picking`]).
590    #[must_use]
591    pub fn pick(&self) -> Option<Pick> {
592        let schema = self.schema.as_ref()?;
593        let tag = schema.get(PICK_ANNOTATION)?.as_str()?;
594        if tag == Pick::RESOURCE_TAG {
595            let kind = schema.get(RESOURCE_KIND_ANNOTATION)?.as_str()?;
596            return Some(Pick::Resource { kind: kind.into() });
597        }
598        Pick::TAGGED.into_iter().find(|pick| pick.tag() == tag)
599    }
600
601    /// How `choice` reads to a person ([`Self::with_labelled_choices`]).
602    #[must_use]
603    pub fn choice_label(&self, choice: &str) -> Option<&str> {
604        self.schema
605            .as_ref()?
606            .get(CHOICE_LABELS_ANNOTATION)?
607            .get(choice)?
608            .as_str()
609    }
610
611    /// Let the value the argument `argument` is given decide this
612    /// parameter's shape ([`SHAPED_BY_ANNOTATION`]): `shapes` names a schema
613    /// for each value of it that has one. A call is held to the shape its
614    /// own value of `argument` names, and to this parameter's own schema
615    /// alone where it names none.
616    #[must_use]
617    pub fn shaped_by<V: Into<String>>(
618        self,
619        argument: &str,
620        shapes: impl IntoIterator<Item = (V, serde_json::Value)>,
621    ) -> Self {
622        self.annotate(SHAPED_BY_ANNOTATION, shapes_decided_by(argument, shapes))
623    }
624
625    /// The argument whose value decides this parameter's shape, and the
626    /// shape each of its values names, where the declaration says so
627    /// ([`SHAPED_BY_ANNOTATION`]).
628    #[must_use]
629    pub fn shapes_by(&self) -> Option<(&str, &serde_json::Map<String, serde_json::Value>)> {
630        let declared = self.schema.as_deref()?.get(SHAPED_BY_ANNOTATION)?;
631        Some((
632            declared.get("argument")?.as_str()?,
633            declared.get("shapes")?.as_object()?,
634        ))
635    }
636
637    fn annotate(mut self, key: &str, value: serde_json::Value) -> Self {
638        let mut schema = match self.schema.take() {
639            Some(schema) => match std::sync::Arc::unwrap_or_clone(schema) {
640                serde_json::Value::Object(schema) => schema,
641                _ => serde_json::Map::new(),
642            },
643            _ => serde_json::Map::new(),
644        };
645        schema.insert(key.into(), value);
646        self.schema = Some(std::sync::Arc::new(serde_json::Value::Object(schema)));
647        self
648    }
649
650    /// The kind of resource this parameter takes, when it is a resource
651    /// parameter that names one ([`Self::of_resource_kind`]).
652    #[must_use]
653    pub fn resource_kind(&self) -> Option<&str> {
654        if self.ty != ParamType::Resource {
655            return None;
656        }
657        self.schema
658            .as_ref()?
659            .get(RESOURCE_KIND_ANNOTATION)?
660            .as_str()
661            .filter(|kind| !kind.is_empty())
662    }
663
664    /// Make this a place inside the resource the action is on: an object
665    /// naming one of its items (`{"item": id}`), a caret in it
666    /// (`{"item": id, "at": n}`) or a range of it
667    /// (`{"item": id, "start": n, "end": n}`). Marked with the
668    /// [`PLACE_ANNOTATION`], so a palette or an agent offers the resource's
669    /// items rather than free text. An action given one acts there instead
670    /// of at the invoker's caret.
671    #[must_use]
672    pub fn as_place(mut self) -> Self {
673        self.ty = ParamType::Object;
674        self.schema = Some(std::sync::Arc::new(place_schema()));
675        self
676    }
677
678    /// [`Self::as_place`], its items being those of the collection `field`
679    /// (a document's paragraphs, `blocks`): the item resources published as
680    /// `<resource>/<field>/<item>`.
681    #[must_use]
682    pub fn as_place_in(mut self, field: &str) -> Self {
683        let mut schema = place_schema();
684        if let Some(object) = schema.as_object_mut() {
685            object.insert(
686                PLACE_ANNOTATION.into(),
687                serde_json::Value::String(field.into()),
688            );
689        }
690        self.ty = ParamType::Object;
691        self.schema = Some(std::sync::Arc::new(schema));
692        self
693    }
694
695    /// Make this text parameter the address of content another action
696    /// produced: a caller chains it from that action's result, never from
697    /// words (marked with the [`CONTENT_ANNOTATION`]).
698    #[must_use]
699    pub fn as_content(mut self) -> Self {
700        self.ty = ParamType::Text;
701        self.schema = Some(std::sync::Arc::new(serde_json::json!({
702            "type": "string",
703            CONTENT_ANNOTATION: true,
704        })));
705        self
706    }
707
708    /// Make this list parameter a list of content addresses, each one
709    /// content another action produced ([`Self::as_content`]), in order.
710    #[must_use]
711    pub fn as_content_list(mut self) -> Self {
712        self.ty = ParamType::Array;
713        self.schema = Some(std::sync::Arc::new(serde_json::json!({
714            "type": "array",
715            "items": { "type": "string", CONTENT_ANNOTATION: true },
716        })));
717        self
718    }
719
720    /// Whether this parameter takes a list of content
721    /// ([`Self::as_content_list`]).
722    #[must_use]
723    pub fn is_content_list(&self) -> bool {
724        self.ty == ParamType::Array
725            && self
726                .schema
727                .as_ref()
728                .and_then(|schema| schema.get("items"))
729                .and_then(|items| items.get(CONTENT_ANNOTATION))
730                .and_then(serde_json::Value::as_bool)
731                .unwrap_or(false)
732    }
733
734    /// Whether this parameter takes content another action produced
735    /// ([`Self::as_content`]).
736    #[must_use]
737    pub fn is_content(&self) -> bool {
738        self.ty == ParamType::Text
739            && self
740                .schema
741                .as_ref()
742                .and_then(|schema| schema.get(CONTENT_ANNOTATION))
743                .and_then(serde_json::Value::as_bool)
744                .unwrap_or(false)
745    }
746
747    /// Whether this parameter is a place inside the resource
748    /// ([`Self::as_place`]).
749    #[must_use]
750    pub fn is_place(&self) -> bool {
751        self.ty == ParamType::Object
752            && self
753                .schema
754                .as_ref()
755                .and_then(|schema| schema.get(PLACE_ANNOTATION))
756                .is_some_and(|place| place.as_bool() == Some(true) || place.is_string())
757    }
758
759    /// The collection whose items this place parameter names, when it says
760    /// ([`Self::as_place_in`]).
761    #[must_use]
762    pub fn place_field(&self) -> Option<&str> {
763        self.schema
764            .as_ref()?
765            .get(PLACE_ANNOTATION)?
766            .as_str()
767            .filter(|field| !field.is_empty())
768    }
769
770    #[must_use]
771    pub fn nullable(mut self) -> Self {
772        self.nullable = true;
773        self
774    }
775
776    /// How a value of this parameter is written, where its declaration says
777    /// more of it than its type does (the keys of an object, the items of a
778    /// list, its choices, its bounds): JSON with a word in angle brackets
779    /// where a value goes and `?` after a key that may be left out. What a
780    /// listing shows before a call, and what a refusal tells after one.
781    #[must_use]
782    pub fn declared_shape(&self) -> Option<String> {
783        refused::declared_shape(self)
784    }
785
786    /// Validate this parameter's descriptor independently of any supplied
787    /// value, suitable for an untrusted publication boundary.
788    pub fn validate_declaration(&self) -> Vec<String> {
789        let mut errors = Vec::new();
790        if self.name.trim().is_empty() {
791            errors.push("parameter name must be non-empty".into());
792        }
793        if self.description.trim().is_empty() {
794            errors.push("parameter description must be non-empty".into());
795        }
796        if self.ty == ParamType::Secret && !self.choices.is_empty() {
797            errors.push("secret parameters must not publish possible values".into());
798        }
799        for choice in &self.choices {
800            let valid = match self.ty {
801                ParamType::Text => true,
802                // As wide as an integer argument carries: an id past `i64::MAX` is a
803                // choice like any other ([`ArgValue::Integer`]).
804                ParamType::Integer => choice.parse::<i128>().is_ok(),
805                ParamType::Number => choice.parse::<f64>().is_ok(),
806                ParamType::Boolean => matches!(choice.as_ref(), "true" | "false"),
807                ParamType::Object => {
808                    serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(choice)
809                        .is_ok()
810                }
811                ParamType::Array => serde_json::from_str::<Vec<serde_json::Value>>(choice).is_ok(),
812                ParamType::Resource => {
813                    !choice.trim().is_empty()
814                        && !choice.contains(crate::KEY_SEP)
815                        && choice.contains(':')
816                }
817                ParamType::DateTime => looks_like_rfc3339(choice),
818                ParamType::Secret => false,
819            };
820            if !valid {
821                errors.push(format!(
822                    "choice `{choice}` does not have declared type {}",
823                    self.ty.label()
824                ));
825            }
826        }
827        if let Some(schema) = &self.schema
828            && let Err(reason) = validate_shared_schema_definition(schema)
829        {
830            errors.push(format!("invalid schema: {reason}"));
831        }
832        errors
833    }
834}
835
836const VALID_SCHEMA_LIMIT: usize = 64;
837
838thread_local! {
839    static VALID_SCHEMAS: std::cell::RefCell<Vec<std::sync::Weak<serde_json::Value>>> =
840        const { std::cell::RefCell::new(Vec::new()) };
841}
842
843/// Publications reuse immutable type-generation schemas. Remember only successful
844/// structural checks, never argument values, descriptor fields or authority.
845/// Weak identities keep neither the schema tree nor its generation alive and
846/// prevent an allocation at a recycled address from borrowing an old result.
847/// `Arc::make_mut` dissociates these weak identities before changing a schema.
848fn validate_shared_schema_definition(
849    schema: &std::sync::Arc<serde_json::Value>,
850) -> Result<(), String> {
851    let known = VALID_SCHEMAS.with(|schemas| {
852        schemas
853            .borrow()
854            .iter()
855            .any(|validated| std::ptr::eq(validated.as_ptr(), std::sync::Arc::as_ptr(schema)))
856    });
857    if known {
858        return Ok(());
859    }
860    validate_schema_definition(schema)?;
861    VALID_SCHEMAS.with(|schemas| {
862        let mut schemas = schemas.borrow_mut();
863        schemas.retain(|schema| schema.strong_count() != 0);
864        if schemas.len() == VALID_SCHEMA_LIMIT {
865            schemas.remove(0);
866        }
867        schemas.push(std::sync::Arc::downgrade(schema));
868    });
869    Ok(())
870}
871
872/// One bound argument value.
873#[derive(Clone, PartialEq)]
874pub enum ArgValue {
875    Text(String),
876    /// A whole number, as wide as JSON's integers are: a layout's ids span all of `u64`, which `i64`
877    /// does not.
878    Integer(i128),
879    Number(f64),
880    Boolean(bool),
881    Object(serde_json::Map<String, serde_json::Value>),
882    Array(Vec<serde_json::Value>),
883    Resource(String),
884    DateTime(String),
885    Secret(String),
886    Null,
887}
888
889impl std::fmt::Debug for ArgValue {
890    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
891        match self {
892            Self::Text(value) => f.debug_tuple("Text").field(value).finish(),
893            Self::Integer(value) => f.debug_tuple("Integer").field(value).finish(),
894            Self::Number(value) => f.debug_tuple("Number").field(value).finish(),
895            Self::Boolean(value) => f.debug_tuple("Boolean").field(value).finish(),
896            Self::Object(value) => f.debug_tuple("Object").field(value).finish(),
897            Self::Array(value) => f.debug_tuple("Array").field(value).finish(),
898            Self::Resource(value) => f.debug_tuple("Resource").field(value).finish(),
899            Self::DateTime(value) => f.debug_tuple("DateTime").field(value).finish(),
900            Self::Secret(_) => f.debug_tuple("Secret").field(&"[REDACTED]").finish(),
901            Self::Null => f.write_str("Null"),
902        }
903    }
904}
905
906impl ArgValue {
907    /// The declared type this value satisfies.
908    pub fn ty(&self) -> ParamType {
909        match self {
910            ArgValue::Text(_) | ArgValue::Null => ParamType::Text,
911            ArgValue::Integer(_) => ParamType::Integer,
912            ArgValue::Number(_) => ParamType::Number,
913            ArgValue::Boolean(_) => ParamType::Boolean,
914            ArgValue::Object(_) => ParamType::Object,
915            ArgValue::Array(_) => ParamType::Array,
916            ArgValue::Resource(_) => ParamType::Resource,
917            ArgValue::DateTime(_) => ParamType::DateTime,
918            ArgValue::Secret(_) => ParamType::Secret,
919            // Null is validated against `ActionParam::nullable`, so its
920            // nominal type is irrelevant. Text keeps diagnostics stable.
921        }
922    }
923
924    /// Whether this value satisfies `want`.
925    ///
926    /// Exact, with one deliberate widening: an [`Integer`](Self::Integer)
927    /// satisfies [`Number`](ParamType::Number). JSON has one numeric type and
928    /// spells `1.0` as `1`, so refusing it would make a perfectly good rate of
929    /// `1` un-passable over the wire. The widening is one-way — a fractional
930    /// value never satisfies `Integer`.
931    pub fn satisfies(&self, want: ParamType) -> bool {
932        self.ty() == want || (want == ParamType::Number && self.ty() == ParamType::Integer)
933    }
934
935    /// Read as JSON, using the same spelling the compositor's control socket
936    /// already accepts: string → `Text`, bool → `Boolean`, integral number →
937    /// `Integer`, fractional number → `Number`.
938    pub fn from_json(value: &serde_json::Value) -> Option<Self> {
939        match value {
940            serde_json::Value::String(s) => Some(ArgValue::Text(s.clone())),
941            serde_json::Value::Bool(b) => Some(ArgValue::Boolean(*b)),
942            serde_json::Value::Number(n) => match (n.as_i64(), n.as_u64()) {
943                (Some(i), _) => Some(ArgValue::Integer(i128::from(i))),
944                (None, Some(i)) => Some(ArgValue::Integer(i128::from(i))),
945                (None, None) => n.as_f64().map(ArgValue::Number),
946            },
947            serde_json::Value::Object(value) => Some(ArgValue::Object(value.clone())),
948            serde_json::Value::Array(value) => Some(ArgValue::Array(value.clone())),
949            serde_json::Value::Null => Some(ArgValue::Null),
950        }
951    }
952
953    /// Write as JSON, the inverse of [`from_json`](Self::from_json).
954    pub fn to_json(&self) -> serde_json::Value {
955        match self {
956            ArgValue::Text(s) => serde_json::Value::String(s.clone()),
957            ArgValue::Integer(i) => i64::try_from(*i).map_or_else(
958                |_| u64::try_from(*i).map_or(serde_json::Value::Null, serde_json::Value::from),
959                serde_json::Value::from,
960            ),
961            ArgValue::Number(f) => serde_json::Number::from_f64(*f)
962                .map_or(serde_json::Value::Null, serde_json::Value::Number),
963            ArgValue::Boolean(b) => serde_json::Value::Bool(*b),
964            ArgValue::Object(value) => serde_json::Value::Object(value.clone()),
965            ArgValue::Array(value) => serde_json::Value::Array(value.clone()),
966            ArgValue::Resource(value) | ArgValue::DateTime(value) | ArgValue::Secret(value) => {
967                serde_json::Value::String(value.clone())
968            }
969            ArgValue::Null => serde_json::Value::Null,
970        }
971    }
972}
973
974/// How a value broke its parameter's declared range, as data: what a
975/// failure's [`details`](crate::ActionFailure::details) carry beside its
976/// message, so a caller corrects the call without reading the prose.
977#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
978#[serde(tag = "kind", rename_all = "snake_case")]
979pub enum ArgViolation {
980    /// Below the schema's `minimum`.
981    Minimum { bound: serde_json::Value },
982    /// Above the schema's `maximum`.
983    Maximum { bound: serde_json::Value },
984}
985
986impl std::fmt::Display for ArgViolation {
987    /// The bound as the schema spells it: a whole id reads as the id, not a rounded float.
988    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
989        let (side, bound) = match self {
990            Self::Minimum { bound } => ("least", bound),
991            Self::Maximum { bound } => ("most", bound),
992        };
993        write!(f, "must be at {side} {bound}")
994    }
995}
996
997/// Why a set of arguments does not satisfy an action's parameters.
998///
999/// Each variant names the parameter, because a caller that cannot see the
1000/// screen has nothing else to correct against.
1001#[derive(Clone, Debug, PartialEq, Eq)]
1002pub enum ArgError {
1003    Missing {
1004        name: String,
1005        /// The kind of thing it takes and the shape that works.
1006        takes: String,
1007    },
1008    /// A number outside the range the parameter's schema declares.
1009    OutOfRange {
1010        name: String,
1011        violation: ArgViolation,
1012    },
1013    Unknown {
1014        name: String,
1015        /// The arguments the action does take: the shape of the call that works.
1016        takes: String,
1017    },
1018    WrongType {
1019        name: String,
1020        expected: ParamType,
1021        got: ParamType,
1022        /// The shape that works.
1023        shape: String,
1024    },
1025    /// The value was the right type but outside the parameter's declared
1026    /// [`choices`](ActionParam::choices).
1027    NotAllowed {
1028        name: String,
1029        /// The kind of thing it was given: never the value itself.
1030        given: &'static str,
1031        allowed: Vec<String>,
1032    },
1033    /// The JSON value was not one of the shapes an [`ArgValue`] can carry (an
1034    /// object, an array, or `null`).
1035    Unrepresentable {
1036        name: String,
1037    },
1038    Constraint {
1039        name: String,
1040        reason: String,
1041    },
1042}
1043
1044impl std::fmt::Display for ArgError {
1045    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1046        match self {
1047            ArgError::Missing { name, takes } => write!(
1048                f,
1049                "required argument `{name}` was not supplied: it must be {takes}"
1050            ),
1051            ArgError::Unknown { name, takes } => write!(
1052                f,
1053                "`{name}` is not a parameter of this action; its arguments are {takes}"
1054            ),
1055            ArgError::WrongType {
1056                name,
1057                expected,
1058                got,
1059                shape,
1060            } => write!(
1061                f,
1062                "argument `{name}` was given {} and must be {}: {shape}",
1063                refused::kind(*got),
1064                refused::kind(*expected)
1065            ),
1066            ArgError::NotAllowed {
1067                name,
1068                given,
1069                allowed,
1070            } => write!(
1071                f,
1072                "argument `{name}` must be one of {}; it was given {given} that is none of them",
1073                allowed.join(", ")
1074            ),
1075            ArgError::Unrepresentable { name } => {
1076                write!(f, "argument `{name}` has an unsupported JSON value")
1077            }
1078            ArgError::Constraint { name, reason } => {
1079                write!(f, "argument `{name}` {reason}")
1080            }
1081            ArgError::OutOfRange { name, violation } => {
1082                write!(f, "argument `{name}` {violation}")
1083            }
1084        }
1085    }
1086}
1087
1088impl std::error::Error for ArgError {}
1089
1090/// Arguments for one invocation, already checked against the action's declared
1091/// parameters.
1092///
1093/// There is no way to build one except through [`bind`](Self::bind) or
1094/// [`none`](Self::none), so an action's builder never has to re-validate: if it
1095/// holds an `ActionArgs`, every required parameter is present and every value
1096/// has the declared type. That is what keeps a bad call from becoming a
1097/// half-applied edit.
1098#[derive(Clone, Debug, Default, PartialEq)]
1099pub struct ActionArgs {
1100    values: BTreeMap<String, ArgValue>,
1101    from: Option<MadeFrom>,
1102}
1103
1104/// The argument key a caller names the resource it makes the invocation from with: what the
1105/// resources the action makes were made from (`created(r)?.from`, `linked(r)`). It is no
1106/// parameter of any action, and every builder may read it, the ones that record provenance and
1107/// the ones that ignore it alike.
1108pub const FROM_ARGUMENT: &str = "$from";
1109
1110/// The resource an invocation is made from: its address, as the caller names it, and the
1111/// type it points at.
1112#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
1113pub struct MadeFrom {
1114    pub resource: String,
1115    pub kind: String,
1116}
1117
1118impl MadeFrom {
1119    /// The address and type of a reference argument (`{"ref": "…", "ty": "…"}`): the shape a
1120    /// reference travels in, and the one [`Self::to_json`] writes.
1121    #[must_use]
1122    pub fn from_json(value: &serde_json::Value) -> Option<Self> {
1123        let object = value.as_object()?;
1124        Some(Self {
1125            resource: object.get("ref")?.as_str()?.to_owned(),
1126            kind: object.get("ty")?.as_str()?.to_owned(),
1127        })
1128    }
1129
1130    /// This as a reference argument.
1131    #[must_use]
1132    pub fn to_json(&self) -> serde_json::Value {
1133        serde_json::json!({"ref": self.resource, "ty": self.kind})
1134    }
1135
1136    /// The app whose resource this is, where its kind names it as a tilolang app stores it
1137    /// (`tl.<app>.<Type>`): the app at whose node a read of it is decided. `None` for a kind
1138    /// that names no app.
1139    #[must_use]
1140    pub fn app(&self) -> Option<&str> {
1141        let (app, kind) = self.kind.strip_prefix("tl.")?.rsplit_once('.')?;
1142        (!app.is_empty() && !kind.is_empty()).then_some(app)
1143    }
1144}
1145
1146/// A typed reference to an item an earlier member of one group made:
1147/// `{"$made": {"member": 0, "item": 0}}`, where `member` is the place of the
1148/// invocation in the group (counted from 0) and `item` the one it made
1149/// (counted from 0, in the order it made them). A group is one change, so a
1150/// later member can name what an earlier one creates though neither has run
1151/// when the call is made: the framework puts the id that member minted in the
1152/// reference's place as the group applies, and the change keeps the reference
1153/// itself, so every replica puts the same id there.
1154pub const MADE: &str = "$made";
1155
1156/// The word a bound [`MADE`] reference carries, until the group applies.
1157#[must_use]
1158pub fn made_marker(member: usize, item: usize) -> String {
1159    format!("{MADE}:{member}:{item}")
1160}
1161
1162/// The member and item `value` names, when it is a [`MADE`] reference.
1163#[must_use]
1164pub fn made_reference(value: &serde_json::Value) -> Option<(usize, usize)> {
1165    let reference = value.get(MADE)?;
1166    let number = |key: &str| {
1167        reference
1168            .get(key)
1169            .and_then(serde_json::Value::as_u64)
1170            .and_then(|number| usize::try_from(number).ok())
1171    };
1172    Some((number("member")?, number("item")?))
1173}
1174
1175/// The member and item `text` names, when it is a [`made_marker`].
1176#[must_use]
1177pub fn made_of_marker(text: &str) -> Option<(usize, usize)> {
1178    let rest = text.strip_prefix(MADE)?.strip_prefix(':')?;
1179    let (member, item) = rest.split_once(':')?;
1180    Some((member.parse().ok()?, item.parse().ok()?))
1181}
1182
1183impl ActionArgs {
1184    /// The empty argument set — what a nullary action is invoked with.
1185    pub fn none() -> Self {
1186        Self::default()
1187    }
1188
1189    /// The resource this invocation is made from, when it is made from one.
1190    #[must_use]
1191    pub fn from(&self) -> Option<&MadeFrom> {
1192        self.from.as_ref()
1193    }
1194
1195    /// This invocation as one made from `from`.
1196    #[must_use]
1197    pub fn with_from(mut self, from: Option<MadeFrom>) -> Self {
1198        self.from = from;
1199        self
1200    }
1201
1202    /// Check `supplied` against `params` and bind it.
1203    ///
1204    /// Fails on the first problem rather than accumulating: the caller has to
1205    /// fix them one at a time anyway, and a partial bind must never reach an
1206    /// action.
1207    pub fn bind(
1208        params: &[ActionParam],
1209        supplied: impl IntoIterator<Item = (String, ArgValue)>,
1210    ) -> Result<Self, ArgError> {
1211        let mut values: BTreeMap<String, ArgValue> = BTreeMap::new();
1212        for (name, value) in supplied {
1213            let Some(param) = params.iter().find(|p| p.name.as_ref() == name.as_str()) else {
1214                // An unknown argument is refused rather than dropped. A silently
1215                // ignored argument is the failure mode this whole surface exists
1216                // to remove: the caller believes it asked for something it did
1217                // not get.
1218                return Err(refused::unknown(name, params));
1219            };
1220            // Callers (models especially) write null for "not set": for an
1221            // optional parameter that is leaving it out. A nullable one
1222            // takes null as its value.
1223            if matches!(value, ArgValue::Null) && !param.nullable && !param.required {
1224                continue;
1225            }
1226            if matches!(value, ArgValue::Null) && !param.nullable {
1227                return Err(refused::null(param));
1228            }
1229            if !matches!(value, ArgValue::Null)
1230                && !value.satisfies(param.ty)
1231                && !schema_alternative_of(param, &value)
1232            {
1233                return Err(refused::wrong_type(param, &value));
1234            }
1235            match &value {
1236                ArgValue::Number(number) if !number.is_finite() => {
1237                    return Err(ArgError::Constraint {
1238                        name,
1239                        reason: "must be a finite number".into(),
1240                    });
1241                }
1242                ArgValue::Resource(address)
1243                    if address.trim().is_empty()
1244                        || address.contains(crate::KEY_SEP)
1245                        || !address.contains(':') =>
1246                {
1247                    return Err(ArgError::Constraint {
1248                        name,
1249                        reason: "must be a stable resource address (`kind:id`)".into(),
1250                    });
1251                }
1252                ArgValue::DateTime(value) if !looks_like_rfc3339(value) => {
1253                    return Err(ArgError::Constraint {
1254                        name,
1255                        reason: "must be an RFC 3339 date-time with a timezone".into(),
1256                    });
1257                }
1258                _ => {}
1259            }
1260            if let Some(schema) = &param.schema {
1261                validate_shared_schema_definition(schema).map_err(|reason| {
1262                    ArgError::Constraint {
1263                        name: name.clone(),
1264                        reason,
1265                    }
1266                })?;
1267                check_schema_value(&value.to_json(), schema).map_err(|refusal| match refusal {
1268                    SchemaRefusal::Bound(violation) => ArgError::OutOfRange {
1269                        name: name.clone(),
1270                        violation,
1271                    },
1272                    SchemaRefusal::Other(reason) => ArgError::Constraint {
1273                        name: name.clone(),
1274                        reason,
1275                    },
1276                })?;
1277            }
1278            if !param.choices.is_empty() {
1279                let got = match &value {
1280                    ArgValue::Text(s)
1281                    | ArgValue::Resource(s)
1282                    | ArgValue::DateTime(s)
1283                    | ArgValue::Secret(s) => s.clone(),
1284                    other => other.to_json().to_string(),
1285                };
1286                if !param.choices.iter().any(|c| c.as_ref() == got.as_str()) {
1287                    return Err(refused::not_a_choice(param, &value));
1288                }
1289            }
1290            values.insert(name, value);
1291        }
1292        for param in params.iter().filter(|p| p.required) {
1293            if !values.contains_key(param.name.as_ref()) {
1294                return Err(refused::missing(param));
1295            }
1296        }
1297        hold_to_decided_shapes(params, &values)?;
1298        Ok(Self { values, from: None })
1299    }
1300
1301    /// Bind arguments that arrived as a JSON object — the shape a control
1302    /// socket delivers.
1303    pub fn bind_json(
1304        params: &[ActionParam],
1305        supplied: &serde_json::Map<String, serde_json::Value>,
1306    ) -> Result<Self, ArgError> {
1307        let mut pairs = Vec::with_capacity(supplied.len());
1308        for (name, value) in supplied {
1309            // What the invocation is made from is no parameter of the action.
1310            if name == FROM_ARGUMENT {
1311                continue;
1312            }
1313            let Some(param) = params.iter().find(|param| param.name.as_ref() == name) else {
1314                return Err(refused::unknown(name.clone(), params));
1315            };
1316            let value = match (param.ty, value) {
1317                (ParamType::Resource, serde_json::Value::String(value)) => {
1318                    Some(ArgValue::Resource(value.clone()))
1319                }
1320                // A reference to an item an earlier member of one group made:
1321                // bound as the marker the group fills with that member's id
1322                // as it applies, so a later member can name what an earlier
1323                // one creates before either has run.
1324                (ParamType::Text | ParamType::Resource, value)
1325                    if made_reference(value).is_some() =>
1326                {
1327                    made_reference(value)
1328                        .map(|(member, item)| ArgValue::Text(made_marker(member, item)))
1329                }
1330                (ParamType::DateTime, serde_json::Value::String(value)) => {
1331                    Some(ArgValue::DateTime(value.clone()))
1332                }
1333                (ParamType::Secret, serde_json::Value::String(value)) => {
1334                    Some(ArgValue::Secret(value.clone()))
1335                }
1336                _ => ArgValue::from_json(value),
1337            };
1338            let Some(v) = value else {
1339                return Err(ArgError::Unrepresentable { name: name.clone() });
1340            };
1341            pairs.push((name.clone(), v));
1342        }
1343        let from = supplied.get(FROM_ARGUMENT).and_then(MadeFrom::from_json);
1344        Self::bind(params, pairs).map(|args| args.with_from(from))
1345    }
1346
1347    pub fn text(&self, name: &str) -> Option<&str> {
1348        match self.values.get(name) {
1349            Some(
1350                ArgValue::Text(s)
1351                | ArgValue::Resource(s)
1352                | ArgValue::DateTime(s)
1353                | ArgValue::Secret(s),
1354            ) => Some(s.as_str()),
1355            _ => None,
1356        }
1357    }
1358
1359    /// The integer bound to `name`, where it fits one a caller works in.
1360    pub fn integer(&self, name: &str) -> Option<i64> {
1361        match self.values.get(name) {
1362            Some(ArgValue::Integer(i)) => i64::try_from(*i).ok(),
1363            _ => None,
1364        }
1365    }
1366
1367    /// The whole number bound to `name`, as wide as the id it names.
1368    pub fn whole(&self, name: &str) -> Option<u64> {
1369        match self.values.get(name) {
1370            Some(ArgValue::Integer(i)) => u64::try_from(*i).ok(),
1371            _ => None,
1372        }
1373    }
1374
1375    pub fn array(&self, name: &str) -> Option<&[serde_json::Value]> {
1376        match self.values.get(name) {
1377            Some(ArgValue::Array(values)) => Some(values),
1378            _ => None,
1379        }
1380    }
1381
1382    /// The number bound to `name`, if any. An integer argument widens, matching
1383    /// [`ArgValue::satisfies`].
1384    #[allow(
1385        clippy::cast_precision_loss,
1386        reason = "Number parameters deliberately widen integer JSON values to f64"
1387    )]
1388    pub fn number(&self, name: &str) -> Option<f64> {
1389        match self.values.get(name) {
1390            Some(ArgValue::Number(f)) => Some(*f),
1391            Some(ArgValue::Integer(i)) => Some(*i as f64),
1392            _ => None,
1393        }
1394    }
1395
1396    pub fn boolean(&self, name: &str) -> Option<bool> {
1397        match self.values.get(name) {
1398            Some(ArgValue::Boolean(b)) => Some(*b),
1399            _ => None,
1400        }
1401    }
1402
1403    /// The raw bound value, for a caller that wants to switch on the type.
1404    pub fn get(&self, name: &str) -> Option<&ArgValue> {
1405        self.values.get(name)
1406    }
1407
1408    /// Whether anything is bound.
1409    pub fn is_empty(&self) -> bool {
1410        self.values.is_empty()
1411    }
1412
1413    /// Every bound argument as JSON — the inverse of
1414    /// [`bind_json`](Self::bind_json), so a caller can echo back exactly what it
1415    /// sent.
1416    pub fn to_json(&self) -> serde_json::Map<String, serde_json::Value> {
1417        self.values
1418            .iter()
1419            .map(|(k, v)| (k.clone(), v.to_json()))
1420            .collect()
1421    }
1422}
1423
1424/// Whether `value` is an RFC 3339 date and time, as JSON Schema's `date-time` names one:
1425/// `2026-01-31T09:00:00Z`, with `T`, `t` or ` ` between the date and the time, any fraction of a
1426/// second, a leap second, and `Z` or an offset such as `+01:00`. Read field by field rather than through a date
1427/// library, whose whole calendar and time-zone parser a browser page would download for this one
1428/// check.
1429fn looks_like_rfc3339(value: &str) -> bool {
1430    let bytes = value.as_bytes();
1431    let at = |index: usize| bytes.get(index).copied();
1432    // The number the `count` digits from `start` spell, if they all are digits.
1433    let digits = |start: usize, count: usize| -> Option<u32> {
1434        bytes
1435            .get(start..start.checked_add(count)?)?
1436            .iter()
1437            .try_fold(0_u32, |sum, digit| {
1438                let digit = char::from(*digit).to_digit(10)?;
1439                sum.checked_mul(10)?.checked_add(digit)
1440            })
1441    };
1442    let (Some(year), Some(month), Some(day), Some(hour), Some(minute), Some(second)) = (
1443        digits(0, 4),
1444        digits(5, 2),
1445        digits(8, 2),
1446        digits(11, 2),
1447        digits(14, 2),
1448        digits(17, 2),
1449    ) else {
1450        return false;
1451    };
1452    let leap = (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400);
1453    let days = match month {
1454        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
1455        4 | 6 | 9 | 11 => 30,
1456        2 if leap => 29,
1457        2 => 28,
1458        _ => return false,
1459    };
1460    let separated = at(4) == Some(b'-')
1461        && at(7) == Some(b'-')
1462        && matches!(at(10), Some(b'T' | b't' | b' '))
1463        && at(13) == Some(b':')
1464        && at(16) == Some(b':');
1465    if !separated || !(1..=days).contains(&day) || hour > 23 || minute > 59 || second > 60 {
1466        return false;
1467    }
1468    // Where the offset starts: after the seconds, or after their fraction.
1469    let mut zone = 19;
1470    if at(zone) == Some(b'.') {
1471        let fraction = bytes
1472            .iter()
1473            .skip(20)
1474            .take_while(|digit| digit.is_ascii_digit())
1475            .count();
1476        if fraction == 0 {
1477            return false;
1478        }
1479        zone = fraction.saturating_add(20);
1480    }
1481    let rest = bytes.get(zone..).unwrap_or_default();
1482    match rest {
1483        [b'Z' | b'z'] => true,
1484        [b'+' | b'-', _, _, b':', _, _] => {
1485            digits(zone.saturating_add(1), 2).is_some_and(|hours| hours <= 23)
1486                && digits(zone.saturating_add(4), 2).is_some_and(|minutes| minutes <= 59)
1487        }
1488        _ => false,
1489    }
1490}
1491
1492/// Distinct schema patterns kept compiled. A directory publishes a handful;
1493/// past this the cache starts again rather than growing with whatever a
1494/// caller's schemas name.
1495const COMPILED_PATTERNS: usize = 64;
1496
1497/// `pattern` compiled, from the cache when an earlier argument or schema
1498/// already compiled it: every validated value used to compile its schema's
1499/// pattern again.
1500fn schema_pattern(pattern: &str) -> Result<regex_lite::Regex, regex_lite::Error> {
1501    static COMPILED: std::sync::LazyLock<
1502        std::sync::Mutex<std::collections::HashMap<String, regex_lite::Regex>>,
1503    > = std::sync::LazyLock::new(std::sync::Mutex::default);
1504    let mut compiled = COMPILED.lock_recover();
1505    if let Some(expression) = compiled.get(pattern) {
1506        return Ok(expression.clone());
1507    }
1508    let expression = regex_lite::Regex::new(pattern)?;
1509    if compiled.len() >= COMPILED_PATTERNS {
1510        compiled.clear();
1511    }
1512    compiled.insert(pattern.to_owned(), expression.clone());
1513    drop(compiled);
1514    Ok(expression)
1515}
1516
1517fn validate_string_schema(
1518    text: &str,
1519    schema: &serde_json::Map<String, serde_json::Value>,
1520) -> Result<(), String> {
1521    let length = u64::try_from(text.chars().count()).unwrap_or(u64::MAX);
1522    if let Some(minimum) = schema.get("minLength").and_then(serde_json::Value::as_u64)
1523        && length < minimum
1524    {
1525        return Err(format!("must contain at least {minimum} characters"));
1526    }
1527    if let Some(maximum) = schema.get("maxLength").and_then(serde_json::Value::as_u64)
1528        && length > maximum
1529    {
1530        return Err(format!("must contain at most {maximum} characters"));
1531    }
1532    if let Some(pattern) = schema.get("pattern") {
1533        let pattern = pattern
1534            .as_str()
1535            .ok_or_else(|| "has a non-string schema pattern".to_string())?;
1536        let expression = schema_pattern(pattern)
1537            .map_err(|error| format!("has an invalid schema pattern: {error}"))?;
1538        if !expression.is_match(text) {
1539            return Err(format!("must match pattern `{pattern}`"));
1540        }
1541    }
1542    if let Some(format) = schema.get("format") {
1543        let format = format
1544            .as_str()
1545            .ok_or_else(|| "has a non-string schema format".to_string())?;
1546        let valid = match format {
1547            "date-time" => looks_like_rfc3339(text),
1548            // RFC 3339's full-date is the date of a date-time.
1549            "date" => text.len() == 10 && looks_like_rfc3339(&format!("{text}T00:00:00Z")),
1550            "uuid" => uuid::Uuid::parse_str(text).is_ok(),
1551            "uri" => text.split_once(':').is_some_and(|(scheme, rest)| {
1552                !scheme.is_empty()
1553                    && !rest.is_empty()
1554                    && scheme
1555                        .chars()
1556                        .next()
1557                        .is_some_and(|ch| ch.is_ascii_alphabetic())
1558                    && scheme
1559                        .chars()
1560                        .skip(1)
1561                        .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '+' | '-' | '.'))
1562                    && !text.chars().any(char::is_whitespace)
1563            }),
1564            _ => return Err(format!("uses unsupported schema format `{format}`")),
1565        };
1566        if !valid {
1567            return Err(refused::off_format(format, schema));
1568        }
1569    }
1570    Ok(())
1571}
1572
1573fn validate_object_schema(
1574    object: &serde_json::Map<String, serde_json::Value>,
1575    schema: &serde_json::Map<String, serde_json::Value>,
1576) -> Result<(), String> {
1577    if let Some(required) = schema.get("required").and_then(serde_json::Value::as_array) {
1578        for key in required.iter().filter_map(serde_json::Value::as_str) {
1579            if !object.contains_key(key) {
1580                return Err(refused::lacks(key, schema));
1581            }
1582        }
1583    }
1584    if let Some(properties) = schema
1585        .get("properties")
1586        .and_then(serde_json::Value::as_object)
1587    {
1588        for (key, property_schema) in properties {
1589            if let Some(property) = object.get(key) {
1590                validate_schema_value(property, property_schema)
1591                    .map_err(|reason| format!("property `{key}` {reason}"))?;
1592            }
1593        }
1594    }
1595    // What the object declares of the keys it does not list: `false` takes
1596    // none, and a schema holds the value under each of them (a map's values).
1597    let listed = |key: &str| {
1598        schema
1599            .get("properties")
1600            .and_then(serde_json::Value::as_object)
1601            .is_some_and(|properties| properties.contains_key(key))
1602    };
1603    match schema.get("additionalProperties") {
1604        Some(serde_json::Value::Bool(false)) => {
1605            if let Some(key) = object.keys().find(|key| !listed(key.as_str())) {
1606                return Err(refused::takes_no(key, schema));
1607            }
1608        }
1609        Some(of_its_own @ serde_json::Value::Object(_)) => {
1610            // Such a key is the caller's own, so a refusal never says it.
1611            for (key, value) in object {
1612                if !listed(key.as_str()) {
1613                    validate_schema_value(value, of_its_own)
1614                        .map_err(|reason| format!("property <key> {reason}"))?;
1615                }
1616            }
1617        }
1618        _ => {}
1619    }
1620    Ok(())
1621}
1622
1623/// Validate the commonly useful, deterministic JSON Schema vocabulary used by
1624/// action inputs and outputs. Unknown annotations are intentionally ignored;
1625/// all assertion keywords accepted here are enforced centrally.
1626pub(crate) fn validate_schema(
1627    value: &serde_json::Value,
1628    schema: &serde_json::Value,
1629) -> Result<(), String> {
1630    check_schema(value, schema).map_err(|refusal| refusal.to_string())
1631}
1632
1633/// Why a value failed its schema: a numeric bound its top level declares,
1634/// as data, or anything else, in words.
1635enum SchemaRefusal {
1636    Bound(ArgViolation),
1637    Other(String),
1638}
1639
1640impl From<String> for SchemaRefusal {
1641    fn from(reason: String) -> Self {
1642        Self::Other(reason)
1643    }
1644}
1645
1646impl From<ArgViolation> for SchemaRefusal {
1647    fn from(violation: ArgViolation) -> Self {
1648        Self::Bound(violation)
1649    }
1650}
1651
1652impl std::fmt::Display for SchemaRefusal {
1653    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1654        match self {
1655            Self::Bound(violation) => violation.fmt(f),
1656            Self::Other(reason) => f.write_str(reason),
1657        }
1658    }
1659}
1660
1661/// [`validate_schema`], keeping a refusal by the top level's own numeric
1662/// bound as data. A bound nested inside is refused in words, as part of the
1663/// property or item it bounds.
1664/// Hold each argument whose shape another argument's value decides
1665/// ([`SHAPED_BY_ANNOTATION`]) against the shape that value names, in the
1666/// words of every refused argument. An argument left out is asked for with
1667/// the shape, unless the shape takes nothing.
1668fn hold_to_decided_shapes(
1669    params: &[ActionParam],
1670    values: &BTreeMap<String, ArgValue>,
1671) -> Result<(), ArgError> {
1672    for param in params {
1673        let Some((argument, shapes)) = param.shapes_by() else {
1674            continue;
1675        };
1676        let Some(ArgValue::Text(decides)) = values.get(argument) else {
1677            continue;
1678        };
1679        let Some(shape) = shapes.get(decides.as_str()) else {
1680            continue;
1681        };
1682        let name = param.name.to_string();
1683        if let Some(own) = &param.schema {
1684            validate_shared_schema_definition(own).map_err(|reason| ArgError::Constraint {
1685                name: name.clone(),
1686                reason,
1687            })?;
1688        }
1689        let Some(given) = values.get(param.name.as_ref()).map(ArgValue::to_json) else {
1690            if check_schema_value(&serde_json::Value::Null, shape).is_ok() {
1691                continue;
1692            }
1693            return Err(refused::missing_shaped(param, shape));
1694        };
1695        check_schema_value(&given, shape).map_err(|refusal| match refusal {
1696            SchemaRefusal::Bound(violation) => ArgError::OutOfRange {
1697                name: name.clone(),
1698                violation,
1699            },
1700            SchemaRefusal::Other(reason) => ArgError::Constraint {
1701                name: name.clone(),
1702                reason,
1703            },
1704        })?;
1705    }
1706    Ok(())
1707}
1708
1709fn check_schema(
1710    value: &serde_json::Value,
1711    schema: &serde_json::Value,
1712) -> Result<(), SchemaRefusal> {
1713    // Check even branches the value never visits before enforcing the contract.
1714    validate_schema_definition(schema)?;
1715    check_schema_value(value, schema)
1716}
1717
1718fn validate_schema_value(
1719    value: &serde_json::Value,
1720    schema: &serde_json::Value,
1721) -> Result<(), String> {
1722    check_schema_value(value, schema).map_err(|refusal| refusal.to_string())
1723}
1724
1725/// Whether `param`'s schema offers `value`'s JSON type as one of its
1726/// alternatives (`oneOf`), beside the parameter's own type: a byte parameter
1727/// takes its bytes inline, as an array, or a content reference, as a string.
1728/// The schema then decides which alternative the value is.
1729fn schema_alternative_of(param: &ActionParam, value: &ArgValue) -> bool {
1730    let json_type = match value.to_json() {
1731        serde_json::Value::String(_) => "string",
1732        serde_json::Value::Number(number) if number.is_i64() || number.is_u64() => "integer",
1733        serde_json::Value::Number(_) => "number",
1734        serde_json::Value::Bool(_) => "boolean",
1735        serde_json::Value::Object(_) => "object",
1736        serde_json::Value::Array(_) => "array",
1737        serde_json::Value::Null => return false,
1738    };
1739    param
1740        .schema
1741        .as_deref()
1742        .is_some_and(|schema| has_alternative(schema, json_type))
1743}
1744
1745/// Whether one of `schema`'s alternatives, or theirs (an optional value's
1746/// alternatives), is of `json_type`.
1747fn has_alternative(schema: &serde_json::Value, json_type: &str) -> bool {
1748    schema
1749        .get("oneOf")
1750        .and_then(serde_json::Value::as_array)
1751        .is_some_and(|alternatives| {
1752            alternatives.iter().any(|alternative| {
1753                alternative.get("type").and_then(serde_json::Value::as_str) == Some(json_type)
1754                    || has_alternative(alternative, json_type)
1755            })
1756        })
1757}
1758
1759fn check_schema_value(
1760    value: &serde_json::Value,
1761    schema: &serde_json::Value,
1762) -> Result<(), SchemaRefusal> {
1763    let Some(schema) = schema.as_object() else {
1764        return Err(SchemaRefusal::Other(
1765            "has a schema that is not an object".into(),
1766        ));
1767    };
1768    if let Some(alternatives) = schema.get("oneOf").and_then(serde_json::Value::as_array) {
1769        validate_one_of(value, alternatives)?;
1770    }
1771    validate_schema_type(value, schema)?;
1772    validate_schema_equality(value, schema)?;
1773    validate_schema_number(value, schema)?;
1774    validate_schema_string(value, schema)?;
1775    validate_schema_array(value, schema)?;
1776    validate_schema_object(value, schema)?;
1777    Ok(())
1778}
1779
1780/// Exactly one alternative must accept `value`. When none does, the refusal
1781/// says why in terms of the alternative the value evidently meant — the one
1782/// whose required keys and constants it has (`{"SpliceText": {..}}` meant
1783/// the `SpliceText` alternative) — or else names the alternatives, so a
1784/// caller can correct the call rather than guess.
1785fn validate_one_of(
1786    value: &serde_json::Value,
1787    alternatives: &[serde_json::Value],
1788) -> Result<(), String> {
1789    let mut failures = Vec::new();
1790    let mut matched = 0_usize;
1791    for alternative in alternatives {
1792        match validate_schema_value(value, alternative) {
1793            Ok(()) => matched = matched.saturating_add(1),
1794            Err(reason) => failures.push((alternative, reason)),
1795        }
1796    }
1797    match matched {
1798        1 => return Ok(()),
1799        0 => {}
1800        _ => return Err("matches more than one `oneOf` alternative".into()),
1801    }
1802    let meant: Vec<_> = failures
1803        .iter()
1804        .filter(|(alternative, _)| selects(value, alternative))
1805        .collect();
1806    if let [(alternative, reason)] = meant.as_slice() {
1807        return Err(match alternative_name(alternative) {
1808            Some(name) => format!("as `{name}`: {reason}"),
1809            None => reason.clone(),
1810        });
1811    }
1812    let names: Option<Vec<String>> = alternatives.iter().map(alternative_name).collect();
1813    Err(match names {
1814        Some(names) if !names.is_empty() => format!("must be one of: {}", names.join(", ")),
1815        _ => refused::no_alternative(alternatives),
1816    })
1817}
1818
1819/// Whether `value` carries what tells `alternative` apart: the values of its
1820/// constant or enumerated properties (a tag, or one of several), or else all
1821/// of its required keys.
1822fn selects(value: &serde_json::Value, alternative: &serde_json::Value) -> bool {
1823    let Some(schema) = alternative.as_object() else {
1824        return false;
1825    };
1826    if let Some(expected) = schema.get("const") {
1827        return value == expected;
1828    }
1829    let Some(object) = value.as_object() else {
1830        return false;
1831    };
1832    let tags: Vec<(&String, &serde_json::Value)> = schema
1833        .get("properties")
1834        .and_then(serde_json::Value::as_object)
1835        .into_iter()
1836        .flatten()
1837        .filter(|(_, property)| property.get("const").is_some() || property.get("enum").is_some())
1838        .collect();
1839    if !tags.is_empty() {
1840        return tags.iter().all(|(key, property)| {
1841            object.get(key.as_str()).is_some_and(|given| {
1842                property.get("const") == Some(given)
1843                    || property
1844                        .get("enum")
1845                        .and_then(serde_json::Value::as_array)
1846                        .is_some_and(|names| names.contains(given))
1847            })
1848        });
1849    }
1850    let required = schema
1851        .get("required")
1852        .and_then(serde_json::Value::as_array)
1853        .map_or(&[][..], Vec::as_slice);
1854    !required.is_empty()
1855        && required
1856            .iter()
1857            .filter_map(serde_json::Value::as_str)
1858            .all(|key| object.contains_key(key))
1859}
1860
1861/// What an alternative is called: its title, its constant, the constant of
1862/// its first required property, or its one required key.
1863fn alternative_name(alternative: &serde_json::Value) -> Option<String> {
1864    let schema = alternative.as_object()?;
1865    if let Some(title) = schema.get("title").and_then(serde_json::Value::as_str) {
1866        return Some(title.to_owned());
1867    }
1868    if let Some(constant) = schema.get("const") {
1869        return Some(
1870            constant
1871                .as_str()
1872                .map_or_else(|| constant.to_string(), str::to_owned),
1873        );
1874    }
1875    let required = schema.get("required")?.as_array()?;
1876    let first = required.first()?.as_str()?;
1877    if let Some(constant) = schema
1878        .get("properties")
1879        .and_then(|properties| properties.get(first))
1880        .and_then(|property| property.get("const"))
1881        .and_then(serde_json::Value::as_str)
1882    {
1883        return Some(constant.to_owned());
1884    }
1885    (required.len() == 1).then(|| first.to_owned())
1886}
1887
1888fn validate_schema_type(
1889    value: &serde_json::Value,
1890    schema: &serde_json::Map<String, serde_json::Value>,
1891) -> Result<(), String> {
1892    if let Some(expected) = schema.get("type") {
1893        let matches_type = |name: &str| match name {
1894            "null" => value.is_null(),
1895            "boolean" => value.is_boolean(),
1896            "object" => value.is_object(),
1897            "array" => value.is_array(),
1898            "number" => value.is_number(),
1899            "integer" => value
1900                .as_number()
1901                .is_some_and(|number| number.as_i64().is_some() || number.as_u64().is_some()),
1902            "string" => value.is_string(),
1903            _ => false,
1904        };
1905        let valid = expected.as_str().is_some_and(matches_type)
1906            || expected.as_array().is_some_and(|types| {
1907                !types.is_empty()
1908                    && types.iter().all(serde_json::Value::is_string)
1909                    && types
1910                        .iter()
1911                        .filter_map(serde_json::Value::as_str)
1912                        .any(matches_type)
1913            });
1914        if !valid {
1915            return Err(refused::wrong_kind(value, schema));
1916        }
1917    }
1918    Ok(())
1919}
1920
1921fn validate_schema_equality(
1922    value: &serde_json::Value,
1923    schema: &serde_json::Map<String, serde_json::Value>,
1924) -> Result<(), String> {
1925    if let Some(values) = schema.get("enum").and_then(serde_json::Value::as_array)
1926        && !values.contains(value)
1927    {
1928        return Err(refused::none_of(values));
1929    }
1930    if let Some(expected) = schema.get("const")
1931        && value != expected
1932    {
1933        return Err(format!("must be {expected}"));
1934    }
1935    Ok(())
1936}
1937
1938fn validate_schema_number(
1939    value: &serde_json::Value,
1940    schema: &serde_json::Map<String, serde_json::Value>,
1941) -> Result<(), ArgViolation> {
1942    if let Some(minimum) = schema
1943        .get("minimum")
1944        .filter(|minimum| past(value, minimum, Side::Below))
1945    {
1946        return Err(ArgViolation::Minimum {
1947            bound: minimum.clone(),
1948        });
1949    }
1950    if let Some(maximum) = schema
1951        .get("maximum")
1952        .filter(|maximum| past(value, maximum, Side::Above))
1953    {
1954        return Err(ArgViolation::Maximum {
1955            bound: maximum.clone(),
1956        });
1957    }
1958    Ok(())
1959}
1960
1961/// Which side of a bound is out.
1962#[derive(Clone, Copy)]
1963enum Side {
1964    Below,
1965    Above,
1966}
1967
1968/// Whether `value` lies past `bound` on `side`. Two whole numbers compare exactly: as floats,
1969/// an id past 2^53 compares equal to its neighbour.
1970fn past(value: &serde_json::Value, bound: &serde_json::Value, side: Side) -> bool {
1971    if let (Some(value), Some(bound)) = (whole(value), whole(bound)) {
1972        return match side {
1973            Side::Below => value < bound,
1974            Side::Above => value > bound,
1975        };
1976    }
1977    let (Some(value), Some(bound)) = (value.as_f64(), bound.as_f64()) else {
1978        return false;
1979    };
1980    match side {
1981        Side::Below => value < bound,
1982        Side::Above => value > bound,
1983    }
1984}
1985
1986/// A JSON number as the whole number it is, when it is one.
1987fn whole(value: &serde_json::Value) -> Option<i128> {
1988    value
1989        .as_i64()
1990        .map(i128::from)
1991        .or_else(|| value.as_u64().map(i128::from))
1992}
1993
1994fn validate_schema_string(
1995    value: &serde_json::Value,
1996    schema: &serde_json::Map<String, serde_json::Value>,
1997) -> Result<(), String> {
1998    if let Some(text) = value.as_str() {
1999        validate_string_schema(text, schema)?;
2000    }
2001    Ok(())
2002}
2003
2004fn validate_schema_array(
2005    value: &serde_json::Value,
2006    schema: &serde_json::Map<String, serde_json::Value>,
2007) -> Result<(), String> {
2008    if let Some(items) = value.as_array() {
2009        let length = u64::try_from(items.len()).unwrap_or(u64::MAX);
2010        if let Some(minimum) = schema.get("minItems").and_then(serde_json::Value::as_u64)
2011            && length < minimum
2012        {
2013            return Err(format!("must contain at least {minimum} items"));
2014        }
2015        if let Some(maximum) = schema.get("maxItems").and_then(serde_json::Value::as_u64)
2016            && length > maximum
2017        {
2018            return Err(format!("must contain at most {maximum} items"));
2019        }
2020        if schema
2021            .get("uniqueItems")
2022            .and_then(serde_json::Value::as_bool)
2023            .unwrap_or(false)
2024            && items
2025                .iter()
2026                .enumerate()
2027                .any(|(index, item)| items.get(..index).is_some_and(|prior| prior.contains(item)))
2028        {
2029            return Err("must contain unique items".into());
2030        }
2031        // `prefixItems` checks the leading items one schema each; `items`
2032        // the ones after them (JSON Schema 2020-12).
2033        let prefix = schema
2034            .get("prefixItems")
2035            .and_then(serde_json::Value::as_array)
2036            .map_or(&[][..], Vec::as_slice);
2037        for (index, (item, item_schema)) in items.iter().zip(prefix).enumerate() {
2038            validate_schema_value(item, item_schema)
2039                .map_err(|reason| format!("item {index} {reason}"))?;
2040        }
2041        if let Some(item_schema) = schema.get("items") {
2042            for (index, item) in items.iter().enumerate().skip(prefix.len()) {
2043                validate_schema_value(item, item_schema)
2044                    .map_err(|reason| format!("item {index} {reason}"))?;
2045            }
2046        }
2047    }
2048    Ok(())
2049}
2050
2051fn validate_schema_object(
2052    value: &serde_json::Value,
2053    schema: &serde_json::Map<String, serde_json::Value>,
2054) -> Result<(), String> {
2055    if let Some(object) = value.as_object() {
2056        validate_object_schema(object, schema)?;
2057    }
2058    Ok(())
2059}
2060
2061/// Validate one JSON value against the deterministic JSON Schema subset used
2062/// by Tilo action contracts.
2063pub fn validate_json_schema(
2064    value: &serde_json::Value,
2065    schema: &serde_json::Value,
2066) -> Result<(), String> {
2067    validate_schema(value, schema)
2068}
2069
2070const SCHEMA_ASSERTIONS: &[&str] = &[
2071    "type",
2072    "enum",
2073    "const",
2074    "minimum",
2075    "maximum",
2076    "minLength",
2077    "maxLength",
2078    "pattern",
2079    "format",
2080    "minItems",
2081    "maxItems",
2082    "uniqueItems",
2083    "items",
2084    "prefixItems",
2085    "required",
2086    "properties",
2087    "additionalProperties",
2088    "oneOf",
2089];
2090const SCHEMA_ANNOTATIONS: &[&str] = &[
2091    "$schema",
2092    "$id",
2093    "$comment",
2094    "title",
2095    "description",
2096    "default",
2097    "examples",
2098    "deprecated",
2099    "readOnly",
2100    "writeOnly",
2101    RESOURCE_KIND_ANNOTATION,
2102    RESOURCE_KINDS_ANNOTATION,
2103    PLACE_ANNOTATION,
2104    CONTENT_ANNOTATION,
2105    CHOICE_LABELS_ANNOTATION,
2106    PEOPLE_ANNOTATION,
2107    PICK_ANNOTATION,
2108    SHAPED_BY_ANNOTATION,
2109];
2110
2111/// Validate the assertion vocabulary itself before a surface is published.
2112/// Runtime value validation is too late to discover a malformed regular
2113/// expression or an unsupported format: callers must be able to trust every
2114/// schema they enumerate.
2115pub(crate) fn validate_schema_definition(schema: &serde_json::Value) -> Result<(), String> {
2116    let object = schema
2117        .as_object()
2118        .ok_or_else(|| "schema must be an object".to_string())?;
2119    for keyword in object.keys() {
2120        if !SCHEMA_ASSERTIONS.contains(&keyword.as_str())
2121            && !SCHEMA_ANNOTATIONS.contains(&keyword.as_str())
2122        {
2123            return Err(format!(
2124                "schema uses unsupported keyword `{keyword}`; Tilo rejects unknown keywords instead of silently weakening a contract"
2125            ));
2126        }
2127    }
2128    validate_schema_definition_type(object)?;
2129    validate_schema_definition_strings(object)?;
2130    validate_schema_definition_collections(object)?;
2131    validate_schema_definition_shaped(object)?;
2132    validate_schema_definition_numbers(object)
2133}
2134
2135fn validate_schema_definition_type(
2136    object: &serde_json::Map<String, serde_json::Value>,
2137) -> Result<(), String> {
2138    if let Some(types) = object.get("type") {
2139        let supported = |name: &str| {
2140            matches!(
2141                name,
2142                "null" | "boolean" | "object" | "array" | "number" | "integer" | "string"
2143            )
2144        };
2145        let valid = types.as_str().is_some_and(supported)
2146            || types.as_array().is_some_and(|types| {
2147                !types.is_empty()
2148                    && types
2149                        .iter()
2150                        .all(|value| value.as_str().is_some_and(supported))
2151            });
2152        if !valid {
2153            return Err("schema has an unsupported `type`".into());
2154        }
2155    }
2156    Ok(())
2157}
2158
2159fn validate_schema_definition_strings(
2160    object: &serde_json::Map<String, serde_json::Value>,
2161) -> Result<(), String> {
2162    if let Some(pattern) = object.get("pattern") {
2163        let pattern = pattern
2164            .as_str()
2165            .ok_or_else(|| "schema `pattern` must be a string".to_string())?;
2166        schema_pattern(pattern)
2167            .map_err(|error| format!("schema has an invalid pattern: {error}"))?;
2168    }
2169    if let Some(format) = object.get("format") {
2170        let format = format
2171            .as_str()
2172            .ok_or_else(|| "schema `format` must be a string".to_string())?;
2173        if !matches!(format, "date" | "date-time" | "uuid" | "uri") {
2174            return Err(format!("schema uses unsupported format `{format}`"));
2175        }
2176    }
2177    Ok(())
2178}
2179
2180fn validate_schema_definition_collections(
2181    object: &serde_json::Map<String, serde_json::Value>,
2182) -> Result<(), String> {
2183    if let Some(required) = object.get("required")
2184        && !required
2185            .as_array()
2186            .is_some_and(|values| values.iter().all(serde_json::Value::is_string))
2187    {
2188        return Err("schema `required` must be an array of strings".into());
2189    }
2190    if object.get("enum").is_some_and(|values| !values.is_array()) {
2191        return Err("schema `enum` must be an array".into());
2192    }
2193    // `false` closes an object; a schema says what stands under the keys of
2194    // the caller's own (a map's values).
2195    match object.get("additionalProperties") {
2196        None | Some(serde_json::Value::Bool(_)) => {}
2197        Some(of_its_own @ serde_json::Value::Object(_)) => {
2198            validate_schema_definition(of_its_own)
2199                .map_err(|reason| format!("additionalProperties {reason}"))?;
2200        }
2201        Some(_) => {
2202            return Err("schema `additionalProperties` must be a boolean or a schema".into());
2203        }
2204    }
2205    if object
2206        .get("uniqueItems")
2207        .is_some_and(|value| !value.is_boolean())
2208    {
2209        return Err("schema `uniqueItems` must be a boolean".into());
2210    }
2211    if let Some(properties) = object.get("properties") {
2212        let properties = properties
2213            .as_object()
2214            .ok_or_else(|| "schema `properties` must be an object".to_string())?;
2215        for (name, child) in properties {
2216            validate_schema_definition(child)
2217                .map_err(|reason| format!("property `{name}` {reason}"))?;
2218        }
2219    }
2220    if let Some(items) = object.get("items") {
2221        validate_schema_definition(items).map_err(|reason| format!("items {reason}"))?;
2222    }
2223    if let Some(prefix) = object.get("prefixItems") {
2224        let prefix = prefix
2225            .as_array()
2226            .ok_or_else(|| "schema `prefixItems` must be an array".to_string())?;
2227        for (index, item) in prefix.iter().enumerate() {
2228            validate_schema_definition(item)
2229                .map_err(|reason| format!("prefixItems {index} {reason}"))?;
2230        }
2231    }
2232    if let Some(alternatives) = object.get("oneOf") {
2233        let alternatives = alternatives
2234            .as_array()
2235            .filter(|alternatives| !alternatives.is_empty())
2236            .ok_or_else(|| "schema `oneOf` must be a non-empty array".to_string())?;
2237        for (index, alternative) in alternatives.iter().enumerate() {
2238            validate_schema_definition(alternative)
2239                .map_err(|reason| format!("oneOf alternative {index} {reason}"))?;
2240        }
2241    }
2242    Ok(())
2243}
2244
2245/// A [`SHAPED_BY_ANNOTATION`] names the argument that decides and, for values
2246/// of it, shapes that are themselves schemas a value can be held to.
2247fn validate_schema_definition_shaped(
2248    object: &serde_json::Map<String, serde_json::Value>,
2249) -> Result<(), String> {
2250    let Some(declared) = object.get(SHAPED_BY_ANNOTATION) else {
2251        return Ok(());
2252    };
2253    let argument = declared
2254        .get("argument")
2255        .and_then(serde_json::Value::as_str)
2256        .filter(|argument| !argument.trim().is_empty());
2257    let shapes = declared
2258        .get("shapes")
2259        .and_then(serde_json::Value::as_object);
2260    let (Some(_), Some(shapes)) = (argument, shapes) else {
2261        return Err(format!(
2262            "schema `{SHAPED_BY_ANNOTATION}` must name an `argument` and the `shapes` its values decide"
2263        ));
2264    };
2265    for (value, shape) in shapes {
2266        validate_schema_definition(shape)
2267            .map_err(|reason| format!("`{SHAPED_BY_ANNOTATION}` shape `{value}` {reason}"))?;
2268    }
2269    Ok(())
2270}
2271
2272fn validate_schema_definition_numbers(
2273    object: &serde_json::Map<String, serde_json::Value>,
2274) -> Result<(), String> {
2275    for keyword in ["minimum", "maximum"] {
2276        if object.get(keyword).is_some_and(|value| !value.is_number()) {
2277            return Err(format!("schema `{keyword}` must be a number"));
2278        }
2279    }
2280    for keyword in ["minLength", "maxLength", "minItems", "maxItems"] {
2281        if object
2282            .get(keyword)
2283            .is_some_and(|value| value.as_u64().is_none())
2284        {
2285            return Err(format!("schema `{keyword}` must be a non-negative integer"));
2286        }
2287    }
2288    Ok(())
2289}
2290
2291#[cfg(test)]
2292mod declaration_reuse_tests {
2293    use std::sync::Arc;
2294    use std::time::Instant;
2295
2296    use serde_json::json;
2297
2298    use super::{ActionArgs, ActionParam, ParamType};
2299
2300    tilo_test_env::scenario! {
2301        fn a_shared_declaration_is_validated_once_per_schema;
2302
2303        phase shared_schema_edits_and_descriptor_changes_are_still_refused;
2304        {
2305            let original = ActionParam::required("body", ParamType::Text, "Body")
2306                .with_schema(json!({"type": "string", "minLength": 3}));
2307            assert!(original.validate_declaration().is_empty());
2308            assert!(
2309                ActionArgs::bind_json(
2310                    std::slice::from_ref(&original),
2311                    json!({"body": "a"}).as_object().unwrap()
2312                )
2313                .is_err()
2314            );
2315            let mut edited = original.clone();
2316            assert!(edited.validate_declaration().is_empty());
2317            Arc::make_mut(edited.schema.as_mut().unwrap())["minLength"] = json!(-1);
2318            assert!(edited.validate_declaration()[0].contains("non-negative integer"));
2319            assert!(original.validate_declaration().is_empty());
2320            let mut renamed = original.clone();
2321            renamed.name = " ".into();
2322            assert_eq!(
2323                renamed.validate_declaration(),
2324                ["parameter name must be non-empty"]
2325            );
2326            let mut secret = original;
2327            secret.ty = ParamType::Secret;
2328            secret.choices.push("private".into());
2329            assert!(secret.validate_declaration()[0].contains("must not publish possible values"));
2330        }
2331
2332        phase last_owner_schema_mutation_dissociates_prior_validation;
2333        {
2334            let mut parameter = ActionParam::required("body", ParamType::Text, "Body")
2335                .with_schema(json!({"type": "string"}));
2336            assert!(parameter.validate_declaration().is_empty());
2337            Arc::make_mut(parameter.schema.as_mut().unwrap())["type"] = json!("unsupported");
2338            assert_eq!(
2339                parameter.validate_declaration(),
2340                ["invalid schema: schema has an unsupported `type`"]
2341            );
2342            Arc::make_mut(parameter.schema.as_mut().unwrap())["type"] = json!("string");
2343            assert!(parameter.validate_declaration().is_empty());
2344        }
2345
2346        phase retired_generations_are_released_and_new_invalid_schemas_are_refused;
2347        {
2348            for _ in 0..128 {
2349                let schema = Arc::new(json!({"type": "string"}));
2350                let retired = Arc::downgrade(&schema);
2351                let parameter =
2352                    ActionParam::required("body", ParamType::Text, "Body").with_shared_schema(schema);
2353                assert!(parameter.validate_declaration().is_empty());
2354                drop(parameter);
2355                assert!(retired.upgrade().is_none());
2356                let invalid = ActionParam::required("body", ParamType::Text, "Body")
2357                    .with_schema(json!({"pattern": "["}));
2358                assert!(invalid.validate_declaration()[0].contains("invalid pattern"));
2359            }
2360        }
2361
2362        phase shared_declaration_observes_recursive_publication_work;
2363        {
2364            let properties: serde_json::Map<String, serde_json::Value> = (0..128)
2365                .map(|index| {
2366                    (
2367                        format!("field{index}"),
2368                        json!({"type": "array", "items": {"type": "object", "properties": {
2369                            "text": {"type": "string", "minLength": 1},
2370                            "count": {"type": "integer", "minimum": 0}
2371                        }, "additionalProperties": false}}),
2372                    )
2373                })
2374                .collect();
2375            let parameter = ActionParam::required("request", ParamType::Object, "Request")
2376                .with_shared_schema(Arc::new(
2377                    json!({"type": "object", "properties": properties}),
2378                ));
2379            let start = Instant::now();
2380            for _ in 0..1000 {
2381                assert!(
2382                    std::hint::black_box(&parameter)
2383                        .validate_declaration()
2384                        .is_empty()
2385                );
2386            }
2387            eprintln!(
2388                "ACTION_SCHEMA_DECLARATION_OBSERVATION iterations=1000 fields=128 elapsed_ns={} includes_gpu_or_display=false",
2389                start.elapsed().as_nanos()
2390            );
2391        }
2392    }
2393
2394    /// A layout's ids span all of `u64`; a device whose key folds high mints ids above `i64::MAX`,
2395    /// and an integer argument has to carry them exactly.
2396    #[test]
2397    fn an_integer_argument_carries_a_whole_id() {
2398        let id = u64::MAX - 7;
2399        let params = [ActionParam::required("row", ParamType::Integer, "Row")];
2400        let bound = ActionArgs::bind_json(&params, json!({"row": id}).as_object().unwrap())
2401            .expect("an integer argument takes the whole id");
2402        assert_eq!(bound.to_json()["row"], json!(id), "it reads back exactly");
2403        assert_eq!(
2404            bound.whole("row"),
2405            Some(id),
2406            "and a caller reads the whole id"
2407        );
2408        assert_eq!(bound.integer("row"), None, "which is no i64");
2409        let negative = ActionArgs::bind_json(&params, json!({"row": -48}).as_object().unwrap())
2410            .expect("a negative integer binds too");
2411        assert_eq!(negative.to_json()["row"], json!(-48));
2412    }
2413
2414    /// A choice is a value the parameter takes, at the same width: a list of ids holds the ones a
2415    /// device mints past `i64::MAX`, and binding one of them is a call the parameter allows.
2416    #[test]
2417    fn an_integers_choices_are_as_wide_as_its_values() {
2418        for id in [u64::MAX - 7, 4_294_967_296, 7] {
2419            let param = ActionParam::required("place", ParamType::Integer, "Place")
2420                .with_choices([id.to_string()]);
2421            assert!(
2422                param.validate_declaration().is_empty(),
2423                "`{id}` declares as a choice: {:?}",
2424                param.validate_declaration()
2425            );
2426            let bound = ActionArgs::bind_json(
2427                std::slice::from_ref(&param),
2428                json!({"place": id}).as_object().unwrap(),
2429            )
2430            .expect("the id binds as its own choice");
2431            assert_eq!(
2432                bound.to_json()["place"],
2433                json!(id),
2434                "exactly what was given"
2435            );
2436            let other = ActionArgs::bind_json(
2437                std::slice::from_ref(&param),
2438                json!({"place": id - 1}).as_object().unwrap(),
2439            );
2440            assert!(
2441                other.is_err_and(|error| matches!(error, super::ArgError::NotAllowed { .. })),
2442                "an id not in the list is refused"
2443            );
2444        }
2445    }
2446
2447    /// A refusal names the bound the schema holds, not a float that rounds it.
2448    #[test]
2449    fn a_bounds_refusal_names_the_whole_number() {
2450        let id = u64::MAX - 7;
2451        let param = ActionParam::required("place", ParamType::Integer, "Place")
2452            .with_schema(json!({"type": "integer", "maximum": id}));
2453        let refused = ActionArgs::bind_json(
2454            std::slice::from_ref(&param),
2455            json!({"place": id + 1}).as_object().unwrap(),
2456        )
2457        .expect_err("beyond the bound");
2458        assert_eq!(
2459            refused.to_string(),
2460            format!("argument `place` must be at most {id}")
2461        );
2462    }
2463}
2464
2465#[cfg(test)]
2466mod rich_schema_tests {
2467    use super::*;
2468    use serde_json::json;
2469
2470    tilo_test_env::scenario! {
2471        fn parameters_bind_and_validate_by_their_schema;
2472
2473        phase action_parameters_are_typed_validated_and_round_trip;
2474        // Structured arguments are typed and recursively validated; resource, datetime, secret and
2475        // nullable values round-trip; a malformed schema is rejected before it describes values; unique
2476        // array items are published and enforced.
2477        // Runs each phase below in order; every phase builds its own fixture.
2478        {
2479            structured_arguments_are_typed_and_recursively_validated();
2480            resource_datetime_secret_and_nullable_values_round_trip();
2481            malformed_schema_is_rejected_before_it_describes_values();
2482            unique_array_items_are_published_and_enforced();
2483        }
2484
2485        phase null_leaves_an_optional_argument_out_and_is_no_required_ones_value;
2486        {
2487            let params = vec![
2488                ActionParam::required("media", ParamType::Text, "media"),
2489                ActionParam::optional("fade_in", ParamType::Number, "fade in"),
2490                ActionParam::optional("parent", ParamType::Text, "parent").nullable(),
2491            ];
2492            let supplied = json!({"media": "shot-a.mp4", "fade_in": null, "parent": null});
2493            let bound = ActionArgs::bind_json(&params, supplied.as_object().unwrap()).unwrap();
2494            assert_eq!(
2495                bound.to_json(),
2496                *json!({"media": "shot-a.mp4", "parent": null})
2497                    .as_object()
2498                    .unwrap()
2499            );
2500            assert_eq!(bound.number("fade_in"), None);
2501
2502            let missing = json!({"media": null});
2503            assert_eq!(
2504                ActionArgs::bind_json(&params, missing.as_object().unwrap())
2505                    .unwrap_err()
2506                    .to_string(),
2507                "argument `media` was given null and must be text: \"<text>\""
2508            );
2509        }
2510
2511        phase shared_schema_preserves_wire_binding_and_copy_on_write;
2512        {
2513            use crate::{ActionSpec, EncodedAction, ExecutionLocus};
2514            use std::sync::Arc;
2515
2516            let schema = serde_json::json!({"type": "integer", "minimum": 1});
2517            let original =
2518                ActionParam::required("count", ParamType::Integer, "Count").with_schema(schema.clone());
2519            let clone = original.clone();
2520            assert!(Arc::ptr_eq(
2521                original.schema.as_ref().unwrap(),
2522                clone.schema.as_ref().unwrap()
2523            ));
2524            let expected = serde_json::json!({
2525                "name":"count", "ty":"integer", "required":true,
2526                "description":"Count", "schema":schema
2527            });
2528            assert_eq!(serde_json::to_value(&clone).unwrap(), expected);
2529            let decoded: ActionParam = serde_json::from_value(expected).unwrap();
2530            assert_eq!(decoded, original);
2531            let spec = ActionSpec::typed(
2532                "count",
2533                "Count",
2534                "Count",
2535                ExecutionLocus::ClientLocal,
2536                vec![clone],
2537                |args| EncodedAction {
2538                    type_id: "test.count".into(),
2539                    payload: serde_json::to_vec(&args.to_json()).unwrap(),
2540                },
2541            );
2542            let valid = serde_json::json!({"count":2});
2543            let encoded = spec.build_json(valid.as_object().unwrap()).unwrap();
2544            assert_eq!(
2545                serde_json::from_slice::<serde_json::Value>(&encoded.payload).unwrap(),
2546                valid
2547            );
2548            assert!(
2549                spec.build_json(serde_json::json!({"count":0}).as_object().unwrap())
2550                    .is_err()
2551            );
2552            assert_eq!(spec.build_text("2"), Some(encoded));
2553            assert_eq!(
2554                spec.build_text("0").unwrap().type_id,
2555                crate::resource::INVALID_ARGUMENTS_TYPE
2556            );
2557            let mut edited = original.clone();
2558            Arc::make_mut(edited.schema.as_mut().unwrap())["minimum"] = serde_json::json!(3);
2559            assert_eq!(original.schema.as_ref().unwrap()["minimum"], 1);
2560            assert!(ActionArgs::bind_json(&[edited], valid.as_object().unwrap()).is_err());
2561            assert!(spec.build_json(valid.as_object().unwrap()).is_ok());
2562
2563            let resource = ActionParam::required("target", ParamType::Resource, "Target")
2564                .with_schema(serde_json::json!({"type":"string"}));
2565            let annotated = resource.clone().of_resource_kind("test.page");
2566            assert_eq!(resource.resource_kind(), None);
2567            assert_eq!(annotated.resource_kind(), Some("test.page"));
2568            assert_eq!(
2569                resource
2570                    .schema
2571                    .as_ref()
2572                    .unwrap()
2573                    .get(RESOURCE_KIND_ANNOTATION),
2574                None
2575            );
2576        }
2577
2578        phase a_picked_resource_is_a_reference_of_its_kind;
2579        {
2580            let note =
2581                ActionParam::required("note", ParamType::Object, "The note").picking(Pick::Resource {
2582                    kind: "notes.notebook.pages".into(),
2583                });
2584            assert!(
2585                note.validate_declaration().is_empty(),
2586                "{:?}",
2587                note.validate_declaration()
2588            );
2589            assert_eq!(
2590                note.pick(),
2591                Some(Pick::Resource {
2592                    kind: "notes.notebook.pages".into()
2593                })
2594            );
2595            let params = [note];
2596            let reference = serde_json::json!({ "note": {
2597                "app": "so.tilo.notes",
2598                "kind": "notes.notebook.pages",
2599                "id": "notes.notebook/pages/p1",
2600                "label": "Plan",
2601            }});
2602            assert!(ActionArgs::bind_json(&params, reference.as_object().unwrap()).is_ok());
2603            let typed_id = serde_json::json!({ "note": { "id": "notes.notebook/pages/p1" } });
2604            assert!(
2605                ActionArgs::bind_json(&params, typed_id.as_object().unwrap()).is_err(),
2606                "a reference names its app and kind"
2607            );
2608            let subject = ActionParam::required("who", ParamType::Object, "Who").picking(Pick::Grantee);
2609            assert_eq!(subject.pick(), Some(Pick::Grantee));
2610        }
2611
2612        phase a_parameter_with_labelled_choices_of_people_binds_its_values;
2613        {
2614            let param = ActionParam::required("id", ParamType::Text, "The identity")
2615                .with_labelled_choices([("ada", "Ada"), ("bob", "Bob")])
2616                .choosing_people(["ada", "bob"]);
2617            assert!(param.validate_declaration().is_empty());
2618            let params = [param];
2619            assert!(ActionArgs::bind(&params, [("id".into(), ArgValue::Text("ada".into()))]).is_ok());
2620            assert!(
2621                ActionArgs::bind(&params, [("id".into(), ArgValue::Text("eve".into()))]).is_err(),
2622                "only the values offered"
2623            );
2624        }
2625
2626        phase prefix_items_check_the_leading_items_and_items_the_rest;
2627        {
2628            let schema = json!({
2629                "type": "array",
2630                "prefixItems": [{"const": "a"}, {"type": "string"}],
2631                "items": {"type": "integer"},
2632            });
2633            assert!(validate_schema_definition(&schema).is_ok());
2634            assert!(validate_schema(&json!(["a", "x", 1, 2]), &schema).is_ok());
2635            assert!(validate_schema(&json!(["b", "x"]), &schema).is_err());
2636            assert!(validate_schema(&json!(["a", 1]), &schema).is_err());
2637            assert!(validate_schema(&json!(["a", "x", "y"]), &schema).is_err());
2638            assert!(validate_schema_definition(&json!({"prefixItems": {}})).is_err());
2639        }
2640
2641        phase a_maximum_violation_carries_its_bound;
2642        // A number outside its parameter's declared range is refused with the
2643        // bound as data, in the same words as before, and the API's failure
2644        // carries it as `details`. A bound nested in a property stays words.
2645        {
2646            let params = vec![
2647                ActionParam::required("pageSize", ParamType::Integer, "Items")
2648                    .with_schema(json!({"type": "integer", "minimum": 1, "maximum": 64})),
2649                ActionParam::optional("scale", ParamType::Number, "Zoom")
2650                    .with_schema(json!({"type": "number", "minimum": 0.5})),
2651                ActionParam::optional("box", ParamType::Object, "Bounds").with_schema(json!({
2652                    "type": "object",
2653                    "properties": {"width": {"type": "integer", "maximum": 10}}
2654                })),
2655            ];
2656            let bind = |arguments: serde_json::Value| {
2657                ActionArgs::bind_json(&params, arguments.as_object().unwrap())
2658            };
2659            let refused = bind(json!({"pageSize": 200})).unwrap_err();
2660            assert_eq!(
2661                refused,
2662                ArgError::OutOfRange {
2663                    name: "pageSize".into(),
2664                    violation: ArgViolation::Maximum { bound: json!(64) },
2665                }
2666            );
2667            assert_eq!(
2668                refused.to_string(),
2669                "argument `pageSize` must be at most 64"
2670            );
2671            let api = crate::ApiError::from(refused);
2672            assert_eq!(api.code(), "invalid_arguments");
2673            assert_eq!(api.to_string(), "argument `pageSize` must be at most 64");
2674            assert_eq!(
2675                api.failure_details(),
2676                Some(json!({"param": "pageSize", "violation": {"kind": "maximum", "bound": 64}}))
2677            );
2678
2679            let refused = bind(json!({"pageSize": 1, "scale": 0.25})).unwrap_err();
2680            assert_eq!(
2681                refused,
2682                ArgError::OutOfRange {
2683                    name: "scale".into(),
2684                    violation: ArgViolation::Minimum { bound: json!(0.5) },
2685                }
2686            );
2687            assert_eq!(refused.to_string(), "argument `scale` must be at least 0.5");
2688
2689            let nested = bind(json!({"pageSize": 1, "box": {"width": 11}})).unwrap_err();
2690            assert!(matches!(nested, ArgError::Constraint { .. }), "{nested:?}");
2691            assert_eq!(crate::ApiError::from(nested).failure_details(), None);
2692            assert!(bind(json!({"pageSize": 64, "scale": 0.5})).is_ok());
2693        }
2694
2695        phase a_refusal_names_the_alternative_an_enumerated_tag_selects;
2696        {
2697            let schema = json!({"oneOf": [
2698                {"type": "object", "required": ["action"], "properties": {
2699                    "action": {"enum": ["draw", "paint"]}, "args": {"type": "object"}
2700                }, "additionalProperties": false},
2701                {"type": "object", "required": ["action", "args"], "properties": {
2702                    "action": {"const": "apply"}, "args": {"type": "object", "required": ["action"]}
2703                }, "additionalProperties": false},
2704            ]});
2705            assert!(validate_schema(&json!({"action": "draw", "args": {}}), &schema).is_ok());
2706            let refused = validate_schema(&json!({"action": "apply", "args": {}}), &schema);
2707            assert_eq!(
2708                refused,
2709                Err("as `apply`: property `args` must contain property `action`".into())
2710            );
2711            let refused = validate_schema(&json!({"action": "paint", "args": 3}), &schema).unwrap_err();
2712            assert!(refused.contains("property `args`"), "{refused}");
2713        }
2714    }
2715
2716    fn structured_arguments_are_typed_and_recursively_validated() {
2717        let params = vec![
2718            ActionParam::required("request", ParamType::Object, "request").with_schema(json!({
2719                "required": ["items"],
2720                "additionalProperties": false,
2721                "properties": {
2722                    "items": {"minItems": 1, "items": {"minimum": 1}}
2723                }
2724            })),
2725        ];
2726        let good = json!({"request": {"items": [1, 2]}})
2727            .as_object()
2728            .cloned()
2729            .unwrap();
2730        assert!(ActionArgs::bind_json(&params, &good).is_ok());
2731
2732        let bad = json!({"request": {"items": [0], "surprise": true}})
2733            .as_object()
2734            .cloned()
2735            .unwrap();
2736        assert!(matches!(
2737            ActionArgs::bind_json(&params, &bad),
2738            Err(ArgError::Constraint { .. })
2739        ));
2740
2741        assert!(
2742            validate_schema(
2743                &json!("#A0b1C2"),
2744                &json!({
2745                    "type": "string",
2746                    "pattern": "^#[0-9A-Fa-f]{6}$"
2747                })
2748            )
2749            .is_ok()
2750        );
2751        assert!(validate_schema(&json!(42), &json!({"type": "string"})).is_err());
2752        assert!(
2753            validate_schema(
2754                &json!("red"),
2755                &json!({
2756                    "type": "string",
2757                    "pattern": "^#[0-9A-Fa-f]{6}$"
2758                })
2759            )
2760            .is_err()
2761        );
2762    }
2763
2764    fn resource_datetime_secret_and_nullable_values_round_trip() {
2765        let params = vec![
2766            ActionParam::required("resource", ParamType::Resource, "target"),
2767            ActionParam::required("at", ParamType::DateTime, "time"),
2768            ActionParam::required("token", ParamType::Secret, "credential"),
2769            ActionParam::optional("metadata", ParamType::Object, "metadata").nullable(),
2770        ];
2771        let supplied = json!({
2772            "resource": "files.entry:abc",
2773            "at": "2026-09-01T00:00:00Z",
2774            "token": "not-for-logs",
2775            "metadata": null
2776        })
2777        .as_object()
2778        .cloned()
2779        .unwrap();
2780        let bound = ActionArgs::bind_json(&params, &supplied).unwrap();
2781        assert_eq!(bound.text("resource"), Some("files.entry:abc"));
2782        assert_eq!(bound.to_json(), supplied);
2783        for moment in [
2784            "2028-02-29t23:59:60.123456789z",
2785            "2026-09-01 08:30:00-07:00",
2786            "2026-12-31T23:59:59.5+14:00",
2787        ] {
2788            assert!(looks_like_rfc3339(moment), "{moment} is RFC 3339");
2789        }
2790        for not_a_moment in [
2791            "2026-02-29T00:00:00Z",
2792            "2026-09-01T24:00:00Z",
2793            "2026-09-01T00:00:00.Z",
2794            "2026-09-01T00:00:00+0100",
2795            "2026-09-01T00:00:00+01:00x",
2796            "2026-09-01T00:00Z",
2797        ] {
2798            assert!(!looks_like_rfc3339(not_a_moment), "{not_a_moment} is not");
2799        }
2800
2801        for invalid in [
2802            json!({"resource": "label only", "at": "2026-09-01T00:00:00Z", "token": "x"}),
2803            json!({"resource": "files.entry:abc", "at": "tomorrow", "token": "x"}),
2804            json!({"resource": "files.entry:abc", "at": "2026-09-01T00:00:00", "token": "x"}),
2805            json!({"resource": "files.entry:abc", "at": "2026-02-31T00:00:00Z", "token": "x"}),
2806        ] {
2807            assert!(matches!(
2808                ActionArgs::bind_json(&params, invalid.as_object().unwrap()),
2809                Err(ArgError::Constraint { .. })
2810            ));
2811        }
2812    }
2813
2814    fn malformed_schema_is_rejected_before_it_describes_values() {
2815        assert!(validate_schema_definition(&json!({"pattern":"["})).is_err());
2816        assert!(validate_schema_definition(&json!({"format":"tilo-maybe"})).is_err());
2817        // A day without a time, as a date field publishes it.
2818        let day = json!({"type": "string", "format": "date"});
2819        assert!(validate_schema_definition(&day).is_ok());
2820        assert!(validate_schema(&json!("2026-10-29"), &day).is_ok());
2821        for not_a_day in ["2026-02-30", "2026-1-5", "2026-10-29T10:00:00Z", "tomorrow"] {
2822            assert!(
2823                validate_schema(&json!(not_a_day), &day).is_err(),
2824                "{not_a_day}"
2825            );
2826        }
2827        assert!(validate_schema_definition(&json!({"oneOf": []})).is_err());
2828        let one_of = json!({
2829            "oneOf": [
2830                {"const": "Workspace"},
2831                {"type": "object", "required": ["App"], "properties": {
2832                    "App": {"type": "string"}
2833                }, "additionalProperties": false}
2834            ]
2835        });
2836        assert!(validate_schema_definition(&one_of).is_ok());
2837        assert!(validate_json_schema(&json!("Workspace"), &one_of).is_ok());
2838        assert!(validate_json_schema(&json!({"App": "so.tilo.notes"}), &one_of).is_ok());
2839        assert!(validate_json_schema(&json!({"App": "notes", "extra": true}), &one_of).is_err());
2840        assert!(
2841            validate_schema_definition(&json!({
2842                "properties": {"nested": {"type":"mystery"}}
2843            }))
2844            .is_err()
2845        );
2846        assert!(validate_schema_definition(&json!({"minProperties": 1})).is_err());
2847        assert!(validate_schema_definition(&json!({"additionalProperties": 1})).is_err());
2848        assert!(
2849            validate_schema_definition(&json!({"additionalProperties": {"type": "mystery"}}))
2850                .is_err()
2851        );
2852        assert!(
2853            validate_schema_definition(&json!({"additionalProperties": {"type": "integer"}}))
2854                .is_ok()
2855        );
2856        assert!(validate_schema_definition(&json!({"title": "accepted annotation"})).is_ok());
2857    }
2858
2859    fn unique_array_items_are_published_and_enforced() {
2860        let schema = json!({
2861            "type": "array",
2862            "uniqueItems": true,
2863            "items": {"type": "string"}
2864        });
2865        assert!(validate_schema_definition(&schema).is_ok());
2866        assert!(
2867            validate_json_schema(&json!(["photos.photo:a", "photos.photo:b"]), &schema).is_ok()
2868        );
2869        assert!(
2870            validate_json_schema(&json!(["photos.photo:a", "photos.photo:a"]), &schema).is_err()
2871        );
2872        assert!(validate_schema_definition(&json!({"uniqueItems": "yes"})).is_err());
2873    }
2874}