tilo-actions 0.5.0

The Tilo action model: resources, the actions on them, and their registry, with the plain resource vocabulary that needs no store, search index entries included.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
//! What a committed action did, as data.
//!
//! Every change an action commits carries a history entry
//! ([`crate::ActionContext`]): who acted, for whom, on which item and what
//! they did. "What they did" is a [`Did`]: a field edit with its path and,
//! for scalars, the value before and after; a verb with its [`ActionKey`]
//! and scalar arguments; a group of those; or a history step (undo, redo,
//! restore, checkpoint). No sentence is stored. Readers render one in their
//! own language (`tilo-history`), and agents, scripts and logs read the data.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::key::ActionKey;

/// Longest text kept for one scalar value, in characters.
pub const MAX_SCALAR_CHARS: usize = 80;
/// Most arguments kept for one verb.
pub const MAX_VERB_ARGS: usize = 8;
/// Most members of a group kept by value; [`GroupOf::count`] keeps the total.
pub const MAX_GROUP_MEMBERS: usize = 8;

/// What an action did.
#[derive(Debug, PartialEq, Eq, Serialize)]
#[serde(remote = "Self", tag = "did", rename_all = "kebab-case")]
pub enum Did {
    Edit(FieldEdit),
    Verb(VerbCall),
    Group(GroupOf),
    History(HistoryStep),
}

// Written through its JSON text: the derived writer is compiled once, for
// JSON bytes, and every serializer an entry goes to (bytes, a value, a size
// count) takes that text as it is, rather than holding a copy of the derived
// writer of its own. The bytes are the derive's, tag first. Like its reading,
// this is for JSON only (see `read_through_json_value!`).
impl serde::Serialize for Did {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.to_json_text()
            .map_err(serde::ser::Error::custom)?
            .serialize(serializer)
    }
}

impl<'de> serde::Deserialize<'de> for Did {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
        Self::from_json_value(value).map_err(serde::de::Error::custom)
    }
}

impl Did {
    /// Its JSON text, as the derived writer writes it.
    #[inline(never)]
    fn to_json_text(&self) -> Result<Box<serde_json::value::RawValue>, serde_json::Error> {
        /// The derived writer, as a value to serialize.
        struct Derived<'a>(&'a Did);
        impl serde::Serialize for Derived<'_> {
            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                Did::serialize(self.0, serializer)
            }
        }
        serde_json::value::to_raw_value(&Derived(self))
    }

    /// Read by its `did` tag, each variant's fields straight from the
    /// object: no buffered copy of the entry.
    #[inline(never)]
    fn from_json_value(value: serde_json::Value) -> Result<Self, serde_json::Error> {
        use serde::de::Error;
        let serde_json::Value::Object(mut fields) = value else {
            return Err(serde_json::Error::custom("an entry is an object"));
        };
        let tag = match fields.remove("did") {
            Some(serde_json::Value::String(tag)) => tag,
            Some(_) => return Err(serde_json::Error::custom("`did` is a string")),
            None => return Err(serde_json::Error::missing_field("did")),
        };
        let fields = serde_json::Value::Object(fields);
        match tag.as_str() {
            "edit" => serde_json::from_value(fields).map(Self::Edit),
            "verb" => serde_json::from_value(fields).map(Self::Verb),
            "group" => serde_json::from_value(fields).map(Self::Group),
            "history" => serde_json::from_value(fields).map(Self::History),
            other => Err(serde_json::Error::unknown_variant(
                other,
                &["edit", "verb", "group", "history"],
            )),
        }
    }
}

// Written out rather than derived: a derived clone is inlined into every
// crate that clones an entry, and entries are cloned throughout the toolkit.
impl Clone for Did {
    fn clone(&self) -> Self {
        match self {
            Self::Edit(edit) => Self::Edit(edit.clone()),
            Self::Verb(verb) => Self::Verb(verb.clone()),
            Self::Group(group) => Self::Group(group.clone()),
            Self::History(step) => Self::History(step.clone()),
        }
    }
}

impl Did {
    /// A verb with its arguments bounded to plain values.
    pub fn verb(action: ActionKey, args: impl IntoIterator<Item = (String, Scalar)>) -> Self {
        Self::Verb(VerbCall::new(action, args))
    }

    /// A group of `members`, keeping at most [`MAX_GROUP_MEMBERS`] by value
    /// and every distinct action among them without its values.
    pub fn group(members: impl IntoIterator<Item = Did>) -> Self {
        let mut count = 0u32;
        let mut kept = Vec::new();
        let mut distinct: Vec<Did> = Vec::new();
        for member in members {
            count = count.saturating_add(1);
            let mut action = member.clone();
            action.forget_values();
            if !distinct.contains(&action) {
                distinct.push(action);
            }
            if kept.len() < MAX_GROUP_MEMBERS {
                kept.push(member);
            }
        }
        Self::Group(GroupOf {
            members: kept,
            count,
            distinct,
        })
    }

    /// Drop every value, keeping only which action ran where.
    fn forget_values(&mut self) {
        self.forget_args();
        match self {
            Self::Edit(edit) => edit.args.clear(),
            Self::Group(group) => {
                group.members.iter_mut().for_each(Self::forget_values);
                group.distinct.iter_mut().for_each(Self::forget_values);
            }
            Self::Verb(_) | Self::History(_) => {}
        }
    }

    /// Drop every verb argument and field value, keeping what was done and
    /// where: the form a public audit keeps.
    pub fn forget_args(&mut self) {
        match self {
            Self::Edit(edit) => {
                edit.old = None;
                edit.new = None;
            }
            Self::Verb(verb) => verb.args.clear(),
            Self::Group(group) => group.members.iter_mut().for_each(Self::forget_args),
            Self::History(step) => {
                if let Some(of) = &mut step.of {
                    of.what.forget_args();
                }
            }
        }
    }

    pub fn history(op: HistoryOp, steps: u32, of: Option<Described>) -> Self {
        Self::History(HistoryStep {
            op,
            steps,
            of: of.map(Box::new),
            undoes: None,
            verb: String::new(),
        })
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FieldEdit {
    /// The model type that owns the field, kebab-case (`snippet`).
    pub ty: String,
    /// The field's storage key (`favorite`).
    pub field: String,
    /// Where the field is, from the resource's root.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub path: Vec<PathStep>,
    pub op: EditOp,
    /// The value before, for a scalar field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old: Option<Scalar>,
    /// The value after, for a scalar field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub new: Option<Scalar>,
    /// Plain facts of an edit the field's own type describes (a rich-text
    /// edit's mark, the words it covered), by name.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub args: BTreeMap<String, Scalar>,
}

/// One step of a path from a resource's root to a field.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PathStep {
    Field(String),
    Item(String),
    Key(String),
    Cell(String, String),
}

/// The operation of a field edit.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum EditOp {
    Set,
    Splice,
    Replace,
    Add,
    Insert,
    Remove,
    MoveTo,
    Mark,
    SetCell,
    InsertRow,
    InsertColumn,
    RemoveRow,
    RemoveColumn,
    /// The owning device recorded how an outbox entry settled (`$state`:
    /// `done` or `failed`, with `$reason`).
    Settle,
    /// A settled outbox entry was forgotten.
    Forget,
    /// The actor reacted with an emoji (`new`).
    React,
    /// The actor took back their reaction with an emoji (`new`).
    Unreact,
}

impl EditOp {
    /// The name readers pass to messages as `$op`.
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Set => "set",
            Self::Splice => "splice",
            Self::Replace => "replace",
            Self::Add => "add",
            Self::Insert => "insert",
            Self::Remove => "remove",
            Self::MoveTo => "move-to",
            Self::Mark => "mark",
            Self::SetCell => "set-cell",
            Self::InsertRow => "insert-row",
            Self::InsertColumn => "insert-column",
            Self::RemoveRow => "remove-row",
            Self::RemoveColumn => "remove-column",
            Self::Settle => "settle",
            Self::Forget => "forget",
            Self::React => "react",
            Self::Unreact => "unreact",
        }
    }
}

/// A verb and its plain arguments by parameter name.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct VerbCall {
    pub action: ActionKey,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub args: BTreeMap<String, Scalar>,
}

impl VerbCall {
    /// Keeps at most [`MAX_VERB_ARGS`] arguments.
    pub fn new(action: ActionKey, args: impl IntoIterator<Item = (String, Scalar)>) -> Self {
        Self {
            action,
            args: args.into_iter().take(MAX_VERB_ARGS).collect(),
        }
    }
}

/// Several actions committed as one change.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct GroupOf {
    /// The first [`MAX_GROUP_MEMBERS`] members.
    pub members: Vec<Did>,
    pub count: u32,
    /// Every distinct action among the members, without values, however
    /// many members there were: what a receiver decides the change by.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub distinct: Vec<Did>,
}

impl GroupOf {
    /// The one thing every member did, when they all did the same.
    pub fn shared(&self) -> Option<&Did> {
        let first = self.members.first()?;
        (self.count as usize == self.members.len() && self.members.iter().all(|m| m == first))
            .then_some(first)
    }
}

/// A step through history itself.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct HistoryStep {
    pub op: HistoryOp,
    /// How many steps it took back or brought back.
    #[serde(default)]
    pub steps: u32,
    /// What it took back or brought back, when it was one step.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub of: Option<Box<Described>>,
    /// The invocation it took back or brought back, when it moved one: each change of an undo
    /// moves one invocation, so whoever admits it reads one invocation per change.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub undoes: Option<String>,
    /// The verb of that invocation, as it was invoked.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub verb: String,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum HistoryOp {
    Undo,
    Redo,
    Restore,
    Checkpoint {
        name: String,
    },
    /// The document was brought to the storage version `to`.
    Migrate {
        to: u32,
    },
}

/// The item an action addressed, with its label at the time: one line that
/// names it ([`Described::on`]), never its text.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActionItem {
    pub id: String,
    pub label: String,
}

/// What an action says about itself before it applies: what it does and to
/// which item ([`crate::Action::describe`]).
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Described {
    pub what: Did,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub item: Option<ActionItem>,
}

impl Described {
    pub fn new(what: Did) -> Self {
        Self { what, item: None }
    }

    /// About the item `id`, named by `label` as one line people read
    /// ([`one_line`](crate::context::one_line), at most
    /// [`MAX_LABEL_CHARS`](crate::context::MAX_LABEL_CHARS) characters): an
    /// entry names its item, it never carries what the item reads. A message
    /// is labelled by its text, so a label kept whole put the whole reply so
    /// far into every change that grew it. An item with no name of its own
    /// is called by its id, which stays whole: a reader takes a label that
    /// repeats the id for no name.
    ///
    /// Only an entry being written passes here. A kept entry is read back as
    /// it was written, so a change from before this rule keeps its bytes, and
    /// is verified and undone under them ([`crate::verify_change`]).
    #[must_use]
    pub fn on(mut self, id: impl Into<String>, label: impl Into<String>) -> Self {
        let (id, label) = (id.into(), label.into());
        let label = if label == id {
            label
        } else {
            crate::context::one_line(&label, crate::context::MAX_LABEL_CHARS).unwrap_or_default()
        };
        self.item = Some(ActionItem { id, label });
        self
    }

    /// The published action `key` invoked with `encoded`: the verb with the
    /// plain arguments the encoded value carries. An empty `key.app` is
    /// filled by the executor from the entry's app.
    pub fn of_published(encoded: &crate::EncodedAction, key: ActionKey) -> Option<Self> {
        let value = without_lists(&encoded.payload)?;
        let args = variant_of(&value).and_then(|(_, fields)| fields);
        Some(Self::new(Did::verb(key, plain_args(args))))
    }

    /// What an encoded action says about itself when its type describes
    /// nothing: the verb its serde variant names, with its plain arguments.
    /// `app` names the publishing app; without one the action type's stem
    /// (`notes` of `notes.action`) stands in.
    pub fn from_encoded(encoded: &crate::EncodedAction, app: Option<&str>) -> Option<Self> {
        let value = without_lists(&encoded.payload)?;
        Self::from_value(&encoded.type_id, &value, app)
    }

    /// [`Self::from_encoded`] for an action value already in JSON.
    pub fn from_value(type_id: &str, value: &serde_json::Value, app: Option<&str>) -> Option<Self> {
        let (variant, fields) = variant_of(value)?;
        let app = app
            .filter(|app| !app.trim().is_empty())
            .map_or_else(|| type_stem(type_id), str::to_owned);
        Some(Self::new(Did::verb(
            ActionKey::new(app, type_id, kebab(variant)),
            plain_args(fields),
        )))
    }
}

/// The plain arguments of a variant's fields (an adjacently tagged value's
/// `args`, else the fields beside an internal `action` tag): its plain
/// values by name, then the plain values of its nested records as
/// `record.field`. Text arguments are kept whole ([`Scalar::argument`]):
/// what a person, a script or an agent passed is what the change says it
/// did, and a reader that recalls it (a calculation put back, a formula
/// opened) gets all of it.
fn plain_args(
    fields: Option<&serde_json::Map<String, serde_json::Value>>,
) -> impl Iterator<Item = (String, Scalar)> + '_ {
    let tagged = fields.is_some_and(|fields| fields.contains_key("action"));
    let fields = match fields.and_then(|fields| fields.get("args")) {
        Some(serde_json::Value::Object(args)) if tagged => Some(args),
        _ => fields,
    };
    let own = move || {
        fields
            .into_iter()
            .flat_map(serde_json::Map::iter)
            .filter(move |(name, _)| !(tagged && name.as_str() == "action"))
    };
    let plain = own().filter_map(|(name, value)| Some((name.clone(), Scalar::argument(value)?)));
    let nested = own().flat_map(|(name, value)| {
        value
            .as_object()
            .into_iter()
            .flat_map(serde_json::Map::iter)
            .filter_map(move |(field, value)| {
                Some((format!("{name}.{field}"), Scalar::argument(value)?))
            })
    });
    plain.chain(nested)
}

/// The JSON value of `payload` with every list in it read as empty: what an
/// action is described by, as no list is a plain argument, read without
/// building the lists an action carries in bulk (the issues of a long list
/// made in one call).
fn without_lists(payload: &[u8]) -> Option<serde_json::Value> {
    use serde::de::{IgnoredAny, MapAccess, SeqAccess, Visitor};

    struct Shallow(serde_json::Value);

    impl<'de> Deserialize<'de> for Shallow {
        fn deserialize<D: serde::Deserializer<'de>>(from: D) -> Result<Self, D::Error> {
            from.deserialize_any(ShallowVisitor)
        }
    }

    struct ShallowVisitor;

    impl<'de> Visitor<'de> for ShallowVisitor {
        type Value = Shallow;

        fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            formatter.write_str("a JSON value")
        }

        fn visit_bool<E>(self, value: bool) -> Result<Shallow, E> {
            Ok(Shallow(value.into()))
        }

        fn visit_i64<E>(self, value: i64) -> Result<Shallow, E> {
            Ok(Shallow(value.into()))
        }

        fn visit_u64<E>(self, value: u64) -> Result<Shallow, E> {
            Ok(Shallow(value.into()))
        }

        fn visit_f64<E>(self, value: f64) -> Result<Shallow, E> {
            Ok(Shallow(value.into()))
        }

        fn visit_str<E>(self, value: &str) -> Result<Shallow, E> {
            Ok(Shallow(value.into()))
        }

        fn visit_string<E>(self, value: String) -> Result<Shallow, E> {
            Ok(Shallow(value.into()))
        }

        fn visit_unit<E>(self) -> Result<Shallow, E> {
            Ok(Shallow(serde_json::Value::Null))
        }

        fn visit_none<E>(self) -> Result<Shallow, E> {
            Ok(Shallow(serde_json::Value::Null))
        }

        fn visit_seq<A: SeqAccess<'de>>(self, mut items: A) -> Result<Shallow, A::Error> {
            while items.next_element::<IgnoredAny>()?.is_some() {}
            Ok(Shallow(serde_json::Value::Array(Vec::new())))
        }

        fn visit_map<A: MapAccess<'de>>(self, mut entries: A) -> Result<Shallow, A::Error> {
            let mut fields = serde_json::Map::new();
            while let Some((name, Shallow(value))) = entries.next_entry::<String, Shallow>()? {
                fields.insert(name, value);
            }
            Ok(Shallow(serde_json::Value::Object(fields)))
        }
    }

    serde_json::from_slice::<Shallow>(payload)
        .ok()
        .map(|Shallow(value)| value)
}

/// The variant name and fields of an externally, adjacently or internally
/// tagged action value, looking through a stamped `{op, at}` envelope.
fn variant_of(
    value: &serde_json::Value,
) -> Option<(&str, Option<&serde_json::Map<String, serde_json::Value>>)> {
    match value {
        serde_json::Value::String(variant) => Some((variant, None)),
        serde_json::Value::Object(fields) => {
            if let (Some(op), Some(_)) = (fields.get("op"), fields.get("at"))
                && fields.len() == 2
            {
                return variant_of(op);
            }
            if let Some(serde_json::Value::String(variant)) = fields.get("action") {
                return Some((variant, Some(fields)));
            }
            if fields.len() == 1 {
                let (variant, inner) = fields.iter().next()?;
                return Some((variant, inner.as_object()));
            }
            None
        }
        _ => None,
    }
}

fn type_stem(type_id: &str) -> String {
    type_id.split('.').next().unwrap_or(type_id).to_owned()
}

/// `RemoveMarks`, `remove_marks` and `remove-marks` all become `remove-marks`.
pub fn kebab(name: &str) -> String {
    let mut out = String::with_capacity(name.len().saturating_add(4));
    let mut previous_lower_or_digit = false;
    for ch in name.chars() {
        if ch == '_' || ch == '-' || ch == ' ' {
            if !out.is_empty() && !out.ends_with('-') {
                out.push('-');
            }
            previous_lower_or_digit = false;
            continue;
        }
        if ch.is_uppercase() && previous_lower_or_digit {
            out.push('-');
        }
        previous_lower_or_digit = ch.is_lowercase() || ch.is_ascii_digit();
        out.extend(ch.to_lowercase());
    }
    out
}

/// One plain value in an entry: a boolean, a number, a short text or an
/// enum variant. Nested values are never stored.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Scalar(serde_json::Value);

impl Scalar {
    /// A plain JSON value, text cut to [`MAX_SCALAR_CHARS`]. `None` for
    /// arrays and objects, and for null.
    pub fn from_json(value: &serde_json::Value) -> Option<Self> {
        match value {
            serde_json::Value::Bool(_) | serde_json::Value::Number(_) => Some(Self(value.clone())),
            serde_json::Value::String(text) => Some(Self::text(text)),
            _ => None,
        }
    }

    /// A verb's argument as passed: a plain JSON value, text kept whole
    /// ([`Self::whole_text`]). `None` for arrays and objects, and for null.
    pub fn argument(value: &serde_json::Value) -> Option<Self> {
        match value {
            serde_json::Value::String(text) => Some(Self::whole_text(text)),
            _ => Self::from_json(value),
        }
    }

    /// Text cut to [`MAX_SCALAR_CHARS`], without control characters.
    pub fn text(text: &str) -> Self {
        let mut chars = text.chars().filter(|ch| !ch.is_control());
        let cut: String = chars.by_ref().take(MAX_SCALAR_CHARS).collect();
        if chars.next().is_some() {
            Self(serde_json::Value::String(cut + "…"))
        } else {
            Self(serde_json::Value::String(cut))
        }
    }

    /// A text an edit wrote whole (a formula, a title), kept whole without
    /// control characters: the change carries the text anyway, and a reader
    /// elides it where it draws it. Other text is cut ([`Self::text`]).
    pub fn whole_text(text: &str) -> Self {
        Self(serde_json::Value::String(
            text.chars().filter(|ch| !ch.is_control()).collect(),
        ))
    }

    /// Any serializable plain value (a bool, a number, a unit enum, a
    /// string). `None` when it serializes to anything else.
    pub fn of<T: Serialize + ?Sized>(value: &T) -> Option<Self> {
        Self::from_json(&serde_json::to_value(value).ok()?)
    }

    pub fn as_json(&self) -> &serde_json::Value {
        &self.0
    }

    pub fn as_bool(&self) -> Option<bool> {
        self.0.as_bool()
    }

    pub fn as_str(&self) -> Option<&str> {
        self.0.as_str()
    }

    pub fn as_f64(&self) -> Option<f64> {
        self.0.as_f64()
    }
}

impl From<bool> for Scalar {
    fn from(value: bool) -> Self {
        Self(serde_json::Value::Bool(value))
    }
}

impl From<i64> for Scalar {
    fn from(value: i64) -> Self {
        Self(value.into())
    }
}

impl From<&str> for Scalar {
    fn from(value: &str) -> Self {
        Self::text(value)
    }
}

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

    tilo_test_env::scenario! {
        fn an_entry_describes_what_an_action_did;

        phase encoded_actions_describe_themselves_as_verbs;
        {
            let encoded = crate::EncodedAction {
                type_id: "notes.action".into(),
                payload: br#"{"RenameNote":{"id":"n1","title":"Groceries","tags":["a"]}}"#.to_vec(),
            };
            let described = Described::from_encoded(&encoded, None).unwrap();
            let Did::Verb(verb) = &described.what else {
                panic!("a verb: {described:?}");
            };
            assert_eq!(
                verb.action,
                ActionKey::new("notes", "notes.action", "rename-note")
            );
            assert_eq!(verb.args.get("title"), Some(&Scalar::from("Groceries")));
            assert!(
                !verb.args.contains_key("tags"),
                "nested values are left out"
            );

            let tagged = crate::EncodedAction {
                type_id: "canvas.action".into(),
                payload: br#"{"op":{"action":"draw","args":{"size":3}},"at":17}"#.to_vec(),
            };
            let Did::Verb(verb) = Described::from_encoded(&tagged, Some("canvas"))
                .unwrap()
                .what
            else {
                panic!("a verb");
            };
            assert_eq!(verb.action.action, "draw");
            assert_eq!(verb.args.get("size"), Some(&Scalar::from(3)));
            assert!(
                Described::from_encoded(
                    &crate::EncodedAction {
                        type_id: "x".into(),
                        payload: b"7".to_vec()
                    },
                    None
                )
                .is_none()
            );
        }

        phase a_verbs_text_arguments_are_kept_whole;
        // A long text argument reaches the entry whole, as passed: a formula
        // an agent added, a calculation the palette committed.
        {
            let formula = ["x"; 60].join("+");
            let tagged = crate::EncodedAction {
                type_id: "calculator.action".into(),
                payload: serde_json::to_vec(&serde_json::json!({
                    "action": "commit-history",
                    "args": {"expr": formula, "result": "1", "nested": {"note": formula}},
                }))
                .unwrap(),
            };
            let Did::Verb(verb) = Described::from_encoded(&tagged, Some("calculator"))
                .unwrap()
                .what
            else {
                panic!("a verb");
            };
            assert_eq!(verb.args.get("expr"), Some(&Scalar::whole_text(&formula)));
            assert_eq!(
                verb.args.get("nested.note"),
                Some(&Scalar::whole_text(&formula))
            );
        }

        phase values_are_bounded;
        {
            let long = "x".repeat(MAX_SCALAR_CHARS * 2);
            assert_eq!(
                Scalar::text(&long).as_str().unwrap().chars().count(),
                MAX_SCALAR_CHARS + 1
            );
            assert!(Scalar::from_json(&serde_json::json!({"a": 1})).is_none());
            assert!(Scalar::from_json(&serde_json::Value::Null).is_none());
            let args = (0..20).map(|n| (format!("a{n}"), Scalar::from(i64::from(n))));
            let Did::Verb(verb) = Did::verb(ActionKey::default(), args) else {
                unreachable!()
            };
            assert_eq!(verb.args.len(), MAX_VERB_ARGS);
            let Did::Group(group) = Did::group((0..20).map(|_| Did::verb(ActionKey::default(), [])))
            else {
                unreachable!()
            };
            assert_eq!((group.members.len(), group.count), (MAX_GROUP_MEMBERS, 20));
            assert_eq!(group.distinct.len(), 1, "every member ran the same action");
            assert!(
                group.shared().is_none(),
                "a cut group does not claim one shared step"
            );
        }

        phase every_kind_of_entry_reads_back_from_its_json;
        {
            let edit = Did::Edit(FieldEdit {
                ty: "snippet".into(),
                field: "title".into(),
                path: vec![
                    PathStep::Item("s1".into()),
                    PathStep::Cell("r1".into(), "c2".into()),
                ],
                op: EditOp::Set,
                old: Some(Scalar::text("a")),
                new: Some(Scalar::text("b")),
                args: BTreeMap::from([("mark".to_owned(), Scalar::from(true))]),
            });
            let verb = Did::verb(ActionKey::default(), [("size".to_owned(), Scalar::from(3))]);
            let group = Did::group([edit.clone(), verb.clone()]);
            let history = Did::history(
                HistoryOp::Checkpoint {
                    name: "draft".into(),
                },
                1,
                Some(Described::new(group.clone()).on("s1", "First")),
            );
            for did in [edit, verb, group, history] {
                let json = serde_json::to_string(&did).unwrap();
                assert!(json.starts_with(r#"{"did":"#), "the tag leads: {json}");
                let read: Did = serde_json::from_str(&json).unwrap();
                assert_eq!(read, did);
                assert_eq!(serde_json::to_string(&read).unwrap(), json);
                let from_value: Did =
                    serde_json::from_value(serde_json::to_value(&did).unwrap()).unwrap();
                assert_eq!(from_value, did);
            }
            for bad in [r#"{"did":"wave"}"#, r#"{"ty":"x"}"#, r#"{"did":3}"#, "[]"] {
                assert!(serde_json::from_str::<Did>(bad).is_err(), "{bad}");
            }
        }

        phase kebab_names;
        {
            assert_eq!(kebab("RemoveMarks"), "remove-marks");
            assert_eq!(kebab("remove_marks"), "remove-marks");
            assert_eq!(kebab("Set2Up"), "set2-up");
        }
    }
}