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
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
//! Verbs: public ids and parameter names, parameter structs with schemas from
//! their types, item verbs, kinds, and the resource options that replace a
//! hand-written `Resource`.
#![allow(
    clippy::unwrap_used,
    clippy::indexing_slicing,
    clippy::arithmetic_side_effects,
    reason = "test assertions"
)]

use serde::{Deserialize, Serialize};
use tilo_resource::AppNamed;
use tilo_resource::{
    ActionCx, ActionKind, Availability, Collection, Derived, Id, Invoke, JsonSchema, Model, Outbox,
    Params, Refusal, Replica, Resource, resource,
};

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Colour {
    pub red: u8,
    pub green: u8,
    pub blue: u8,
}

#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Card {
    #[model(label)]
    pub title: String,
    pub colour: String,
}

#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Shelf {
    pub name: String,
    pub cards: Collection<Card>,
    pub archive: Collection<Card>,
    pub mail: Outbox<String>,
    pub seeded: bool,
}

#[resource(
    kind = "test.shelf",
    params = shelf,
    initialize = Shelf::genesis,
    seed = Shelf::first_content,
    available = Shelf::available,
    children = Shelf::colours,
    read_content = Shelf::content, catalogue = "tests/locales")]
impl Shelf {
    /// Rename the shelf.
    #[action(id = "retitle")]
    pub fn rename(&mut self, #[param("The new name", name = "title")] name: String) {
        self.name = name;
    }

    /// Add a card.
    #[action]
    pub fn add(&mut self, cx: &mut ActionCx, title: String, colour: Option<Colour>) {
        let colour = colour.map_or_else(String::new, |colour| {
            format!("#{:02x}{:02x}{:02x}", colour.red, colour.green, colour.blue)
        });
        self.cards.push(cx.id(), Card { title, colour });
    }

    /// Archive a card.
    #[action(item = cards, icon = "archive")]
    pub fn archive_card(&mut self, card: &Id) -> Result<(), Refusal> {
        let taken = self.cards.remove(card).ok_or("no such card")?;
        self.archive.push(card.clone(), taken);
        Ok(())
    }

    /// Restore an archived card.
    #[action]
    pub fn restore(&mut self, archive: &Id) {
        if let Some(card) = self.archive.remove(archive) {
            self.cards.push(archive.clone(), card);
        }
    }

    /// Place a picture on the shelf.
    #[action]
    pub fn place_picture(&mut self, #[param("The picture", content)] picture: String) {
        self.name = format!("{} with {picture}", self.name);
    }

    /// Caption a picture: content another action produced, beside words.
    #[action]
    pub fn caption_picture(
        &mut self,
        #[param("The picture", content)] picture: String,
        #[param("Its caption")] caption: String,
    ) {
        self.name = format!("{} with {picture}: {caption}", self.name);
    }

    /// Mail the shelf to someone.
    #[action]
    pub fn mail_to(&mut self, cx: &mut ActionCx, mail: &mut Outbox<String>, to: String) {
        mail.push(cx.id(), format!("{} to {to}", self.name));
    }

    fn genesis() -> Self {
        Self {
            name: "New shelf".into(),
            ..Self::default()
        }
    }

    fn first_content(&mut self, cx: &mut ActionCx) {
        self.seeded = true;
        self.cards.push(
            cx.id(),
            Card {
                title: "Welcome".into(),
                colour: String::new(),
            },
        );
    }

    fn available(&self, verb: shelf::Verb) -> Availability {
        match verb {
            shelf::Verb::MailTo if self.cards.is_empty() => Availability::Unavailable {
                code: "empty".into(),
                reason: "An empty shelf is not worth mailing".into(),
            },
            _ => Availability::Available,
        }
    }

    fn colours(&self) -> Vec<Derived<Self>> {
        let colours = if self.name.is_empty() {
            Vec::new()
        } else {
            vec!["red", "blue"]
        };
        colours
            .into_iter()
            .map(|colour| {
                Derived::new(colour)
                    .of_kind("colour")
                    .with_child(Derived::new("shade").with(
                        Self::RENAME.bind(shelf::Rename::paths().name, format!("{colour} shelf")),
                    ))
                    .with(Self::ADD.bind(
                        shelf::Add::paths().colour,
                        Some(Colour {
                            red: u8::from(colour == "red") * 255,
                            green: 0,
                            blue: u8::from(colour == "blue") * 255,
                        }),
                    ))
            })
            .collect()
    }

    fn content(&self, item: Option<&Id>) -> Result<serde_json::Value, String> {
        match item {
            None => Ok(serde_json::json!({ "name": self.name, "cards": self.cards.len() })),
            Some(id) => self
                .cards
                .get(id)
                .map(|card| serde_json::json!({ "title": card.title }))
                .ok_or_else(|| "no such card".to_owned()),
        }
    }
}

/// A record that publishes that it changed and answers no read: what it
/// holds is not anyone's to read by path.
#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Scratch {
    pub kept: String,
}

#[resource(kind = "test.scratch", read = false, catalogue = "tests/locales")]
impl Scratch {
    /// Remember something, without publishing what it was.
    #[action]
    pub fn keep(&mut self, #[param("Words kept")] kept: String) {
        self.kept = kept;
    }
}

/// A note, left at a place.
#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Note {
    #[model(label)]
    pub text: String,
    pub place: String,
}

/// Notes left at places. Its notes are the record's only collection, and a
/// place is none of them.
#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Wall {
    pub notes: Collection<Note>,
}

#[resource(kind = "test.wall", params = wall, catalogue = "tests/locales")]
impl Wall {
    /// Leave a note at a place.
    #[action]
    pub fn leave(&mut self, cx: &mut ActionCx, place: Id, text: String) {
        self.notes.push(
            cx.id(),
            Note {
                text,
                place: place.as_str().to_owned(),
            },
        );
    }

    /// Take a note down.
    #[action]
    pub fn take_down(&mut self, note: Id) -> Result<(), Refusal> {
        self.notes.remove(&note).ok_or("no such note")?;
        Ok(())
    }
}

/// A note is labelled by its text. A verb whose argument names a note is
/// about that note, and its change says so in one line, however much the note
/// reads: the change does not grow with the label.
#[test]
fn a_verbs_change_names_its_item_by_one_line() {
    let left_beside = |text: &str| {
        let mut wall = Replica::<Wall>::new().in_app("so.tilo.model", "Model");
        wall.apply(Wall::LEAVE.with((Id::from_raw("lobby"), text.to_owned())))
            .unwrap();
        let first = wall.state().unwrap().notes.ids().next().unwrap().clone();
        let label = wall
            .apply(Wall::LEAVE.with((first, "Seen".to_owned())))
            .unwrap()
            .context
            .as_ref()
            .and_then(|entry| entry.item.as_ref())
            .map(|item| item.label.clone())
            .unwrap();
        let bytes = wall
            .doc_mut()
            .get_changes(&[])
            .last()
            .map_or(0, |change| change.raw_bytes().len());
        (label, bytes)
    };
    let (label, short) = left_beside("Mind the step");
    assert_eq!(label, "Mind the step");
    let long = "Mind the step ".repeat(4_000);
    let (label, bytes) = left_beside(&long);
    assert_eq!(label.chars().count(), 96, "{label}");
    assert!(long.starts_with(&label), "{label}");
    assert!(
        bytes.saturating_sub(short) < 200,
        "a change beside a note of {} bytes is {bytes} bytes; beside one of 13 bytes, {short}",
        long.len()
    );
}

/// A verb that makes an item names it, though the record before it applied
/// held none: the change it commits says which item it made, as History and
/// every replica read it.
#[test]
fn a_verbs_change_names_the_item_it_makes() {
    let mut shelf = Replica::<Shelf>::new().in_app("so.tilo.model", "Model");
    let made = shelf
        .apply(Shelf::ADD.with(("Plan the launch".to_owned(), None)))
        .unwrap();
    let item = made
        .context
        .as_ref()
        .and_then(|entry| entry.item.as_ref())
        .expect("the change names the card it made")
        .clone();
    assert_eq!(item.label, "Plan the launch");
    // The change itself records it: what a peer verifies and a History lists.
    let recorded = shelf
        .versions()
        .into_iter()
        .rev()
        .find_map(|version| version.context)
        .and_then(|entry| entry.item)
        .expect("the committed change names the card");
    assert_eq!(recorded.id, item.id);
    assert_eq!(recorded.label, "Plan the launch");
    assert!(
        shelf
            .state()
            .unwrap()
            .cards
            .get(&Id::from_raw(recorded.id))
            .is_some(),
        "the item it names is the card the shelf holds"
    );
}

fn published(replica: &Replica<Shelf, AppNamed>) -> tilo_actions::ResourceSpec {
    tilo_resource::publish::<Shelf>("shelf", "Shelf", &replica.state().unwrap())
}

tilo_test_env::scenario! {
    fn a_records_verbs_publish_and_bind_as_declared;

    phase ids_and_parameter_names_are_public_names;
    {
        let mut shelf = Replica::<Shelf>::new().in_app("so.tilo.model", "Model");
        assert_eq!(shelf.state().unwrap().name, "New shelf");
        shelf.apply(Shelf::RENAME.with("Kitchen")).unwrap();
        assert_eq!(shelf.state().unwrap().name, "Kitchen");
        let tree = published(&shelf);
        let rename = tree
            .actions
            .iter()
            .find(|spec| spec.id == "retitle")
            .unwrap();
        assert_eq!(rename.params()[0].name, "title");
        assert!(tree.actions.iter().all(|spec| spec.id != "rename"));
        let arguments = Shelf::RENAME
            .arguments(&shelf::Rename { name: "x".into() })
            .unwrap();
        assert_eq!(arguments["title"], "x");
        assert_eq!(<shelf::Rename as Params>::ACTION.id, "retitle");
        // A form reaches the parameters' paths through the trait.
        assert_eq!(
            <shelf::Rename as Params>::paths().name.segments(),
            [tilo_resource::Segment::Field("title".into())]
        );
    }

    phase a_parameter_schema_comes_from_its_type;
    {
        let schema = <shelf::Add as JsonSchema>::json_schema();
        let text = serde_json::to_string(&schema).unwrap();
        assert!(text.contains("\"red\""), "{text}");
        assert_eq!(schema["required"], serde_json::json!(["title"]));
        let tree = published(&Replica::<Shelf>::new().in_app("so.tilo.model", "Model"));
        let add = tree.actions.iter().find(|spec| spec.id == "add").unwrap();
        let param = add
            .params()
            .iter()
            .find(|param| param.name == "colour")
            .unwrap();
        assert!(
            serde_json::to_string(param.schema.as_deref().unwrap())
                .unwrap()
                .contains("\"green\"")
        );
        // A colour outside its type is refused when the arguments bind.
        let mut shelf = Replica::<Shelf>::new().in_app("so.tilo.model", "Model");
        let mut arguments = Shelf::ADD
            .with(shelf::Add {
                title: "x".into(),
                colour: None,
            })
            .arguments;
        arguments.insert(
            "colour".into(),
            serde_json::json!({ "red": 300, "green": 0, "blue": 0 }),
        );
        assert!(tilo_resource::build_action::<Shelf>("add", &arguments, 0).is_err());
        shelf
            .apply(Shelf::ADD.with((
                "Blue".to_owned(),
                Some(Colour {
                    red: 0,
                    green: 0,
                    blue: 255,
                }),
            )))
            .unwrap();
        assert!(
            shelf
                .state()
                .unwrap()
                .cards
                .values()
                .any(|card| card.colour == "#0000ff")
        );
    }

    phase item_verbs_are_offered_on_the_items_of_their_collection;
    {
        let mut shelf = Replica::<Shelf>::new().in_app("so.tilo.model", "Model");
        shelf
            .apply(Shelf::ADD.with(("Tea".to_owned(), None)))
            .unwrap();
        let id = shelf.state().unwrap().cards.ids().next().unwrap().clone();
        let tree = published(&shelf);
        let card = tree
            .children
            .iter()
            .find(|child| child.id.as_str() == format!("test.shelf/cards/{id}"))
            .unwrap();
        assert_eq!(card.label, "Tea");
        let archive = card
            .actions
            .iter()
            .find(|spec| spec.id == "archive-card")
            .expect("the card offers its archiving");
        assert_eq!(
            archive.icon.as_deref(),
            Some("archive"),
            "on its item the verb wears its own icon"
        );
        assert!(card.actions.iter().all(|spec| spec.id != "restore"));
        shelf.apply(Shelf::ARCHIVE_CARD.with(id.clone())).unwrap();
        let tree = published(&shelf);
        let archived = tree
            .children
            .iter()
            .find(|child| child.id.as_str() == format!("test.shelf/archive/{id}"))
            .unwrap();
        assert!(archived.actions.iter().any(|spec| spec.id == "restore"));
    }

    phase an_item_is_named_by_its_id_its_address_or_its_title;
    {
        let mut shelf = Replica::<Shelf>::new().in_app("so.tilo.model", "Model");
        shelf.apply(Shelf::ADD.with(("Tea".to_owned(), None))).unwrap();
        let id = shelf
            .state()
            .unwrap()
            .cards
            .iter()
            .map(|(id, _)| id.clone())
            .next()
            .unwrap();
        // By its name, what a person or an agent reads in a listing.
        shelf
            .apply(Shelf::ARCHIVE_CARD.with(Id::from_raw("Tea")))
            .unwrap();
        assert!(shelf.state().unwrap().cards.is_empty());
        shelf.apply(Shelf::RESTORE.with(id.clone())).unwrap();
        // By the address it is published under, in either form.
        shelf
            .apply(Shelf::ARCHIVE_CARD.with(Id::from_raw(format!(
                "test.shelf/cards/{id}"
            ))))
            .unwrap();
        shelf.apply(Shelf::RESTORE.with(id.clone())).unwrap();
        shelf
            .apply(Shelf::ARCHIVE_CARD.with(Id::from_raw(format!(
                "test.shelf.cards:{id}"
            ))))
            .unwrap();
        shelf.apply(Shelf::RESTORE.with(id)).unwrap();
        // A reference to no card of the collection is the verb's to refuse, in
        // its own words, rather than reporting a card that went away.
        let why = shelf
            .apply(Shelf::ARCHIVE_CARD.with(Id::from_raw("Milk")))
            .expect_err("no card is named Milk")
            .to_string();
        assert_eq!(why, "no such card");
    }

    phase an_id_that_names_no_item_is_handed_to_the_verb_as_written;
    {
        // The wall keeps notes alone and a place is none of them: the verb is
        // handed the place as written, while no note is there yet and also
        // where a note reads as the place is called.
        let mut wall = Replica::<Wall>::new().in_app("so.tilo.model", "Model");
        wall.apply(Wall::LEAVE.with((Id::from_raw("lobby"), "kitchen".to_owned())))
            .unwrap();
        wall.apply(Wall::LEAVE.with((Id::from_raw("kitchen"), "Mind the step".to_owned())))
            .unwrap();
        let places: Vec<String> = wall
            .state()
            .unwrap()
            .notes
            .values()
            .map(|note| note.place.clone())
            .collect();
        assert_eq!(places, ["lobby", "kitchen"]);
        // A note is still named by what it says, as any item is, and one that
        // is not there is the verb's to refuse, in its own words.
        wall.apply(Wall::TAKE_DOWN.with(Id::from_raw("Mind the step")))
            .unwrap();
        let why = wall
            .apply(Wall::TAKE_DOWN.with(Id::from_raw("Wet paint")))
            .expect_err("no note says so")
            .to_string();
        assert_eq!(why, "no such note");
    }

    phase a_verb_with_an_outbox_reaches_outside;
    {
        let mut shelf = Replica::<Shelf>::new().in_app("so.tilo.model", "Model");
        shelf.apply(Shelf::RENAME.with("Pantry")).unwrap();
        shelf
            .apply(Shelf::ADD.with(("Tea".to_owned(), None)))
            .unwrap();
        shelf.apply(Shelf::MAIL_TO.with("ada")).unwrap();
        let state = shelf.state().unwrap();
        assert_eq!(
            state
                .mail
                .pending()
                .map(|(_, text)| text.as_str())
                .collect::<Vec<_>>(),
            ["Pantry to ada"]
        );
        let mail = Shelf::MAIL_TO.with("x").build(0).unwrap();
        assert_eq!(Shelf::kind_of(&mail), ActionKind::Outside);
        let rename = Shelf::RENAME.with("x").build(0).unwrap();
        assert_eq!(Shelf::kind_of(&rename), ActionKind::Undoable);
        let tree = published(&shelf);
        let spec = |id: &str| tree.actions.iter().find(|spec| spec.id == id).unwrap();
        // The kind follows from what each action is able to do: a verb that
        // queues reaches outside, one that only edits the document is undoable,
        // and so is the generic `apply`.
        assert_eq!(spec("mail-to").contract.kind, ActionKind::Outside);
        assert_eq!(spec("retitle").contract.kind, ActionKind::Undoable);
        assert_eq!(
            spec(tilo_resource::APPLY).contract.kind,
            ActionKind::Undoable
        );
        assert!(!spec("mail-to").contract.can_be_undone());
        assert!(spec("retitle").contract.can_be_undone());
        assert!(spec(tilo_resource::APPLY).contract.can_be_undone());
        assert_eq!(
            tilo_resource::spec_kind(spec("mail-to")),
            ActionKind::Outside
        );
        assert_eq!(
            tilo_resource::spec_kind(spec("retitle")),
            ActionKind::Undoable
        );
        assert_eq!(
            tilo_resource::spec_kind(spec(tilo_resource::FIELD_EDIT)),
            ActionKind::Undoable
        );
    }

    phase seed_availability_children_and_content;
    {
        let mut shelf = Replica::<Shelf>::new().in_app("so.tilo.model", "Model");
        // Nothing to mail on an empty shelf.
        let tree = published(&shelf);
        let mail = tree
            .actions
            .iter()
            .find(|spec| spec.id == "mail-to")
            .unwrap();
        assert!(!mail.contract.availability.is_available());

        let seed = Shelf::seed().unwrap();
        shelf.apply_action(&seed).unwrap();
        let state = shelf.state().unwrap();
        assert!(state.seeded);
        assert_eq!(state.cards.values().next().unwrap().title, "Welcome");
        let tree = published(&shelf);
        let mail = tree
            .actions
            .iter()
            .find(|spec| spec.id == "mail-to")
            .unwrap();
        assert!(mail.contract.availability.is_available());

        let red = tree
            .children
            .iter()
            .find(|child| child.id.as_str() == "test.shelf/derived/red")
            .unwrap();
        assert_eq!(red.kind, "test.shelf.colour");
        let add = red.actions.iter().find(|spec| spec.id == "add").unwrap();
        assert_eq!(add.params().len(), 1, "the colour is bound");
        let built = add.build_json(&serde_json::Map::from_iter([(
            "title".to_owned(),
            serde_json::json!("Ruby"),
        )]));
        let encoded = built.unwrap();
        let action: <Shelf as Resource>::Action = serde_json::from_slice(&encoded.payload).unwrap();
        shelf.apply_action(&action).unwrap();
        assert!(
            shelf
                .state()
                .unwrap()
                .cards
                .values()
                .any(|card| card.colour == "#ff0000")
        );

        const { assert!(Shelf::READABLE) };
        let content = Shelf::read_content(&shelf.state().unwrap(), shelf.doc(), None).unwrap();
        assert_eq!(content["cards"], 2);
    }

    phase a_record_that_answers_no_read_declares_it;
    {
        const { assert!(!Scratch::READABLE) };
        let scratch = Replica::<Scratch>::new().in_app("so.tilo.model", "Model");
        let refusal = Scratch::read_content(&scratch.state().unwrap(), scratch.doc(), None)
            .expect_err("a record that answers no read has no content to answer");
        assert!(refusal.contains("does not answer reads"), "{refusal}");
    }

    phase an_input_that_does_not_bind_refuses_where_it_is_submitted;
    {
        // A hand-written reference whose names do not match its input.
        let wrong: tilo_resource::ActionRef<Shelf, (String,)> = tilo_resource::ActionRef::new(
            "add",
            &["title", "colour"],
            tilo_resource::ResourceKind::of::<Shelf>(),
        );
        let invoke = wrong.with(("a".to_owned(),));
        assert!(invoke.refusal().is_some());
        assert!(invoke.arguments.is_empty());
        assert!(wrong.try_with(("a".to_owned(),)).is_err());
        let mut shelf = Replica::<Shelf>::new().in_app("so.tilo.model", "Model");
        assert!(shelf.apply(invoke.clone()).is_err());
        assert!(invoke.build(0).is_err());
        assert!(
            shelf
                .apply(tilo_resource::Invoke::group([
                    Shelf::RENAME.with("x"),
                    invoke
                ]))
                .is_err()
        );
        assert_eq!(shelf.state().unwrap().name, "New shelf");
    }

    phase item_resources_resolve_lazily_as_the_tree_publishes_them;
    {
        let mut shelf = Replica::<Shelf>::new().in_app("so.tilo.model", "Model");
        for title in ["Tea", "Coffee", "Cocoa"] {
            shelf
                .apply(Shelf::ADD.with((title.to_owned(), None)))
                .unwrap();
        }
        let state = shelf.state().unwrap();
        let eager = Shelf::children(&state);
        for child in &eager {
            let lazy = Shelf::child(&state, child.id.as_str()).unwrap();
            assert_eq!(
                tilo_resource::items::fingerprint(&lazy),
                tilo_resource::items::fingerprint(child)
            );
        }
        assert!(Shelf::child(&state, "test.shelf/cards/gone").is_none());
        // Published again, the tree is the same.
        let again = Shelf::children(&state);
        assert_eq!(
            eager
                .iter()
                .map(tilo_resource::items::fingerprint)
                .collect::<Vec<_>>(),
            again
                .iter()
                .map(tilo_resource::items::fingerprint)
                .collect::<Vec<_>>()
        );
        // A renamed item is published under its new label.
        let id = state.cards.ids().next().unwrap().clone();
        shelf
            .apply(Invoke::edit(&Shelf::paths().cards.item(&id).title.set("Green tea".into())).unwrap())
            .unwrap();
        let state = shelf.state().unwrap();
        let renamed = Shelf::child(&state, &format!("test.shelf/cards/{id}")).unwrap();
        assert_eq!(renamed.label, "Green tea");
    }

    phase each_labelled_item_is_its_own_search_entry;
    {
        let mut shelf = Replica::<Shelf>::new().in_app("so.tilo.model", "Model");
        shelf
            .apply(Shelf::ADD.with(("Tea".to_owned(), None)))
            .unwrap();
        let state = shelf.state().unwrap();
        let entries = Shelf::search(&state);
        // The welcome card is not there: no seed was applied.
        assert_eq!(entries.len(), 1);
        let id = state.cards.ids().next().unwrap();
        assert_eq!(entries[0].title, "Tea");
        assert_eq!(
            entries[0].anchor.as_deref(),
            Some(format!("test.shelf/cards/{id}").as_str())
        );
    }

    phase content_inputs_nested_derived_places_and_edit_effects;
    {
        use tilo_resource::Effect;
        let shelf = Replica::<Shelf>::new().in_app("so.tilo.model", "Model");
        let tree = published(&shelf);
        let place = tree
            .actions
            .iter()
            .find(|spec| spec.id == "place-picture")
            .unwrap();
        assert!(matches!(
            place.input(),
            tilo_actions::ActionInput::Prompted {
                collects: tilo_actions::Collects::Content,
                ..
            }
        ));
        let encoded = place.build_json(&serde_json::Map::from_iter([(
            tilo_actions::PROMPTED_PARAM.to_owned(),
            serde_json::json!("blake3:abc"),
        )]));
        assert!(encoded.is_ok(), "{encoded:?}");

        // Content beside other parameters: every parameter is published, the
        // content one marked as taking what another action produced.
        let caption = tree
            .actions
            .iter()
            .find(|spec| spec.id == "caption-picture")
            .unwrap();
        let params = caption.params();
        let names: Vec<&str> = params.iter().map(|param| &*param.name).collect();
        assert_eq!(names, ["picture", "caption"]);
        assert!(params[0].is_content() && !params[1].is_content());
        let encoded = caption.build_json(&serde_json::Map::from_iter([
            ("picture".to_owned(), serde_json::json!("abc")),
            ("caption".to_owned(), serde_json::json!("Sunset")),
        ]));
        assert!(encoded.is_ok(), "{encoded:?}");

        let shade = Shelf::child(&shelf.state().unwrap(), "test.shelf/derived/red/shade").unwrap();
        assert!(shade.actions.iter().any(|spec| spec.id == "retitle"));

        let kinds: Vec<ActionKind> = ShelfView::specs()
            .iter()
            .map(tilo_resource::spec_kind)
            .collect();
        assert_eq!(kinds, [ActionKind::Undoable, ActionKind::Read]);
    }

    phase a_search_entry_opens_by_its_rows_effect;
    // A hit opened by a view effect of a live row is anchored at the row and
    // runs that effect there.
    {
        let entry =
            tilo_resource::SearchEntry::new("Chapter 2", "").opening("shelf.top:2", &ShelfView::Top);
        assert_eq!(entry.anchor.as_deref(), Some("shelf.top:2"));
        let action = entry.action.expect("the row's effect");
        assert_eq!(action.resource, "shelf.top:2");
        assert_eq!(action.action, "top");
    }

    phase an_absent_positional_option_is_not_sent;
    // An absent option given positionally is left out, as a parameter not
    // given, rather than sent as `null` the API refuses.
    {
        let add: tilo_resource::ActionRef<Shelf, (String, Option<Colour>)> =
            tilo_resource::ActionRef::new(
                "add",
                &["title", "colour"],
                tilo_resource::ResourceKind::of::<Shelf>(),
            );
        let arguments = add.arguments(&("Tea".to_owned(), None)).unwrap();
        assert_eq!(arguments.len(), 1);
        assert_eq!(arguments["title"], "Tea");
        let single: tilo_resource::ActionRef<Shelf, Option<String>> = tilo_resource::ActionRef::new(
            "retitle",
            &["title"],
            tilo_resource::ResourceKind::of::<Shelf>(),
        );
        assert!(single.arguments(&None).unwrap().is_empty());
        let mut shelf = Replica::<Shelf>::new().in_app("so.tilo.model", "Model");
        shelf.apply(add.with(("Tea".to_owned(), None))).unwrap();
        assert_eq!(shelf.state().unwrap().cards.len(), 1);
    }

    phase typed_secret_parameters_bind_redacted_variants_and_refuse_plaintext_arguments;
    {
        use tilo_actions::{ActionArgs, ArgValue, ParamType};
        let mut record = Replica::<PrivateImport>::new().in_app("so.tilo.model", "Model");
        let tree = tilo_resource::publish::<PrivateImport>(
            "private",
            "Private import",
            &record.state().unwrap(),
        );
        let action = tree
            .actions
            .iter()
            .find(|action| action.id == "import")
            .unwrap();
        let params = action.params();
        assert_eq!(params[0].ty, ParamType::Secret);
        assert!(params[0].required);
        assert!(params[0].choices.is_empty());
        let supplied = serde_json::json!({"payload":"private-history-sentinel"});
        let bound = ActionArgs::bind_json(params, supplied.as_object().unwrap()).unwrap();
        let debug = format!("{bound:?}");
        assert!(debug.contains("REDACTED"));
        assert!(!debug.contains("private-history-sentinel"));
        assert!(
            ActionArgs::bind(
                params,
                [(
                    "payload".to_owned(),
                    ArgValue::Text("private-history-sentinel".into())
                )]
            )
            .is_err()
        );
        assert!(
            ActionArgs::bind_json(
                params,
                serde_json::json!({"payload":37}).as_object().unwrap()
            )
            .is_err()
        );
        record
            .apply(PrivateImport::IMPORT.with("private-history-sentinel".to_owned()))
            .unwrap();
        assert_eq!(record.state().unwrap().received_bytes, 24);
        let optional = tree
            .actions
            .iter()
            .find(|action| action.id == "optional-import")
            .unwrap();
        assert_eq!(optional.params()[0].ty, ParamType::Secret);
        assert!(!optional.params()[0].required);
        assert!(ActionArgs::bind_json(optional.params(), &serde_json::Map::new()).is_ok());
    }
}

#[derive(Clone, Debug, PartialEq, tilo_resource::Effect)]
#[effect(operation = "test.shelf.view", catalogue = "tests/locales")]
pub enum ShelfView {
    /// Type at the invoker's caret.
    #[effect(edit, member)]
    TypeHere { text: String },
    /// Scroll to the top.
    #[effect(view)]
    Top,
}

/// A card's id, as the app names it.
pub type CardKey = uuid::Uuid;

#[derive(Clone, Debug, PartialEq, tilo_resource::Effect)]
#[effect(operation = "test.shelf.cards", catalogue = "tests/locales")]
pub enum CardEffect {
    /// Show a card.
    #[effect(kind = "outside")]
    Show {
        card: CardKey,
        colour: Option<Colour>,
    },
}

/// The host's web links, as a record a parameter carries.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Links {
    pub web_entry: String,
    pub origin: String,
}

/// Where a plan's notice points readers: a link, and the host's web links when it has them.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Context {
    pub link: String,
    pub links: Option<Links>,
}

#[derive(Clone, Debug, PartialEq, tilo_resource::Effect)]
#[effect(operation = "test.shelf.records", catalogue = "tests/locales")]
pub enum RecordsEffect {
    /// Plan a record.
    #[effect(kind = "read")]
    Plan { context: Option<Context> },
}

tilo_test_env::scenario! {
    fn an_effect_publishes_its_parameters_tags_and_asking;

    phase an_effect_parameter_publishes_what_its_type_is_written_as;
    {
        use tilo_resource::Effect as _;
        let spec = CardEffect::specs()
            .into_iter()
            .find(|spec| spec.id == "show")
            .unwrap();
        let kinds: Vec<(String, tilo_actions::ParamType)> = spec
            .params()
            .iter()
            .map(|param| (param.name.to_string(), param.ty))
            .collect();
        assert_eq!(
            kinds,
            [
                ("card".to_owned(), tilo_actions::ParamType::Text),
                ("colour".to_owned(), tilo_actions::ParamType::Object),
            ]
        );
    }

    phase an_optional_record_parameter_keeps_its_type_schema_and_named_types;
    {
        use tilo_resource::Effect as _;
        use tilo_resource::surface::{TypeSet, effect_verbs};

        let mut types = TypeSet::new();
        let verbs = effect_verbs(&RecordsEffect::rows(), &mut types);
        assert_eq!(verbs.len(), 1, "a read effect is a verb of the surface");
        let surface = tilo_resource::Surface {
            kind: "test.shelf".to_owned(),
            label: "Shelf".to_owned(),
            version: 1,
            person: false,
            readers: None,
            verbs,
            fields: Vec::new(),
            types: types.into_types(),
            shows: Vec::new(),
            live: None,
            setters: false,
        };
        let written = tilo_surface_compile::file::render(
            "# Written by a test\n\n",
            &[serde_json::to_value(&surface).unwrap()],
            &[],
        )
        .unwrap();
        let filed = tilo_surface_compile::file::filed(
            &serde_json::to_value(&surface).unwrap(),
        );
        let param = &filed["verbs"][0]["params"][0];
        assert_eq!(param["name"], "context");
        assert_eq!(param["required"], false, "an `Option` parameter is optional");
        assert_eq!(
            param["type"],
            serde_json::json!({"option": {"named": "Context"}}),
            "the optional record parameter keeps its type: {written}"
        );
        assert_eq!(
            param["schema"]["type"],
            serde_json::json!(["object", "null"]),
            "{written}"
        );
        let links = &param["schema"]["properties"]["links"];
        assert_eq!(
            links["type"],
            serde_json::json!(["object", "null"]),
            "{written}"
        );
        assert_eq!(
            links["properties"]["web_entry"]["type"], "string",
            "the schema of the record the parameter holds is kept: {written}"
        );
        let mut named: Vec<&str> = filed["types"]
            .as_array()
            .unwrap()
            .iter()
            .map(|named| named["name"].as_str().unwrap())
            .collect();
        named.sort_unstable();
        assert_eq!(
            named,
            ["Context", "Links"],
            "the record and the record it holds are both declared: {written}"
        );
        assert!(written.contains(r#"named = "Context""#), "{written}");
        assert!(written.contains(r#"named = "Links""#), "{written}");
    }

    phase an_export_reaches_outside_only_when_told_where_to_write;
    {
        use tilo_resource::Effect as _;
        let export = PressEffect::specs()
            .into_iter()
            .find(|spec| spec.id == "export")
            .unwrap();
        assert_eq!(
            export.contract.kind,
            ActionKind::Read,
            "offered as the least it does"
        );
        let need = |arguments: serde_json::Value| {
            export
                .need_for(Some(arguments.as_object().unwrap()), None)
                .kind
        };
        assert_eq!(need(serde_json::json!({})), ActionKind::Read);
        assert_eq!(need(serde_json::json!({ "path": null })), ActionKind::Read);
        assert_eq!(
            need(serde_json::json!({ "path": "/tmp/shelf.json" })),
            ActionKind::Outside
        );
        // Every field optional: a person choosing it exports, asked nothing,
        // never the path's help text as a line to type. A required field
        // still asks.
        assert!(matches!(
            export.input(),
            tilo_actions::ActionInput::Immediate(_)
        ));
        let show = CardEffect::specs()
            .into_iter()
            .find(|spec| spec.id == "show")
            .unwrap();
        assert!(matches!(
            show.input(),
            tilo_actions::ActionInput::Prompted { .. }
        ));
    }

    phase an_effect_carries_the_tags_its_host_treats_it_by;
    {
        use tilo_resource::Effect as _;
        let specs = PressEffect::specs();
        let tags = |id: &str| {
            specs
                .iter()
                .find(|spec| spec.id == id)
                .unwrap()
                .contract
                .tags
                .clone()
        };
        let print = tags("print");
        assert!(
            print.iter().any(|tag| tag == tilo_actions::HOST_RENDER_TAG),
            "a host-rendered effect says so: {print:?}"
        );
        assert!(print.iter().any(|tag| tag == PRINTED_TAG), "{print:?}");
        let count = tags("count");
        assert!(
            count
                .iter()
                .all(|tag| tag != tilo_actions::HOST_RENDER_TAG && tag != PRINTED_TAG),
            "an untagged effect carries neither: {count:?}"
        );
    }

    phase a_bound_destructive_effect_asks_its_caller_to_type_what_it_erases;
    {
        use tilo_resource::Effect as _;
        let wipe = WipeEffect::Wipe {
            device: "/dev/sdb".into(),
        };
        assert_eq!(wipe.confirmation_phrase().as_deref(), Some("sdb"));
        assert_eq!(WipeEffect::Rescan.confirmation_phrase(), None);
        let bound = wipe.bound();
        assert_eq!(bound.contract.risk, tilo_actions::RiskLevel::Destructive);
        assert_eq!(
            bound.contract.confirmation,
            tilo_actions::ConfirmationPolicy::Phrase {
                phrase: "sdb".into()
            }
        );
        assert!(
            bound.contract.validate_declaration().is_empty(),
            "{:?}",
            bound.contract.validate_declaration()
        );
        let other = WipeEffect::Wipe {
            device: "/dev/sdc".into(),
        }
        .bound();
        assert_eq!(
            other.contract.confirmation,
            tilo_actions::ConfirmationPolicy::Phrase {
                phrase: "sdc".into()
            },
            "each bound invocation names its own drive"
        );
    }
}

/// A tag a test host treats an effect by.
const PRINTED_TAG: &str = "test:printed";

#[derive(Clone, Debug, PartialEq, tilo_resource::Effect)]
#[effect(operation = "test.shelf.press", catalogue = "tests/locales")]
pub enum PressEffect {
    /// Print the shelf.
    #[effect(kind = "outside")]
    #[effect(job, returns, host_render, tag = PRINTED_TAG)]
    Print,
    /// Count the cards.
    #[effect(kind = "outside")]
    #[effect(returns)]
    Count,
    /// Export the shelf.
    #[effect(returns, kind = "read", outside_with = "path")]
    Export {
        #[param("Where to write it; kept as content when absent")]
        path: Option<String>,
    },
}

/// A card in an address book: named by first and last name, else its
/// organization.
#[derive(tilo_resource::Model, Default, Debug, Clone, PartialEq)]
#[model(label = "first last")]
pub struct Person {
    pub first: String,
    pub last: String,
    #[model(label)]
    pub organization: String,
}

#[derive(tilo_resource::Model, Default, Debug, Clone, PartialEq)]
pub struct Book {
    pub people: Collection<Person>,
}

#[resource(kind = "test.book", params = book, catalogue = "tests/locales")]
impl Book {
    /// Add a card.
    #[action]
    pub fn add(&mut self, cx: &mut ActionCx, first: String, last: String, organization: String) {
        self.people.push(
            cx.id(),
            Person {
                first,
                last,
                organization,
            },
        );
    }

    /// Remove a card.
    #[action(item = people)]
    pub fn remove(person: &mut Person, cx: &mut ActionCx) {
        let _ = person;
        cx.remove_item();
    }

    /// Change a card's first name.
    #[action(item = people)]
    pub fn rename(person: &mut Person, cx: &mut ActionCx, first: String) {
        let _ = cx.now_ms();
        person.first = first;
    }
}

tilo_test_env::scenario! {
    fn items_and_map_entries_are_labelled_and_edited_alone;

    phase an_item_label_is_made_of_several_fields;
    {
        let mut book = Replica::<Book>::new().in_app("so.tilo.model", "Model");
        book.apply(Book::ADD.with(("Ada".to_owned(), "Lovelace".to_owned(), String::new())))
            .unwrap();
        book.apply(Book::ADD.with((
            String::new(),
            String::new(),
            "Analytical Engines".to_owned(),
        )))
        .unwrap();
        let state = book.state().unwrap();
        let labels: Vec<Option<String>> = state.people.values().map(Model::label).collect();
        assert_eq!(
            labels,
            [
                Some("Ada Lovelace".to_owned()),
                Some("Analytical Engines".to_owned())
            ]
        );
        let tree = book.published().unwrap();
        let mut items: Vec<&str> = tree
            .children
            .iter()
            .map(|child| child.label.as_str())
            .collect();
        items.sort_unstable();
        assert_eq!(items, ["Ada Lovelace", "Analytical Engines"]);

        // History names the item the same way.
        let (ada, _) = state.people.iter().next().unwrap();
        let edit = Book::edit_action(Book::paths().people.item(ada).last.replace("Byron")).unwrap();
        let entry = book.apply_action(&edit).unwrap().context.clone().unwrap();
        assert_eq!(entry.item.unwrap().label, "Ada Lovelace");
    }

    phase an_item_label_can_be_named_by_a_function;
    // A label that is not a field's text as stored is what the type's
    // `label = path` names it: the value, its item resource and its search
    // entry all read so.
    {
        let mut pins = Replica::<Pins>::new().in_app("so.tilo.model", "Model");
        pins.apply(Pins::PIN.with("std:docs".to_owned())).unwrap();
        pins.apply(Pins::PIN.with("/srv/media".to_owned())).unwrap();
        let state = pins.state().unwrap();
        let labels: Vec<Option<String>> = state.pins.values().map(Model::label).collect();
        assert_eq!(
            labels,
            [Some("Documents".to_owned()), Some("media".to_owned())]
        );
        let tree = pins.published().unwrap();
        let mut items: Vec<&str> = tree
            .children
            .iter()
            .map(|child| child.label.as_str())
            .collect();
        items.sort_unstable();
        assert_eq!(items, ["Documents", "media"]);
    }

    phase an_edit_under_a_map_key_is_about_that_entry_and_a_set_names_its_element;
    {
        let mut reports = Replica::<Reports>::new().in_app("so.tilo.model", "Model");
        reports
            .apply(Reports::FILE.with(("so.tilo.notes".to_owned(), "Notes crash".to_owned())))
            .unwrap();
        let note = described(
            &mut reports,
            Reports::paths()
                .reports
                .key("so.tilo.notes")
                .note
                .replace("on save"),
        );
        let tilo_actions::Did::Edit(field) = &note.what else {
            panic!("a field edit");
        };
        assert_eq!(
            (field.ty.as_str(), field.field.as_str()),
            ("report", "note")
        );
        let item = note.item.unwrap();
        assert_eq!(
            (item.id.as_str(), item.label.as_str()),
            ("so.tilo.notes", "Notes crash")
        );

        let removed = described(
            &mut reports,
            Reports::paths().reports.remove("so.tilo.notes"),
        );
        let item = removed.item.unwrap();
        assert_eq!(
            (item.id.as_str(), item.label.as_str()),
            ("so.tilo.notes", "Notes crash")
        );

        let tagged = described(
            &mut reports,
            Reports::paths().tags.insert(&"urgent".to_owned()),
        );
        let tilo_actions::Did::Edit(field) = &tagged.what else {
            panic!("a field edit");
        };
        assert_eq!(
            field.new.as_ref().and_then(|new| new.as_str()),
            Some("urgent")
        );
    }

    phase an_item_method_reads_and_writes_its_item_alone;
    {
        use automerge::transaction::Transactable as _;
        use automerge::{ObjType, ReadDoc as _, ScalarValue, Value};
        let mut book = Replica::<Book>::new().in_app("so.tilo.model", "Model");
        book.apply(Book::ADD.with(("Ada".to_owned(), "Lovelace".to_owned(), String::new())))
            .unwrap();
        book.apply(Book::ADD.with(("Charles".to_owned(), "Babbage".to_owned(), String::new())))
            .unwrap();
        let state = book.state().unwrap();
        let ids: Vec<Id> = state.people.ids().cloned().collect();

        // It is offered on each card, its id bound.
        let tree = book.published().unwrap();
        assert!(
            tree.children
                .iter()
                .all(|card| card.actions.iter().any(|spec| spec.id == "rename"))
        );

        // Another card that no longer reads (written by a newer version) is
        // quarantined, and does not stop a change of this one: only this one is
        // read.
        let doc = book.doc_mut();
        let Ok(Some((Value::Object(ObjType::Map), people))) = doc.get(automerge::ROOT, "people") else {
            panic!("people is a map");
        };
        let Ok(Some((Value::Object(ObjType::Map), other))) = doc.get(&people, ids[1].as_str()) else {
            panic!("the card is there");
        };
        doc.put(&other, "v", ScalarValue::Str("from the future".into()))
            .unwrap();
        doc.commit();
        let held: Vec<Id> = book
            .state()
            .unwrap()
            .people
            .quarantined()
            .iter()
            .map(|held| held.id.clone())
            .collect();
        assert_eq!(held, [ids[1].clone()], "only that card is held aside");
        let rename = Book::RENAME
            .with((ids[0].clone(), "Augusta".to_owned()))
            .build(0)
            .unwrap();
        tilo_actions::Action::apply(&rename, book.doc_mut()).unwrap();
        let first = book.doc().get(&people, ids[0].as_str()).unwrap().unwrap().1;
        let value = book.doc().get(&first, "v").unwrap().unwrap().1;
        let person: Person = tilo_resource::read_key(book.doc(), &first, "v").unwrap();
        let _ = value;
        assert_eq!(person.first, "Augusta");
        assert_eq!(person.last, "Lovelace");
        // An item method removes its item alone, the card held aside unread.
        let remove = Book::REMOVE.with(ids[0].clone()).build(0).unwrap();
        tilo_actions::Action::apply(&remove, book.doc_mut()).unwrap();
        assert!(
            book.doc().get(&people, ids[0].as_str()).unwrap().is_none(),
            "the card is removed"
        );
        assert!(book.doc().get(&people, ids[1].as_str()).unwrap().is_some());
    }

    phase an_edit_inside_a_missing_map_entry_starts_the_entry;
    {
        let mut reports = Replica::<Reports>::new().in_app("so.tilo.model", "Model");
        let action = Reports::edit_action(
            Reports::paths()
                .reports
                .key("so.tilo.maps")
                .note
                .replace("needs a key"),
        )
        .unwrap();
        reports.apply_action(&action).unwrap();
        let state = reports.state().unwrap();
        let report = state.reports.get("so.tilo.maps").unwrap();
        assert_eq!(report.note, "needs a key");
        assert_eq!(report.title, "");
    }
}

/// A pinned folder, kept as a place every device resolves (`std:docs`) and
/// named as a person knows it.
#[derive(tilo_resource::Model, Default, Debug, Clone, PartialEq)]
#[model(label = Pin::name)]
pub struct Pin {
    pub place: tilo_resource::Atom,
}

impl Pin {
    fn name(&self) -> String {
        match self.place.0.as_str() {
            "std:docs" => "Documents".to_owned(),
            other => other.rsplit('/').next().unwrap_or(other).to_owned(),
        }
    }
}

#[derive(tilo_resource::Model, Default, Debug, Clone, PartialEq)]
pub struct Pins {
    pub pins: Collection<Pin>,
}

#[resource(kind = "test.pins", params = pins, catalogue = "tests/locales")]
impl Pins {
    /// Pin a place.
    #[action]
    pub fn pin(&mut self, cx: &mut ActionCx, place: String) {
        self.pins.push(
            cx.id(),
            Pin {
                place: tilo_resource::Atom(place),
            },
        );
    }
}

/// A report, kept under the id of the app it is about.
#[derive(tilo_resource::Model, Default, Debug, Clone, PartialEq)]
pub struct Report {
    #[model(label)]
    pub title: String,
    pub note: String,
}

#[derive(tilo_resource::Model, Default, Debug, Clone, PartialEq)]
pub struct Reports {
    pub reports: std::collections::BTreeMap<String, Report>,
    pub tags: tilo_resource::Set<String>,
}

#[resource(kind = "test.reports", params = reports, catalogue = "tests/locales")]
impl Reports {
    /// File a report.
    #[action]
    pub fn file(&mut self, app: String, title: String) {
        self.reports.insert(
            app,
            Report {
                title,
                note: String::new(),
            },
        );
    }
}

fn described(
    replica: &mut Replica<Reports, AppNamed>,
    edit: tilo_resource::Edit<Reports>,
) -> tilo_actions::Described {
    let action = Reports::edit_action(edit).unwrap();
    replica
        .apply_action(&action)
        .unwrap()
        .context
        .clone()
        .unwrap()
        .described()
        .unwrap()
}

/// Pages whose places are published only once a view loaded them.
#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Pages {
    pub titles: Vec<String>,
    #[model(skip)]
    pub loaded: Vec<usize>,
}

#[resource(kind = "test.pages", load = Pages::load_pages, children = Pages::places, catalogue = "tests/locales")]
impl Pages {
    /// Add a page.
    #[action]
    pub fn add_page(&mut self, title: String) {
        self.titles.push(title);
    }

    #[allow(clippy::unnecessary_wraps, reason = "the load hook's signature")]
    fn load_pages(
        &mut self,
        _doc: &tilo_resource::Doc,
        demand: &tilo_resource::Demand,
    ) -> Result<(), tilo_resource::ModelError> {
        self.loaded = demand
            .keys
            .iter()
            .filter_map(|key| key.strip_prefix('p')?.parse().ok())
            .filter(|index| *index < self.titles.len())
            .collect();
        Ok(())
    }

    fn places(&self) -> Vec<Derived<Self>> {
        self.loaded
            .iter()
            .map(|&index| {
                Derived::new(self.titles[index].clone())
                    .identified(format!("p{index}"))
                    .in_field("pages")
            })
            .collect()
    }
}

tilo_test_env::scenario! {
    fn a_place_not_loaded_resolves_and_reads_on_demand;

    phase a_place_not_loaded_still_resolves_by_id;
    {
        let mut pages = Replica::<Pages>::new().in_app("so.tilo.model", "Model");
        for title in ["Cover", "Contents", "Chapter one"] {
            pages.apply(Pages::ADD_PAGE.with(title.to_owned())).unwrap();
        }
        let state = Pages::read(pages.doc()).unwrap();
        let id = "test.pages/pages/p2";
        assert!(Pages::child(&state, id).is_none(), "nothing is loaded");
        let child = tilo_resource::child_by_id::<Pages>(&state, pages.doc(), id).expect("resolved");
        assert_eq!(child.label, "Chapter one");
    }

    phase reading_more_of_a_document_is_no_revision;
    {
        let mut pages = three_pages();
        let mut reader = tilo_resource::Reader::<Pages>::open(pages.doc_mut()).unwrap();
        let revision = reader.revision();
        let demand = tilo_resource::Demand::none().with_keys(["p0", "p2"]);
        assert!(reader.demand(pages.doc(), demand).unwrap());
        assert_eq!(reader.state().loaded, [0, 2]);
        assert_eq!(reader.revision(), revision);
        assert_eq!(reader.loads(), 1);

        pages
            .apply(Pages::ADD_PAGE.with("Index".to_owned()))
            .unwrap();
        assert!(reader.sync(pages.doc()).unwrap());
        assert_ne!(reader.revision(), revision);
    }
}

fn three_pages() -> Replica<Pages, AppNamed> {
    let mut pages = Replica::<Pages>::new().in_app("so.tilo.model", "Model");
    for title in ["Cover", "Contents", "Chapter one"] {
        pages.apply(Pages::ADD_PAGE.with(title.to_owned())).unwrap();
    }
    pages
}

#[test]
fn places_as_they_were_are_the_publication_they_were() {
    let pages = three_pages();
    let mut state = Pages::read(pages.doc()).unwrap();
    state.loaded = vec![0, 1];
    let first = tilo_resource::derived::published::<Pages>(state.places());
    let again = tilo_resource::derived::published::<Pages>(state.places());
    assert!(std::rc::Rc::ptr_eq(&first, &again));

    state.loaded = vec![0, 1, 2];
    let more = tilo_resource::derived::published::<Pages>(state.places());
    assert!(!std::rc::Rc::ptr_eq(&first, &more));
    let labels: Vec<&str> = more
        .resources()
        .iter()
        .map(|place| place.label.as_str())
        .collect();
    assert_eq!(labels, ["Cover", "Contents", "Chapter one"]);
    for (was, now) in first.resources().iter().zip(more.resources().iter()) {
        assert!(
            std::rc::Rc::ptr_eq(was, now),
            "{} is published again",
            was.label
        );
    }
}

#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct PrivateImport {
    pub received_bytes: u64,
}

#[resource(kind = "test.private-import", catalogue = "tests/locales")]
impl PrivateImport {
    /// Receive a private snapshot.
    #[action]
    pub fn import(&mut self, #[param(secret, "Private snapshot")] payload: String) {
        self.received_bytes = payload.len() as u64;
    }

    /// Receive an optional private snapshot.
    #[action]
    pub fn optional_import(
        &mut self,
        #[param("Private snapshot", secret)] payload: Option<String>,
    ) {
        self.received_bytes = payload.map_or(0, |payload| payload.len() as u64);
    }
}

#[derive(Clone, Debug, PartialEq, tilo_resource::Effect)]
#[effect(operation = "test.shelf.wipe", catalogue = "tests/locales")]
pub enum WipeEffect {
    /// Wipe a drive. Offered on each drive.
    #[effect(kind = "outside")]
    #[effect(row, destructive, phrase = "Self::drive")]
    Wipe {
        #[param("Device path of the drive")]
        device: String,
    },
    /// Rescan drives.
    #[effect(kind = "outside")]
    Rescan,
}

impl WipeEffect {
    fn drive(&self) -> String {
        match self {
            Self::Wipe { device } => device.trim_start_matches("/dev/").to_owned(),
            Self::Rescan => String::new(),
        }
    }
}