Skip to main content

tilo_actions/
entry.rs

1//! What a committed action did, as data.
2//!
3//! Every change an action commits carries a history entry
4//! ([`crate::ActionContext`]): who acted, for whom, on which item and what
5//! they did. "What they did" is a [`Did`]: a field edit with its path and,
6//! for scalars, the value before and after; a verb with its [`ActionKey`]
7//! and scalar arguments; a group of those; or a history step (undo, redo,
8//! restore, checkpoint). No sentence is stored. Readers render one in their
9//! own language (`tilo-history`), and agents, scripts and logs read the data.
10
11use std::collections::BTreeMap;
12
13use serde::{Deserialize, Serialize};
14
15use crate::key::ActionKey;
16
17/// Longest text kept for one scalar value, in characters.
18pub const MAX_SCALAR_CHARS: usize = 80;
19/// Most arguments kept for one verb.
20pub const MAX_VERB_ARGS: usize = 8;
21/// Most members of a group kept by value; [`GroupOf::count`] keeps the total.
22pub const MAX_GROUP_MEMBERS: usize = 8;
23
24/// What an action did.
25#[derive(Debug, PartialEq, Eq, Serialize)]
26#[serde(remote = "Self", tag = "did", rename_all = "kebab-case")]
27pub enum Did {
28    Edit(FieldEdit),
29    Verb(VerbCall),
30    Group(GroupOf),
31    History(HistoryStep),
32}
33
34// Written through its JSON text: the derived writer is compiled once, for
35// JSON bytes, and every serializer an entry goes to (bytes, a value, a size
36// count) takes that text as it is, rather than holding a copy of the derived
37// writer of its own. The bytes are the derive's, tag first. Like its reading,
38// this is for JSON only (see `read_through_json_value!`).
39impl serde::Serialize for Did {
40    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
41        self.to_json_text()
42            .map_err(serde::ser::Error::custom)?
43            .serialize(serializer)
44    }
45}
46
47impl<'de> serde::Deserialize<'de> for Did {
48    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
49        let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
50        Self::from_json_value(value).map_err(serde::de::Error::custom)
51    }
52}
53
54impl Did {
55    /// Its JSON text, as the derived writer writes it.
56    #[inline(never)]
57    fn to_json_text(&self) -> Result<Box<serde_json::value::RawValue>, serde_json::Error> {
58        /// The derived writer, as a value to serialize.
59        struct Derived<'a>(&'a Did);
60        impl serde::Serialize for Derived<'_> {
61            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
62                Did::serialize(self.0, serializer)
63            }
64        }
65        serde_json::value::to_raw_value(&Derived(self))
66    }
67
68    /// Read by its `did` tag, each variant's fields straight from the
69    /// object: no buffered copy of the entry.
70    #[inline(never)]
71    fn from_json_value(value: serde_json::Value) -> Result<Self, serde_json::Error> {
72        use serde::de::Error;
73        let serde_json::Value::Object(mut fields) = value else {
74            return Err(serde_json::Error::custom("an entry is an object"));
75        };
76        let tag = match fields.remove("did") {
77            Some(serde_json::Value::String(tag)) => tag,
78            Some(_) => return Err(serde_json::Error::custom("`did` is a string")),
79            None => return Err(serde_json::Error::missing_field("did")),
80        };
81        let fields = serde_json::Value::Object(fields);
82        match tag.as_str() {
83            "edit" => serde_json::from_value(fields).map(Self::Edit),
84            "verb" => serde_json::from_value(fields).map(Self::Verb),
85            "group" => serde_json::from_value(fields).map(Self::Group),
86            "history" => serde_json::from_value(fields).map(Self::History),
87            other => Err(serde_json::Error::unknown_variant(
88                other,
89                &["edit", "verb", "group", "history"],
90            )),
91        }
92    }
93}
94
95// Written out rather than derived: a derived clone is inlined into every
96// crate that clones an entry, and entries are cloned throughout the toolkit.
97impl Clone for Did {
98    fn clone(&self) -> Self {
99        match self {
100            Self::Edit(edit) => Self::Edit(edit.clone()),
101            Self::Verb(verb) => Self::Verb(verb.clone()),
102            Self::Group(group) => Self::Group(group.clone()),
103            Self::History(step) => Self::History(step.clone()),
104        }
105    }
106}
107
108impl Did {
109    /// A verb with its arguments bounded to plain values.
110    pub fn verb(action: ActionKey, args: impl IntoIterator<Item = (String, Scalar)>) -> Self {
111        Self::Verb(VerbCall::new(action, args))
112    }
113
114    /// A group of `members`, keeping at most [`MAX_GROUP_MEMBERS`] by value
115    /// and every distinct action among them without its values.
116    pub fn group(members: impl IntoIterator<Item = Did>) -> Self {
117        let mut count = 0u32;
118        let mut kept = Vec::new();
119        let mut distinct: Vec<Did> = Vec::new();
120        for member in members {
121            count = count.saturating_add(1);
122            let mut action = member.clone();
123            action.forget_values();
124            if !distinct.contains(&action) {
125                distinct.push(action);
126            }
127            if kept.len() < MAX_GROUP_MEMBERS {
128                kept.push(member);
129            }
130        }
131        Self::Group(GroupOf {
132            members: kept,
133            count,
134            distinct,
135        })
136    }
137
138    /// Drop every value, keeping only which action ran where.
139    fn forget_values(&mut self) {
140        self.forget_args();
141        match self {
142            Self::Edit(edit) => edit.args.clear(),
143            Self::Group(group) => {
144                group.members.iter_mut().for_each(Self::forget_values);
145                group.distinct.iter_mut().for_each(Self::forget_values);
146            }
147            Self::Verb(_) | Self::History(_) => {}
148        }
149    }
150
151    /// Drop every verb argument and field value, keeping what was done and
152    /// where: the form a public audit keeps.
153    pub fn forget_args(&mut self) {
154        match self {
155            Self::Edit(edit) => {
156                edit.old = None;
157                edit.new = None;
158            }
159            Self::Verb(verb) => verb.args.clear(),
160            Self::Group(group) => group.members.iter_mut().for_each(Self::forget_args),
161            Self::History(step) => {
162                if let Some(of) = &mut step.of {
163                    of.what.forget_args();
164                }
165            }
166        }
167    }
168
169    pub fn history(op: HistoryOp, steps: u32, of: Option<Described>) -> Self {
170        Self::History(HistoryStep {
171            op,
172            steps,
173            of: of.map(Box::new),
174            undoes: None,
175            verb: String::new(),
176        })
177    }
178}
179
180#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
181pub struct FieldEdit {
182    /// The model type that owns the field, kebab-case (`snippet`).
183    pub ty: String,
184    /// The field's storage key (`favorite`).
185    pub field: String,
186    /// Where the field is, from the resource's root.
187    #[serde(default, skip_serializing_if = "Vec::is_empty")]
188    pub path: Vec<PathStep>,
189    pub op: EditOp,
190    /// The value before, for a scalar field.
191    #[serde(default, skip_serializing_if = "Option::is_none")]
192    pub old: Option<Scalar>,
193    /// The value after, for a scalar field.
194    #[serde(default, skip_serializing_if = "Option::is_none")]
195    pub new: Option<Scalar>,
196    /// Plain facts of an edit the field's own type describes (a rich-text
197    /// edit's mark, the words it covered), by name.
198    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
199    pub args: BTreeMap<String, Scalar>,
200}
201
202/// One step of a path from a resource's root to a field.
203#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
204#[serde(rename_all = "kebab-case")]
205pub enum PathStep {
206    Field(String),
207    Item(String),
208    Key(String),
209    Cell(String, String),
210}
211
212/// The operation of a field edit.
213#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
214#[serde(rename_all = "kebab-case")]
215pub enum EditOp {
216    Set,
217    Splice,
218    Replace,
219    Add,
220    Insert,
221    Remove,
222    MoveTo,
223    Mark,
224    SetCell,
225    InsertRow,
226    InsertColumn,
227    RemoveRow,
228    RemoveColumn,
229    /// The owning device recorded how an outbox entry settled (`$state`:
230    /// `done` or `failed`, with `$reason`).
231    Settle,
232    /// A settled outbox entry was forgotten.
233    Forget,
234    /// The actor reacted with an emoji (`new`).
235    React,
236    /// The actor took back their reaction with an emoji (`new`).
237    Unreact,
238}
239
240impl EditOp {
241    /// The name readers pass to messages as `$op`.
242    pub const fn as_str(&self) -> &'static str {
243        match self {
244            Self::Set => "set",
245            Self::Splice => "splice",
246            Self::Replace => "replace",
247            Self::Add => "add",
248            Self::Insert => "insert",
249            Self::Remove => "remove",
250            Self::MoveTo => "move-to",
251            Self::Mark => "mark",
252            Self::SetCell => "set-cell",
253            Self::InsertRow => "insert-row",
254            Self::InsertColumn => "insert-column",
255            Self::RemoveRow => "remove-row",
256            Self::RemoveColumn => "remove-column",
257            Self::Settle => "settle",
258            Self::Forget => "forget",
259            Self::React => "react",
260            Self::Unreact => "unreact",
261        }
262    }
263}
264
265/// A verb and its plain arguments by parameter name.
266#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
267pub struct VerbCall {
268    pub action: ActionKey,
269    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
270    pub args: BTreeMap<String, Scalar>,
271}
272
273impl VerbCall {
274    /// Keeps at most [`MAX_VERB_ARGS`] arguments.
275    pub fn new(action: ActionKey, args: impl IntoIterator<Item = (String, Scalar)>) -> Self {
276        Self {
277            action,
278            args: args.into_iter().take(MAX_VERB_ARGS).collect(),
279        }
280    }
281}
282
283/// Several actions committed as one change.
284#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
285pub struct GroupOf {
286    /// The first [`MAX_GROUP_MEMBERS`] members.
287    pub members: Vec<Did>,
288    pub count: u32,
289    /// Every distinct action among the members, without values, however
290    /// many members there were: what a receiver decides the change by.
291    #[serde(default, skip_serializing_if = "Vec::is_empty")]
292    pub distinct: Vec<Did>,
293}
294
295impl GroupOf {
296    /// The one thing every member did, when they all did the same.
297    pub fn shared(&self) -> Option<&Did> {
298        let first = self.members.first()?;
299        (self.count as usize == self.members.len() && self.members.iter().all(|m| m == first))
300            .then_some(first)
301    }
302}
303
304/// A step through history itself.
305#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
306pub struct HistoryStep {
307    pub op: HistoryOp,
308    /// How many steps it took back or brought back.
309    #[serde(default)]
310    pub steps: u32,
311    /// What it took back or brought back, when it was one step.
312    #[serde(default, skip_serializing_if = "Option::is_none")]
313    pub of: Option<Box<Described>>,
314    /// The invocation it took back or brought back, when it moved one: each change of an undo
315    /// moves one invocation, so whoever admits it reads one invocation per change.
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub undoes: Option<String>,
318    /// The verb of that invocation, as it was invoked.
319    #[serde(default, skip_serializing_if = "String::is_empty")]
320    pub verb: String,
321}
322
323#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
324#[serde(rename_all = "kebab-case")]
325pub enum HistoryOp {
326    Undo,
327    Redo,
328    Restore,
329    Checkpoint {
330        name: String,
331    },
332    /// The document was brought to the storage version `to`.
333    Migrate {
334        to: u32,
335    },
336}
337
338/// The item an action addressed, with its label at the time: one line that
339/// names it ([`Described::on`]), never its text.
340#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
341pub struct ActionItem {
342    pub id: String,
343    pub label: String,
344}
345
346/// What an action says about itself before it applies: what it does and to
347/// which item ([`crate::Action::describe`]).
348#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
349pub struct Described {
350    pub what: Did,
351    #[serde(default, skip_serializing_if = "Option::is_none")]
352    pub item: Option<ActionItem>,
353}
354
355impl Described {
356    pub fn new(what: Did) -> Self {
357        Self { what, item: None }
358    }
359
360    /// About the item `id`, named by `label` as one line people read
361    /// ([`one_line`](crate::context::one_line), at most
362    /// [`MAX_LABEL_CHARS`](crate::context::MAX_LABEL_CHARS) characters): an
363    /// entry names its item, it never carries what the item reads. A message
364    /// is labelled by its text, so a label kept whole put the whole reply so
365    /// far into every change that grew it. An item with no name of its own
366    /// is called by its id, which stays whole: a reader takes a label that
367    /// repeats the id for no name.
368    ///
369    /// Only an entry being written passes here. A kept entry is read back as
370    /// it was written, so a change from before this rule keeps its bytes, and
371    /// is verified and undone under them ([`crate::verify_change`]).
372    #[must_use]
373    pub fn on(mut self, id: impl Into<String>, label: impl Into<String>) -> Self {
374        let (id, label) = (id.into(), label.into());
375        let label = if label == id {
376            label
377        } else {
378            crate::context::one_line(&label, crate::context::MAX_LABEL_CHARS).unwrap_or_default()
379        };
380        self.item = Some(ActionItem { id, label });
381        self
382    }
383
384    /// The published action `key` invoked with `encoded`: the verb with the
385    /// plain arguments the encoded value carries. An empty `key.app` is
386    /// filled by the executor from the entry's app.
387    pub fn of_published(encoded: &crate::EncodedAction, key: ActionKey) -> Option<Self> {
388        let value = without_lists(&encoded.payload)?;
389        let args = variant_of(&value).and_then(|(_, fields)| fields);
390        Some(Self::new(Did::verb(key, plain_args(args))))
391    }
392
393    /// What an encoded action says about itself when its type describes
394    /// nothing: the verb its serde variant names, with its plain arguments.
395    /// `app` names the publishing app; without one the action type's stem
396    /// (`notes` of `notes.action`) stands in.
397    pub fn from_encoded(encoded: &crate::EncodedAction, app: Option<&str>) -> Option<Self> {
398        let value = without_lists(&encoded.payload)?;
399        Self::from_value(&encoded.type_id, &value, app)
400    }
401
402    /// [`Self::from_encoded`] for an action value already in JSON.
403    pub fn from_value(type_id: &str, value: &serde_json::Value, app: Option<&str>) -> Option<Self> {
404        let (variant, fields) = variant_of(value)?;
405        let app = app
406            .filter(|app| !app.trim().is_empty())
407            .map_or_else(|| type_stem(type_id), str::to_owned);
408        Some(Self::new(Did::verb(
409            ActionKey::new(app, type_id, kebab(variant)),
410            plain_args(fields),
411        )))
412    }
413}
414
415/// The plain arguments of a variant's fields (an adjacently tagged value's
416/// `args`, else the fields beside an internal `action` tag): its plain
417/// values by name, then the plain values of its nested records as
418/// `record.field`. Text arguments are kept whole ([`Scalar::argument`]):
419/// what a person, a script or an agent passed is what the change says it
420/// did, and a reader that recalls it (a calculation put back, a formula
421/// opened) gets all of it.
422fn plain_args(
423    fields: Option<&serde_json::Map<String, serde_json::Value>>,
424) -> impl Iterator<Item = (String, Scalar)> + '_ {
425    let tagged = fields.is_some_and(|fields| fields.contains_key("action"));
426    let fields = match fields.and_then(|fields| fields.get("args")) {
427        Some(serde_json::Value::Object(args)) if tagged => Some(args),
428        _ => fields,
429    };
430    let own = move || {
431        fields
432            .into_iter()
433            .flat_map(serde_json::Map::iter)
434            .filter(move |(name, _)| !(tagged && name.as_str() == "action"))
435    };
436    let plain = own().filter_map(|(name, value)| Some((name.clone(), Scalar::argument(value)?)));
437    let nested = own().flat_map(|(name, value)| {
438        value
439            .as_object()
440            .into_iter()
441            .flat_map(serde_json::Map::iter)
442            .filter_map(move |(field, value)| {
443                Some((format!("{name}.{field}"), Scalar::argument(value)?))
444            })
445    });
446    plain.chain(nested)
447}
448
449/// The JSON value of `payload` with every list in it read as empty: what an
450/// action is described by, as no list is a plain argument, read without
451/// building the lists an action carries in bulk (the issues of a long list
452/// made in one call).
453fn without_lists(payload: &[u8]) -> Option<serde_json::Value> {
454    use serde::de::{IgnoredAny, MapAccess, SeqAccess, Visitor};
455
456    struct Shallow(serde_json::Value);
457
458    impl<'de> Deserialize<'de> for Shallow {
459        fn deserialize<D: serde::Deserializer<'de>>(from: D) -> Result<Self, D::Error> {
460            from.deserialize_any(ShallowVisitor)
461        }
462    }
463
464    struct ShallowVisitor;
465
466    impl<'de> Visitor<'de> for ShallowVisitor {
467        type Value = Shallow;
468
469        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
470            formatter.write_str("a JSON value")
471        }
472
473        fn visit_bool<E>(self, value: bool) -> Result<Shallow, E> {
474            Ok(Shallow(value.into()))
475        }
476
477        fn visit_i64<E>(self, value: i64) -> Result<Shallow, E> {
478            Ok(Shallow(value.into()))
479        }
480
481        fn visit_u64<E>(self, value: u64) -> Result<Shallow, E> {
482            Ok(Shallow(value.into()))
483        }
484
485        fn visit_f64<E>(self, value: f64) -> Result<Shallow, E> {
486            Ok(Shallow(value.into()))
487        }
488
489        fn visit_str<E>(self, value: &str) -> Result<Shallow, E> {
490            Ok(Shallow(value.into()))
491        }
492
493        fn visit_string<E>(self, value: String) -> Result<Shallow, E> {
494            Ok(Shallow(value.into()))
495        }
496
497        fn visit_unit<E>(self) -> Result<Shallow, E> {
498            Ok(Shallow(serde_json::Value::Null))
499        }
500
501        fn visit_none<E>(self) -> Result<Shallow, E> {
502            Ok(Shallow(serde_json::Value::Null))
503        }
504
505        fn visit_seq<A: SeqAccess<'de>>(self, mut items: A) -> Result<Shallow, A::Error> {
506            while items.next_element::<IgnoredAny>()?.is_some() {}
507            Ok(Shallow(serde_json::Value::Array(Vec::new())))
508        }
509
510        fn visit_map<A: MapAccess<'de>>(self, mut entries: A) -> Result<Shallow, A::Error> {
511            let mut fields = serde_json::Map::new();
512            while let Some((name, Shallow(value))) = entries.next_entry::<String, Shallow>()? {
513                fields.insert(name, value);
514            }
515            Ok(Shallow(serde_json::Value::Object(fields)))
516        }
517    }
518
519    serde_json::from_slice::<Shallow>(payload)
520        .ok()
521        .map(|Shallow(value)| value)
522}
523
524/// The variant name and fields of an externally, adjacently or internally
525/// tagged action value, looking through a stamped `{op, at}` envelope.
526fn variant_of(
527    value: &serde_json::Value,
528) -> Option<(&str, Option<&serde_json::Map<String, serde_json::Value>>)> {
529    match value {
530        serde_json::Value::String(variant) => Some((variant, None)),
531        serde_json::Value::Object(fields) => {
532            if let (Some(op), Some(_)) = (fields.get("op"), fields.get("at"))
533                && fields.len() == 2
534            {
535                return variant_of(op);
536            }
537            if let Some(serde_json::Value::String(variant)) = fields.get("action") {
538                return Some((variant, Some(fields)));
539            }
540            if fields.len() == 1 {
541                let (variant, inner) = fields.iter().next()?;
542                return Some((variant, inner.as_object()));
543            }
544            None
545        }
546        _ => None,
547    }
548}
549
550fn type_stem(type_id: &str) -> String {
551    type_id.split('.').next().unwrap_or(type_id).to_owned()
552}
553
554/// `RemoveMarks`, `remove_marks` and `remove-marks` all become `remove-marks`.
555pub fn kebab(name: &str) -> String {
556    let mut out = String::with_capacity(name.len().saturating_add(4));
557    let mut previous_lower_or_digit = false;
558    for ch in name.chars() {
559        if ch == '_' || ch == '-' || ch == ' ' {
560            if !out.is_empty() && !out.ends_with('-') {
561                out.push('-');
562            }
563            previous_lower_or_digit = false;
564            continue;
565        }
566        if ch.is_uppercase() && previous_lower_or_digit {
567            out.push('-');
568        }
569        previous_lower_or_digit = ch.is_lowercase() || ch.is_ascii_digit();
570        out.extend(ch.to_lowercase());
571    }
572    out
573}
574
575/// One plain value in an entry: a boolean, a number, a short text or an
576/// enum variant. Nested values are never stored.
577#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
578#[serde(transparent)]
579pub struct Scalar(serde_json::Value);
580
581impl Scalar {
582    /// A plain JSON value, text cut to [`MAX_SCALAR_CHARS`]. `None` for
583    /// arrays and objects, and for null.
584    pub fn from_json(value: &serde_json::Value) -> Option<Self> {
585        match value {
586            serde_json::Value::Bool(_) | serde_json::Value::Number(_) => Some(Self(value.clone())),
587            serde_json::Value::String(text) => Some(Self::text(text)),
588            _ => None,
589        }
590    }
591
592    /// A verb's argument as passed: a plain JSON value, text kept whole
593    /// ([`Self::whole_text`]). `None` for arrays and objects, and for null.
594    pub fn argument(value: &serde_json::Value) -> Option<Self> {
595        match value {
596            serde_json::Value::String(text) => Some(Self::whole_text(text)),
597            _ => Self::from_json(value),
598        }
599    }
600
601    /// Text cut to [`MAX_SCALAR_CHARS`], without control characters.
602    pub fn text(text: &str) -> Self {
603        let mut chars = text.chars().filter(|ch| !ch.is_control());
604        let cut: String = chars.by_ref().take(MAX_SCALAR_CHARS).collect();
605        if chars.next().is_some() {
606            Self(serde_json::Value::String(cut + "…"))
607        } else {
608            Self(serde_json::Value::String(cut))
609        }
610    }
611
612    /// A text an edit wrote whole (a formula, a title), kept whole without
613    /// control characters: the change carries the text anyway, and a reader
614    /// elides it where it draws it. Other text is cut ([`Self::text`]).
615    pub fn whole_text(text: &str) -> Self {
616        Self(serde_json::Value::String(
617            text.chars().filter(|ch| !ch.is_control()).collect(),
618        ))
619    }
620
621    /// Any serializable plain value (a bool, a number, a unit enum, a
622    /// string). `None` when it serializes to anything else.
623    pub fn of<T: Serialize + ?Sized>(value: &T) -> Option<Self> {
624        Self::from_json(&serde_json::to_value(value).ok()?)
625    }
626
627    pub fn as_json(&self) -> &serde_json::Value {
628        &self.0
629    }
630
631    pub fn as_bool(&self) -> Option<bool> {
632        self.0.as_bool()
633    }
634
635    pub fn as_str(&self) -> Option<&str> {
636        self.0.as_str()
637    }
638
639    pub fn as_f64(&self) -> Option<f64> {
640        self.0.as_f64()
641    }
642}
643
644impl From<bool> for Scalar {
645    fn from(value: bool) -> Self {
646        Self(serde_json::Value::Bool(value))
647    }
648}
649
650impl From<i64> for Scalar {
651    fn from(value: i64) -> Self {
652        Self(value.into())
653    }
654}
655
656impl From<&str> for Scalar {
657    fn from(value: &str) -> Self {
658        Self::text(value)
659    }
660}
661
662#[cfg(test)]
663mod tests {
664    use super::*;
665
666    tilo_test_env::scenario! {
667        fn an_entry_describes_what_an_action_did;
668
669        phase encoded_actions_describe_themselves_as_verbs;
670        {
671            let encoded = crate::EncodedAction {
672                type_id: "notes.action".into(),
673                payload: br#"{"RenameNote":{"id":"n1","title":"Groceries","tags":["a"]}}"#.to_vec(),
674            };
675            let described = Described::from_encoded(&encoded, None).unwrap();
676            let Did::Verb(verb) = &described.what else {
677                panic!("a verb: {described:?}");
678            };
679            assert_eq!(
680                verb.action,
681                ActionKey::new("notes", "notes.action", "rename-note")
682            );
683            assert_eq!(verb.args.get("title"), Some(&Scalar::from("Groceries")));
684            assert!(
685                !verb.args.contains_key("tags"),
686                "nested values are left out"
687            );
688
689            let tagged = crate::EncodedAction {
690                type_id: "canvas.action".into(),
691                payload: br#"{"op":{"action":"draw","args":{"size":3}},"at":17}"#.to_vec(),
692            };
693            let Did::Verb(verb) = Described::from_encoded(&tagged, Some("canvas"))
694                .unwrap()
695                .what
696            else {
697                panic!("a verb");
698            };
699            assert_eq!(verb.action.action, "draw");
700            assert_eq!(verb.args.get("size"), Some(&Scalar::from(3)));
701            assert!(
702                Described::from_encoded(
703                    &crate::EncodedAction {
704                        type_id: "x".into(),
705                        payload: b"7".to_vec()
706                    },
707                    None
708                )
709                .is_none()
710            );
711        }
712
713        phase a_verbs_text_arguments_are_kept_whole;
714        // A long text argument reaches the entry whole, as passed: a formula
715        // an agent added, a calculation the palette committed.
716        {
717            let formula = ["x"; 60].join("+");
718            let tagged = crate::EncodedAction {
719                type_id: "calculator.action".into(),
720                payload: serde_json::to_vec(&serde_json::json!({
721                    "action": "commit-history",
722                    "args": {"expr": formula, "result": "1", "nested": {"note": formula}},
723                }))
724                .unwrap(),
725            };
726            let Did::Verb(verb) = Described::from_encoded(&tagged, Some("calculator"))
727                .unwrap()
728                .what
729            else {
730                panic!("a verb");
731            };
732            assert_eq!(verb.args.get("expr"), Some(&Scalar::whole_text(&formula)));
733            assert_eq!(
734                verb.args.get("nested.note"),
735                Some(&Scalar::whole_text(&formula))
736            );
737        }
738
739        phase values_are_bounded;
740        {
741            let long = "x".repeat(MAX_SCALAR_CHARS * 2);
742            assert_eq!(
743                Scalar::text(&long).as_str().unwrap().chars().count(),
744                MAX_SCALAR_CHARS + 1
745            );
746            assert!(Scalar::from_json(&serde_json::json!({"a": 1})).is_none());
747            assert!(Scalar::from_json(&serde_json::Value::Null).is_none());
748            let args = (0..20).map(|n| (format!("a{n}"), Scalar::from(i64::from(n))));
749            let Did::Verb(verb) = Did::verb(ActionKey::default(), args) else {
750                unreachable!()
751            };
752            assert_eq!(verb.args.len(), MAX_VERB_ARGS);
753            let Did::Group(group) = Did::group((0..20).map(|_| Did::verb(ActionKey::default(), [])))
754            else {
755                unreachable!()
756            };
757            assert_eq!((group.members.len(), group.count), (MAX_GROUP_MEMBERS, 20));
758            assert_eq!(group.distinct.len(), 1, "every member ran the same action");
759            assert!(
760                group.shared().is_none(),
761                "a cut group does not claim one shared step"
762            );
763        }
764
765        phase every_kind_of_entry_reads_back_from_its_json;
766        {
767            let edit = Did::Edit(FieldEdit {
768                ty: "snippet".into(),
769                field: "title".into(),
770                path: vec![
771                    PathStep::Item("s1".into()),
772                    PathStep::Cell("r1".into(), "c2".into()),
773                ],
774                op: EditOp::Set,
775                old: Some(Scalar::text("a")),
776                new: Some(Scalar::text("b")),
777                args: BTreeMap::from([("mark".to_owned(), Scalar::from(true))]),
778            });
779            let verb = Did::verb(ActionKey::default(), [("size".to_owned(), Scalar::from(3))]);
780            let group = Did::group([edit.clone(), verb.clone()]);
781            let history = Did::history(
782                HistoryOp::Checkpoint {
783                    name: "draft".into(),
784                },
785                1,
786                Some(Described::new(group.clone()).on("s1", "First")),
787            );
788            for did in [edit, verb, group, history] {
789                let json = serde_json::to_string(&did).unwrap();
790                assert!(json.starts_with(r#"{"did":"#), "the tag leads: {json}");
791                let read: Did = serde_json::from_str(&json).unwrap();
792                assert_eq!(read, did);
793                assert_eq!(serde_json::to_string(&read).unwrap(), json);
794                let from_value: Did =
795                    serde_json::from_value(serde_json::to_value(&did).unwrap()).unwrap();
796                assert_eq!(from_value, did);
797            }
798            for bad in [r#"{"did":"wave"}"#, r#"{"ty":"x"}"#, r#"{"did":3}"#, "[]"] {
799                assert!(serde_json::from_str::<Did>(bad).is_err(), "{bad}");
800            }
801        }
802
803        phase kebab_names;
804        {
805            assert_eq!(kebab("RemoveMarks"), "remove-marks");
806            assert_eq!(kebab("remove_marks"), "remove-marks");
807            assert_eq!(kebab("Set2Up"), "set2-up");
808        }
809    }
810}