tilo-resource 0.5.2

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

use tilo_resource::AppNamed;
use tilo_resource::{
    ActionCx, Bytes, Collection, Counter, Edit, Grid, Id, Invoke, Model, Outbox, Path, Refusal,
    Replica, Resource, Segment, Set, Settled, resource,
};

#[derive(Model, Default, Debug, Clone, PartialEq)]
#[model(check = Snippet::valid)]
pub struct Snippet {
    /// The snippet's title.
    #[model(label)]
    pub title: String,
    pub body: String,
    pub favorite: bool,
    pub language: Language,
    pub tags: Set<String>,
    #[model(readonly)]
    pub uses: Counter,
}

impl Snippet {
    fn valid(&self) -> Result<(), Refusal> {
        if self.title.chars().count() > 20 {
            return Err(Refusal::new("a title has at most 20 characters"));
        }
        Ok(())
    }
}

#[derive(Model, Default, Debug, Clone, Copy, PartialEq, Eq)]
pub enum Language {
    #[default]
    Text,
    Rust,
}

#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Library {
    pub name: String,
    #[model(unit)]
    pub snippets: Collection<Snippet>,
    pub sheet: Grid<String>,
    pub sent: Outbox<String>,
    pub stars: Counter,
    pub logo: Bytes,
}

#[resource(kind = "test.library", catalogue = "tests/locales")]
impl Library {
    /// Create a snippet: a unit of its own.
    #[action(writes = snippets)]
    pub fn new_snippet(&mut self, cx: &mut ActionCx, title: String) {
        self.snippets.push(
            cx.id(),
            Snippet {
                title,
                ..Snippet::default()
            },
        );
    }

    /// Record a use.
    #[action]
    pub fn record_use(&mut self, snippet: &Id) {
        if let Some(snippet) = self.snippets.get_mut(snippet) {
            snippet.uses.add(1);
        }
    }

    /// Star the library.
    #[action]
    pub fn star(&mut self) {
        self.stars.add(1);
    }

    /// Share the library with someone.
    #[action]
    pub fn share(&mut self, cx: &mut ActionCx, with: String) {
        self.sent.push(cx.id(), with);
    }
}

fn edit(replica: &mut Replica<Library, AppNamed>, edit: &Edit<Library>) -> Result<(), String> {
    replica
        .apply(Invoke::edit(edit).map_err(|error| error.to_string())?)
        .map(drop)
        .map_err(|error| error.to_string())
}

fn first_snippet(replica: &Replica<Library, AppNamed>) -> Id {
    replica
        .state()
        .unwrap()
        .snippets
        .ids()
        .next()
        .unwrap()
        .clone()
}

tilo_test_env::scenario! {
    fn a_path_names_reads_and_edits_what_it_addresses;

    phase a_path_is_plain_data_naming_fields_and_items;
    {
        let id = Id::from_raw("s1");
        let favorite: Path<Library, bool> = Library::paths().snippets.item(&id).favorite;
        assert_eq!(
            favorite.segments(),
            [
                Segment::Field("snippets".into()),
                Segment::Item(id.clone()),
                Segment::Field("favorite".into()),
            ]
        );
        let json = serde_json::to_string(&favorite).unwrap();
        let back: Path<Library, bool> = serde_json::from_str(&json).unwrap();
        assert_eq!(back, favorite);
        // A row's own paths, rooted at the item, read the same from the record.
        let row = Snippet::paths().favorite;
        let item = Library::paths().snippets.item(&id);
        assert_eq!(row.under(item.path()), favorite);
        assert!(favorite.starts_with(item.path()));
        assert_ne!(Library::paths().snippets.item(&id).title, favorite.cast());
    }

    phase field_edits_apply_at_their_path_and_merge;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        library.apply(Library::NEW_SNIPPET.with("Deploy")).unwrap();
        let id = first_snippet(&library);
        let snippet = Library::paths().snippets.item(&id);
        edit(&mut library, &snippet.favorite.set(true)).unwrap();
        edit(&mut library, &snippet.language.set(Language::Rust)).unwrap();
        edit(&mut library, &snippet.body.splice(0, 0, "cargo")).unwrap();
        edit(&mut library, &snippet.tags.insert(&"ops".to_owned())).unwrap();

        let mut other = library.fork();
        edit(&mut library, &snippet.body.splice(5, 0, " build")).unwrap();
        edit(&mut other, &snippet.body.splice(0, 0, "$ ")).unwrap();
        edit(&mut other, &snippet.tags.insert(&"ci".to_owned())).unwrap();
        library.sync_with(&mut other).unwrap();

        for replica in [&library, &other] {
            let state = replica.state().unwrap();
            let snippet = state.snippets.get(&id).unwrap();
            assert!(snippet.favorite);
            assert_eq!(snippet.language, Language::Rust);
            assert_eq!(snippet.body, "$ cargo build");
            assert_eq!(
                snippet.tags.iter().cloned().collect::<Vec<_>>(),
                ["ci", "ops"]
            );
        }
        assert_eq!(library.state().unwrap(), other.state().unwrap());
        // The log replays to the same state.
        let mut replay = Replica::<Library>::from_doc(other.doc_mut().fork()).in_app("so.tilo.model", "Model");
        replay.sync_with(&mut library).unwrap();
        assert_eq!(replay.state().unwrap(), library.state().unwrap());
    }

    phase collection_edits_insert_move_and_remove_items;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        let snippets = Library::paths().snippets;
        let titled = |title: &str| Snippet {
            title: title.into(),
            ..Snippet::default()
        };
        edit(&mut library, &snippets.insert(0, &titled("b"))).unwrap();
        edit(&mut library, &snippets.insert(0, &titled("a"))).unwrap();
        edit(&mut library, &snippets.insert(9, &titled("c"))).unwrap();
        let order = |replica: &Replica<Library, AppNamed>| {
            replica
                .state()
                .unwrap()
                .snippets
                .values()
                .map(|snippet| snippet.title.clone())
                .collect::<Vec<_>>()
        };
        assert_eq!(order(&library), ["a", "b", "c"]);
        let ids: Vec<Id> = library.state().unwrap().snippets.ids().cloned().collect();
        edit(&mut library, &snippets.move_to(&ids[2], 0)).unwrap();
        assert_eq!(order(&library), ["c", "a", "b"]);

        let mut other = library.fork();
        // Removing an item is undoable: it asks nothing, as a delete verb of
        // the record does not.
        edit(&mut library, &snippets.remove(&ids[0])).unwrap();
        edit(&mut other, &snippets.insert(1, &titled("d"))).unwrap();
        library.sync_with(&mut other).unwrap();
        assert_eq!(order(&library), ["c", "d", "b"]);
        assert_eq!(order(&other), order(&library));
        assert!(
            library
                .apply_confirmed(snippets.remove(&ids[0]))
                .unwrap_err()
                .to_string()
                .contains("no item")
        );
    }

    phase an_edit_reads_only_its_path;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        library.apply(Library::NEW_SNIPPET.with("Deploy")).unwrap();
        let id = first_snippet(&library);
        library.apply(Library::NEW_SNIPPET.with("Other")).unwrap();
        let before = library.heads();
        edit(
            &mut library,
            &Library::paths().snippets.item(&id).favorite.set(true),
        )
        .unwrap();
        let changes = library.doc_mut().get_changes(&before);
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].len(), 1, "one scalar written");
    }

    phase readonly_fields_change_only_through_verbs;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        library.apply(Library::NEW_SNIPPET.with("Deploy")).unwrap();
        let id = first_snippet(&library);
        let uses = Library::paths().snippets.item(&id).uses;
        let refused = edit(&mut library, &uses.add(5)).unwrap_err();
        assert!(
            refused.contains("only by the record's actions"),
            "{refused}"
        );
        library.apply(Library::RECORD_USE.with(id.clone())).unwrap();
        assert_eq!(library.state().unwrap().snippets[&id].uses.get(), 1);
        assert!(Library::shape().unwrap().readonly_at(uses.segments()));
    }

    phase counters_add_up_across_replicas;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        let mut other = library.fork();
        library.apply(Library::STAR.invoke()).unwrap();
        other.apply(Library::STAR.invoke()).unwrap();
        edit(&mut other, &Library::paths().stars.add(3)).unwrap();
        library.sync_with(&mut other).unwrap();
        assert_eq!(library.state().unwrap().stars.get(), 5);
        assert_eq!(other.state().unwrap().stars.get(), 5);
        assert_eq!(library.live().unwrap().stars.get(), 5);
    }

    phase an_outbox_queues_entries_the_owner_settles;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        library.apply(Library::SHARE.with("ada")).unwrap();
        let state = library.state().unwrap();
        let (id, with) = state.sent.pending().next().unwrap();
        assert_eq!(with, "ada");
        let id = id.clone();
        edit(
            &mut library,
            &Library::paths().sent.settle(&id, &Settled::Done(())),
        )
        .unwrap();
        let state = library.state().unwrap();
        assert_eq!(state.sent.pending().count(), 0);
        assert_eq!(
            state.sent.get(&id).unwrap().settled,
            Some(Settled::Done(()))
        );
    }

    phase bytes_inline_small_values_and_reference_large_ones;
    {
        let small = Bytes::of(b"logo");
        assert_eq!(small.inline(), Some(&b"logo"[..]));
        let large = Bytes::of(&[7; 4096]);
        assert!(large.inline().is_none());
        assert_eq!(large.len(), 4096);
        for value in [small, large, Bytes::default()] {
            assert_eq!(Bytes::from_json(&value.to_json()).unwrap(), value);
            let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
            edit(&mut library, &Library::paths().logo.set(value.clone())).unwrap();
            assert_eq!(library.state().unwrap().logo, value);
        }
    }

    phase the_shape_names_units_titles_and_labels;
    {
        let shape = Library::shape().unwrap();
        let id = Id::from_raw("s");
        let title = Library::paths().snippets.item(&id).title;
        assert_eq!(
            shape.unit_of(title.segments()),
            [Segment::Field("snippets".into()), Segment::Item(id)]
        );
        assert!(shape.unit_of(Library::paths().name.segments()).is_empty());
        let snippet = Snippet::SHAPE.fields();
        assert_eq!(snippet[0].title, "The snippet's title");
        assert!(snippet[0].label);
        assert_eq!(
            Snippet {
                title: "Deploy\nmore".into(),
                ..Snippet::default()
            }
            .label()
            .as_deref(),
            Some("Deploy")
        );
    }

    phase a_path_reads_its_value_and_names_its_tree_node;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        library.apply(Library::NEW_SNIPPET.with("Deploy")).unwrap();
        let id = first_snippet(&library);
        let state = library.state().unwrap();
        let snippet = Library::paths().snippets.item(&id);
        assert_eq!(
            snippet.title.get(&state).map(String::as_str),
            Some("Deploy")
        );
        assert_eq!(snippet.favorite.get(&state), Some(&false));
        assert!(
            Library::paths()
                .snippets
                .item(&Id::from_raw("gone"))
                .title
                .get(&state)
                .is_none()
        );
        let tree = snippet
            .favorite
            .set(true)
            .tree_path("workspace", "app", "record");
        assert_eq!(
            tree,
            tilo_action_policy::TreePath::workspace("workspace")
                .app("app")
                .kind("test.library")
                .resource("record")
                .item(id.as_str())
                .field("favorite")
                .action(tilo_resource::FIELD_EDIT)
        );
        assert_eq!(
            Library::STAR.key(),
            tilo_resource::ActionKey::new(
                <Library as tilo_resource::Resource>::APP_ID,
                "test.library",
                "star",
            )
        );
    }

    phase search_finds_an_item_by_its_codes_and_variants;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        library.apply(Library::NEW_SNIPPET.with("Deploy")).unwrap();
        let id = first_snippet(&library);
        edit(
            &mut library,
            &Library::paths()
                .snippets
                .item(&id)
                .language
                .set(Language::Rust),
        )
        .unwrap();
        let entries = Library::search(&library.state().unwrap());
        assert_eq!(entries.len(), 1);
        assert!(
            entries[0]
                .fields
                .iter()
                .any(|(text, _)| text.to_lowercase().contains("rust")),
            "{:?}",
            entries[0].fields
        );
    }

    phase a_path_finds_the_object_its_value_is_stored_in;
    // A path names the object its value is stored in, through the items of a
    // collection: what an editor working on document objects binds to.
    {
        use automerge::ReadDoc as _;

        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        library
            .apply(Library::NEW_SNIPPET.with(library::NewSnippet {
                title: "Deploy".into(),
            }))
            .unwrap();
        let id = library
            .state()
            .unwrap()
            .snippets
            .ids()
            .next()
            .unwrap()
            .clone();
        let paths = Library::paths();
        let body = paths.snippets.item(&id).body;
        let text = body.object(library.doc()).expect("the body's text");
        assert_eq!(library.doc().text(&text).unwrap(), "");
        library
            .apply(Invoke::edit(&body.splice(0, 0, "kubectl")).unwrap())
            .unwrap();
        assert_eq!(library.doc().text(&text).unwrap(), "kubectl");
        assert!(
            paths
                .snippets
                .item(&id)
                .favorite
                .object(library.doc())
                .is_none(),
            "a scalar is stored in no object of its own"
        );
        assert!(
            paths
                .snippets
                .item(&Id::from_raw("gone"))
                .body
                .object(library.doc())
                .is_none()
        );
    }
}

tilo_test_env::scenario! {
    fn a_records_check_guards_every_way_in;

    phase a_check_refuses_every_way_in;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        library.apply(Library::NEW_SNIPPET.with("Deploy")).unwrap();
        let id = first_snippet(&library);
        let long = "a title that is far too long".to_owned();
        let title = Library::paths().snippets.item(&id).title;
        // A field edit.
        let refused = edit(&mut library, &title.set(long.clone())).unwrap_err();
        assert!(refused.contains("at most 20"), "{refused}");
        // A splice that makes it too long.
        assert!(edit(&mut library, &title.splice(6, 0, &long)).is_err());
        // A verb.
        assert!(
            library
                .apply(Library::NEW_SNIPPET.with(long.clone()))
                .is_err()
        );
        // A group, refused whole.
        let group = Invoke::group([
            Library::NEW_SNIPPET.with("fine"),
            Library::NEW_SNIPPET.with(long),
        ]);
        assert!(library.apply(group).is_err());
        let state = library.state().unwrap();
        assert_eq!(state.snippets.len(), 1);
        assert_eq!(state.snippets.get(&id).unwrap().title, "Deploy");
        // Within the invariant it applies.
        edit(&mut library, &title.set("Deploy prod".into())).unwrap();
    }

    phase an_edit_outside_what_a_check_reads_does_not_read_the_record_to_check_it;
    {
        let mut shelf = Replica::<Shelf>::new().in_app("so.tilo.model", "Model");
        shelf.apply(Shelf::SHELVE.with("Dune")).unwrap();
        let id = shelf.state().unwrap().books.ids().next().unwrap().clone();
        let apply = |shelf: &mut Replica<Shelf, AppNamed>, edit: &Edit<Shelf>| {
            shelf
                .apply(Invoke::edit(edit).map_err(|error| error.to_string())?)
                .map(drop)
                .map_err(|error| error.to_string())
        };
        // What the declaration says an edit at each path can change. (Builds
        // with debug assertions still check the record after the skipped ones,
        // to catch a wrong declaration, so this reads the decision itself.)
        let reads = tilo_resource::table::CheckReads {
            fields: &["name"],
            items: &["books"],
        };
        let books = Shelf::paths().books;
        assert!(!reads.touched_by(Shelf::paths().note.segments()));
        assert!(!reads.touched_by(books.item(&id).title.segments()));
        assert!(reads.touched_by(Shelf::paths().name.segments()));
        assert!(reads.touched_by(books.item(&id).path().segments()));
        assert!(reads.touched_by(books.segments()));
        assert!(reads.touched_by(&[]));
        apply(&mut shelf, &Shelf::paths().note.set("by the API".into())).unwrap();
        apply(
            &mut shelf,
            &books.item(&id).title.set("Dune Messiah".into()),
        )
        .unwrap();
        #[cfg(not(debug_assertions))]
        let before = SHELF_CHECKS.with(std::cell::Cell::get);
        let refused = apply(&mut shelf, &Shelf::paths().name.set("bad".into())).unwrap_err();
        assert!(refused.contains("called bad"), "{refused}");
        #[cfg(not(debug_assertions))]
        assert!(SHELF_CHECKS.with(std::cell::Cell::get) > before);
        let state = shelf.state().unwrap();
        assert_eq!(state.note, "by the API");
        assert_eq!(state.books[&id].title, "Dune Messiah");
        assert_eq!(state.name, "");
    }
}

thread_local! {
    /// How often `Shelf::valid` ran on this thread.
    static SHELF_CHECKS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

/// A record whose invariant reads its name and counts its books.
#[derive(Model, Default, Debug, Clone, PartialEq)]
#[model(check = Shelf::valid, check_reads = "name", check_items = "books")]
pub struct Shelf {
    pub name: String,
    pub note: String,
    pub books: Collection<Book>,
}

#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Book {
    pub title: String,
}

impl Shelf {
    fn valid(&self) -> Result<(), Refusal> {
        SHELF_CHECKS.with(|checks| checks.set(checks.get().saturating_add(1)));
        if self.name == "bad" {
            return Err(Refusal::new("no shelf is called bad"));
        }
        Ok(())
    }
}

#[resource(kind = "test.shelf", catalogue = "tests/locales")]
impl Shelf {
    /// Shelve a book.
    #[action]
    pub fn shelve(&mut self, cx: &mut ActionCx, title: String) {
        self.books.push(cx.id(), Book { title });
    }
}

/// A record whose check reads its note but declares it reads only its
/// name: a mistake the framework catches where debug assertions are on.
#[derive(Model, Default, Debug, Clone, PartialEq)]
#[model(check = Misdeclared::valid, check_reads = "name")]
pub struct Misdeclared {
    pub name: String,
    pub note: String,
}

impl Misdeclared {
    fn valid(&self) -> Result<(), Refusal> {
        if self.note == "bad" {
            return Err(Refusal::new("no note says bad"));
        }
        Ok(())
    }
}

#[resource(kind = "test.misdeclared", catalogue = "tests/locales")]
impl Misdeclared {
    /// Rename it.
    #[action]
    pub fn rename(&mut self, name: String) {
        self.name = name;
    }
}

#[test]
#[cfg(debug_assertions)]
#[should_panic(expected = "say that edit cannot change what it reads")]
fn a_check_that_reads_an_undeclared_field_is_caught() {
    let mut record = Replica::<Misdeclared>::new().in_app("so.tilo.model", "Model");
    let edit = Misdeclared::paths().note.set("bad".into());
    let _ = record.apply(Invoke::edit(&edit).unwrap());
}

tilo_test_env::scenario! {
    fn grid_rows_and_cells_keep_identity_under_concurrent_edits;

    phase first_writes_into_one_row_both_survive;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        let sheet = Library::paths().sheet;
        edit(&mut library, &sheet.insert_row(0)).unwrap();
        edit(&mut library, &sheet.insert_column(0)).unwrap();
        edit(&mut library, &sheet.insert_column(1)).unwrap();
        let grid = library.state().unwrap().sheet;
        let row = grid.rows().next().cloned().unwrap();
        let columns: Vec<Id> = grid.columns().cloned().collect();
        let mut other = library.fork();
        edit(
            &mut library,
            &sheet.set_cell(&row, &columns[0], Some(&"a".to_owned())),
        )
        .unwrap();
        edit(
            &mut other,
            &sheet.set_cell(&row, &columns[1], Some(&"b".to_owned())),
        )
        .unwrap();
        library.sync_with(&mut other).unwrap();
        let grid = library.state().unwrap().sheet;
        assert_eq!(grid.cell(&row, &columns[0]).map(String::as_str), Some("a"));
        assert_eq!(grid.cell(&row, &columns[1]).map(String::as_str), Some("b"));
        assert_eq!(grid, other.state().unwrap().sheet);
    }

    phase rows_two_replicas_add_under_one_id_keep_both_cells;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        let sheet = Library::paths().sheet;
        edit(&mut library, &sheet.insert_column(0)).unwrap();
        let column = library
            .state()
            .unwrap()
            .sheet
            .columns()
            .next()
            .cloned()
            .unwrap();
        let mut other = library.fork();
        let row = |id: &str| {
            sheet.edit(tilo_resource::EditOp::InsertRow {
                id: Some(Id::from_raw(id)),
                at: 0,
            })
        };
        edit(&mut library, &row("r40")).unwrap();
        edit(&mut other, &row("r40")).unwrap();
        edit(&mut other, &row("r39")).unwrap();
        edit(
            &mut library,
            &sheet.set_cell(&Id::from_raw("r40"), &column, Some(&"A40".to_owned())),
        )
        .unwrap();
        edit(
            &mut other,
            &sheet.set_cell(&Id::from_raw("r39"), &column, Some(&"B39".to_owned())),
        )
        .unwrap();
        library.sync_with(&mut other).unwrap();
        let grid = library.state().unwrap().sheet;
        assert_eq!(
            grid.cell(&Id::from_raw("r40"), &column).map(String::as_str),
            Some("A40")
        );
        assert_eq!(
            grid.cell(&Id::from_raw("r39"), &column).map(String::as_str),
            Some("B39")
        );
        assert_eq!(grid, other.state().unwrap().sheet);
    }

    phase rows_stored_as_their_order_keys_order_as_items_do_under_concurrent_inserts;
    {
        use automerge::ReadDoc as _;
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        let sheet = Library::paths().sheet;
        let snippets = Library::paths().snippets;
        let row = |id: &str, at| {
            sheet.edit(tilo_resource::EditOp::InsertRow {
                id: Some(Id::from_raw(id)),
                at,
            })
        };
        let item = |id: &str, at| {
            snippets.insert_as(
                &Id::from_raw(id),
                at,
                &Snippet {
                    title: id.into(),
                    ..Snippet::default()
                },
            )
        };
        let both = |replica: &mut Replica<Library, AppNamed>, id: &str, at| {
            edit(replica, &row(id, at)).unwrap();
            edit(replica, &item(id, at)).unwrap();
        };
        both(&mut library, "a", 0);
        both(&mut library, "b", 1);
        let mut other = library.fork();
        // Concurrent inserts at the same place and at different places.
        both(&mut library, "x", 1);
        both(&mut library, "y", 0);
        both(&mut other, "z", 1);
        both(&mut other, "w", 2);
        library.sync_with(&mut other).unwrap();
        let state = library.state().unwrap();
        let rows: Vec<&str> = state.sheet.rows().map(Id::as_str).collect();
        let items: Vec<&str> = state.snippets.ids().map(Id::as_str).collect();
        assert_eq!(
            rows, items,
            "a row orders as an item stored with its value does"
        );
        assert_eq!(other.state().unwrap().sheet, state.sheet);
        // A row is its order key alone: no map around it.
        let doc = library.doc();
        let (_, grid) = doc.get(automerge::ROOT, "sheet").unwrap().unwrap();
        let (_, axis) = doc.get(&grid, "rows").unwrap().unwrap();
        for id in &rows {
            let (value, _) = doc.get(&axis, *id).unwrap().unwrap();
            assert!(
                matches!(value, automerge::Value::Scalar(_)),
                "row {id} stored as {value:?}"
            );
        }
    }

    phase a_row_and_cell_gesture_replays_to_the_same_change;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        let sheet = Library::paths().sheet;
        edit(&mut library, &sheet.insert_column(0)).unwrap();
        let column = library
            .state()
            .unwrap()
            .sheet
            .columns()
            .next()
            .cloned()
            .unwrap();
        let row = Id::from_raw("r1");
        library
            .apply(Invoke::group(vec![
                Invoke::edit(&sheet.edit(tilo_resource::EditOp::InsertRow {
                    id: Some(row.clone()),
                    at: 0,
                }))
                .unwrap(),
                Invoke::edit(&sheet.set_cell(&row, &column, Some(&"a1".to_owned()))).unwrap(),
            ]))
            .unwrap();
        let registry = tilo_actions::ActionRegistry::with(tilo_resource::group::register::<Library>);
        let hash = *library.heads().first().unwrap();
        assert_eq!(
            tilo_actions::executor::verify_change(library.doc_mut(), hash, &registry).unwrap(),
            tilo_actions::executor::Verified::Reproduced,
            "the recorded group, written with its shared stamp and path once, reproduces the change"
        );
    }

    phase grid_cells_keep_identity_when_rows_and_columns_move;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        let sheet = Library::paths().sheet;
        edit(&mut library, &sheet.insert_row(0)).unwrap();
        edit(&mut library, &sheet.insert_row(1)).unwrap();
        edit(&mut library, &sheet.insert_column(0)).unwrap();
        edit(&mut library, &sheet.insert_column(1)).unwrap();
        let grid = library.state().unwrap().sheet;
        let rows: Vec<Id> = grid.rows().cloned().collect();
        let columns: Vec<Id> = grid.columns().cloned().collect();
        edit(
            &mut library,
            &sheet.set_cell(&rows[1], &columns[1], Some(&"b2".to_owned())),
        )
        .unwrap();
        edit(
            &mut library,
            &sheet.cell(&rows[0], &columns[0]).set("a1".into()),
        )
        .unwrap();

        let mut other = library.fork();
        edit(&mut library, &sheet.insert_row(0)).unwrap();
        edit(
            &mut other,
            &sheet.cell(&rows[1], &columns[1]).splice(2, 0, "!"),
        )
        .unwrap();
        library.sync_with(&mut other).unwrap();
        let grid = library.state().unwrap().sheet;
        assert_eq!(grid.rows().count(), 3);
        assert_eq!(grid.cell(&rows[1], &columns[1]).unwrap(), "b2!");
        assert_eq!(grid.cell(&rows[0], &columns[0]).unwrap(), "a1");

        edit(&mut library, &sheet.remove_column(&columns[0])).unwrap();
        let grid = library.state().unwrap().sheet;
        assert_eq!(grid.columns().count(), 1);
        assert!(grid.cell(&rows[0], &columns[0]).is_none());
        assert_eq!(grid.cells().count(), 1);
        assert_eq!(library.live().unwrap().sheet, grid);
    }
}

tilo_test_env::scenario! {
    fn the_api_records_gesture_time_history_and_minted_ids;

    phase consecutive_edits_of_one_path_are_one_gesture;
    {
        let id = Id::from_raw("s");
        let snippet = Library::paths().snippets.item(&id);
        let action = |edit: Edit<Library>| Library::edit_action(edit).unwrap();
        assert!(Library::coalesces(
            &action(snippet.title.splice(0, 0, "a")),
            &action(snippet.title.splice(1, 0, "b")),
        ));
        // A space ends the word it follows: it belongs to that step, and the
        // next word is a step of its own.
        assert!(Library::coalesces(
            &action(snippet.title.splice(0, 0, "a")),
            &action(snippet.title.splice(1, 0, " ")),
        ));
        assert!(!Library::coalesces(
            &action(snippet.title.splice(0, 0, "a ")),
            &action(snippet.title.splice(2, 0, "b")),
        ));
        assert!(Library::coalesces(
            &action(snippet.favorite.set(true)),
            &action(snippet.favorite.set(false)),
        ));
        assert!(!Library::coalesces(
            &action(snippet.favorite.set(true)),
            &action(snippet.body.replace("x")),
        ));
    }

    phase the_api_stamps_the_time_not_the_caller;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        library.set_now_ms(42);
        let value = serde_json::json!({ "op": { "action": "star", "args": {} }, "at": 7 });
        let applied = library
            .apply(Invoke::<Library>::apply(&serde_json::from_value(value).unwrap()).unwrap())
            .unwrap();
        let action: <Library as Resource>::Action =
            serde_json::from_slice(&applied.action.payload).unwrap();
        assert_eq!(action.now_ms, 42);
    }

    phase history_records_what_an_edit_or_verb_did_and_to_which_item;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        library
            .apply(Library::NEW_SNIPPET.with("Deploy script"))
            .unwrap();
        let id = first_snippet(&library);
        edit(
            &mut library,
            &Library::paths().snippets.item(&id).favorite.set(true),
        )
        .unwrap();
        let described = |library: &mut Replica<Library, AppNamed>| {
            library
                .versions()
                .last()
                .and_then(|version| version.context.clone())
                .and_then(|context| context.described())
                .unwrap()
        };
        let favorite = described(&mut library);
        let tilo_actions::Did::Edit(edit_entry) = &favorite.what else {
            panic!("{favorite:?}");
        };
        assert_eq!(
            (edit_entry.ty.as_str(), edit_entry.field.as_str()),
            ("snippet", "favorite")
        );
        assert_eq!(
            edit_entry.old,
            tilo_actions::Scalar::from_json(&false.into())
        );
        assert_eq!(
            edit_entry.new,
            tilo_actions::Scalar::from_json(&true.into())
        );
        let item = favorite.item.unwrap();
        assert_eq!(
            (item.id.as_str(), item.label.as_str()),
            (id.as_str(), "Deploy script")
        );

        library.apply(Library::RECORD_USE.with(id)).unwrap();
        let used = described(&mut library);
        let tilo_actions::Did::Verb(verb) = &used.what else {
            panic!("{used:?}");
        };
        assert_eq!(verb.action.action, "record-use");
        assert_eq!(used.item.unwrap().label, "Deploy script");
    }

    phase the_invoker_learns_the_ids_its_action_minted;
    {
        let mut library = Replica::<Library>::new().in_app("so.tilo.model", "Model");
        library.apply(Library::NEW_SNIPPET.with("One")).unwrap();
        let envelope = library
            .apply(Library::NEW_SNIPPET.with("Two"))
            .unwrap()
            .clone();
        let created = tilo_resource::minted_ids(&envelope).next().unwrap();
        assert_eq!(library.state().unwrap().snippets[&created].title, "Two");
    }
}