tilo-resource 0.5.0

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
1567
1568
1569
1570
1571
1572
//! Field options and the small conveniences around edits: atoms written
//! whole, skipped fields read as their type's default, a typed word as one
//! undo step, nullary destructive verbs asking first, and a replica's author
//! reaching its verbs.
#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::float_cmp,
    reason = "test assertions over exact values written and read back"
)]

use tilo_resource::{ActionCx, Collection, Derived, Id, Invoke, Model, Replica, resource};

#[derive(Model, Debug, Clone, PartialEq)]
pub struct Board {
    /// The layer the board draws on, written whole.
    #[model(atom)]
    pub layer: String,
    pub title: String,
    pub author: String,
    #[model(skip)]
    pub admin: bool,
    pub cards: u32,
    pub notes: Collection<Note>,
    #[model(remove = "quiet")]
    pub drafts: Collection<String>,
}

/// The title as the origin resolves it: upper case.
#[allow(clippy::unnecessary_wraps, reason = "a prepare hook may refuse")]
fn shouted(params: &mut board::Shout) -> Result<(), String> {
    params.title = params.title.to_uppercase();
    Ok(())
}

/// How the board looks.
#[derive(
    Default,
    Debug,
    Clone,
    PartialEq,
    serde::Serialize,
    serde::Deserialize,
    tilo_resource::JsonSchema,
)]
pub struct BoardStyle {
    /// The board's title.
    pub title: String,
    /// How many cards it shows.
    pub cards: Option<u32>,
}

#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Note {
    #[model(label)]
    pub title: String,
    pub body: Vec<String>,
}

impl Default for Board {
    fn default() -> Self {
        Self {
            layer: String::new(),
            title: String::new(),
            author: String::new(),
            admin: true,
            cards: 0,
            notes: Collection::new(),
            drafts: Collection::new(),
        }
    }
}

#[resource(kind = "test.board", catalogue = "tests/locales")]
impl Board {
    /// Remove every card.
    #[action(destructive)]
    pub fn clear(&mut self) {
        self.cards = 0;
    }

    /// Retitle the board and set its card count.
    #[action]
    pub fn restyle(&mut self, #[param(flatten)] style: BoardStyle) {
        self.title = style.title;
        if let Some(cards) = style.cards {
            self.cards = cards;
        }
    }

    /// Retitle the board loudly: the title is resolved once, where invoked.
    #[action(prepare = shouted)]
    pub fn shout(&mut self, title: String) {
        self.title = title;
    }

    /// Retitle the board, with an optional suffix.
    #[action]
    pub fn retitle(&mut self, title: String, suffix: Option<String>) {
        self.title = format!("{title}{}", suffix.unwrap_or_default());
    }

    /// Clear a note's lines, answering what it cleared.
    #[action(answers)]
    pub fn clear_note(&mut self, notes: &Id) {
        if let Some(note) = self.notes.get_mut(notes) {
            note.body.clear();
        }
    }

    /// Note who a card was added for, and by what.
    #[action]
    pub fn add_card_for(&mut self, cx: &mut ActionCx) {
        self.cards = self.cards.saturating_add(1);
        let acting = cx.invoked_by();
        self.author = format!(
            "{} for {}",
            if acting.as_ref().is_some_and(tilo_actions::Acting::is_agent) {
                "Agent"
            } else {
                "Person"
            },
            acting
                .as_ref()
                .and_then(tilo_actions::Acting::acted_for_person)
                .unwrap_or_default()
        );
    }

    /// Add a card, signed by whoever adds it.
    #[action]
    pub fn add_card(&mut self, cx: &mut ActionCx) {
        self.cards = self.cards.saturating_add(1);
        self.author = cx
            .author()
            .map(|author| author.id().to_owned())
            .unwrap_or_default();
    }
}

/// The field-edit operation among `published`'s actions.
fn field_edit(published: &tilo_actions::ResourceSpec) -> &tilo_actions::ActionSpec {
    published
        .actions
        .iter()
        .find(|spec| spec.id == tilo_resource::FIELD_EDIT)
        .unwrap()
}

tilo_test_env::scenario! {
    fn a_field_is_stored_and_listed_as_it_declares;

    phase an_atom_is_written_whole_and_the_last_writer_wins;
    {
        let mut a = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        a.apply(Board::paths().layer.set("layer-1".into())).unwrap();
        let mut b = a.fork();
        a.apply(Board::paths().layer.set("layer-2".into())).unwrap();
        b.apply(Board::paths().layer.set("layer-3".into())).unwrap();
        a.sync_with(&mut b).unwrap();
        let merged = a.state().unwrap();
        assert_eq!(merged, b.state().unwrap());
        assert!(
            ["layer-2", "layer-3"].contains(&merged.layer.as_str()),
            "one of the two, not a mix of them: {}",
            merged.layer
        );
        assert!(
            a.apply(Board::paths().layer.splice(0, 0, "x")).is_err(),
            "an atom is not edited by character"
        );
    }

    phase an_agent_reads_from_the_descriptor_what_it_can_change;
    // The field edit's description is the listing an agent reads before it changes anything:
    // the paths it may address and the operations each field's shape takes.
    {
        let published = Replica::<Board>::new().in_app("so.tilo.model", "Model").published().unwrap();
        let schema = field_edit(&published).params()[0]
            .schema
            .as_deref()
            .unwrap()
            .clone();
        let description = schema["description"]
            .as_str()
            .expect("the field edit says what it edits");
        for path in ["- `title`", "- `layer`", "- `notes`"] {
            assert!(
                description
                    .lines()
                    .any(|line| line.starts_with(path)),
                "{path} is listed: {description}"
            );
        }
        assert!(
            description.contains("splice {at, delete, insert}"),
            "a text says how it may be edited: {description}"
        );
    }

    phase a_skipped_field_reads_as_the_containing_types_default;
    {
        let replica = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        assert!(replica.state().unwrap().admin);
    }

    phase a_space_ends_the_typed_word_it_follows;
    {
        let title = Board::paths().title;
        let typed = ["h", "e", "y", " ", "y", "o", "u"];
        let edits: Vec<_> = typed
            .iter()
            .enumerate()
            .map(|(at, text)| title.splice(at, 0, *text))
            .collect();
        let breaks: Vec<usize> = edits
            .windows(2)
            .enumerate()
            .filter(|(_, pair)| !pair[0].coalesces(&pair[1]))
            .map(|(at, _)| at + 1)
            .collect();
        assert_eq!(breaks, [4], "`hey ` then `you`: undo leaves `hey `");
    }

    phase whole_text_replacements_undo_a_word_at_a_time;
    // A text field bound to a record replaces the whole text on every keystroke.
    // Those replacements still undo a word at a time, like splices: a space
    // ends the word it follows, erasing runs on, and a paste is its own step.
    {
        let title = Board::paths().title;
        let texts = [
            "h",
            "he",
            "hey",
            "hey ",
            "hey y",
            "hey yo",
            "hey you",
            "hey yo",
            "hey y",
            "hey yesterday",
            "hey yesterday!",
        ];
        let edits: Vec<_> = texts.iter().map(|text| title.replace(*text)).collect();
        let breaks: Vec<usize> = edits
            .windows(2)
            .enumerate()
            .filter(|(_, pair)| !pair[0].coalesces(&pair[1]))
            .map(|(at, _)| at + 1)
            .collect();
        assert_eq!(
            breaks,
            [4, 9],
            "`hey ` is one step, `you` erased back to `y` another, the pasted \
         `esterday` a third, typed on by `!`"
        );
    }

    phase a_field_publishes_what_it_declares;
    // What a field declares is published with it, so an agent knows the
    // bounds, the choices and the default before it changes the field.
    {
        let scale = comfort_schema("text_scale");
        assert_eq!(
            (&scale["minimum"], &scale["maximum"], &scale["default"]),
            (
                &serde_json::json!(0.5),
                &serde_json::json!(3.0),
                &serde_json::json!(1.0)
            )
        );
        let schedule = comfort_schema("schedule");
        assert_eq!(schedule["enum"], serde_json::json!(["sun", "custom"]));
        assert_eq!(schedule["default"], serde_json::json!("sun"));
        let cursor = comfort_schema("cursor").to_string();
        assert!(
            cursor.contains("\"minimum\":24") && cursor.contains("\"maximum\":64"),
            "{cursor}"
        );
        assert_eq!(comfort_schema("note")["default"], serde_json::json!(""));
    }

    phase a_field_holds_only_what_it_declares;
    // A change outside what a field declares is refused, through a field edit
    // and through a verb alike; within it, it applies.
    {
        let paths = Comfort::paths();
        let mut comfort = Replica::<Comfort>::new().in_app("so.tilo.model", "Model");
        comfort.apply(paths.text_scale.set(2.0)).unwrap();
        let refused = format!(
            "{:?}",
            comfort.apply(paths.text_scale.set(9.0)).unwrap_err()
        );
        assert!(refused.contains("between 0.5 and 3"), "{refused}");
        assert!(comfort.apply(Comfort::SCALE_TEXT.with(0.1)).is_err());
        assert!(
            comfort
                .apply(paths.schedule.set("dusk".to_owned()))
                .is_err()
        );
        comfort
            .apply(paths.schedule.set("custom".to_owned()))
            .unwrap();
        comfort.apply(paths.cursor.set(Some(32))).unwrap();
        assert!(comfort.apply(paths.cursor.set(Some(8))).is_err());
        comfort.apply(paths.cursor.set(None)).unwrap();
        comfort
            .apply(paths.note.set("anything".to_owned()))
            .unwrap();
        let state = comfort.state().unwrap();
        assert_eq!(
            (state.text_scale, state.schedule.as_str(), state.cursor),
            (2.0, "custom", None)
        );
    }

    phase an_optional_atom_and_a_list_atom_are_one_of_the_values_set;
    {
        let paths = Swatch::paths();
        let merged = merged_swatch(
            paths.colour.set(Some("#000000".into())).into(),
            paths.colour.set(Some("#ff0000".into())).into(),
            paths.colour.set(Some("#00ff00".into())).into(),
        );
        assert!(
            [Some("#ff0000"), Some("#00ff00")].contains(&merged.colour.as_deref()),
            "one colour, not a mix: {:?}",
            merged.colour
        );
        let merged = merged_swatch(
            paths.outline.set(vec![[0.0, 0.0]]).into(),
            paths.outline.set(vec![[1.0, 1.0], [2.0, 2.0]]).into(),
            paths.outline.set(vec![[3.0, 3.0]]).into(),
        );
        assert!(
            merged.outline == [[1.0, 1.0], [2.0, 2.0]] || merged.outline == [[3.0, 3.0]],
            "one outline, not a mix: {:?}",
            merged.outline
        );
        let mut replica = Replica::<Swatch>::new().in_app("so.tilo.model", "Model");
        replica
            .apply(paths.colour.set(Some("#123456".into())))
            .unwrap();
        replica.apply(Swatch::CLEAR.with(())).unwrap();
        assert_eq!(replica.state().unwrap().colour, None, "`None` is absent");
    }

    phase a_variants_atoms_are_one_of_the_values_set_and_its_other_fields_merge;
    {
        let glyph = Swatch::paths().glyph;
        let merged = merged_swatch(
            glyph
                .set(Some(path("M0 0", "#000000", &[[0.0, 0.0]], 1.0)))
                .into(),
            glyph
                .set(Some(path("M1 1L2 2", "#ff0000", &[[1.0, 1.0]], 1.0)))
                .into(),
            glyph
                .set(Some(path(
                    "M3 3",
                    "#00ff00",
                    &[[3.0, 3.0], [4.0, 4.0]],
                    1.0,
                )))
                .into(),
        );
        let Some(Glyph::Path {
            d, colour, points, ..
        }) = merged.glyph
        else {
            panic!("still a path: {:?}", merged.glyph);
        };
        assert!(["M1 1L2 2", "M3 3"].contains(&d.as_str()), "one path: {d}");
        assert!(
            [Some("#ff0000"), Some("#00ff00")].contains(&colour.as_deref()),
            "one colour: {colour:?}"
        );
        assert!(
            points == [[1.0, 1.0]] || points == [[3.0, 3.0], [4.0, 4.0]],
            "one list of points: {points:?}"
        );
        let merged = merged_swatch(
            glyph
                .set(Some(path("M0 0", "#000000", &[[0.0, 0.0]], 1.0)))
                .into(),
            glyph
                .set(Some(path("M0 0", "#ff0000", &[[0.0, 0.0]], 1.0)))
                .into(),
            glyph
                .set(Some(path("M0 0", "#000000", &[[0.0, 0.0]], 2.0)))
                .into(),
        );
        assert_eq!(
            merged.glyph,
            Some(path("M0 0", "#ff0000", &[[0.0, 0.0]], 2.0)),
            "a colour and a width changed apart both survive"
        );
    }

    phase a_records_field_is_edited_through_the_records_field_edit;
    // A record's fields are set one at a time through the field edit: the
    // unpublished inner fields are addressed by a path below the record.
    {
        let published = Replica::<Frame>::new().in_app("so.tilo.model", "Model").published().unwrap();
        let spec = field_edit(&published);
        let schema = spec.params()[0].schema.as_deref().unwrap().clone();
        let edit = serde_json::json!({
            "path": [{ "field": "look" }, { "field": "width" }],
            "op": "set",
            "value": 2.0,
        });
        tilo_actions::validate_json_schema(&edit, &schema).expect("the edit fits the schema");
        let edit: tilo_resource::Edit<Frame> = serde_json::from_value(edit).unwrap();
        let mut frame = Replica::<Frame>::new().in_app("so.tilo.model", "Model");
        frame.apply(edit).unwrap();
        assert_eq!(frame.state().unwrap().look.width, 2.0);
    }
}

tilo_test_env::scenario! {
    fn a_verb_takes_its_parameters_invoker_and_group_as_declared;

    phase a_nullary_destructive_verb_applies_at_once;
    // A destructive verb of the record is undoable, so it applies at once:
    // nobody is asked first.
    {
        let mut board = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        board.apply(Board::ADD_CARD.with(())).unwrap();
        board.apply(Board::CLEAR.with(())).unwrap();
        assert_eq!(board.state().unwrap().cards, 0);
    }

    phase a_replicas_author_is_the_invoker_its_verbs_see;
    {
        let mut board = Replica::<Board>::new().in_app("so.tilo.model", "Model").as_author("ada");
        board.apply(Board::ADD_CARD.with(())).unwrap();
        assert_eq!(board.state().unwrap().author, "ada");
        // An edit converts into an invocation where one is expected.
        let invoke: Invoke<Board> = Board::paths().title.set("Sprint".into()).into();
        board.apply(invoke).unwrap();
        assert_eq!(board.state().unwrap().title, "Sprint");
        assert_eq!(Id::default().as_str(), "");
    }

    phase a_flattened_struct_is_the_verbs_parameters;
    {
        let decl = <Board as tilo_resource::Resource>::declarations()
            .into_iter()
            .find(|decl| decl.id == "restyle")
            .unwrap();
        let params: Vec<(String, bool, tilo_actions::ParamType)> = decl
            .params
            .iter()
            .map(|param| (param.name.to_string(), param.required, param.ty))
            .collect();
        assert_eq!(
            params,
            [
                ("title".to_owned(), true, tilo_actions::ParamType::Text),
                ("cards".to_owned(), false, tilo_actions::ParamType::Integer),
            ]
        );
        let mut board = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        board
            .apply(Board::RESTYLE.with(BoardStyle {
                title: "Sprint".into(),
                cards: Some(3),
            }))
            .unwrap();
        let state = board.state().unwrap();
        assert_eq!((state.title.as_str(), state.cards), ("Sprint", 3));
    }

    phase a_flattened_struct_is_the_effects_arguments;
    {
        use tilo_resource::Effect as _;
        let decl = BoardView::declarations().into_iter().next().unwrap();
        let params: Vec<(String, bool, tilo_actions::ParamType)> = decl
            .params
            .iter()
            .map(|param| (param.name.to_string(), param.required, param.ty))
            .collect();
        assert_eq!(
            params,
            [
                ("region".to_owned(), true, tilo_actions::ParamType::Array),
                ("grid".to_owned(), false, tilo_actions::ParamType::Boolean),
            ]
        );
        let look = BoardView::Look {
            look: LookAt {
                region: vec![0, 0, 10, 10],
                grid: Some(true),
            },
        };
        let arguments = look.arguments();
        assert_eq!(arguments["region"], serde_json::json!([0, 0, 10, 10]));
        assert_eq!(BoardView::decode("look", &arguments).unwrap(), look);
    }

    phase a_flattened_argument_names_the_field_that_does_not_decode;
    // A flattened struct's field that does not decode is named as the caller
    // typed it, not by the struct that carries it: a refusal says which
    // argument to fix.
    {
        use tilo_resource::Effect as _;
        for (arguments, field) in [
            (serde_json::json!({ "region": "everywhere" }), "region"),
            (
                serde_json::json!({ "region": [0, 0, 10, 10], "grid": "yes" }),
                "grid",
            ),
        ] {
            let error = BoardView::decode("look", arguments.as_object().unwrap()).unwrap_err();
            assert!(
                matches!(
                    &error,
                    tilo_resource::EffectDecodeError::Argument { name, .. } if name == field
                ),
                "`{field}` is named: {error}"
            );
        }
    }

    phase an_optional_parameter_bound_to_nothing_is_left_out;
    {
        let decl = Board::RETITLE
            .bind(board::Retitle::paths().title, "Sprint".to_owned())
            .and(board::Retitle::paths().suffix, None)
            .declaration(
                "retitle-sprint",
                tilo_resource::word!("test-board-retitle-sprint", catalogue = "tests/locales"),
            )
            .unwrap();
        let action = decl
            .build_action(&tilo_actions::ActionArgs::default(), 0)
            .expect("it builds");
        let mut board = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        board.apply_action(&action).unwrap();
        assert_eq!(board.state().unwrap().title, "Sprint");
    }

    phase a_group_is_checked_once_at_its_end;
    {
        let mut pair = Replica::<Pair>::new().in_app("so.tilo.model", "Model");
        let paths = Pair::paths();
        assert!(
            pair.apply(paths.left.set(1)).is_err(),
            "alone it breaks the pair"
        );
        pair.apply(Invoke::group([
            paths.left.set(1).into(),
            paths.right.set(1).into(),
        ]))
        .expect("together they keep it");
        pair.apply(Invoke::group([
            Pair::MOVE_LEFT.with(2),
            paths.right.set(2).into(),
        ]))
        .expect("a verb and an edit together keep it too");
        assert!(
            pair.apply(Invoke::group([
                paths.left.set(3).into(),
                paths.right.set(4).into()
            ]))
            .is_err(),
            "a group that ends broken is refused"
        );
        let state = pair.state().unwrap();
        assert_eq!((state.left, state.right), (2, 2));
    }

    phase a_group_of_one_is_that_action;
    // A control whose gesture is sometimes several actions is bound to a
    // group; when it is one, it records that action alone, so an edit in it
    // continues the undo step of the edit before as the edit itself would.
    {
        let mut pair = Replica::<Pair>::new().in_app("so.tilo.model", "Model");
        let paths = Pair::paths();
        let alone = pair
            .apply(Pair::MOVE_LEFT.with(0))
            .expect("a verb")
            .action
            .clone();
        let grouped = pair
            .apply(Invoke::group([Pair::MOVE_LEFT.with(0)]))
            .expect("a group of one verb")
            .action
            .clone();
        assert_eq!(grouped.type_id, alone.type_id);
        let pair_of = pair
            .apply(Invoke::group([
                paths.left.set(0).into(),
                paths.right.set(0).into(),
            ]))
            .expect("a group of two")
            .action
            .clone();
        assert_ne!(pair_of.type_id, alone.type_id, "two actions stay a group");
    }

    phase a_verb_reads_who_its_invoker_acted_for;
    {
        let mut board = Replica::<Board>::new().in_app("so.tilo.model", "Model").as_agent_for("claude", "ada");
        board.apply(Board::ADD_CARD_FOR.with(())).unwrap();
        assert_eq!(board.state().unwrap().author, "Agent for ada");
    }

    phase a_search_entry_lies_in_a_scope_it_names;
    {
        let entry = tilo_resource::SearchEntry::new("Rust 2.0", "news")
            .anchored("feeds.library/articles/a1")
            .inside("feeds.library/feeds/f1");
        assert_eq!(entry.within.as_deref(), Some("feeds.library/feeds/f1"));
    }

    phase a_verb_prepares_its_arguments_once_where_it_is_invoked;
    {
        let mut origin = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        let mut peer = origin.fork();
        origin.apply(Board::SHOUT.with("sprint")).unwrap();
        assert_eq!(origin.state().unwrap().title, "SPRINT");
        for envelope in origin.log().to_vec() {
            peer.replay(&envelope).unwrap();
        }
        assert_eq!(
            peer.state().unwrap().title,
            "SPRINT",
            "the action carries what was prepared"
        );

        // A flattened struct's absent options are left out.
        origin
            .apply(Board::RESTYLE.with(BoardStyle {
                title: "Plain".into(),
                cards: None,
            }))
            .unwrap();
        assert_eq!(origin.state().unwrap().title, "Plain");
    }
}

tilo_test_env::scenario! {
    fn a_field_edit_is_addressed_guarded_and_confirmed_by_its_contract;

    phase removing_an_item_by_field_edit_asks_nothing;
    // A field edit changes only the record: removing an item, of any
    // collection, is undoable and asks nothing.
    {
        let mut board = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        let paths = Board::paths();
        let note = Id::from_raw("n");
        board
            .apply(paths.notes.insert_as(&note, 0, &Note::default()))
            .unwrap();
        board
            .apply(paths.drafts.insert_as(&note, 0, &"draft".to_owned()))
            .unwrap();
        board.apply(paths.notes.remove(&note)).unwrap();
        board.apply(paths.drafts.remove(&note)).unwrap();
        let state = board.state().unwrap();
        assert!(state.notes.is_empty() && state.drafts.is_empty());
    }

    phase any_api_reads_a_field_edit_s_confirmation_from_the_published_contract;
    // An action API without the app's code — the broker, a server — decides from the
    // published field edit alone, and as the app does: the record's edits are
    // undoable, so none asks, whatever it removes.
    {
        use tilo_actions::ConfirmationPolicy;
        let board = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        let published = board.published().unwrap();
        let spec = field_edit(&published);
        let paths = Board::paths();
        let note = Id::from_raw("n");
        let api = |edit: &dyn erased_edit::Encode| {
            let argument = format!(
                "{}{}",
                tilo_actions::ARGUMENTS_JSON_PREFIX,
                serde_json::json!({ "edit": edit.encode() })
            );
            spec.contract.confirmation_for_argument(Some(&argument))
        };
        assert_eq!(api(&paths.notes.remove(&note)), ConfirmationPolicy::None);
        assert_eq!(api(&paths.drafts.remove(&note)), ConfirmationPolicy::None);
        assert_eq!(
            api(&paths.title.set("Plan".to_owned())),
            ConfirmationPolicy::None
        );
        assert_eq!(
            spec.contract.confirmation_for_argument(Some("not an edit")),
            ConfirmationPolicy::None,
            "an argument nobody can read builds nothing; Undo covers whatever does"
        );
    }

    phase a_guarded_field_asks_before_any_edit_and_a_weakening_one_is_privileged;
    // A field's trust decides its every edit, in the app and at any API that
    // reads only the published contract: a weakening one asks and is
    // privileged, a sensitive one asks, an ordinary one neither.
    {
        use tilo_actions::{ConfirmationPolicy, RiskLevel};
        let paths = Lock::paths();
        assert_eq!(paths.minutes.set(10).risk(), RiskLevel::Privileged);
        assert_eq!(
            paths.shown_name.set("Ada".to_owned()).risk(),
            RiskLevel::Destructive
        );
        assert_eq!(paths.label.set("Tower".to_owned()).risk(), RiskLevel::Low);

        let mut lock = Replica::<Lock>::new().in_app("so.tilo.model", "Model");
        assert!(matches!(
            lock.apply(paths.minutes.set(0)),
            Err(tilo_actions::ApiError::ConfirmationRequired)
        ));
        assert!(matches!(
            lock.apply(paths.shown_name.set("Ada".to_owned())),
            Err(tilo_actions::ApiError::ConfirmationRequired)
        ));
        lock.apply(paths.label.set("Tower".to_owned())).unwrap();
        lock.apply_confirmed(paths.minutes.set(0)).unwrap();
        assert_eq!(lock.state().unwrap().minutes, 0);

        let published = lock.published().unwrap();
        let spec = field_edit(&published);
        let api = |edit: &dyn erased_edit::Encode| {
            let argument = format!(
                "{}{}",
                tilo_actions::ARGUMENTS_JSON_PREFIX,
                serde_json::json!({ "edit": edit.encode() })
            );
            spec.contract.confirmation_for_argument(Some(&argument))
        };
        assert_eq!(api(&paths.minutes.set(5)), ConfirmationPolicy::Confirm);
        assert_eq!(
            api(&paths.shown_name.set(String::new())),
            ConfirmationPolicy::Confirm
        );
        assert_eq!(
            api(&paths.label.set(String::new())),
            ConfirmationPolicy::None
        );
        let need = |edit: &dyn erased_edit::Encode| {
            let serde_json::Value::Object(json) = serde_json::json!({ "edit": edit.encode() }) else {
                panic!("an object");
            };
            spec.need_for(Some(&json), None)
        };
        assert!(
            need(&paths.minutes.set(5)).privileged,
            "a weakening edit needs the person's own grant"
        );
        assert!(!need(&paths.shown_name.set(String::new())).privileged);
        assert!(!need(&paths.label.set(String::new())).privileged);
    }

    phase a_field_edit_may_start_at_the_record_s_own_name;
    // A record read that nests its fields under the record's name is written
    // back as `board.title`: a path starting at the record's own name (the
    // last part of its kind, or its label) edits the field after it, through
    // the published field edit and when built from JSON alike.
    {
        let mut board = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        board.apply(set_at(&["board", "title"], "Plan")).unwrap();
        board.apply(set_at(&["Board", "author"], "Ada")).unwrap();
        let state = board.state().unwrap();
        assert_eq!(
            (state.title.as_str(), state.author.as_str()),
            ("Plan", "Ada")
        );

        let built = tilo_resource::build_action::<Board>(
            tilo_resource::FIELD_EDIT,
            &serde_json::Map::from_iter([(
                "edit".to_owned(),
                serde_json::json!({ "path": [{ "field": "board" }, { "field": "title" }], "op": "set", "value": "Sprint" }),
            )]),
            0,
        );
        assert!(built.is_ok(), "{built:?}");
    }

    phase a_field_edit_naming_neither_a_field_nor_the_record_lists_the_fields;
    // A field edit naming no field, nor the record, still says which fields
    // there are; one naming the record alone says to start at a field.
    {
        let mut board = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        let unknown = format!(
            "{:?}",
            board.apply(set_at(&["deck", "title"], "Plan")).unwrap_err()
        );
        assert!(
            unknown.contains("no field `deck`; the fields here are layer, title, author"),
            "{unknown}"
        );
        let below = format!(
            "{:?}",
            board.apply(set_at(&["board", "deck"], "Plan")).unwrap_err()
        );
        assert!(
            below.contains("no field `deck`; the fields here are"),
            "the field after the record's name is the one refused: {below}"
        );
        let bare = format!("{:?}", board.apply(set_at(&["board"], "Plan")).unwrap_err());
        assert!(
            bare.contains("`board` is the resource itself") && bare.contains("title"),
            "{bare}"
        );
        assert_eq!(board.state().unwrap().title, "");
    }

    phase a_guarded_field_under_the_record_s_name_is_sent_again_from_the_root;
    // An action API decides an edit's confirmation from the path as sent: a guarded
    // field under the record's name is not edited, but sent again from the
    // root, where the API sees which field it is.
    {
        let mut lock = Replica::<Lock>::new().in_app("so.tilo.model", "Model");
        for field in ["minutes", "shown_name"] {
            let refused = format!(
                "{:?}",
                lock.apply_confirmed(set_at(&["lock", field], "5"))
                    .unwrap_err()
            );
            assert!(
                refused.contains(&format!("start the path at `{field}`")),
                "{refused}"
            );
        }
        lock.apply(set_at(&["lock", "label"], "Tower")).unwrap();
        let state = lock.state().unwrap();
        assert_eq!((state.minutes, state.label.as_str()), (0, "Tower"));
    }

    phase only_a_change_making_a_field_weaker_asks_and_is_privileged;
    // A field that weakens one way asks, and needs the person's own grant,
    // only for a change that way from what it holds now: in the app and at any
    // API that reads only the published contract.
    {
        use tilo_actions::{ConfirmationPolicy, RiskLevel};
        let paths = Screen::paths();
        assert_eq!(
            paths.lock_minutes.set(1).risk(),
            RiskLevel::Privileged,
            "without the value now, any change counts as weakening"
        );

        let mut screen = Replica::<Screen>::new().in_app("so.tilo.model", "Model");
        screen
            .apply(paths.lock_minutes.set(10))
            .expect("from never, a delay is stricter");
        screen
            .apply(paths.lock_minutes.set(5))
            .expect("sooner is stricter");
        screen
            .apply(paths.lock_minutes.set(5))
            .expect("the same is no weaker");
        for weaker in [15, 0] {
            assert!(matches!(
                screen.apply(paths.lock_minutes.set(weaker)),
                Err(tilo_actions::ApiError::ConfirmationRequired)
            ));
        }
        assert!(matches!(
            screen.apply(paths.notifications_when_locked.set(true)),
            Err(tilo_actions::ApiError::ConfirmationRequired)
        ));
        screen.apply(paths.guard.set("strict".to_owned())).unwrap();
        assert!(matches!(
            screen.apply(paths.guard.set("off".to_owned())),
            Err(tilo_actions::ApiError::ConfirmationRequired)
        ));
        screen
            .apply_confirmed(paths.notifications_when_locked.set(true))
            .unwrap();
        screen
            .apply(paths.notifications_when_locked.set(false))
            .expect("hiding them is stricter");
        assert_eq!(screen.state().unwrap().lock_minutes, 5);

        let published = screen.published().unwrap();
        let spec = field_edit(&published);
        let api = |edit: &dyn erased_edit::Encode| {
            let argument = format!(
                "{}{}",
                tilo_actions::ARGUMENTS_JSON_PREFIX,
                serde_json::json!({ "edit": edit.encode() })
            );
            spec.contract.confirmation_for_argument(Some(&argument))
        };
        assert_eq!(api(&paths.lock_minutes.set(1)), ConfirmationPolicy::None);
        assert_eq!(
            api(&paths.lock_minutes.set(30)),
            ConfirmationPolicy::Confirm
        );
        assert_eq!(
            api(&paths.lock_minutes.set(0)),
            ConfirmationPolicy::Confirm
        );
        assert_eq!(
            api(&paths.notifications_when_locked.set(true)),
            ConfirmationPolicy::Confirm
        );
        assert_eq!(
            api(&paths.guard.set("strict".to_owned())),
            ConfirmationPolicy::None
        );
        assert_eq!(
            api(&paths.guard.set("normal".to_owned())),
            ConfirmationPolicy::Confirm
        );

        // An agent acting for the person needs their own grant only to weaken.
        let need = |edit: &dyn erased_edit::Encode| {
            let serde_json::Value::Object(json) = serde_json::json!({ "edit": edit.encode() }) else {
                panic!("an object");
            };
            spec.need_for(Some(&json), None)
        };
        assert!(need(&paths.lock_minutes.set(30)).privileged);
        assert!(need(&paths.lock_minutes.set(0)).privileged);
        assert!(need(&paths.notifications_when_locked.set(true)).privileged);
        assert!(!need(&paths.lock_minutes.set(1)).privileged);
        assert!(!need(&paths.lock_minutes.set(5)).privileged);
        assert!(!need(&paths.notifications_when_locked.set(false)).privileged);
    }

    phase a_path_names_the_object_its_value_is_stored_in;
    {
        let mut board = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        let paths = Board::paths();
        let note = Id::from_raw("n");
        board
            .apply(paths.notes.insert_as(&note, 0, &Note::default()))
            .unwrap();
        let body = paths.notes.item(&note).body.object(board.doc());
        assert!(
            body.is_some(),
            "the body's text object, under the entry's value"
        );
        assert!(
            paths
                .notes
                .item(&Id::from_raw("gone"))
                .body
                .object(board.doc())
                .is_none()
        );
        assert!(
            paths.cards.object(board.doc()).is_none(),
            "a scalar has no object"
        );
    }

    phase an_agent_builds_a_field_edit_from_the_published_descriptor_alone;
    {
        let mut board = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        board
            .apply(
                Board::paths()
                    .notes
                    .insert_as(&Id::from_raw("n1"), 0, &Note::default()),
            )
            .unwrap();
        let published = board.published().unwrap();
        let spec = field_edit(&published);
        let schema = spec.params()[0].schema.as_deref().unwrap().clone();

        // Built from the descriptor: the example's path with the item's id in
        // place of its placeholder, an op it lists, a value of its type.
        let example = example_at(&schema, "notes.*.body");
        let mut path = example["path"].clone();
        for step in path.as_array_mut().unwrap() {
            if step.get("item").is_some() {
                *step = serde_json::json!({ "item": "n1" });
            }
        }
        let edit = serde_json::json!({ "path": path, "op": "set", "value": ["line"] });
        tilo_actions::validate_json_schema(&edit, &schema).expect("the edit fits the schema");
        let edit: tilo_resource::Edit<Board> = serde_json::from_value(edit).unwrap();
        board.apply(edit).unwrap();
        assert_eq!(
            board
                .state()
                .unwrap()
                .notes
                .get(&Id::from_raw("n1"))
                .unwrap()
                .body,
            ["line"]
        );
    }

    phase a_field_edit_refuses_null_for_a_field_that_is_not_optional;
    // A field edit sets a value of the field's type: `null` only where the
    // field is optional, never for a number, a flag or a text.
    {
        use tilo_resource::{Edit, EditOp, Segment};
        let mut board = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        for field in ["cards", "title", "layer"] {
            let edit = Edit::<Board>::new(
                vec![Segment::Field(field.into())],
                EditOp::Set {
                    value: serde_json::Value::Null,
                },
            );
            assert!(board.apply(edit).is_err(), "`{field}` refuses null");
        }
        board
            .apply(Edit::<Board>::new(
                vec![Segment::Field("cards".into())],
                EditOp::Set {
                    value: serde_json::json!(3),
                },
            ))
            .unwrap();
        assert_eq!(board.state().unwrap().cards, 3);
    }
}

/// A lock whose delay can weaken security and whose shown name can expose
/// its owner.
#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Lock {
    #[model(trust = "weakening")]
    pub minutes: u32,
    #[model(trust = "sensitive")]
    pub shown_name: String,
    pub label: String,
}

#[resource(kind = "test.lock", catalogue = "tests/locales")]
impl Lock {}

/// The field edit setting `value` at the fields `path`, as a caller sends
/// it.
fn set_at<R: tilo_resource::Resource>(path: &[&str], value: &str) -> Invoke<R> {
    let path = path
        .iter()
        .map(|key| tilo_resource::Segment::Field((*key).to_owned()))
        .collect();
    let op = tilo_resource::EditOp::Set {
        value: serde_json::json!(value),
    };
    Invoke::edit(&tilo_resource::Edit::new(path, op)).unwrap()
}

/// A screen whose lock delay weakens when longer (`0` is never) and whose
/// notifications on the lock screen weaken it when shown.
#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Screen {
    #[model(weaker = "higher", weakest = 0)]
    pub lock_minutes: u32,
    #[model(weaker = true)]
    pub notifications_when_locked: bool,
    #[model(weaker = ["strict", "normal", "off"])]
    pub guard: String,
}

#[resource(kind = "test.screen", catalogue = "tests/locales")]
impl Screen {}

/// The JSON form of an edit, whatever record it is of.
mod erased_edit {
    pub trait Encode {
        fn encode(&self) -> serde_json::Value;
    }
    impl<R> Encode for tilo_resource::Edit<R> {
        fn encode(&self) -> serde_json::Value {
            serde_json::to_value(self).unwrap()
        }
    }
}

tilo_test_env::scenario! {
    fn places_and_items_offer_the_edits_and_verbs_of_their_own;

    phase a_derived_place_offers_a_bound_edit;
    {
        let place = Derived::<Board>::new("Sprint board").with_edit(
            "name-sprint",
            "Name it Sprint",
            Board::paths().title.set("Sprint".into()),
        );
        let published = place.publish();
        let spec = published
            .actions
            .iter()
            .find(|spec| spec.id == "name-sprint")
            .expect("the edit is offered on the place");
        assert!(spec.params().is_empty(), "its value is bound");
    }

    phase a_derived_place_offers_an_edit_that_asks_for_its_value;
    {
        let place = Derived::<Board>::new("Sprint board").with_edit_asking(
            "rename",
            "Rename the board",
            "title",
            "The new name",
            |title: String| Board::paths().title.replace(title),
        );
        let published = place.publish();
        let spec = published
            .actions
            .iter()
            .find(|spec| spec.id == "rename")
            .expect("the edit is offered on the place");
        let params: Vec<(String, tilo_actions::ParamType)> = spec
            .params()
            .iter()
            .map(|param| (param.name.to_string(), param.ty))
            .collect();
        assert_eq!(
            params,
            [("title".to_owned(), tilo_actions::ParamType::Text)]
        );

        let encoded = spec
            .build_json(
                &serde_json::json!({ "title": "Sprint 12" })
                    .as_object()
                    .unwrap()
                    .clone(),
            )
            .unwrap();
        let action: <Board as tilo_resource::Resource>::Action =
            serde_json::from_slice(&encoded.payload).unwrap();
        let mut board = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        board.apply_action(&action).unwrap();
        assert_eq!(board.state().unwrap().title, "Sprint 12");
    }

    phase an_item_resource_offers_the_field_edits_of_its_item;
    {
        let mut board = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        board
            .apply(Board::paths().notes.insert_as(
                &Id::from_raw("n1"),
                0,
                &Note {
                    title: "Plan".into(),
                    ..Note::default()
                },
            ))
            .unwrap();
        let published = board.published().unwrap();
        let item = published
            .children
            .iter()
            .find(|child| child.id.as_str().ends_with("/notes/n1"))
            .expect("the note is an item resource");
        let spec = item
            .actions
            .iter()
            .find(|spec| spec.id == tilo_resource::FIELD_EDIT)
            .expect("its fields are edited from it");
        let schema = spec.params()[0].schema.as_deref().unwrap().clone();
        let example = example_at(&schema, "body");
        let edit =
            serde_json::json!({ "path": example["path"], "op": "set", "value": ["from the item"] });
        tilo_actions::validate_json_schema(&edit, &schema).expect("the edit fits the item's schema");
    }

    phase an_answering_verb_published_on_its_item_still_answers;
    {
        let mut board = Replica::<Board>::new().in_app("so.tilo.model", "Model");
        board
            .apply(Board::paths().notes.insert_as(
                &Id::from_raw("n1"),
                0,
                &Note {
                    title: "Plan".into(),
                    ..Note::default()
                },
            ))
            .unwrap();
        let published = board.published().unwrap();
        let on_root = published
            .actions
            .iter()
            .find(|spec| spec.id == "clear-note")
            .unwrap();
        assert!(matches!(
            on_root.contract.result,
            tilo_actions::ResultSpec::Json { .. }
        ));
        let item = published
            .children
            .iter()
            .find(|child| child.id.as_str().ends_with("/notes/n1"))
            .unwrap();
        let on_item = item
            .actions
            .iter()
            .find(|spec| spec.id == "clear-note")
            .expect("offered on its item");
        assert_eq!(
            on_item.contract.result, on_root.contract.result,
            "the item's copy declares the same answer"
        );
    }

    phase a_place_offers_a_verb_with_nothing_bound;
    {
        let place = Derived::<Board>::new("Board").with(Board::RETITLE.unbound());
        let published = place.publish();
        let spec = published
            .actions
            .iter()
            .find(|spec| spec.id == "retitle")
            .expect("offered on the place");
        let params: Vec<String> = spec.params().iter().map(|p| p.name.to_string()).collect();
        assert_eq!(params, ["title", "suffix"]);
    }

    phase items_of_a_nested_collection_are_resources_of_their_own;
    {
        let mut deck = Replica::<Deck>::new().in_app("so.tilo.model", "Model");
        let mut slide = Slide {
            title: "Intro".into(),
            ..Slide::default()
        };
        slide.elements.push(
            Id::from_raw("e1"),
            Element {
                name: "Logo".into(),
                x: 1.0,
            },
        );
        deck.apply(
            Deck::paths()
                .slides
                .insert_as(&Id::from_raw("s1"), 0, &slide),
        )
        .unwrap();
        let published = deck.published().unwrap();
        let element = published
            .children
            .iter()
            .find(|child| child.id.as_str() == "test.deck/slides/s1/elements/e1")
            .expect("the element is a resource of its own");
        assert_eq!(element.label, "Logo");
        let edit = element
            .actions
            .iter()
            .find(|spec| spec.id == tilo_resource::FIELD_EDIT)
            .expect("its fields are edited from it");
        let encoded = edit
            .build_json(
                serde_json::json!({ "edit": { "path": [{"field": "x"}], "op": "set", "value": 4.5 } })
                    .as_object()
                    .unwrap(),
            )
            .unwrap();
        let action: <Deck as tilo_resource::Resource>::Action =
            serde_json::from_slice(&encoded.payload).unwrap();
        deck.apply_action(&action).unwrap();

        // The verbs on elements are offered on each, both ids bound.
        let published = deck.published().unwrap();
        let element = published
            .children
            .iter()
            .find(|child| child.id.as_str() == "test.deck/slides/s1/elements/e1")
            .unwrap();
        let nudge = element
            .actions
            .iter()
            .find(|spec| spec.id == "nudge")
            .expect("the element's verb");
        let params: Vec<String> = nudge.params().iter().map(|p| p.name.to_string()).collect();
        assert_eq!(params, ["by"]);
        let encoded = nudge
            .build_json(serde_json::json!({ "by": 0.5 }).as_object().unwrap())
            .unwrap();
        let action: <Deck as tilo_resource::Resource>::Action =
            serde_json::from_slice(&encoded.payload).unwrap();
        deck.apply_action(&action).unwrap();
        let state = deck.state().unwrap();
        let x = state
            .slides
            .get(&Id::from_raw("s1"))
            .unwrap()
            .elements
            .get(&Id::from_raw("e1"))
            .unwrap()
            .x;
        assert_eq!(x, 5.0);
    }

    phase a_nested_item_verb_is_known_offered_without_building_children;
    {
        use tilo_resource::Resource as _;
        let built = |deck: &Deck| -> Vec<&'static str> {
            let children = Deck::children(deck);
            let mut ids = Vec::new();
            for decl in Deck::declarations() {
                if tilo_resource::items::offered_bound(&children, &decl) {
                    ids.push(decl.id);
                }
            }
            ids
        };
        let mut deck = Deck::default();
        assert_eq!(Deck::children_offer_bound(&deck), built(&deck), "no slides");
        deck.slides.push(Id::from_raw("s1"), Slide::default());
        assert_eq!(
            Deck::children_offer_bound(&deck),
            built(&deck),
            "a slide, no elements"
        );
        assert!(Deck::children_offer_bound(&deck).is_empty());
        if let Some(slide) = deck.slides.get_mut(&Id::from_raw("s1")) {
            slide.elements.push(Id::from_raw("e1"), Element::default());
        }
        assert_eq!(
            Deck::children_offer_bound(&deck),
            built(&deck),
            "an element"
        );
        assert_eq!(Deck::children_offer_bound(&deck), ["nudge"]);
    }
}

/// An agent's edit at `path` (`notes.*.body`) built from the descriptor's
/// example of its shape (one example per shape of path: a field, an item's
/// field, …), with the path naming the fields the caller wrote.
fn example_at(schema: &serde_json::Value, path: &str) -> serde_json::Value {
    let segments: Vec<&str> = path.split('.').collect();
    let mut example = schema["examples"]
        .as_array()
        .unwrap()
        .iter()
        .find(|example| {
            let steps = example["path"].as_array().unwrap();
            steps.len() == segments.len()
                && steps
                    .iter()
                    .zip(&segments)
                    .all(|(step, segment)| (*segment == "*") == step.get("item").is_some())
        })
        .expect("an example edit of the path's shape")
        .clone();
    for (step, segment) in example
        .get_mut("path")
        .and_then(serde_json::Value::as_array_mut)
        .unwrap()
        .iter_mut()
        .zip(&segments)
    {
        if *segment != "*" {
            *step = serde_json::json!({ "field": segment });
        }
    }
    example
}

/// What to look at.
#[derive(
    Clone,
    Debug,
    Default,
    PartialEq,
    Eq,
    serde::Serialize,
    serde::Deserialize,
    tilo_resource::JsonSchema,
)]
pub struct LookAt {
    /// The region, as x, y, width, height.
    pub region: Vec<u32>,
    /// Whether to draw the grid.
    pub grid: Option<bool>,
}

#[derive(Clone, Debug, PartialEq, Eq, tilo_resource::Effect)]
#[effect(operation = "test.board.view", catalogue = "tests/locales")]
pub enum BoardView {
    /// Look at part of the board.
    #[effect(view)]
    Look {
        #[param(flatten)]
        look: LookAt,
    },
}

#[derive(Model, Default, Debug, Clone, PartialEq)]
#[model(check = Pair::matched)]
pub struct Pair {
    pub left: u32,
    pub right: u32,
}

impl Pair {
    fn matched(&self) -> Result<(), tilo_resource::Refusal> {
        if self.left == self.right {
            Ok(())
        } else {
            Err(tilo_resource::Refusal::new("the two sides differ"))
        }
    }
}

#[resource(kind = "test.pair", catalogue = "tests/locales")]
impl Pair {
    /// Move the left side.
    #[action]
    pub fn move_left(&mut self, to: u32) {
        self.left = to;
    }
}

#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Element {
    #[model(label)]
    pub name: String,
    pub x: f64,
}

#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Slide {
    #[model(label)]
    pub title: String,
    pub elements: Collection<Element>,
}

#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Deck {
    pub slides: Collection<Slide>,
}

#[resource(kind = "test.deck", catalogue = "tests/locales")]
impl Deck {
    /// Nudge an element along.
    #[action(item = slides.elements)]
    pub fn nudge(&mut self, slides: &Id, elements: &Id, by: f64) -> Result<(), &'static str> {
        let element = self
            .slides
            .get_mut(slides)
            .and_then(|slide| slide.elements.get_mut(elements))
            .ok_or("no such element")?;
        element.x += by;
        Ok(())
    }
}

/// A record whose fields declare what they may hold.
#[derive(Model, Debug, Clone, PartialEq)]
#[model(defaults)]
pub struct Comfort {
    /// How large text is drawn.
    #[model(range = 0.5..=3.0)]
    pub text_scale: f64,
    /// When the dark look starts.
    #[model(choices = ["sun", "custom"])]
    pub schedule: String,
    /// The cursor's size in pixels, when it is not the theme's.
    #[model(range = 24..=64)]
    pub cursor: Option<u32>,
    pub note: String,
}

impl Default for Comfort {
    fn default() -> Self {
        Self {
            text_scale: 1.0,
            schedule: "sun".into(),
            cursor: None,
            note: String::new(),
        }
    }
}

#[resource(kind = "test.comfort", catalogue = "tests/locales")]
impl Comfort {
    /// Draw text at `scale`.
    #[action]
    pub fn scale_text(&mut self, scale: f64) {
        self.text_scale = scale;
    }
}

fn comfort_schema(key: &str) -> serde_json::Value {
    let fields = match Comfort::SHAPE {
        tilo_resource::Shape::Record(fields) => fields,
        _ => &[],
    };
    let field = fields.iter().find(|field| field.key == key).unwrap();
    (field.schema)()
}

/// A swatch: a colour, the outline it fills and the glyph it shows, each
/// one value two people setting at once never mix.
#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Swatch {
    #[model(atom)]
    pub colour: Option<String>,
    #[model(atom)]
    pub outline: Vec<[f64; 2]>,
    pub glyph: Option<Glyph>,
}

#[derive(Model, Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum Glyph {
    Path {
        #[model(atom)]
        d: String,
        #[model(atom)]
        colour: Option<String>,
        #[model(atom)]
        points: Vec<[f64; 2]>,
        width: f64,
    },
}

#[resource(kind = "test.swatch", catalogue = "tests/locales")]
impl Swatch {
    /// Clear the colour.
    #[action]
    pub fn clear(&mut self) {
        self.colour = None;
    }
}

fn path(d: &str, colour: &str, points: &[[f64; 2]], width: f64) -> Glyph {
    Glyph::Path {
        d: d.into(),
        colour: Some(colour.into()),
        points: points.to_vec(),
        width,
    }
}

/// Two replicas set `ours` and `theirs` at once from `first`; both read the
/// merged state.
fn merged_swatch(first: Invoke<Swatch>, ours: Invoke<Swatch>, theirs: Invoke<Swatch>) -> Swatch {
    let mut a = Replica::<Swatch>::new().in_app("so.tilo.model", "Model");
    a.apply(first).unwrap();
    let mut b = a.fork();
    a.apply(ours).unwrap();
    b.apply(theirs).unwrap();
    a.sync_with(&mut b).unwrap();
    let merged = a.state().unwrap();
    assert_eq!(merged, b.state().unwrap());
    merged
}

/// A frame and how it looks: the look stored field by field.
#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Frame {
    pub title: String,
    pub look: Look,
}

/// How a frame looks.
#[derive(Model, Default, Debug, Clone, PartialEq)]
pub struct Look {
    #[model(atom)]
    pub colour: String,
    pub width: f64,
    /// Typed into, so edited by character.
    pub caption: String,
}

#[resource(kind = "test.frame", catalogue = "tests/locales")]
impl Frame {
    /// Clear the title.
    #[action]
    pub fn untitle(&mut self) {
        self.title.clear();
    }
}