tilo-resource 0.5.1

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
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
//! Typed paths into a model and the field edits made at them.
//!
//! `#[derive(Model)]` gives every type a path struct: `Snippets::paths()`
//! has one field per model field, a [`Collection`](crate::Collection) path
//! offers [`item`](Path::item), a [`Grid`](crate::Grid) path
//! [`cell`](Path::cell), a map path [`key`](Path::key). A [`Path`] is plain
//! data — the stored field names and item ids from the record's root — so it
//! can be stored, compared and sent.
//!
//! Each path offers the edits its type supports. An edit is an [`Edit`]: a
//! path and an [`EditOp`]. It is one of the resource's actions, so it
//! replays, syncs, undoes and is named in history like a verb, and it
//! applies at its path without reading the rest of the record.

use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;

use serde::{Deserialize, Serialize};

use crate::collection::Id;
use crate::model::Model;
pub use crate::upsert::At;

/// One step of a [`Path`].
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Segment {
    /// A field of a record, by the key it is stored under.
    Field(String),
    /// An item of a [`Collection`](crate::Collection) or an entry of an
    /// [`Outbox`](crate::Outbox), by its id.
    Item(Id),
    /// An entry of a map.
    Key(String),
    /// A cell of a [`Grid`](crate::Grid), by its row and column ids.
    Cell { row: Id, column: Id },
}

impl std::fmt::Display for Segment {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Field(key) | Self::Key(key) => f.write_str(key),
            Self::Item(id) => write!(f, "{id}"),
            Self::Cell { row, column } => write!(f, "{row}:{column}"),
        }
    }
}

/// The location of a `T` inside the record `R`. See the module docs.
pub struct Path<R, T> {
    segments: Vec<Segment>,
    marker: PhantomData<fn() -> (R, T)>,
}

#[allow(
    clippy::mismatching_type_param_order,
    reason = "the root is the record seen as a value of itself"
)]
impl<R> Path<R, R> {
    /// The record itself.
    #[must_use]
    pub const fn root() -> Self {
        Self {
            segments: Vec::new(),
            marker: PhantomData,
        }
    }
}

impl<R: Model, T> Path<R, T> {
    /// The object the value at this path is stored in — a record's map, a
    /// list, a text — resolved through each container's own layout, for an
    /// editor that binds to the object itself (a rich-text field inside a
    /// collection item); `None` when absent or stored as a scalar.
    #[must_use]
    pub fn object(&self, doc: &crate::Doc) -> Option<automerge::ObjId> {
        object_at(R::SHAPE, &self.segments, doc)
    }
}

/// [`Path::object`] of the path `segments` into a record stored as `shape`.
fn object_at(
    shape: crate::Shape,
    segments: &[Segment],
    doc: &crate::Doc,
) -> Option<automerge::ObjId> {
    use crate::Shape;
    use automerge::ReadDoc;
    fn child(doc: &crate::Doc, obj: &automerge::ObjId, key: &str) -> Option<automerge::ObjId> {
        match doc.get(obj, key).ok()?? {
            (automerge::Value::Object(_), id) => Some(id),
            (automerge::Value::Scalar(_), _) => None,
        }
    }
    let mut obj = automerge::ROOT;
    let mut shape = shape;
    for segment in segments {
        match (shape, segment) {
            (Shape::Record(fields), Segment::Field(key)) => {
                shape = fields
                    .iter()
                    .find(|field| field.key == key)
                    .map_or(Shape::Value, |field| field.shape);
                obj = child(doc, &obj, key)?;
            }
            (Shape::Collection(item), Segment::Item(id)) => {
                let entry = child(doc, &obj, id.as_str())?;
                obj = child(doc, &entry, crate::collection::VALUE)?;
                shape = *item;
            }
            (Shape::Keyed(item), Segment::Item(id)) => {
                obj = child(doc, &obj, id.as_str())?;
                shape = *item;
            }
            (_, Segment::Field(key) | Segment::Key(key)) => {
                obj = child(doc, &obj, key)?;
                shape = Shape::Value;
            }
            (_, Segment::Item(id)) => {
                obj = child(doc, &obj, id.as_str())?;
                shape = Shape::Value;
            }
            (_, Segment::Cell { .. }) => return None,
        }
    }
    Some(obj)
}

impl<R, T> Path<R, T> {
    /// A path from stored segments. A path read back from storage or the
    /// wire is checked when an edit at it applies.
    #[must_use]
    pub fn from_segments(segments: Vec<Segment>) -> Self {
        Self {
            segments,
            marker: PhantomData,
        }
    }

    pub fn segments(&self) -> &[Segment] {
        &self.segments
    }

    #[must_use]
    pub fn into_segments(self) -> Vec<Segment> {
        self.segments
    }

    /// One step further down, to a value of type `U`.
    #[doc(hidden)]
    #[must_use]
    #[inline]
    pub fn child<U>(&self, segment: Segment) -> Path<R, U> {
        Path::from_segments(extended(&self.segments, segment))
    }

    /// The same location seen as another type: the inner value of a `Box`,
    /// the present value of an `Option`.
    #[doc(hidden)]
    #[must_use]
    pub fn cast<U>(self) -> Path<R, U> {
        Path::from_segments(self.segments)
    }

    /// This path, rooted at an item, seen from the record containing it: a
    /// row's `favorite` as `Snippets › snippets › <id> › favorite`.
    #[must_use]
    pub fn under<P>(&self, prefix: &Path<P, R>) -> Path<P, T> {
        let mut segments = prefix.segments.clone();
        segments.extend(self.segments.iter().cloned());
        Path::from_segments(segments)
    }

    /// The value at this path in `root`, if it is there.
    pub fn get<'a>(&self, root: &'a R) -> Option<&'a T>
    where
        R: Model + 'static,
        T: 'static,
    {
        root.get_at(&self.segments)?.downcast_ref()
    }

    /// Whether `self` is `other` or lies inside it.
    pub fn starts_with<U>(&self, other: &Path<R, U>) -> bool {
        self.segments.starts_with(&other.segments)
    }

    /// The field edits that turn `before`, the value at this path, into
    /// `after`: what a surface that edited a local copy submits, field by
    /// field and item by item ([`Model::diff`]).
    #[must_use]
    pub fn edits(&self, before: &T, after: &T) -> Vec<Edit<R>>
    where
        T: Model,
    {
        let mut found: Vec<Edit<()>> = Vec::new();
        before.diff(after, &self.segments, &mut found);
        retyped_all(found)
    }

    /// The edit `op` at this path.
    #[must_use]
    #[inline]
    pub fn edit(&self, op: EditOp) -> Edit<R> {
        Edit {
            path: self.segments.clone(),
            op,
            marker: PhantomData,
        }
    }
}

/// [`Edit::risk`] of the edit `op` at `path` in a record stored as `shape`:
/// the field's [`Trust`](crate::Trust), or a removal's. `now` holds the
/// values, as JSON text by dotted path, of the fields that weaken one way:
/// a change of one the other way, or to a value as strong, is ordinary;
/// without its value now, any change of it counts as weakening.
pub(crate) fn edit_risk(
    shape: crate::Shape,
    path: &[Segment],
    op: &EditOp,
    now: Option<&[(String, String)]>,
) -> tilo_actions::RiskLevel {
    use tilo_action_policy::edits::{EditStep, field_edit_asks};
    let mut steps: Vec<EditStep<'_>> = Vec::with_capacity(path.len());
    for segment in path {
        steps.push(match segment {
            Segment::Field(key) => EditStep::Field(key),
            Segment::Item(_) | Segment::Key(_) | Segment::Cell { .. } => EditStep::Item,
        });
    }
    match shape.trust_at(path) {
        crate::Trust::Ordinary => {}
        crate::Trust::Weakens(weaker) => {
            let at = tilo_action_policy::edits::dotted(&steps);
            let weakens = match op {
                EditOp::Set { value } => weaker.weakens(
                    now.and_then(|now| now.iter().find(|(path, _)| *path == at))
                        .map(|(_, now)| now.as_str()),
                    &value.to_string(),
                ),
                _ => true,
            };
            if weakens {
                return tilo_actions::RiskLevel::Privileged;
            }
        }
        trust => return trust.risk(),
    }
    let quiet = shape.quiet_removals();
    let quiet: Vec<&str> = quiet.iter().map(String::as_str).collect();
    if field_edit_asks(op.name(), &steps, &quiet, &[]) {
        tilo_actions::RiskLevel::Destructive
    } else {
        tilo_actions::RiskLevel::Low
    }
}

/// `segments` and one step more.
fn extended(segments: &[Segment], segment: Segment) -> Vec<Segment> {
    let mut extended = Vec::with_capacity(segments.len().saturating_add(1));
    extended.extend_from_slice(segments);
    extended.push(segment);
    extended
}

impl<R, T> Clone for Path<R, T> {
    fn clone(&self) -> Self {
        Self::from_segments(self.segments.clone())
    }
}

impl<R, T> std::fmt::Debug for Path<R, T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt_segments(&self.segments, f)
    }
}

fn fmt_segments(segments: &[Segment], f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.write_str("Path(")?;
    for (index, segment) in segments.iter().enumerate() {
        if index > 0 {
            f.write_str(" › ")?;
        }
        write!(f, "{segment}")?;
    }
    f.write_str(")")
}

impl<R, T> PartialEq for Path<R, T> {
    fn eq(&self, other: &Self) -> bool {
        self.segments == other.segments
    }
}

impl<R, T> Eq for Path<R, T> {}

impl<R, T> PartialOrd for Path<R, T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<R, T> Ord for Path<R, T> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.segments.cmp(&other.segments)
    }
}

impl<R, T> Hash for Path<R, T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.segments.hash(state);
    }
}

impl<R, T> Serialize for Path<R, T> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.segments.serialize(serializer)
    }
}

impl<'de, R, T> Deserialize<'de> for Path<R, T> {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = serde_json::Value::deserialize(deserializer)?;
        match segments_from_json(value) {
            Ok(segments) => Ok(Self::from_segments(segments)),
            Err(error) => Err(serde::de::Error::custom(error)),
        }
    }
}

// Paths and edits are decoded in every crate naming a record type, and serde
// instantiates a generic decoder per calling crate. Going through JSON values
// keeps one decoder, compiled here.
#[inline(never)]
fn segments_from_json(value: serde_json::Value) -> Result<Vec<Segment>, serde_json::Error> {
    Vec::<Segment>::deserialize(value)
}

#[inline(never)]
fn edit_from_json(value: serde_json::Value) -> Result<(Vec<Segment>, EditOp), serde_json::Error> {
    use serde::de::Error as _;
    let serde_json::Value::Object(mut map) = value else {
        return Err(serde_json::Error::custom("an edit is a JSON object"));
    };
    let path = map
        .remove("path")
        .ok_or_else(|| serde_json::Error::missing_field("path"))?;
    let path = segments_from_json(path)?;
    let op = op_from_json(serde_json::Value::Object(map))?;
    Ok((path, op))
}

/// Values a path can [`set`](Path::set) whole: scalars, enums, text, short
/// lists, options of them and nested records. Containers whose merge is per
/// element (`Counter`, `Set`, `Collection`, `Grid`, `Outbox`) are edited per
/// element instead.
pub trait Settable: Model {}

impl<R, T: Settable> Path<R, T> {
    /// Replace the value.
    #[must_use]
    #[allow(
        clippy::needless_pass_by_value,
        reason = "a value is set as written: `set(true)`, `set(Language::Rust)`"
    )]
    pub fn set(&self, value: T) -> Edit<R> {
        self.edit(EditOp::Set {
            value: crate::shape::without_absent::<T>(value.to_json()),
        })
    }
}

/// A type with its own vocabulary of edits beside the generic ones: rich
/// text's marks and blocks. Its paths offer [`Path::perform`]; its `Model`
/// impl calls [`operations_model!`](crate::operations_model) so records
/// holding it route those edits' gestures, landing places and schema to it.
pub trait Operations: Model {
    /// One edit of the type, in its own terms.
    type Op: Serialize + serde::de::DeserializeOwned + crate::JsonSchema;

    /// Whether `next`, straight after `previous` by the same actor, is the
    /// same gesture (typing on in one word): one undo step.
    fn coalesces(previous: &Self::Op, next: &Self::Op) -> bool {
        let _ = (previous, next);
        false
    }

    /// Whether a gesture may go on after `op`.
    fn continuable(op: &Self::Op) -> bool {
        let _ = op;
        true
    }

    /// What `op` did, as a history entry records it: the kind of edit and
    /// its plain facts by name (`{mark: "strong", words: 3}`), which the
    /// reader's message receives.
    fn describe(op: &Self::Op) -> OpDescription {
        let _ = op;
        OpDescription::default()
    }

    /// Where the actor of `op` is after it applied (the caret after typed
    /// text), read from the value it applied to.
    fn lands(&self, op: &Self::Op) -> Option<crate::Place> {
        let _ = op;
        None
    }
}

/// [`Model::op_coalesces`] of an [`Operations`] type.
#[doc(hidden)]
pub fn op_coalesces<T: Operations>(
    path: &[Segment],
    previous: &serde_json::Value,
    next: &serde_json::Value,
) -> Option<bool> {
    if !path.is_empty() {
        return None;
    }
    let previous = serde_json::from_value(previous.clone()).ok()?;
    let next = serde_json::from_value(next.clone()).ok()?;
    Some(T::coalesces(&previous, &next))
}

/// What an edit in a type's own vocabulary did ([`Operations::describe`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OpDescription {
    pub op: tilo_actions::EditOp,
    pub args: std::collections::BTreeMap<String, tilo_actions::Scalar>,
}

impl Default for OpDescription {
    fn default() -> Self {
        Self {
            op: tilo_actions::EditOp::Mark,
            args: std::collections::BTreeMap::new(),
        }
    }
}

/// [`Model::op_describe`] of an [`Operations`] type.
#[doc(hidden)]
pub fn op_describe<T: Operations>(
    path: &[Segment],
    op: &serde_json::Value,
) -> Option<OpDescription> {
    if !path.is_empty() {
        return None;
    }
    Some(T::describe(&serde_json::from_value(op.clone()).ok()?))
}

/// [`Model::op_continuable`] of an [`Operations`] type.
#[doc(hidden)]
pub fn op_continuable<T: Operations>(path: &[Segment], op: &serde_json::Value) -> Option<bool> {
    if !path.is_empty() {
        return None;
    }
    Some(T::continuable(&serde_json::from_value(op.clone()).ok()?))
}

/// [`Model::op_lands`] of an [`Operations`] type.
#[doc(hidden)]
pub fn op_lands<T: Operations>(
    value: &T,
    path: &[Segment],
    op: &serde_json::Value,
) -> Option<crate::Place> {
    if !path.is_empty() {
        return None;
    }
    value.lands(&serde_json::from_value(op.clone()).ok()?)
}

/// Implements the `Model` items that route a record's edits of an
/// [`Operations`] type to it; call it inside the type's `impl Model`.
#[macro_export]
macro_rules! operations_model {
    () => {
        const OPS: bool = true;
        fn op_coalesces(
            path: &[$crate::Segment],
            previous: &$crate::__private::serde_json::Value,
            next: &$crate::__private::serde_json::Value,
        ) -> ::core::option::Option<bool> {
            $crate::path::op_coalesces::<Self>(path, previous, next)
        }
        fn op_continuable(
            path: &[$crate::Segment],
            op: &$crate::__private::serde_json::Value,
        ) -> ::core::option::Option<bool> {
            $crate::path::op_continuable::<Self>(path, op)
        }
        fn op_describe(
            path: &[$crate::Segment],
            op: &$crate::__private::serde_json::Value,
        ) -> ::core::option::Option<$crate::path::OpDescription> {
            $crate::path::op_describe::<Self>(path, op)
        }
        fn op_lands(
            &self,
            path: &[$crate::Segment],
            op: &$crate::__private::serde_json::Value,
        ) -> ::core::option::Option<$crate::Place> {
            $crate::path::op_lands::<Self>(self, path, op)
        }
        fn op_schemas(
            prefix: &str,
            out: &mut ::std::vec::Vec<(
                ::std::string::String,
                $crate::__private::serde_json::Value,
            )>,
        ) {
            out.push((
                ::std::string::String::from(prefix.trim_end_matches('.')),
                <<Self as $crate::Operations>::Op as $crate::JsonSchema>::json_schema(),
            ));
        }
    };
}

impl<R, T: Operations> Path<R, T> {
    /// The edit `op` of the value at this path, in the type's own vocabulary.
    ///
    /// # Errors
    /// Returns the serialization error of `op`.
    pub fn perform(&self, op: &T::Op) -> Result<Edit<R>, serde_json::Error> {
        Ok(self.edit(EditOp::Rich {
            rich: crate::__private::json_via_bytes(op)?,
        }))
    }
}

impl<R, T: Model> Path<R, Option<T>> {
    /// The value when present; edits at it refuse while it is absent.
    #[must_use]
    pub fn some(&self) -> T::Paths<R> {
        T::paths_at(self.clone().cast())
    }
}

impl<R> Path<R, String> {
    /// Replace `delete` characters at `at` with `insert`.
    #[must_use]
    pub fn splice(&self, at: usize, delete: usize, insert: impl Into<String>) -> Edit<R> {
        self.edit(EditOp::Splice {
            at,
            delete,
            insert: insert.into(),
        })
    }

    /// Replace the whole text, written as the smallest splice that turns the
    /// stored text into it.
    #[must_use]
    pub fn replace(&self, text: impl Into<String>) -> Edit<R> {
        self.edit(EditOp::Replace { text: text.into() })
    }
}

impl<R> Path<R, crate::Counter> {
    /// Add `by` (negative to subtract). Concurrent additions add up.
    #[must_use]
    pub fn add(&self, by: i64) -> Edit<R> {
        self.edit(EditOp::Add { by })
    }
}

impl<R, T: Model> Path<R, crate::Set<T>> {
    /// Add an element.
    #[must_use]
    pub fn insert(&self, value: &T) -> Edit<R> {
        self.edit(EditOp::Insert {
            value: value.to_json(),
        })
    }

    /// Remove an element.
    #[must_use]
    pub fn remove(&self, value: &T) -> Edit<R> {
        self.edit(EditOp::Remove {
            value: value.to_json(),
        })
    }
}

impl<R, T: Model> Path<R, crate::Collection<T>> {
    /// The item `id`, its own paths rooted here.
    #[must_use]
    pub fn item(&self, id: &Id) -> T::Paths<R> {
        T::paths_at(self.child(Segment::Item(id.clone())))
    }

    /// The path of the item `id` itself.
    #[must_use]
    pub fn item_path(&self, id: &Id) -> Path<R, T> {
        self.child(Segment::Item(id.clone()))
    }

    /// Insert `value` at `at` (clamped to the end) under a fresh id minted
    /// when the edit applies.
    #[must_use]
    pub fn insert(&self, at: usize, value: &T) -> Edit<R> {
        self.edit(EditOp::InsertItem {
            id: None,
            at: At::Index(at),
            value: crate::shape::without_absent::<T>(value.to_json()),
        })
    }

    /// Insert `value` at `at` (clamped to the end) under `id`.
    #[must_use]
    pub fn insert_as(&self, id: &Id, at: usize, value: &T) -> Edit<R> {
        self.edit(EditOp::InsertItem {
            id: Some(id.clone()),
            at: At::Index(at),
            value: crate::shape::without_absent::<T>(value.to_json()),
        })
    }

    /// Remove the item `id`.
    #[must_use]
    pub fn remove(&self, id: &Id) -> Edit<R> {
        self.edit(EditOp::RemoveItem { id: id.clone() })
    }

    /// Move the item `id` to `at` (clamped to the end).
    #[must_use]
    pub fn move_to(&self, id: &Id, at: usize) -> Edit<R> {
        self.edit(EditOp::MoveTo {
            id: id.clone(),
            at: At::Index(at),
        })
    }

    /// Update the one item whose fields hold `matching` with the fields of
    /// `value`, else append `value` with them ([`EditOp::UpsertItem`]).
    #[must_use]
    pub fn upsert_by(
        &self,
        matching: serde_json::Map<String, serde_json::Value>,
        value: serde_json::Value,
    ) -> Edit<R> {
        self.edit(EditOp::UpsertItem {
            matching,
            value,
            id: None,
        })
    }
}

impl<R, T: Model> Path<R, std::collections::BTreeMap<String, T>> {
    /// The entry `key`, its own paths rooted here.
    #[must_use]
    pub fn key(&self, key: impl Into<String>) -> T::Paths<R> {
        T::paths_at(self.child(Segment::Key(key.into())))
    }

    /// Remove the entry `key`.
    #[must_use]
    pub fn remove(&self, key: impl Into<String>) -> Edit<R> {
        self.edit(EditOp::RemoveKey { key: key.into() })
    }
}

impl<R, T: Model> Path<R, crate::Grid<T>> {
    /// The cell at `row`, `column`, its own paths rooted here.
    #[must_use]
    pub fn cell(&self, row: &Id, column: &Id) -> T::Paths<R> {
        T::paths_at(self.child(Segment::Cell {
            row: row.clone(),
            column: column.clone(),
        }))
    }

    /// Set or clear one cell.
    #[must_use]
    pub fn set_cell(&self, row: &Id, column: &Id, value: Option<&T>) -> Edit<R> {
        self.edit(EditOp::SetCell {
            row: row.clone(),
            column: column.clone(),
            value: value.map(|value| crate::shape::without_absent::<T>(value.to_json())),
        })
    }

    /// Insert a row at `at` (clamped) under a fresh id minted when the edit
    /// applies.
    #[must_use]
    pub fn insert_row(&self, at: usize) -> Edit<R> {
        self.edit(EditOp::InsertRow { id: None, at })
    }

    /// Insert a column at `at` (clamped) under a fresh id.
    #[must_use]
    pub fn insert_column(&self, at: usize) -> Edit<R> {
        self.edit(EditOp::InsertColumn { id: None, at })
    }

    /// Remove a row and its cells.
    #[must_use]
    pub fn remove_row(&self, row: &Id) -> Edit<R> {
        self.edit(EditOp::RemoveRow { id: row.clone() })
    }

    /// Remove a column and its cells.
    #[must_use]
    pub fn remove_column(&self, column: &Id) -> Edit<R> {
        self.edit(EditOp::RemoveColumn { id: column.clone() })
    }
}

impl<R, T: Model, O: Serialize + serde::de::DeserializeOwned + Default + 'static>
    Path<R, crate::Outbox<T, O>>
{
    /// Record how the owning device settled the entry `id`: content from
    /// outside, nobody's undo step.
    #[must_use]
    pub fn settle(&self, id: &Id, outcome: &crate::Settled<O>) -> Edit<R> {
        self.edit(EditOp::Settle {
            id: id.clone(),
            outcome: Model::to_json(outcome),
        })
    }

    /// Forget the settled entry `id`: housekeeping, nobody's undo step.
    #[must_use]
    pub fn forget(&self, id: &Id) -> Edit<R> {
        self.edit(EditOp::Forget { id: id.clone() })
    }
}

impl<R> Path<R, crate::Reactions> {
    /// React with `emoji` (a Unicode emoji, or a workspace emoji as
    /// `:name:`), as whoever invokes the edit.
    #[must_use]
    pub fn react(&self, emoji: impl Into<String>) -> Edit<R> {
        self.edit(EditOp::React {
            emoji: emoji.into(),
        })
    }

    /// Take back the invoker's reaction with `emoji`.
    #[must_use]
    pub fn unreact(&self, emoji: impl Into<String>) -> Edit<R> {
        self.edit(EditOp::Unreact {
            emoji: emoji.into(),
        })
    }
}

/// What an [`Edit`] does at its path. Text positions count characters.
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(tag = "op", rename_all = "kebab-case")]
pub enum EditOp {
    /// Replace the value with one in its JSON form ([`Model::to_json`]).
    Set {
        value: serde_json::Value,
    },
    /// Replace `delete` characters at `at` with `insert`.
    Splice {
        at: usize,
        delete: usize,
        insert: String,
    },
    /// Replace the whole text by the smallest splice.
    Replace {
        text: String,
    },
    /// Add to a [`Counter`](crate::Counter).
    Add {
        by: i64,
    },
    /// Add an element to a [`Set`](crate::Set).
    Insert {
        value: serde_json::Value,
    },
    /// Remove an element from a [`Set`](crate::Set).
    Remove {
        value: serde_json::Value,
    },
    /// Insert an item into a collection; `id: None` mints one.
    InsertItem {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        id: Option<Id>,
        at: At,
        value: serde_json::Value,
    },
    /// Update the one item of a collection whose fields hold `matching`
    /// with the fields of `value`, else append `value` (with `matching`'s
    /// fields) as a new item, under `id` when given. Resolved against the
    /// document as it is when the edit applies; refused when more than one
    /// item matches.
    UpsertItem {
        #[serde(rename = "match")]
        matching: serde_json::Map<String, serde_json::Value>,
        value: serde_json::Value,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        id: Option<Id>,
    },
    /// Remove an item from a collection.
    RemoveItem {
        id: Id,
    },
    /// Move an item within a collection.
    MoveTo {
        id: Id,
        at: At,
    },
    /// Remove an entry of a map.
    RemoveKey {
        key: String,
    },
    /// Set (`Some`) or clear (`None`) a grid cell.
    SetCell {
        row: Id,
        column: Id,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        value: Option<serde_json::Value>,
    },
    InsertRow {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        id: Option<Id>,
        at: usize,
    },
    InsertColumn {
        #[serde(default, skip_serializing_if = "Option::is_none")]
        id: Option<Id>,
        at: usize,
    },
    RemoveRow {
        id: Id,
    },
    RemoveColumn {
        id: Id,
    },
    /// Settle an outbox entry, with its [`Settled`](crate::Settled) in JSON
    /// form.
    Settle {
        id: Id,
        outcome: serde_json::Value,
    },
    /// Forget a settled outbox entry.
    Forget {
        id: Id,
    },
    /// React with `emoji` to what holds a [`Reactions`](crate::Reactions)
    /// field, as whoever invokes the edit.
    React {
        emoji: String,
    },
    /// Take back the invoker's reaction with `emoji`.
    Unreact {
        emoji: String,
    },
    /// An edit of a type with its own vocabulary ([`Operations`]: rich text
    /// marks and blocks), in that type's JSON form.
    Rich {
        rich: serde_json::Value,
    },
}

// Read through one JSON value: the tag taken out by hand and the rest read
// as an externally tagged twin, so no deserializer buffers the edit's content
// to find its tag, and the reading is compiled once.
impl<'de> Deserialize<'de> for EditOp {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = serde_json::Value::deserialize(deserializer)?;
        match op_from_json(value) {
            Ok(op) => Ok(op),
            Err(error) => Err(serde::de::Error::custom(error)),
        }
    }
}

/// [`EditOp`] as its JSON form tags it, the tag outside.
#[derive(Deserialize)]
#[serde(rename_all = "kebab-case")]
enum EditOpWire {
    Set {
        value: serde_json::Value,
    },
    Splice {
        at: usize,
        delete: usize,
        insert: String,
    },
    Replace {
        text: String,
    },
    Add {
        by: i64,
    },
    Insert {
        value: serde_json::Value,
    },
    Remove {
        value: serde_json::Value,
    },
    InsertItem {
        #[serde(default)]
        id: Option<Id>,
        #[serde(default)]
        at: At,
        value: serde_json::Value,
    },
    UpsertItem {
        #[serde(rename = "match")]
        matching: serde_json::Map<String, serde_json::Value>,
        value: serde_json::Value,
        #[serde(default)]
        id: Option<Id>,
    },
    RemoveItem {
        id: Id,
    },
    MoveTo {
        id: Id,
        #[serde(default)]
        at: At,
    },
    RemoveKey {
        key: String,
    },
    SetCell {
        row: Id,
        column: Id,
        #[serde(default)]
        value: Option<serde_json::Value>,
    },
    InsertRow {
        #[serde(default)]
        id: Option<Id>,
        at: usize,
    },
    InsertColumn {
        #[serde(default)]
        id: Option<Id>,
        at: usize,
    },
    RemoveRow {
        id: Id,
    },
    RemoveColumn {
        id: Id,
    },
    Settle {
        id: Id,
        outcome: serde_json::Value,
    },
    Forget {
        id: Id,
    },
    React {
        emoji: String,
    },
    Unreact {
        emoji: String,
    },
    Rich {
        rich: serde_json::Value,
    },
}

impl From<EditOpWire> for EditOp {
    fn from(wire: EditOpWire) -> Self {
        match wire {
            EditOpWire::Set { value } => Self::Set { value },
            EditOpWire::Splice { at, delete, insert } => Self::Splice { at, delete, insert },
            EditOpWire::Replace { text } => Self::Replace { text },
            EditOpWire::Add { by } => Self::Add { by },
            EditOpWire::Insert { value } => Self::Insert { value },
            EditOpWire::Remove { value } => Self::Remove { value },
            EditOpWire::InsertItem { id, at, value } => Self::InsertItem { id, at, value },
            EditOpWire::UpsertItem {
                matching,
                value,
                id,
            } => Self::UpsertItem {
                matching,
                value,
                id,
            },
            EditOpWire::RemoveItem { id } => Self::RemoveItem { id },
            EditOpWire::MoveTo { id, at } => Self::MoveTo { id, at },
            EditOpWire::RemoveKey { key } => Self::RemoveKey { key },
            EditOpWire::SetCell { row, column, value } => Self::SetCell { row, column, value },
            EditOpWire::InsertRow { id, at } => Self::InsertRow { id, at },
            EditOpWire::InsertColumn { id, at } => Self::InsertColumn { id, at },
            EditOpWire::RemoveRow { id } => Self::RemoveRow { id },
            EditOpWire::RemoveColumn { id } => Self::RemoveColumn { id },
            EditOpWire::Settle { id, outcome } => Self::Settle { id, outcome },
            EditOpWire::Forget { id } => Self::Forget { id },
            EditOpWire::React { emoji } => Self::React { emoji },
            EditOpWire::Unreact { emoji } => Self::Unreact { emoji },
            EditOpWire::Rich { rich } => Self::Rich { rich },
        }
    }
}

/// The operation in `value`, an edit's JSON form without its path.
#[inline(never)]
fn op_from_json(value: serde_json::Value) -> Result<EditOp, serde_json::Error> {
    use serde::de::Error as _;
    let serde_json::Value::Object(mut fields) = value else {
        return Err(serde_json::Error::custom(
            "an edit operation is a JSON object",
        ));
    };
    let Some(serde_json::Value::String(op)) = fields.remove("op") else {
        return Err(serde_json::Error::missing_field("op"));
    };
    let mut tagged = serde_json::Map::new();
    tagged.insert(op, serde_json::Value::Object(fields));
    EditOpWire::deserialize(serde_json::Value::Object(tagged)).map(EditOp::from)
}

/// What each field-edit operation takes beside `path` and `op`, as its JSON
/// form reads it: the operation's name, the arguments it requires and the
/// ones it may be given. The published field-edit schema states these, so an
/// agent reading it sends what the edit needs; `op_arguments_match_what_an_edit_reads`
/// holds the table to the reader.
pub const OP_ARGUMENTS: &[(&str, &[&str], &[&str])] = &[
    ("set", &["value"], &[]),
    ("splice", &["at", "delete", "insert"], &[]),
    ("replace", &["text"], &[]),
    ("add", &["by"], &[]),
    ("insert", &["value"], &[]),
    ("remove", &["value"], &[]),
    ("insert-item", &["value"], &["id", "at"]),
    ("upsert-item", &["match", "value"], &["id"]),
    ("remove-item", &["id"], &[]),
    ("move-to", &["id"], &["at"]),
    ("remove-key", &["key"], &[]),
    ("set-cell", &["row", "column"], &["value"]),
    ("insert-row", &["at"], &["id"]),
    ("insert-column", &["at"], &["id"]),
    ("remove-row", &["id"], &[]),
    ("remove-column", &["id"], &[]),
    ("settle", &["id", "outcome"], &[]),
    ("forget", &["id"], &[]),
    ("react", &["emoji"], &[]),
    ("unreact", &["emoji"], &[]),
    ("rich", &["rich"], &[]),
];

/// The arguments the operation `op` requires and may be given
/// ([`OP_ARGUMENTS`]); `None` for no operation of that name.
#[must_use]
pub fn op_arguments(op: &str) -> Option<(&'static [&'static str], &'static [&'static str])> {
    OP_ARGUMENTS
        .iter()
        .find(|(name, ..)| *name == op)
        .map(|(_, required, optional)| (*required, *optional))
}

/// The schema of the argument `argument` of the operation `op`, as its JSON
/// form reads it. An argument several operations share (`at`, `id`) has one
/// schema that holds for each of them.
#[must_use]
pub fn op_argument_schema(op: &str, argument: &str) -> serde_json::Value {
    let described = |schema: serde_json::Value, description: &str| {
        let mut schema = schema;
        if let Some(object) = schema.as_object_mut() {
            object.insert("description".into(), description.into());
        }
        schema
    };
    match (op, argument) {
        ("splice", "delete") => described(
            serde_json::json!({ "type": "integer", "minimum": 0 }),
            "splice: how many characters it replaces",
        ),
        ("splice", "insert") => described(
            serde_json::json!({ "type": "string" }),
            "splice: the text it puts there",
        ),
        (_, "at") => serde_json::json!({
            "description": "insert-item, move-to: \"end\" (the default), {\"after\": id} or {\"before\": id}; splice: the character the replaced text starts at; insert-row, insert-column: the position it goes at",
            "oneOf": [
                { "const": "end" },
                { "type": "object", "properties": { "after": { "type": "string" } }, "required": ["after"] },
                { "type": "object", "properties": { "before": { "type": "string" } }, "required": ["before"] },
                { "type": "integer", "minimum": 0 }
            ]
        }),
        (_, "text") => described(
            serde_json::json!({ "type": "string" }),
            "replace: the whole new text; rich text takes markdown",
        ),
        (_, "by") => described(serde_json::json!({ "type": "integer" }), "add: how much"),
        (_, "id") => described(
            serde_json::json!({ "type": "string" }),
            "remove-item, move-to, remove-row, remove-column, settle, forget: the item's id; \
             insert-item, upsert-item, insert-row, insert-column: the new item's id, minted without",
        ),
        (_, "key") => described(
            serde_json::json!({ "type": "string" }),
            "remove-key: the entry's key",
        ),
        (_, "row" | "column") => described(
            serde_json::json!({ "type": "string" }),
            "set-cell: the cell's row and column ids",
        ),
        (_, "outcome") => described(
            serde_json::json!({ "type": "object" }),
            "settle: how the entry settled",
        ),
        (_, "emoji") => described(
            serde_json::json!({ "type": "string" }),
            "react, unreact: a Unicode emoji, or a workspace emoji as :name:",
        ),
        (_, "match") => serde_json::json!({
            "type": "object",
            "description": "upsert-item: the fields that identify the item, e.g. {\"name\": \"Ana\"}; it updates the one item holding them with `value`'s fields, else appends `value` as a new item"
        }),
        (_, "rich") => described(
            serde_json::json!({ "type": "object" }),
            "rich: an edit in the field type's own vocabulary",
        ),
        _ => serde_json::json!({}),
    }
}

/// How the operation `op` reads in a listing of what a path takes, with its
/// arguments: `remove-item {id}`, `move-to {id, at?}`; an operation that
/// takes only a value (`set`) by its name.
#[must_use]
pub fn op_usage(op: &str) -> String {
    let Some((required, optional)) = op_arguments(op) else {
        return op.to_owned();
    };
    // A value is what every `set` takes: the listing says the field's kind
    // of value on the same line.
    if required == ["value"] && optional.is_empty() {
        return op.to_owned();
    }
    let arguments: Vec<String> = required
        .iter()
        .map(|argument| (*argument).to_owned())
        .chain(optional.iter().map(|argument| format!("{argument}?")))
        .collect();
    if arguments.is_empty() {
        op.to_owned()
    } else {
        format!("{op} {{{}}}", arguments.join(", "))
    }
}

impl EditOp {
    /// The operation's name, as its JSON form tags it.
    #[must_use]
    pub const fn name(&self) -> &'static str {
        match self {
            Self::Set { .. } => "set",
            Self::Splice { .. } => "splice",
            Self::Replace { .. } => "replace",
            Self::Add { .. } => "add",
            Self::Insert { .. } => "insert",
            Self::Remove { .. } => "remove",
            Self::InsertItem { .. } => "insert-item",
            Self::UpsertItem { .. } => "upsert-item",
            Self::RemoveItem { .. } => "remove-item",
            Self::MoveTo { .. } => "move-to",
            Self::RemoveKey { .. } => "remove-key",
            Self::SetCell { .. } => "set-cell",
            Self::InsertRow { .. } => "insert-row",
            Self::InsertColumn { .. } => "insert-column",
            Self::RemoveRow { .. } => "remove-row",
            Self::RemoveColumn { .. } => "remove-column",
            Self::Settle { .. } => "settle",
            Self::Forget { .. } => "forget",
            Self::React { .. } => "react",
            Self::Unreact { .. } => "unreact",
            Self::Rich { .. } => "rich",
        }
    }

    /// Whether this operation removes something a person may want back
    /// (an item, a row, a map entry).
    #[must_use]
    pub const fn removes(&self) -> bool {
        matches!(
            self,
            Self::RemoveItem { .. }
                | Self::RemoveKey { .. }
                | Self::RemoveRow { .. }
                | Self::RemoveColumn { .. }
        )
    }
}

/// A field edit of the record `R`: a path and an operation. See the module
/// docs.
pub struct Edit<R> {
    path: Vec<Segment>,
    op: EditOp,
    marker: PhantomData<fn() -> R>,
}

impl<R> Edit<R> {
    /// An edit from its parts, as read back from the wire.
    #[must_use]
    pub fn new(path: Vec<Segment>, op: EditOp) -> Self {
        Self {
            path,
            op,
            marker: PhantomData,
        }
    }

    pub fn path(&self) -> &[Segment] {
        &self.path
    }

    pub fn op(&self) -> &EditOp {
        &self.op
    }

    /// The same edit, of the record `S`: the path and operation it carries
    /// do not depend on the record type.
    #[must_use]
    pub fn retyped<S>(self) -> Edit<S> {
        Edit::new(self.path, self.op)
    }

    /// The edit in `value`, its JSON form.
    ///
    /// # Errors
    /// Why `value` is no field edit.
    pub fn from_json(value: serde_json::Value) -> Result<Self, String> {
        match edit_from_json(value) {
            Ok((path, op)) => Ok(Self::new(path, op)),
            Err(error) => Err(error.to_string()),
        }
    }

    /// The same edit of a record stored as `root`, which callers also call
    /// by one of `names`: a path whose first field names no field of the
    /// record but the record itself starts at the field after it. A record
    /// read nests its fields under such a name (a timeline's `project`), and
    /// callers send `project.name` back.
    pub(crate) fn past_resource_name(
        self,
        root: crate::Shape,
        names: &[&str],
    ) -> Result<Self, String> {
        let fields = root.fields();
        let Some((Segment::Field(head), rest)) = self.path.split_first() else {
            return Ok(self);
        };
        if fields.iter().any(|field| field.key == head)
            || !names.iter().any(|name| name.eq_ignore_ascii_case(head))
        {
            return Ok(self);
        }
        let Some(start) = rest.first() else {
            let editable: Vec<&str> = fields
                .iter()
                .filter(|field| !field.readonly)
                .map(|field| field.key)
                .collect();
            return Err(format!(
                "`{head}` is the resource itself, not one of its fields: start the path at the field to change, one of {}",
                editable.join(", ")
            ));
        };
        // An action API decides whether an edit asks first from the path as sent,
        // which names no field that exposes the person or weakens their
        // security; an edit of such a field is sent again from the root.
        if root.trust_at(rest) != crate::Trust::Ordinary {
            return Err(format!(
                "`{head}` is the resource itself, not one of its fields: start the path at `{start}`"
            ));
        }
        Ok(Self::new(rest.to_vec(), self.op))
    }

    /// Whether `next`, by the same actor straight after `self`, continues
    /// the same gesture: one undo step. Setting one path again (dragging a
    /// slider), typing on at the end of the previous splice (a word) and a
    /// text field's whole-text replacements that type or erase within one
    /// word (`replace_continues`) continue; an edit in a type's own vocabulary continues as that type
    /// says ([`Operations::coalesces`]); anything else starts a new step.
    #[must_use]
    pub fn coalesces(&self, next: &Self) -> bool
    where
        R: Model,
    {
        edits_coalesce(
            (&self.path, &self.op),
            (&next.path, &next.op),
            R::op_coalesces,
        )
    }

    /// How much harm this edit can do: removing an item of a collection is
    /// destructive, like a delete verb, unless the collection is
    /// `#[model(remove = "quiet")]`; every other edit is low.
    #[must_use]
    pub fn risk(&self) -> tilo_actions::RiskLevel
    where
        R: Model,
    {
        edit_risk(R::SHAPE, &self.path, &self.op, None)
    }

    /// The node of the published tree this edit acts on, for deciding
    /// grants: `workspace › app › kind › record [› item] › field… › field-edit`.
    /// The collection field holding an item is not a node of its own.
    #[must_use]
    pub fn tree_path(
        &self,
        workspace: &str,
        app: &str,
        record: &str,
    ) -> tilo_action_policy::TreePath
    where
        R: crate::Resource,
    {
        use tilo_action_policy::Level;
        let mut tree = tilo_action_policy::TreePath::workspace(workspace)
            .app(app)
            .kind(R::KIND)
            .resource(record);
        let mut item = false;
        let mut segments = self.path.iter().peekable();
        while let Some(segment) = segments.next() {
            tree = match segment {
                Segment::Field(_) if !item && matches!(segments.peek(), Some(Segment::Item(_))) => {
                    tree
                }
                Segment::Item(id) if !item => {
                    item = true;
                    tree.item(id.as_str())
                }
                Segment::Field(key) | Segment::Key(key) => tree.push(Level::Field, key.as_str()),
                Segment::Item(id) => tree.push(Level::Field, id.as_str()),
                Segment::Cell { row, column } => tree
                    .push(Level::Field, row.as_str())
                    .push(Level::Field, column.as_str()),
            };
        }
        tree.action(crate::FIELD_EDIT)
    }

    /// Apply to a document held apart from any resource (a form's local
    /// value): no action, no history, ids minted from the document alone.
    ///
    /// # Errors
    /// As [`Self::apply`].
    pub fn apply_local(&self, doc: &mut crate::Doc) -> Result<(), crate::ModelError>
    where
        R: crate::Fields,
    {
        let payload = serde_json::to_vec(self)
            .map_err(|error| crate::ModelError::invalid(error.to_string()))?;
        let mut cx = crate::ActionCx::for_write(doc, &payload);
        self.apply(doc, &mut cx)
    }

    /// Apply at its path in `doc`, then run the invariants of every value
    /// the edit touched.
    ///
    /// # Errors
    /// Returns why the path or operation does not fit the model, or the
    /// refusal of a [`check`](crate::Model::check).
    pub fn apply(
        &self,
        doc: &mut crate::Doc,
        cx: &mut crate::ActionCx,
    ) -> Result<(), crate::ModelError>
    where
        R: crate::Fields,
    {
        R::edit_fields(doc, &automerge::ROOT, &self.path, &self.op, cx)
    }
}

/// [`Edit::coalesces`] of the edit `previous` (its path and operation) and
/// `next`, an edit in a type's own vocabulary continuing as `rich` says:
/// compiled once rather than for every record type.
#[inline(never)]
fn edits_coalesce(
    (previous_path, previous_op): (&[Segment], &EditOp),
    (next_path, next_op): (&[Segment], &EditOp),
    rich: fn(&[Segment], &serde_json::Value, &serde_json::Value) -> Option<bool>,
) -> bool {
    if previous_path != next_path {
        return false;
    }
    match (previous_op, next_op) {
        (EditOp::Rich { rich: previous }, EditOp::Rich { rich: next }) => {
            rich(previous_path, previous, next).unwrap_or(false)
        }
        (EditOp::Set { .. }, EditOp::Set { .. }) | (EditOp::Add { .. }, EditOp::Add { .. }) => true,
        (EditOp::Replace { text: previous }, EditOp::Replace { text: next }) => {
            replace_continues(previous, next)
        }
        (
            EditOp::Splice {
                at, delete, insert, ..
            },
            EditOp::Splice {
                at: next_at,
                delete: next_delete,
                insert: next_insert,
            },
        ) => {
            let typed = insert.chars().count();
            // Typing on after the previous insertion, within one word:
            // a space ends the word it follows, so undo takes back
            // `world` and leaves `hello `.
            let typing = *delete == 0
                && *next_delete == 0
                && !next_insert.is_empty()
                && *next_at == at.saturating_add(typed)
                && !insert.ends_with(char::is_whitespace);
            // Deleting backwards from where the previous deletion was.
            let erasing = insert.is_empty()
                && next_insert.is_empty()
                && next_at.saturating_add(*next_delete) == *at;
            typing || erasing
        }
        _ => false,
    }
}

impl<R> Clone for Edit<R> {
    fn clone(&self) -> Self {
        let (path, op) = clone_edit(&self.path, &self.op);
        Self::new(path, op)
    }
}

/// A copy of an edit's path and operation, made by one function for every
/// resource type.
#[inline(never)]
fn clone_edit(path: &[Segment], op: &EditOp) -> (Vec<Segment>, EditOp) {
    (path.to_vec(), op.clone())
}

impl<R> std::fmt::Debug for Edit<R> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        fmt_edit(&self.path, &self.op, f)
    }
}

fn fmt_edit(path: &[Segment], op: &EditOp, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    f.debug_struct("Edit")
        .field("path", &Path::<(), ()>::from_segments(path.to_vec()))
        .field("op", op)
        .finish()
}

impl<R> PartialEq for Edit<R> {
    fn eq(&self, other: &Self) -> bool {
        self.path == other.path && self.op == other.op
    }
}

impl<R> Serialize for Edit<R> {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        edit_to_json(&self.path, &self.op).serialize(serializer)
    }
}

/// The arguments of [`FIELD_EDIT`](crate::FIELD_EDIT) that settle entry
/// `id` of the outbox stored at field `field` with `outcome` (a
/// [`Settled`](crate::Settled) in JSON form): [`Path::settle`] for a host
/// that holds the record without its app's types, such as a workspace's host
/// settling what a bot's connector performed.
#[must_use]
pub fn outbox_settle_arguments(
    field: &str,
    id: &str,
    outcome: &serde_json::Value,
) -> serde_json::Map<String, serde_json::Value> {
    let op = EditOp::Settle {
        id: Id::from_raw(id),
        outcome: outcome.clone(),
    };
    let edit = edit_to_json(&[Segment::Field(field.to_owned())], &op);
    serde_json::Map::from_iter([(crate::EDIT_PARAM.to_owned(), edit)])
}

#[inline(never)]
fn edit_to_json(path: &[Segment], op: &EditOp) -> serde_json::Value {
    // Both are plain data: their JSON never fails to build.
    let mut form = crate::__private::json_via_bytes(op).unwrap_or_default();
    if let serde_json::Value::Object(map) = &mut form {
        map.insert(
            "path".into(),
            crate::__private::json_via_bytes(path).unwrap_or_default(),
        );
    }
    form
}

impl<'de, R> Deserialize<'de> for Edit<R> {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = serde_json::Value::deserialize(deserializer)?;
        match edit_from_json(value) {
            Ok((path, op)) => Ok(Self::new(path, op)),
            Err(error) => Err(serde::de::Error::custom(error)),
        }
    }
}

impl<R> crate::JsonSchema for Edit<R> {
    fn json_schema() -> serde_json::Value {
        edit_schema()
    }
}

fn edit_schema() -> serde_json::Value {
    edit_schema_taking(|_| true)
}

/// The field-edit schema with only the operations `takes` names, and only the
/// arguments those take: what a record whose fields take just those publishes,
/// so an agent reads none of the operations no path of it takes.
#[inline(never)]
pub(crate) fn edit_schema_taking(takes: impl Fn(&str) -> bool) -> serde_json::Value {
    let offered: Vec<&(&str, &[&str], &[&str])> =
        OP_ARGUMENTS.iter().filter(|(op, ..)| takes(op)).collect();
    let ops: Vec<&str> = offered.iter().map(|(op, ..)| *op).collect();
    let mut properties = serde_json::Map::new();
    properties.insert(
        "path".into(),
        serde_json::json!({ "type": "array", "items": {"type": "object"} }),
    );
    properties.insert(
        "op".into(),
        serde_json::json!({ "type": "string", "enum": ops }),
    );
    let mut needs = Vec::new();
    for (op, required, optional) in offered {
        for argument in required.iter().chain(optional.iter()) {
            if !properties.contains_key(*argument) {
                properties.insert((*argument).to_owned(), op_argument_schema(op, argument));
            }
        }
        let mut needed = vec!["path", "op"];
        needed.extend(required.iter().copied());
        needs.push(serde_json::json!({
            "properties": { "op": { "const": op } },
            "required": needed,
        }));
    }
    serde_json::json!({
        "type": "object",
        "description": "A field edit: the path from the record's root (fields by name, items by id) and an operation the field's type supports, with the arguments that operation takes",
        "properties": properties,
        "required": ["path", "op"],
        "oneOf": needs,
    })
}

/// `edits`, of the record `R`.
#[must_use]
pub fn retyped_all<R>(edits: Vec<Edit<()>>) -> Vec<Edit<R>> {
    let mut out = Vec::with_capacity(edits.len());
    for edit in edits {
        out.push(edit.retyped());
    }
    out
}

/// The paths of a type whose values are edited only as a whole or through
/// their own operations: the path itself.
#[doc(hidden)]
pub fn leaf<R, T>(path: Path<R, T>) -> Path<R, T> {
    path
}

/// Whether a text field's replacement of `previous` by `next` continues the
/// same typing gesture, so the keystrokes of one word are one undo step as
/// with splices: the one change between them is typing a single character
/// on after a character that is not a space (a space ends the word it
/// follows), or erasing. A paste or any larger change is a step of its own,
/// so undo takes it back alone.
fn replace_continues(previous: &str, next: &str) -> bool {
    let (was, now): (Vec<char>, Vec<char>) = (previous.chars().collect(), next.chars().collect());
    let (prefix, suffix) = crate::text::common_ends(&was, &now);
    let (before, after) = (was.len(), now.len());
    let kept = prefix.saturating_add(suffix);
    let deleted = before.saturating_sub(kept);
    let inserted = after.saturating_sub(kept);
    match (deleted, inserted) {
        // Erasing: Backspace or Delete runs on through the word.
        (1.., 0) => true,
        // Typing one character on after a non-space.
        (0, 1) => prefix
            .checked_sub(1)
            .and_then(|at| was.get(at))
            .is_some_and(|c| !c.is_whitespace()),
        _ => false,
    }
}