jmap-tasks-server 0.6.1

JMAP Tasks method handlers — backend-agnostic, plugs into jmap-server Dispatcher
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
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
//! In-memory reference implementation of [`TasksBackend`].
//!
//! # This is a reference implementation, not production
//!
//! `MemoryBackend` is intended for three audiences:
//!
//! 1. **Workspace integration tests** — every `tests/*.rs` integration test
//!    in this crate exercises method handlers against this backend.
//! 2. **Downstream contributors** — a documented, complete, source-readable
//!    implementation of the [`TasksBackend`] trait to
//!    study when writing a real (database-backed) backend.
//! 3. **Examples and smoke tests** — boot a real JMAP-for-Tasks dispatcher
//!    with one line of code, without standing up a database.
//!
//! It is **not** suitable for production: all state is held in `HashMap`s
//! behind one [`jmap_server::ScopedState`], persistence is not implemented, and a number
//! of draft-ietf-jmap-tasks-06 edge cases are simplified (see source
//! comments). In particular, UTC-time conversion
//! ([`compute_utc_times`](crate::TasksBackend::compute_utc_times))
//! inherits the trait's default (no time-zone conversion), and
//! [`update_task_per_user`](crate::TasksBackend::update_task_per_user)
//! stores per-user patches on the shared object (single-user backend).
//! `Task/query` has no time-zone database and no recurrence engine:
//! `after` / `before` on a task whose `timeZone` is not the query's is
//! `unsupportedFilter`, and with `expandRecurrences` a recurring match is
//! `cannotCalculateOccurrences`, and a sort by `start` over tasks in more
//! than one zone is `unsupportedSort` (see
//! [`query_tasks`](crate::TasksBackend::query_tasks) on `MemoryBackend`).
//!
//! # Feature flag and API stability
//!
//! This module is gated behind `feature = "memory"` and is **not** enabled
//! by default. Its public API stability is opt-in: it may break across
//! minor versions while the crate is pre-1.0.
//!
//! # Example
//!
//! ```rust,ignore
//! use std::sync::Arc;
//! use jmap_tasks_server::{memory::MemoryBackend, register_tasks_handlers};
//! use jmap_server::Dispatcher;
//!
//! let mut dispatcher: Dispatcher<()> = Dispatcher::new();
//! register_tasks_handlers(&mut dispatcher, Arc::new(MemoryBackend::new()));
//! ```
//!
//! # Concurrency
//!
//! The store is a [`jmap_server::ScopedState`]: a `std::sync::Mutex` behind
//! a gate that a draft-ietf-jmap-conditional-02 Foo/set scope holds
//! (`MemoryBackend`'s `ConditionalBackend` impl). Async backend methods
//! take `lock().await`, which waits while another task's scope is open;
//! sync setup and seeding helpers take `lock_unscoped()`. With no scope
//! open the gate is free. The `await_holding_lock` clippy lint is enabled
//! module-wide and enforces that no lock guard is held across an
//! `.await`.
//!
//! `ScopedState` takes a poisoned mutex anyway, so a panic while holding
//! the guard (already a bug in this module) does not panic every later
//! call; an atomic scope that panicked is rolled back to its snapshot.
//! The crate's tests never poison the lock. A production backend should
//! implement the trait with its own locking
//! rather than copy this pattern.
//!
//! # Tracking
//!
//! Greenfield reference impl per Beads issue JMAP-hwdv (epic) and
//! JMAP-hwdv.7 (this crate, mirror of canonical JMAP-hwdv.1 in
//! jmap-mail-server, following the multi-type-store shape established
//! by jmap-chat-server's `MemoryBackend` and the derived-index pattern
//! pioneered in JMAP-hwdv.5 jmap-calendars-server).

#![allow(async_fn_in_trait)]
#![deny(clippy::await_holding_lock)]

mod history;

use std::cmp::Ordering;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::marker::PhantomData;

use crate::{TaskQueryArgs, TasksBackend};
use jmap_metadata_server::{
    ChangedProperties, MetadataCondition, MetadataFilterError, MetadataOnlyChanges, SetKind,
    changed_properties, check_metadata_depth, check_metadata_write, is_metadata_property,
    metadata_path_exists, metadata_text_contains, metadata_text_equals,
};
use jmap_metadata_types::{DataTypeMetadataInfo, MetadataTextMatch};
use jmap_object_history_server::{ChangeEvent, ChangeKind, fold_restore};
use jmap_server::{
    AddedItem, BackendChangesError, BackendQueryError, BackendSetError, ChangesResult, GetObject,
    JmapAccounts, JmapObject, JmapReads, MemoryCaller, QueryChangesParams, QueryChangesResult,
    QueryObject, QueryParams, QueryResult, SetError, SetErrorType, SetObject,
};
use jmap_server::{
    BeginSetError, ConditionalBackend, PatchPathError, ScopedState, SetScope, SetScopeRequest,
    apply_patch_object, check_patch_paths, limit_or_max, resolve_query_start,
};
use jmap_tasks_types::{
    Task, TaskComparator, TaskComparatorProperty, TaskFilterCondition, TaskList,
};
use jmap_types::{Id, JmapError, State};

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Opaque storage-layer error returned by [`MemoryBackend`] operations.
///
/// The inner description is a human-readable string intended for
/// diagnostic logging; it is not a stable wire-format identifier.
///
/// # Forward compatibility
///
/// This type is `#[non_exhaustive]` and uses a named-field shape so
/// future revisions can add structured context (error kind, source
/// reference, account id, etc.) without a breaking change. Outside-
/// crate construction goes through [`MemoryError::new`]; outside-crate
/// reads go through [`MemoryError::description`].
#[non_exhaustive]
#[derive(Debug)]
pub struct MemoryError {
    description: String,
}

impl MemoryError {
    /// Construct a [`MemoryError`] from a human-readable description.
    pub fn new(description: impl Into<String>) -> Self {
        Self {
            description: description.into(),
        }
    }

    /// Human-readable description of the underlying failure.
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Construct a [`MemoryError`] for a `serde_json` failure during
    /// `context` (the operation that failed).
    ///
    /// Only the error's [`serde_json::error::Category`] is kept. A serde
    /// data error quotes the offending value (`invalid type: string
    /// "alice@example.com", expected u64`), and the `JmapAccounts::Error`
    /// contract forbids PII and blob content in `Display` output
    /// (bd:JMAP-510h.37).
    pub(crate) fn serde(context: impl std::fmt::Display, e: &serde_json::Error) -> Self {
        Self::new(format!("{context}: serde_json {:?} error", e.classify()))
    }
}

impl std::fmt::Display for MemoryError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "MemoryBackend error: {}", self.description)
    }
}

impl std::error::Error for MemoryError {}

// ---------------------------------------------------------------------------
// Change log
// ---------------------------------------------------------------------------

/// Per-ID fate tracker for RFC 8620 §5.2 ID deduplication across change log
/// entries in one `/changes` window.
///
/// - created+updated → `Created`
/// - created+destroyed → omitted (the client never knew the object)
/// - updated+destroyed → `Destroyed`
/// - updated+updated → `Updated`
///
/// Mirrors the canonical jmap-mail-server `IdFate` enum.
#[derive(Debug, Clone, Copy)]
enum IdFate {
    Created,
    Updated,
    Destroyed,
}

/// A change log entry for one state transition.
#[derive(Clone, Debug)]
struct ChangeEntry {
    /// The state counter AFTER this change.
    new_state: u64,
    created: Vec<Id>,
    updated: Vec<Id>,
    destroyed: Vec<Id>,
    /// The top-level properties this change altered on every id in
    /// `updated`, or `None` when not known. Feeds
    /// draft-ietf-jmap-metadata-05 §3.3 `ignoreMetadataOnlyChanges` and
    /// `updatedProperties`.
    updated_props: Option<BTreeSet<String>>,
    /// Ids restored from object history (draft-ietf-jmap-object-history
    /// §5.1).
    restored: Vec<Id>,
}

impl ChangeEntry {
    /// `true` for an update that changed only `metadata` and/or
    /// `privateMetadata` (draft-ietf-jmap-metadata-05 §3.3).
    fn is_metadata_only_update(&self) -> bool {
        self.created.is_empty()
            && self.destroyed.is_empty()
            && self.updated_props.as_ref().is_some_and(|props| {
                !props.is_empty() && props.iter().all(|p| is_metadata_property(p))
            })
    }
}

// ---------------------------------------------------------------------------
// Inner state
// ---------------------------------------------------------------------------

/// Per-account auxiliary state that is not keyed by object type.
#[derive(Default, Clone)]
struct AccountAux {
    /// Refcount of [`TaskList`] ids by the number of Tasks attached to each
    /// (drives `TaskList/set` destroy rejection with `taskListHasTask`
    /// per draft-ietf-jmap-tasks-06 §3.4 when `onDestroyRemoveTasks` is
    /// `false`). Maintained incrementally: `inc_task_ref` on Task create,
    /// `dec_task_ref` on Task destroy, both on a taskListId change. O(1)
    /// per Task mutation — the previous full-scan recompute was O(N).
    /// Entries are removed when the count drops to 0 so `task_list_has_tasks`
    /// can read presence-as-truthy instead of value-as-truthy.
    task_list_refcount: HashMap<Id, u64>,
}

/// Shared inner state, behind a [`ScopedState`] so a conditional Foo/set
/// can isolate and roll it back (docs/design/conditional.md §7).
#[derive(Default, Clone)]
struct Inner {
    /// `type_name` → `account_id` → `id → serialized object`
    objects: HashMap<&'static str, HashMap<String, HashMap<Id, serde_json::Value>>>,
    /// `type_name` → `account_id` → current state counter
    states: HashMap<&'static str, HashMap<String, u64>>,
    /// `type_name` → `account_id` → ordered change entries
    change_log: HashMap<&'static str, HashMap<String, Vec<ChangeEntry>>>,
    /// `account_id` → auxiliary per-account state (derived indexes)
    aux: HashMap<String, AccountAux>,
    /// Explicitly registered account ids (accounts may exist with no objects yet).
    known_accounts: HashSet<String>,
    /// `type_name` → the draft-ietf-jmap-metadata-05 §1.2.1
    /// [`DataTypeMetadataInfo`] set by [`MemoryBackend::with_metadata_info`].
    /// A type without an entry does not have the metadata properties.
    metadata_info: HashMap<&'static str, DataTypeMetadataInfo>,
    /// Object history, once `MemoryBackend::with_object_history` turns it
    /// on.
    history: Option<jmap_object_history_server::HistoryStore>,
}

impl Inner {
    fn current_state(&self, type_name: &'static str, account_id: &str) -> u64 {
        self.states
            .get(type_name)
            .and_then(|m| m.get(account_id))
            .copied()
            .unwrap_or(0)
    }

    fn bump_state(&mut self, type_name: &'static str, account_id: &str) -> u64 {
        let entry = self
            .states
            .entry(type_name)
            .or_default()
            .entry(account_id.to_owned())
            .or_insert(0);
        *entry += 1;
        *entry
    }

    /// The store for `type_name` in `account_id`, created empty on first
    /// use. Pure storage: it never registers the account (bd:JMAP-ayoz.36);
    /// mutations check `require_account` first.
    fn objects_mut(
        &mut self,
        type_name: &'static str,
        account_id: &str,
    ) -> &mut HashMap<Id, serde_json::Value> {
        self.objects
            .entry(type_name)
            .or_default()
            .entry(account_id.to_owned())
            .or_default()
    }

    /// `Err` unless `account_id` was registered. Creates and copies are
    /// per-object mutations, not account lifecycle operations
    /// (bd:JMAP-ayoz.2, JMAP-ayoz.36): one aimed at an unknown account fails
    /// instead of registering it. The handlers answer `accountNotFound`
    /// before this is reached; it guards direct backend callers.
    fn require_account(&self, account_id: &str) -> Result<(), BackendSetError<MemoryError>> {
        if self.known_accounts.contains(account_id) {
            Ok(())
        } else {
            Err(BackendSetError::Other(MemoryError::new(format!(
                "unknown account {account_id:?}"
            ))))
        }
    }

    /// `notFound` for an update or destroy in an account nobody registered:
    /// it has no objects (RFC 8620 §5.3).
    fn require_account_for_target(
        &self,
        account_id: &str,
    ) -> Result<(), BackendSetError<MemoryError>> {
        if self.known_accounts.contains(account_id) {
            Ok(())
        } else {
            Err(BackendSetError::SetError(Box::new(SetError::new(
                SetErrorType::NotFound,
            ))))
        }
    }

    fn objects_ref(
        &self,
        type_name: &'static str,
        account_id: &str,
    ) -> Option<&HashMap<Id, serde_json::Value>> {
        self.objects.get(type_name).and_then(|m| m.get(account_id))
    }

    fn change_log_mut(
        &mut self,
        type_name: &'static str,
        account_id: &str,
    ) -> &mut Vec<ChangeEntry> {
        self.change_log
            .entry(type_name)
            .or_default()
            .entry(account_id.to_owned())
            .or_default()
    }

    fn aux_mut(&mut self, account_id: &str) -> &mut AccountAux {
        self.aux.entry(account_id.to_owned()).or_default()
    }

    fn aux_ref(&self, account_id: &str) -> Option<&AccountAux> {
        self.aux.get(account_id)
    }

    /// Read `taskListId` out of a serialized Task value, if present.
    /// The `workflowStatuses` of task list `list_id`, or `None` when the
    /// list is not stored or has none (the default applies).
    fn workflow_statuses(&mut self, account_id: &str, list_id: Option<&Id>) -> Option<Vec<String>> {
        let list = self
            .objects_mut(TaskList::TYPE_NAME, account_id)
            .get(list_id?)?;
        serde_json::from_value(list.get("workflowStatuses")?.clone()).ok()
    }

    /// Decision 42 on Task `task` under the lock
    /// ([`crate::workflow::apply_workflow_status`]).
    fn apply_workflow(
        &mut self,
        account_id: &str,
        task: &mut serde_json::Value,
        write: crate::workflow::WorkflowWrite<'_>,
    ) -> Result<bool, BackendSetError<MemoryError>> {
        let list = Self::task_list_id_of(task);
        let statuses = self.workflow_statuses(account_id, list.as_ref());
        let serde_json::Value::Object(map) = task else {
            return Ok(false);
        };
        crate::workflow::apply_workflow_status(
            map,
            write,
            statuses.as_deref(),
            jmap_server::now_utc_string().as_ref(),
        )
        .map_err(BackendSetError::SetError)
    }

    fn task_list_id_of(task: &serde_json::Value) -> Option<Id> {
        task.get("taskListId")
            .and_then(|v| v.as_str())
            .map(Id::from)
    }

    /// Increment the refcount for `list_id` in the given account by one.
    /// Called when a Task is created or its `taskListId` changes to
    /// `list_id`. No-op when `list_id` is `None` (well-formed Tasks
    /// always have a taskListId but the helper is defensive against
    /// partial mid-write state).
    fn inc_task_ref(&mut self, account_id: &str, list_id: Option<Id>) {
        if let Some(id) = list_id {
            *self
                .aux_mut(account_id)
                .task_list_refcount
                .entry(id)
                .or_insert(0) += 1;
        }
    }

    /// Decrement the refcount for `list_id` in the given account by one.
    /// Removes the entry when the count drops to zero so `task_list_has_tasks`
    /// can read presence-as-truthy. Safe to call with `None` or an unknown
    /// id (no-op).
    fn dec_task_ref(&mut self, account_id: &str, list_id: Option<Id>) {
        let Some(id) = list_id else { return };
        let aux = self.aux_mut(account_id);
        if let Some(count) = aux.task_list_refcount.get_mut(&id) {
            *count = count.saturating_sub(1);
            if *count == 0 {
                aux.task_list_refcount.remove(&id);
            }
        }
    }
}

// ---------------------------------------------------------------------------
// MemoryBackend
// ---------------------------------------------------------------------------

/// A fully in-memory implementation of [`TasksBackend`].
///
/// Stores objects as serialized JSON; each mutation bumps a monotonic state
/// counter and records a change log entry. Used as both the integration-test
/// harness and the canonical example for backend implementors.
///
/// Cloning is cheap and **shared-state**: every clone retains an
/// handle to the *same* underlying object store and change
/// log. See the [`Clone`] impl below for the contract; a casual reader who
/// reaches for `#[derive(Clone)]` semantics will be wrong. To get a snapshot
/// with independent state, construct a fresh `MemoryBackend::new()` and seed
/// it via `register_account` / the typed test helpers.
///
/// `C` is the [`JmapAccounts::CallerCtx`]: [`Id`], the caller's Principal
/// id, by default, or `()` for a deployment without identity. This
/// backend keeps no per-user state, so every caller acts as the account
/// owner; [`JmapAccounts::principal_id`] returns
/// [`MemoryCaller::principal`].
#[non_exhaustive]
pub struct MemoryBackend<C = Id> {
    inner: ScopedState<Inner>,
    caller: PhantomData<fn() -> C>,
}

/// An empty backend: [`MemoryBackend::new`] for any caller context, such
/// as `MemoryBackend::<()>::default()` for a deployment without identity.
impl<C> Default for MemoryBackend<C> {
    fn default() -> Self {
        Self {
            inner: ScopedState::default(),
            caller: PhantomData,
        }
    }
}

/// Manual `Clone` impl, NOT `#[derive(Clone)]`.
///
/// Cloning a [`MemoryBackend`] does **not** copy any state — both the
/// original and the clone hold handles to the same [`ScopedState`] and
/// observe each other's mutations. This is intentional: handler registration
/// in [`crate::register_tasks_handlers`] takes `Arc<B>` and each method
/// handler closure clones it; without shared mutation semantics, every
/// handler would see a snapshot stale by the time it runs. The manual impl
/// exists (instead of `#[derive(Clone)]`) so the contract is visible at the
/// type, not buried in the module docs.
impl<C> Clone for MemoryBackend<C> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            caller: PhantomData,
        }
    }
}

impl MemoryBackend {
    /// Create a new, empty `MemoryBackend`.
    ///
    /// Its callers are Principal ids (`C = Id`);
    /// `MemoryBackend::<()>::default()` takes callers without identity.
    pub fn new() -> Self {
        Self::default()
    }
}

impl<C: MemoryCaller> MemoryBackend<C> {
    /// Register `account_id` as known and return `self`, for
    /// builder-style fixture setup. Until then the account is unknown
    /// (`accountNotFound`, RFC 8620 §3.6.2). Idempotent; the id is stored
    /// without RFC 8620 §1.2 validation.
    ///
    /// # Panics
    ///
    /// In debug builds, if `account_id` is the empty string (RFC 8620
    /// §1.2, bd:JMAP-dx0s).
    #[must_use]
    pub fn with_account(self, account_id: &Id) -> Self {
        self.register_account(account_id);
        self
    }

    /// Give `data_type` the draft-ietf-jmap-metadata-05 `metadata`
    /// property, configured by `info` (the [`DataTypeMetadataInfo`] of -05
    /// §1.2.1).
    ///
    /// Without this call a type has no metadata: `Foo/set` rejects a
    /// write to `metadata` or `privateMetadata` with `invalidProperties`
    /// and `Foo/query` rejects a metadata filter condition with
    /// `unsupportedFilter`. With it, `Foo/set` validates metadata writes
    /// (-05 §3.2, §4.1), `Task/query` evaluates the -05 §3.6 conditions,
    /// and `Foo/changes` honours `ignoreMetadataOnlyChanges` and reports
    /// `updatedProperties` (-05 §3.3). Advertising the capability in the
    /// session is the server's job: list `info` under `data_type` in the
    /// account's `urn:ietf:params:jmap:metadata` `dataTypes`.
    ///
    /// [`TaskList`] writes need `myRights.maySetMetadata` on the `TaskList`, and
    /// Task writes need it on the Task's `TaskList` before and after the
    /// update, or on the `taskListId` of a create (-05 §4.1). An absent
    /// `maySetMetadata` allows the write (fail-open, JMAP-bghk). This
    /// backend never sets Task `updated`, so a metadata-only change leaves
    /// it alone, as -05 §3.1 requires.
    ///
    /// # Panics
    ///
    /// Panics if `data_type` is not `"TaskList"` or `"Task"` (the rights
    /// object of draft-ietf-jmap-tasks-06 §3 and the type it contains;
    /// -05 §4.1), or if `info.supports_private` is true: this backend has
    /// no per-user state to own `privateMetadata`
    /// (-05 §2).
    #[must_use]
    pub fn with_metadata_info(self, data_type: &str, info: DataTypeMetadataInfo) -> Self {
        let type_name = metadata_type_name(data_type).unwrap_or_else(|| {
            panic!("MemoryBackend supports metadata only on TaskList and Task, not {data_type:?}")
        });
        assert!(
            !info.supports_private,
            "MemoryBackend does not support privateMetadata (supportsPrivate must be false)"
        );
        self.inner
            .lock_unscoped()
            .metadata_info
            .insert(type_name, info);
        self
    }

    /// Test-only entry point that registers an account as known even
    /// if it has no objects yet. Production callers must not use this
    /// method; the API stability disclaimer on the `memory` feature
    /// applies doubly here.
    ///
    /// The name is retained (not renamed to `register_account_for_test`)
    /// for backward compatibility with the workspace's existing
    /// integration test suite, which calls this method through the
    /// public API surface. `#[doc(hidden)]` removes it from `cargo doc`
    /// output so downstream consumers do not see it as a documented
    /// part of the surface.
    #[doc(hidden)]
    pub fn register_account(&self, account_id: &Id) {
        debug_assert!(
            !account_id.as_ref().is_empty(),
            "register_account: account_id must not be the empty string \
             (RFC 8620 §1.2, bd:JMAP-dx0s)"
        );
        let mut inner = self.inner.lock_unscoped();
        inner.known_accounts.insert(account_id.as_ref().to_owned());
        inner.aux.entry(account_id.as_ref().to_owned()).or_default();
    }

    /// Seed a pre-existing object into the store without bumping the
    /// state counter or recording a change-log entry. Test-fixture setup
    /// only; registers `account_id` as known. Mirrors
    /// `jmap_mail_server::memory::MemoryBackend::seed_object`.
    ///
    /// `type_name` is the `TYPE_NAME` of a type this backend stores:
    /// `"TaskList"`, `"Task"`, or `"TaskNotification"`. A seeded Task's
    /// `taskListId` is counted in the [`TaskList`] reference index.
    ///
    /// # Panics
    ///
    /// If `type_name` is not one of the names above, or `value` is not a
    /// JSON object whose `id` string equals `id`.
    pub fn seed_object(
        &self,
        account_id: &Id,
        type_name: &'static str,
        id: &Id,
        value: serde_json::Value,
    ) {
        const KNOWN_TYPES: &[&str] = &[
            jmap_tasks_types::TaskList::TYPE_NAME,
            jmap_tasks_types::Task::TYPE_NAME,
            jmap_tasks_types::TaskNotification::TYPE_NAME,
        ];
        assert!(
            KNOWN_TYPES.contains(&type_name),
            "seed_object: type_name {type_name:?} is not one of the known \
             TYPE_NAME values {KNOWN_TYPES:?}"
        );
        let obj = value.as_object().unwrap_or_else(|| {
            panic!("seed_object: value must be a JSON object with an `id` field, got {value:?}")
        });
        let value_id = obj
            .get("id")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_else(|| {
                panic!(
                    "seed_object: value must contain an `id` string field; got value = {value:?}"
                )
            });
        assert_eq!(
            value_id,
            id.as_ref(),
            "seed_object: value's `id` field {value_id:?} does not match the \
             `id` argument {id:?}"
        );
        let account_id = account_id.as_ref();
        let mut inner = self.inner.lock_unscoped();
        inner.known_accounts.insert(account_id.to_owned());
        let list_id = if type_name == "Task" {
            Inner::task_list_id_of(&value)
        } else {
            None
        };
        let prev = inner
            .objects_mut(type_name, account_id)
            .insert(id.clone(), value);
        if type_name == "Task" {
            // If this id was already seeded, decrement its prior taskListId
            // refcount first to keep the index correct on re-seed.
            if let Some(old) = prev.as_ref() {
                inner.dec_task_ref(account_id, Inner::task_list_id_of(old));
            }
            inner.inc_task_ref(account_id, list_id);
        }
    }
}

// ---------------------------------------------------------------------------
// JmapBackend impl (read-side supertrait)
// ---------------------------------------------------------------------------

impl<C: MemoryCaller> JmapAccounts for MemoryBackend<C> {
    type Error = MemoryError;
    type CallerCtx = C;

    /// [`MemoryCaller::principal`].
    fn principal_id(caller: &C) -> Option<&Id> {
        caller.principal()
    }

    /// The info set by [`MemoryBackend::with_metadata_info`], the same for
    /// every account.
    fn metadata_info<O: JmapObject>(
        &self,
        _caller: &C,
        _account_id: &Id,
    ) -> Option<DataTypeMetadataInfo> {
        self.inner
            .lock_unscoped()
            .metadata_info
            .get(O::TYPE_NAME)
            .cloned()
    }

    async fn account_exists(&self, _caller: &C, account_id: &Id) -> Result<bool, Self::Error> {
        let inner = self.inner.lock().await;
        Ok(inner.known_accounts.contains(account_id.as_ref()))
    }
}

impl<C: MemoryCaller> JmapReads for MemoryBackend<C> {
    async fn get_objects<O: GetObject + Send + Sync>(
        &self,
        _caller: &C,
        account_id: &Id,
        ids: Option<&[Id]>,
        _properties: Option<&[String]>,
    ) -> Result<(Vec<O>, Vec<Id>), Self::Error> {
        let inner = self.inner.lock().await;
        let map = inner.objects_ref(O::TYPE_NAME, account_id.as_ref());

        // The deserialize error closure is shared by both branches.
        let deser_err = |e: serde_json::Error| {
            MemoryError::serde(format_args!("deserialize {}", O::TYPE_NAME), &e)
        };

        match ids {
            None => {
                // Collect every stored object; bail on the first deserialize
                // error via the standard `Result<Vec<_>, _>` collect idiom.
                let list = map
                    .map(|m| {
                        m.values()
                            .map(|val| O::deserialize(val).map_err(deser_err))
                            .collect::<Result<Vec<_>, _>>()
                    })
                    .transpose()?
                    .unwrap_or_default();
                Ok((list, vec![]))
            }
            Some(id_slice) => {
                // Two output vecs (found + not_found) — keep the explicit
                // loop, but use `?` instead of a manual `match Err { return }`.
                let mut found = Vec::new();
                let mut not_found = Vec::new();
                for id in id_slice {
                    match map.and_then(|m| m.get(id)) {
                        Some(val) => found.push(O::deserialize(val).map_err(deser_err)?),
                        None => not_found.push(id.clone()),
                    }
                }
                Ok((found, not_found))
            }
        }
    }

    async fn get_state<O: JmapObject + Send + Sync>(
        &self,
        _caller: &C,
        account_id: &Id,
    ) -> Result<State, Self::Error> {
        let inner = self.inner.lock().await;
        let n = inner.current_state(O::TYPE_NAME, account_id.as_ref());
        Ok(State::from(n.to_string()))
    }

    async fn get_changes<O: JmapObject + Send + Sync>(
        &self,
        _caller: &C,
        account_id: &Id,
        params: jmap_server::ChangesParams<'_>,
    ) -> Result<ChangesResult, BackendChangesError<Self::Error>> {
        let since_state = params.since_state;
        let max_changes = params.max_changes;
        // draft-ietf-jmap-metadata-05 §3: jmap_server::handle_changes has
        // already folded a `using` without the capability into this flag.
        let mode = if params.ignore_metadata_only_changes {
            MetadataOnlyChanges::Ignore
        } else {
            MetadataOnlyChanges::Report
        };
        let inner = self.inner.lock().await;

        let since_n: u64 = since_state
            .as_ref()
            .parse()
            .map_err(|_| BackendChangesError::CannotCalculate)?;

        let log = inner
            .change_log
            .get(O::TYPE_NAME)
            .and_then(|m| m.get(account_id.as_ref()))
            .map(Vec::as_slice)
            .unwrap_or(&[]);

        let mut relevant: Vec<&ChangeEntry> =
            log.iter().filter(|e| e.new_state > since_n).collect();

        let current_state = inner.current_state(O::TYPE_NAME, account_id.as_ref());

        // RFC 8620 §5.2: over maxChanges "the server SHOULD generate an
        // update to take the client to an intermediate state", and only
        // when "unable to calculate an intermediate state" return
        // cannotCalculateChanges. Whole entries are taken, oldest first,
        // while their ids fit; an entry's ids bound what it adds after the
        // dedup below. A metadata-only update under Ignore adds none: -05
        // §3.3 "Excluded ids do not count toward maxChanges". The first
        // entry alone over the limit has no intermediate state.
        let mut has_more = false;
        if let Some(max) = max_changes {
            let mut ids = 0u64;
            if let Some(cut) = relevant.iter().position(|e| {
                if !(mode == MetadataOnlyChanges::Ignore && e.is_metadata_only_update()) {
                    ids +=
                        (e.created.len() + e.updated.len() + e.destroyed.len() + e.restored.len())
                            as u64;
                }
                ids > max
            }) {
                if cut == 0 {
                    return Err(BackendChangesError::TooManyChanges { limit: max });
                }
                relevant.truncate(cut);
                has_more = true;
            }
        }
        let new_state = match relevant.last() {
            Some(e) if has_more => e.new_state,
            _ => current_state,
        };

        // RFC 8620 §5.2 ID deduplication across the window, using the
        // canonical jmap-mail-server `IdFate` rules. `order` keeps first-seen
        // order so the response lists are deterministic.
        let mut fates: HashMap<Id, IdFate> = HashMap::new();
        let mut order: Vec<Id> = Vec::new();
        let mut window_props = ChangedProperties::new();
        for entry in &relevant {
            for id in &entry.created {
                if fates.insert(id.clone(), IdFate::Created).is_none() {
                    order.push(id.clone());
                }
            }
            for id in &entry.updated {
                window_props.record(id.as_ref(), entry.updated_props.as_ref());
                let fate = match fates.get(id) {
                    Some(IdFate::Created) => IdFate::Created,
                    Some(IdFate::Destroyed) => IdFate::Destroyed,
                    _ => IdFate::Updated,
                };
                if fates.insert(id.clone(), fate).is_none() {
                    order.push(id.clone());
                }
            }
            for id in &entry.destroyed {
                // "If a record has been created AND destroyed since the old
                // state, the server SHOULD remove the id from the response
                // entirely." (RFC 8620 §5.2)
                if matches!(fates.get(id), Some(IdFate::Created)) {
                    fates.remove(id);
                } else if fates.insert(id.clone(), IdFate::Destroyed).is_none() {
                    order.push(id.clone());
                }
            }
        }

        // Object history -04 §5.1: an id restored in the window is
        // classified by whether it existed at sinceState and exists now,
        // "exactly as if the object had never been destroyed between them".
        let mut events: HashMap<Id, Vec<ChangeEvent>> = HashMap::new();
        for entry in &relevant {
            for (ids, event) in [
                (&entry.created, ChangeEvent::Created),
                (&entry.updated, ChangeEvent::Updated),
                (&entry.destroyed, ChangeEvent::Destroyed),
                (&entry.restored, ChangeEvent::Restored),
            ] {
                for id in ids {
                    events.entry(id.clone()).or_default().push(event);
                }
            }
        }
        for (id, list) in &events {
            if !list.contains(&ChangeEvent::Restored) {
                continue;
            }
            let fate = match fold_restore(list) {
                Some(ChangeKind::Created) => IdFate::Created,
                Some(ChangeKind::Destroyed) => IdFate::Destroyed,
                Some(_) => {
                    // A restore is never metadata-only.
                    window_props.record(id.as_ref(), None);
                    IdFate::Updated
                }
                None => {
                    fates.remove(id);
                    continue;
                }
            };
            if fates.insert(id.clone(), fate).is_none() {
                order.push(id.clone());
            }
        }

        let mut created: Vec<Id> = Vec::new();
        let mut updated: Vec<Id> = Vec::new();
        let mut destroyed: Vec<Id> = Vec::new();
        // `fates.remove` emits each id once and skips ids omitted above.
        for id in order {
            match fates.remove(&id) {
                Some(IdFate::Created) => created.push(id),
                // -05 §3.3: under Ignore, "exclude from the updated array
                // any id whose only changes since sinceState ... are
                // confined to metadata and/or privateMetadata".
                Some(IdFate::Updated)
                    if mode == MetadataOnlyChanges::Ignore
                        && window_props.is_metadata_only(id.as_ref()) => {}
                Some(IdFate::Updated) => updated.push(id),
                Some(IdFate::Destroyed) => destroyed.push(id),
                None => {}
            }
        }

        // -05 §3.3 `updatedProperties`; no tasks type has the RFC 8621
        // §2.2 count properties that only Mailbox/changes may list.
        let updated_properties = window_props.updated_properties(&updated, mode, &[]);
        Ok(ChangesResult::new(
            created,
            updated,
            destroyed,
            has_more,
            State::from(new_state.to_string()),
        )
        .with_updated_properties(updated_properties))
    }

    /// Returns the matching object ids in this account, sorted by id unless
    /// a Task sort says otherwise, paginated by `position` and `limit`.
    ///
    /// # Task sort
    ///
    /// A Task `sort` may use the docs/specs/jmap-tasks-local.md Sorting
    /// properties `id`, `uid`, `start`, `created` and `updated`, with no
    /// collation or `i;octet`, `i;ascii-casemap` or `i;unicode-casemap`
    /// (applied to `id` and `uid`). Ties are broken by id; a task without
    /// the sort property comes after the tasks with it in ascending order.
    /// With no time-zone database, `start` is compared as a `LocalDateTime`
    /// string and the call is `unsupportedSort` when the matched tasks
    /// with a `start` are in more than one zone (a floating task counts as
    /// the query's zone, here `Etc/UTC`). Any other sort property, and any
    /// sort of another type, is `unsupportedSort`.
    ///
    /// # Filter and other sorts are NOT honored
    ///
    /// This reference implementation supports exactly one filter shape: a
    /// single Task condition whose only set fields are `inTaskLists` (which
    /// the `TaskList/set` `onDestroyRemoveTasks` cascade, draft-tasks-06
    /// §3.4, needs), `workflowStatus`, `progress`, `after` and `before`
    /// (jmapio/jmap #456; see [`TasksBackend::query_tasks`] for the
    /// time-zone limit; here the query zone is `Etc/UTC`), and the
    /// draft-ietf-jmap-metadata-05
    /// §3.6 shared-metadata conditions once [`MemoryBackend::with_metadata_info`]
    /// opts Task in. It does **not** support any other filter, or any sort
    /// beyond the Task sort above. RFC 8620 §5.5 mandates that an unsupported `filter` produces
    /// `unsupportedFilter` at the method level, and an unsupported `sort`
    /// produces `unsupportedSort`. A production backend MUST inspect both
    /// arguments against the type's [`QueryObject`] supported sets and
    /// reject queries that exceed them.
    ///
    /// To prevent consumers copying the silent-drop shape into a real
    /// backend (a workspace test-integrity hazard documented in the
    /// `MemoryBackend` module rustdoc), this method **fails loud** when
    /// either argument is non-trivial:
    ///
    /// - `filter` is `Some` carrying any non-null field other than those
    ///   Task fields, or any operator tree it cannot evaluate → returns
    ///   [`BackendQueryError::Method`] carrying `unsupportedFilter`. A
    ///   metadata condition on a type that is not opted in is also
    ///   `unsupportedFilter`, and a malformed one `invalidArguments`
    ///   (draft-ietf-jmap-metadata-05 §3.6).
    /// - `sort` is `Some` with a comparator other than the Task sort above
    ///   → returns [`BackendQueryError::Method`] carrying `unsupportedSort`.
    ///
    /// Callers that want "all objects in this account" pass
    /// `filter = None`, `sort = None`.
    ///
    /// Mirrors the reference-impl correctness teaching applied to the
    /// isDraft re-check in `update_object` (bd:JMAP-h47t.4): the demo
    /// backend models the spec invariant rather than the spec-violating
    /// shortcut.
    async fn query_objects<O: QueryObject + Send + Sync>(
        &self,
        caller: &C,
        account_id: &Id,
        params: QueryParams<'_, O>,
    ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
        self.query_impl(caller, account_id, params, &TaskQueryArgs::default())
            .await
    }

    /// Returns the changes to a `/query` result set since `since_query_state`.
    ///
    /// RFC 8620 §5.6: `/queryChanges` reports changes to the results of
    /// the same query, so `filter` and `sort` are those of the original
    /// `/query` and are applied by re-running [`Self::query_objects`]
    /// (a filter it refuses fails here the same way). `removed` holds the
    /// destroyed ids and the updated ids that no longer match (a Task moved
    /// out of the queried `inTaskLists`); `added` holds the created and
    /// updated ids that match now, with their index in the current result.
    /// Mirrors the canonical `jmap-mail-server` `MemoryBackend::query_changes`.
    async fn query_changes<O: QueryObject + Send + Sync>(
        &self,
        caller: &C,
        account_id: &Id,
        params: QueryChangesParams<'_, O>,
    ) -> Result<QueryChangesResult, BackendChangesError<Self::Error>> {
        let QueryChangesParams {
            since_query_state,
            filter,
            sort,
            max_changes,
            ..
        } = params;
        let changes = self
            .get_changes::<O>(
                caller,
                account_id,
                jmap_server::ChangesParams::new(since_query_state).max_changes(max_changes),
            )
            .await?;

        // The current result of the same query, unpaginated: `added`
        // indices are positions in it (RFC 8620 §5.6).
        let current = self
            .query_objects::<O>(
                caller,
                account_id,
                QueryParams::new().filter(filter).sort(sort),
            )
            .await
            .map_err(|e| match e {
                BackendQueryError::Other(e) => BackendChangesError::Other(e),
                // Changes to a query the server cannot run cannot be
                // calculated; the client's follow-up /query receives the
                // method error itself.
                _ => BackendChangesError::CannotCalculate,
            })?;
        let created_set: HashSet<&Id> = changes.created.iter().collect();
        let updated_set: HashSet<&Id> = changes.updated.iter().collect();

        // Every destroyed or updated id: an update may touch a filter or
        // sort property, so RFC 8620 §5.6 requires the id in `removed` and,
        // if it still matches, reinserted via `added`.
        let mut removed: Vec<Id> = changes
            .destroyed
            .iter()
            .chain(changes.updated.iter())
            .cloned()
            .collect();
        removed.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
        removed.dedup();

        // Created or updated ids that match the query now.
        let added: Vec<AddedItem> = current
            .ids
            .iter()
            .enumerate()
            .filter(|(_, id)| created_set.contains(id) || updated_set.contains(id))
            .map(|(pos, id)| AddedItem::new(id.clone(), pos as u64))
            .collect();

        Ok(QueryChangesResult::new(
            since_query_state.clone(),
            changes.new_state,
            current.total,
            removed,
            added,
        ))
    }
}

/// The `TYPE_NAME` of the type named `data_type` if it is one this backend
/// can give draft-ietf-jmap-metadata-05 properties: [`TaskList`], which has a
/// rights object (draft-ietf-jmap-tasks-06 §3 `myRights`), and Task, which
/// "takes the right from its containers" (-05 §4.1).
fn metadata_type_name(data_type: &str) -> Option<&'static str> {
    [TaskList::TYPE_NAME, Task::TYPE_NAME]
        .into_iter()
        .find(|t| *t == data_type)
}

fn invalid_metadata_property(property: &str, description: &str) -> BackendSetError<MemoryError> {
    BackendSetError::SetError(Box::new(
        SetError::new(SetErrorType::InvalidProperties)
            .with_properties([property])
            .with_description(description),
    ))
}

impl Inner {
    /// draft-ietf-jmap-metadata-05 §3.2 rules 1 to 3 for a metadata write
    /// on a `type_name` object, before the write is applied. Returns the
    /// type's [`DataTypeMetadataInfo`] for the rule 4 check after applying,
    /// or `None` when `entry` writes no metadata.
    ///
    /// `entry` is the create object or update patch, `stored` the object
    /// before an update (`None` on create), and `containers` the [`TaskList`]
    /// ids whose `maySetMetadata` a Task write needs (-05 §4.1). Rule 1's
    /// `notFound` is the caller's: this backend has no read rights, so
    /// only a missing object is unreadable.
    fn check_metadata_set(
        &self,
        type_name: &'static str,
        account_id: &str,
        kind: SetKind,
        entry: &serde_json::Map<String, serde_json::Value>,
        stored: Option<&serde_json::Map<String, serde_json::Value>>,
        containers: &[&str],
    ) -> Result<Option<DataTypeMetadataInfo>, BackendSetError<MemoryError>> {
        let Some(first) = entry.keys().find(|k| crate::helpers::is_metadata_key(k)) else {
            return Ok(None);
        };
        // -05 §1.2.1: an unlisted type "does not gain the metadata or
        // privateMetadata properties".
        let Some(info) = self.metadata_info.get(type_name) else {
            return Err(invalid_metadata_property(
                first,
                "metadata is not supported on this data type",
            ));
        };
        // Rule 1 / -05 §4.1: "A write to metadata without maySetMetadata
        // MUST be rejected with a "forbidden" SetError". A TaskList has
        // its own rights; a Task takes the right from its TaskList. An
        // absent right or container allows the write (fail-open,
        // JMAP-bghk).
        let writes_shared = entry.keys().any(|k| {
            crate::helpers::is_metadata_key(k)
                && k.split_once('/').map_or(k.as_str(), |(root, _)| root) == "metadata"
        });
        let denies = |rights: Option<&serde_json::Value>| {
            rights
                .and_then(|r| r.get("maySetMetadata"))
                .and_then(serde_json::Value::as_bool)
                == Some(false)
        };
        let forbidden = writes_shared
            && if type_name == TaskList::TYPE_NAME {
                denies(stored.and_then(|l| l.get("myRights")))
            } else {
                let lists = self.objects_ref(TaskList::TYPE_NAME, account_id);
                containers.iter().any(|id| {
                    denies(
                        lists
                            .and_then(|l| l.get(*id))
                            .and_then(|list| list.get("myRights")),
                    )
                })
            };
        if forbidden {
            return Err(BackendSetError::SetError(Box::new(
                SetError::new(SetErrorType::Forbidden)
                    .with_description("maySetMetadata is required to write metadata"),
            )));
        }
        check_metadata_write(kind, entry, stored, info)
            .map_err(|e| invalid_metadata_property(e.property(), e.description()))?;
        Ok(Some(info.clone()))
    }
}

/// The [`TaskList`] ids a Task update's metadata write needs `maySetMetadata`
/// on: the `TaskList` the Task is in before the update and the one `patch`
/// moves it to (-05 §4.1: "on every container both before and after the
/// change"). draft-ietf-jmap-tasks-06 §4: a Task belongs to exactly one
/// `TaskList`, named by the string `taskListId`.
fn task_update_containers<'a>(
    stored: &'a serde_json::Map<String, serde_json::Value>,
    patch: &'a serde_json::Map<String, serde_json::Value>,
) -> Vec<&'a str> {
    [stored.get("taskListId"), patch.get("taskListId")]
        .into_iter()
        .flatten()
        .filter_map(serde_json::Value::as_str)
        .collect()
}

/// draft-ietf-jmap-metadata-05 §3.2 checks for a created object `val` of
/// type `type_name`: rules 1 to 3 on the metadata properties of
/// `supplied`, the create object, then rule 4 on the values it supplied as
/// stored in `val`. A `Foo/set` create passes `val` as both; a `/copy`
/// passes its create object, so the copied values are not revalidated
/// (-05 §3.4: "maxDepth applies only to values supplied in the create
/// object"). A Task needs `maySetMetadata` on the [`TaskList`] of
/// its `taskListId` (-05 §4.1: "on create, on the containers given in the
/// create"). Types without the -05 properties pass unchecked.
fn check_metadata_create(
    inner: &Inner,
    type_name: &'static str,
    account_id: &str,
    supplied: &serde_json::Value,
    val: &serde_json::Value,
) -> Result<(), BackendSetError<MemoryError>> {
    let (Some(type_name), Some(supplied), Some(obj)) = (
        metadata_type_name(type_name),
        supplied.as_object(),
        val.as_object(),
    ) else {
        return Ok(());
    };
    let entry: serde_json::Map<String, serde_json::Value> = supplied
        .iter()
        .filter(|(k, _)| is_metadata_property(k))
        .map(|(k, v)| (k.clone(), v.clone()))
        .collect();
    let containers: Vec<&str> = if type_name == Task::TYPE_NAME {
        obj.get("taskListId")
            .and_then(serde_json::Value::as_str)
            .into_iter()
            .collect()
    } else {
        Vec::new()
    };
    if let Some(info) = inner.check_metadata_set(
        type_name,
        account_id,
        SetKind::Create,
        &entry,
        None,
        &containers,
    )? {
        check_metadata_depth(&entry, obj, &info)
            .map_err(|e| invalid_metadata_property(e.property(), e.description()))?;
    }
    Ok(())
}

/// The six draft-ietf-jmap-metadata-05 §3.6 `FilterCondition` fields.
const METADATA_CONDITION_KEYS: [&str; 6] = [
    "metadataExists",
    "privateMetadataExists",
    "metadataTextContains",
    "privateMetadataTextContains",
    "metadataTextEquals",
    "privateMetadataTextEquals",
];

/// The three -05 §3.6 conditions on shared `metadata` that this backend
/// evaluates; the `privateMetadata*` three never pass
/// [`check_metadata_filter`] because `supportsPrivate` is false.
const SHARED_METADATA_CONDITION_KEYS: [&str; 3] = [
    "metadataExists",
    "metadataTextContains",
    "metadataTextEquals",
];

/// The Task `FilterCondition` properties this backend evaluates (jmapio/jmap
/// #456), besides the shared-metadata ones; any other set property is
/// `unsupportedFilter`.
const TASK_CONDITION_KEYS: [&str; 5] = [
    "inTaskLists",
    "workflowStatus",
    "progress",
    "after",
    "before",
];

/// Whether the stored Task `task` matches `c`, the conditions in
/// [`TASK_CONDITION_KEYS`] and the shared-metadata ones; `query_zone` is
/// the Task/query `timeZone`.
///
/// `after` / `before` follow [`TaskFilterCondition`]: the task's end is its
/// `due` (or `start`), its beginning its `start` (or `due`), and a task
/// with neither matches neither. This backend has no time-zone database,
/// so it compares local times only when the task is floating or in
/// `query_zone`, where both read in the same zone and the fixed-width
/// RFC 8984 `LocalDateTime` strings order as the times do. A task in
/// another zone makes the query `unsupportedFilter` (RFC 8620 §5.5: the
/// server "cannot process the given filter").
fn task_matches(
    c: &TaskFilterCondition,
    task: &serde_json::Value,
    query_zone: &str,
) -> Result<bool, BackendQueryError<MemoryError>> {
    let str_of = |key: &str| task.get(key).and_then(serde_json::Value::as_str);
    if let Some(lists) = &c.in_task_lists
        && !str_of("taskListId").is_some_and(|l| lists.iter().any(|id| id.as_ref() == l))
    {
        return Ok(false);
    }
    if let Some(status) = &c.workflow_status
        && str_of("workflowStatus") != Some(status.as_str())
    {
        return Ok(false);
    }
    if let Some(progress) = &c.progress
        && str_of("progress") != Some(progress.as_str())
    {
        return Ok(false);
    }
    if c.after.is_some() || c.before.is_some() {
        if str_of("timeZone").is_some_and(|z| z != query_zone) {
            let mut err = JmapError::unsupported_filter();
            err.description = Some(
                "after/before on a task in another time zone needs a time-zone database".to_owned(),
            );
            return Err(BackendQueryError::Method(err));
        }
        let (start, due) = (str_of("start"), str_of("due"));
        if let Some(after) = &c.after
            && !due.or(start).is_some_and(|end| end > after.as_ref())
        {
            return Ok(false);
        }
        if let Some(before) = &c.before
            && !start.or(due).is_some_and(|begin| begin < before.as_ref())
        {
            return Ok(false);
        }
    }
    Ok(metadata_matches(
        task.get("metadata").and_then(serde_json::Value::as_object),
        c.metadata_exists.as_deref(),
        c.metadata_text_contains.as_ref(),
        c.metadata_text_equals.as_ref(),
    ))
}

/// The Task/query sort as [`TaskComparator`]s, checked against what this
/// backend can evaluate: the docs/specs/jmap-tasks-local.md Sorting
/// properties ("MUST be supported for sorting: `id`, `uid`, `start`. The
/// following SHOULD be supported: `created`, `updated`."), with no
/// collation or one of [`text_cmp`]'s. Anything else is `unsupportedSort`
/// (RFC 8620 §5.5).
fn task_sort<C: serde::Serialize>(
    sort: &[C],
) -> Result<Vec<TaskComparator>, BackendQueryError<MemoryError>> {
    sort.iter()
        .map(|c| {
            let v = jmap_server::serialize_value(c).map_err(BackendQueryError::Method)?;
            let c: TaskComparator = serde_json::from_value(v)
                .map_err(|e| BackendQueryError::Method(JmapError::server_fail(e.to_string())))?;
            let known = matches!(
                c.property,
                TaskComparatorProperty::Id
                    | TaskComparatorProperty::Uid
                    | TaskComparatorProperty::Start
                    | TaskComparatorProperty::Created
                    | TaskComparatorProperty::Updated
            );
            if known && text_cmp(c.collation.as_deref(), "", "").is_some() {
                Ok(c)
            } else {
                Err(BackendQueryError::Method(JmapError::unsupported_sort()))
            }
        })
        .collect()
}

/// String comparison under a supported RFC 4790 collation (`None` is
/// `i;octet`); `None` back for any other collation.
fn text_cmp(collation: Option<&str>, a: &str, b: &str) -> Option<Ordering> {
    match collation {
        None | Some("i;octet") => Some(a.cmp(b)),
        Some("i;ascii-casemap") => Some(a.to_ascii_lowercase().cmp(&b.to_ascii_lowercase())),
        Some("i;unicode-casemap") => Some(a.to_lowercase().cmp(&b.to_lowercase())),
        Some(_) => None,
    }
}

/// Sorting by `start` "orders tasks by the absolute time they start, not
/// by the lexical value of `start`; a floating task's start is read in the
/// `timeZone` argument" (docs/specs/jmap-tasks-local.md Sorting). With no
/// time-zone database the backend can do that only by comparing `start`
/// values that are all in one zone (a task's `timeZone`, or `query_zone`
/// when it floats); tasks in several zones are `unsupportedSort`.
fn check_one_start_zone(
    matched: &[(&Id, &serde_json::Value)],
    query_zone: &str,
) -> Result<(), BackendQueryError<MemoryError>> {
    let mut zones = matched
        .iter()
        .filter(|(_, t)| t.get("start").is_some_and(serde_json::Value::is_string))
        .map(|(_, t)| {
            t.get("timeZone")
                .and_then(serde_json::Value::as_str)
                .unwrap_or(query_zone)
        });
    let first = zones.next();
    if zones.any(|z| Some(z) != first) {
        let mut err = JmapError::unsupported_sort();
        err.description = Some(
            "sorting tasks in several time zones by start needs a time-zone database".to_owned(),
        );
        return Err(BackendQueryError::Method(err));
    }
    Ok(())
}

/// Order two matched Tasks by `comparators` (from [`task_sort`]), then by
/// id so the order is stable (RFC 8620 §5.5). A task without the sort
/// property comes after every task with it in ascending order (the spec
/// leaves this open). `start` compares as a `LocalDateTime` string, which
/// [`check_one_start_zone`] made safe; `created` and `updated` compare as
/// `UTCDate`s with the trailing `Z` (RFC 8620 §1.4) dropped, so a
/// fractional-second value sorts after the whole second.
fn compare_tasks(
    comparators: &[TaskComparator],
    (a_id, a): &(&Id, &serde_json::Value),
    (b_id, b): &(&Id, &serde_json::Value),
) -> Ordering {
    for c in comparators {
        let text = |id: &Id, t: &serde_json::Value| -> Option<String> {
            let s = |k: &str| t.get(k).and_then(serde_json::Value::as_str);
            match c.property {
                TaskComparatorProperty::Id => Some(id.as_ref().to_owned()),
                TaskComparatorProperty::Uid => s("uid").map(str::to_owned),
                TaskComparatorProperty::Start => s("start").map(str::to_owned),
                TaskComparatorProperty::Created => {
                    s("created").map(|v| v.trim_end_matches('Z').to_owned())
                }
                TaskComparatorProperty::Updated => {
                    s("updated").map(|v| v.trim_end_matches('Z').to_owned())
                }
                _ => None,
            }
        };
        let is_text = matches!(
            c.property,
            TaskComparatorProperty::Id | TaskComparatorProperty::Uid
        );
        let ord = match (text(a_id, a), text(b_id, b)) {
            (Some(x), Some(y)) if is_text => {
                text_cmp(c.collation.as_deref(), &x, &y).unwrap_or(Ordering::Equal)
            }
            (Some(x), Some(y)) => x.cmp(&y),
            (Some(_), None) => Ordering::Less,
            (None, Some(_)) => Ordering::Greater,
            (None, None) => Ordering::Equal,
        };
        let ord = if c.is_ascending { ord } else { ord.reverse() };
        if ord != Ordering::Equal {
            return ord;
        }
    }
    a_id.as_ref().cmp(b_id.as_ref())
}

/// `true` when the stored Task `task` recurs: it has a non-empty
/// `recurrenceRules` or `recurrenceOverrides` (RFC 8984 §4.3).
fn is_recurring(task: &serde_json::Value) -> bool {
    let non_empty = |key: &str| match task.get(key) {
        Some(serde_json::Value::Array(a)) => !a.is_empty(),
        Some(serde_json::Value::Object(o)) => !o.is_empty(),
        _ => false,
    };
    non_empty("recurrenceRules") || non_empty("recurrenceOverrides")
}

/// Validate the draft-ietf-jmap-metadata-05 §3.6 conditions on every leaf
/// of `filter`, a `FilterCondition` or `FilterOperator` tree (RFC 8620 §5.5),
/// before any object is matched.
///
/// A type without `info` has no metadata (-05 §1.2.1: it "does not gain
/// the metadata or privateMetadata properties"), so a metadata leaf is
/// `unsupportedFilter` (RFC 8620 §5.5: "The filter is syntactically valid,
/// but the server cannot process it"). Otherwise
/// [`MetadataCondition::take_from`] applies -05 §3.6: a malformed path is
/// `invalidArguments`, and a `privateMetadata*` condition is
/// `unsupportedFilter` because `supportsPrivate` is false.
fn check_metadata_filter(
    filter: &serde_json::Value,
    info: Option<&DataTypeMetadataInfo>,
) -> Result<(), BackendQueryError<MemoryError>> {
    let unsupported = |description: String| {
        let mut err = JmapError::unsupported_filter();
        err.description = Some(description);
        BackendQueryError::Method(err)
    };
    if filter.get("operator").is_some() {
        return filter
            .get("conditions")
            .and_then(serde_json::Value::as_array)
            .into_iter()
            .flatten()
            .try_for_each(|f| check_metadata_filter(f, info));
    }
    let Some(leaf) = filter.as_object() else {
        return Ok(());
    };
    if !METADATA_CONDITION_KEYS
        .iter()
        .any(|k| leaf.get(*k).is_some_and(|v| !v.is_null()))
    {
        return Ok(());
    }
    let Some(info) = info else {
        return Err(unsupported(
            "metadata filter conditions are not supported".to_owned(),
        ));
    };
    MetadataCondition::take_from(&mut leaf.clone(), info)
        .map(drop)
        .map_err(|e| match e {
            MetadataFilterError::InvalidArguments(d) => {
                BackendQueryError::Method(JmapError::invalid_arguments(d))
            }
            other => unsupported(other.to_string()),
        })
}

/// Match the draft-ietf-jmap-metadata-05 §3.6 shared-metadata conditions of
/// one filter leaf against an object's `metadata` (absent means `{}`, -05
/// §2). The `privateMetadata*` conditions never reach this point:
/// [`check_metadata_filter`] rejects them, since this backend has
/// `supportsPrivate` false.
fn metadata_matches(
    metadata: Option<&serde_json::Map<String, serde_json::Value>>,
    exists: Option<&str>,
    contains: Option<&MetadataTextMatch>,
    equals: Option<&MetadataTextMatch>,
) -> bool {
    let empty = serde_json::Map::new();
    let metadata = metadata.unwrap_or(&empty);
    exists.is_none_or(|p| metadata_path_exists(metadata, p))
        && contains.is_none_or(|m| metadata_text_contains(metadata, m))
        && equals.is_none_or(|m| metadata_text_equals(metadata, m))
}

/// Rebuild `obj` with `id` as its `id` property, for a `/copy` that
/// stores a record read from another account under a new id.
fn with_id<O: SetObject>(obj: &O, id: &Id) -> Result<O, BackendSetError<MemoryError>> {
    let mut val = serde_json::to_value(obj)
        .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize copied object", &e)))?;
    if let Some(map) = val.as_object_mut() {
        map.insert(
            "id".to_owned(),
            serde_json::Value::String(id.as_ref().to_owned()),
        );
    }
    serde_json::from_value(val)
        .map_err(|e| BackendSetError::Other(MemoryError::serde("deserialize copied object", &e)))
}

impl<C: MemoryCaller> MemoryBackend<C> {
    /// Store the object `build` returns for a new id in `account_id`: the
    /// body of [`TasksBackend::create_object`] and
    /// [`TasksBackend::copy_object`]. `supplied` is the `/copy` create
    /// object whose metadata is validated (-05 §3.4); `None` validates the
    /// stored object itself, as a `Foo/set` create does.
    async fn store_created<O: SetObject>(
        &self,
        account_id: &Id,
        build: impl FnOnce(&Id) -> Result<O, BackendSetError<MemoryError>>,
        supplied: Option<&serde_json::Value>,
    ) -> Result<(Id, O), BackendSetError<MemoryError>> {
        let server_id = Id::from(uuid::Uuid::new_v4().to_string());
        // Object history §5.1 covers Task/copy too: a fresh v4 UUID never
        // reuses a destroyed id.
        let mut stored_obj = build(&server_id)?;
        let mut val = serde_json::to_value(&stored_obj)
            .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize", &e)))?;

        let mut inner = self.inner.lock().await;
        // Decision 42 (workflowStatus and progress), under the lock so the
        // list's workflowStatuses cannot change in between.
        if O::TYPE_NAME == Task::TYPE_NAME
            && inner.apply_workflow(
                account_id.as_ref(),
                &mut val,
                crate::workflow::WorkflowWrite::Create,
            )?
        {
            stored_obj = O::deserialize(&val)
                .map_err(|e| BackendSetError::Other(MemoryError::serde("deserialize", &e)))?;
        }
        debug_assert!(!inner.history_retains(O::TYPE_NAME, account_id, &server_id));
        check_metadata_create(
            &inner,
            O::TYPE_NAME,
            account_id.as_ref(),
            supplied.unwrap_or(&val),
            &val,
        )?;
        inner.require_account(account_id.as_ref())?;

        let task_list_id = if O::TYPE_NAME == "Task" {
            Inner::task_list_id_of(&val)
        } else {
            None
        };

        let new_state = inner.bump_state(O::TYPE_NAME, account_id.as_ref());
        inner
            .objects_mut(O::TYPE_NAME, account_id.as_ref())
            .insert(server_id.clone(), val);
        inner
            .change_log_mut(O::TYPE_NAME, account_id.as_ref())
            .push(ChangeEntry {
                new_state,
                created: vec![server_id.clone()],
                updated: vec![],
                destroyed: vec![],
                restored: vec![],
                updated_props: None,
            });

        if O::TYPE_NAME == "Task" {
            inner.inc_task_ref(account_id.as_ref(), task_list_id);
        }

        Ok((server_id, stored_obj))
    }
}

// ---------------------------------------------------------------------------
// TasksBackend impl
// ---------------------------------------------------------------------------

impl<C: MemoryCaller> MemoryBackend<C> {
    /// The body of [`JmapReads::query_objects`] and
    /// [`TasksBackend::query_tasks`]; `task_args` applies to Task only.
    async fn query_impl<O: QueryObject + Send + Sync>(
        &self,
        caller: &C,
        account_id: &Id,
        params: QueryParams<'_, O>,
        task_args: &TaskQueryArgs,
    ) -> Result<QueryResult, BackendQueryError<MemoryError>> {
        let QueryParams {
            filter,
            sort,
            limit,
            position,
            anchor,
            anchor_offset,
            ..
        } = params;
        // Fail loud on any non-trivial filter. A `None` or all-fields-None
        // filter passes (matches everything); any populated field this
        // backend cannot evaluate, and any operator tree, is answered with
        // `unsupportedFilter` (RFC 8620 §5.5: "A server MUST reject the call
        // with an unsupportedFilter error if it cannot process the given
        // filter").
        //
        // The generic `O::Filter` is the concrete `TaskFilter`,
        // `TaskNotificationFilter` or (TaskList) `Value` here. A serializer
        // failure surfaces as serverFail rather than a panic or a silently
        // dropped filter (see the jmap-mail-server memory backend).
        //
        // draft-ietf-jmap-metadata-05 §3.6: on an opted-in Task the shared
        // `metadata*` conditions are evaluable in the same leaf;
        // [`check_metadata_filter`] validates them first, also inside an
        // operator tree, so a malformed path is `invalidArguments`.
        let inner = self.inner.lock().await;
        let is_task = O::TYPE_NAME == Task::TYPE_NAME;
        let mut task_condition: Option<TaskFilterCondition> = None;
        if let Some(f) = filter {
            let v = jmap_server::serialize_value(f).map_err(BackendQueryError::Method)?;
            check_metadata_filter(&v, inner.metadata_info.get(O::TYPE_NAME))?;
            if v.get("operator").is_some() {
                return Err(BackendQueryError::Method(JmapError::unsupported_filter()));
            }
            let any_field_set = match v.as_object() {
                Some(m) => m.iter().any(|(k, val)| {
                    !val.is_null()
                        && !(is_task
                            && (TASK_CONDITION_KEYS.contains(&k.as_str())
                                || SHARED_METADATA_CONDITION_KEYS.contains(&k.as_str())))
                }),
                // Filter serialized as something other than an object (only
                // possible for TaskList's untyped `Value`): treat as
                // non-trivial.
                None => true,
            };
            if any_field_set {
                return Err(BackendQueryError::Method(JmapError::unsupported_filter()));
            }
            if is_task {
                task_condition = Some(serde_json::from_value(v).map_err(|e| {
                    BackendQueryError::Method(JmapError::server_fail(e.to_string()))
                })?);
            }
        }

        // Task sorts by the local profile's properties (task_sort); any
        // other type's non-empty sort fails loud, RFC 8620 §5.5: "A server
        // MUST reject the call with an unsupportedSort error if it cannot
        // sort by the given properties."
        let comparators = match sort.filter(|s| !s.is_empty()) {
            None => Vec::new(),
            Some(s) if is_task => task_sort(s)?,
            Some(_) => return Err(BackendQueryError::Method(JmapError::unsupported_sort())),
        };

        let query_zone = task_args.time_zone.as_deref().unwrap_or("Etc/UTC");
        let mut matched: Vec<(&Id, &serde_json::Value)> = Vec::new();
        if let Some(objects) = inner.objects_ref(O::TYPE_NAME, account_id.as_ref()) {
            for (id, v) in objects {
                let keep = match &task_condition {
                    None => true,
                    Some(c) => task_matches(c, v, query_zone)?,
                };
                if keep {
                    matched.push((id, v));
                }
            }
        }

        if is_task && task_args.expand_recurrences {
            // TasksBackend::query_tasks: the backend re-checks the
            // maxExpandedQueryDuration cap the handler pre-checked.
            let too_long = task_condition
                .as_ref()
                .and_then(crate::task::expand_duration_seconds)
                .is_some_and(|secs| {
                    u64::try_from(secs).is_ok_and(|secs| {
                        secs > self
                            .limits(caller, account_id)
                            .max_expanded_query_duration_seconds
                    })
                });
            if too_long {
                return Err(BackendQueryError::Method(JmapError::custom(
                    "expandDurationTooLarge",
                )));
            }
            // No recurrence engine: a non-recurring task is its own single
            // instance, so its id stands; a recurring one cannot be expanded.
            if matched.iter().any(|(_, v)| is_recurring(v)) {
                return Err(BackendQueryError::Method(JmapError::custom(
                    "cannotCalculateOccurrences",
                )));
            }
        }

        if comparators
            .iter()
            .any(|c| c.property == TaskComparatorProperty::Start)
        {
            check_one_start_zone(&matched, query_zone)?;
        }
        matched.sort_by(|a, b| compare_tasks(&comparators, a, b));
        let ids: Vec<Id> = matched.into_iter().map(|(k, _)| k.clone()).collect();

        let total = ids.len() as u64;
        let query_state = State::from(
            inner
                .current_state(O::TYPE_NAME, account_id.as_ref())
                .to_string()
                .as_str(),
        );

        // RFC 8620 §5.5 position / anchor / anchorOffset.
        let start = resolve_query_start(&ids, position, anchor, anchor_offset)
            .map_err(BackendQueryError::Method)?;

        let ids: Vec<Id> = ids[start..]
            .iter()
            .take(limit_or_max(limit))
            .cloned()
            .collect();

        Ok(QueryResult::new(
            ids,
            start as u64,
            Some(total),
            query_state,
            true,
        ))
    }
}

impl<C: MemoryCaller> TasksBackend for MemoryBackend<C> {
    async fn create_object<O, F>(
        &self,
        _caller: &C,
        account_id: &Id,
        _create_id: &str,
        build: F,
    ) -> Result<(Id, O), BackendSetError<Self::Error>>
    where
        O: SetObject + Send + Sync,
        F: FnOnce(&Id) -> O + Send,
    {
        self.store_created(account_id, |id| Ok(build(id)), None)
            .await
    }

    async fn copy_object<O: SetObject + Send + Sync>(
        &self,
        _caller: &C,
        _from_account_id: &Id,
        to_account_id: &Id,
        obj: O,
        create: &serde_json::Value,
    ) -> Result<(Id, O), BackendSetError<Self::Error>> {
        // -05 §3.4: the create object's metadata follows the Foo/set create
        // rules; the copied values are not revalidated.
        self.store_created(to_account_id, |id| with_id(&obj, id), Some(create))
            .await
    }

    async fn update_object<O: SetObject + Send + Sync>(
        &self,
        _caller: &C,
        account_id: &Id,
        id: &Id,
        patch: O::Patch,
    ) -> Result<Option<O>, BackendSetError<Self::Error>> {
        let patch_val = serde_json::to_value(&patch)
            .map_err(|e| BackendSetError::Other(MemoryError::serde("serialize patch", &e)))?;
        let invalid_patch = |e: PatchPathError| {
            BackendSetError::SetError(Box::new(
                SetError::new(SetErrorType::InvalidPatch).with_description(e.to_string()),
            ))
        };
        // draft-ietf-jmap-metadata-05 §3.2: "Patch errors that can be
        // determined from the request alone (for example, two paths where
        // one is a prefix of the other) MUST be reported with
        // "invalidPatch" before rule 1 is evaluated."
        if let serde_json::Value::Object(patch_map) = &patch_val {
            check_patch_paths(patch_map).map_err(invalid_patch)?;
        }

        let mut inner = self.inner.lock().await;
        inner.require_account_for_target(account_id.as_ref())?;

        // -05 §3.2 rule 1: "If the user cannot read the related object,
        // reject with "notFound"" comes before "forbidden". Here only a
        // missing object is unreadable.
        let existing = inner
            .objects_mut(O::TYPE_NAME, account_id.as_ref())
            .get(id)
            .cloned();

        let Some(mut current) = existing else {
            return Err(BackendSetError::SetError(Box::new(SetError::new(
                SetErrorType::NotFound,
            ))));
        };
        // Object history: the version this update replaces.
        let previous = current.clone();

        let was_draft = current.get("isDraft").and_then(|v| v.as_bool()) == Some(true);

        // Snapshot the pre-patch taskListId so the refcount update below
        // can compute the (old → new) transition without re-fetching after
        // the patch applies.
        let old_task_list_id = if O::TYPE_NAME == "Task" {
            Inner::task_list_id_of(&current)
        } else {
            None
        };

        // JMAP patch (RFC 8620 §5.3): keys are JSON Pointer paths (e.g.
        // "participants/p1/participationStatus"), applied all-or-nothing by
        // the shared `apply_patch_object`, so an invalidPatch leaves the
        // stored object unchanged. Values replace wholesale; the helper caps
        // path plus value nesting depth.
        let mut updated_props = None;
        if let (serde_json::Value::Object(base), serde_json::Value::Object(patch_map)) =
            (&mut current, &patch_val)
        {
            // -05 §3.2 rules 1 to 3 run before the patch is applied.
            let metadata_info = if metadata_type_name(O::TYPE_NAME).is_some() {
                let containers = if O::TYPE_NAME == Task::TYPE_NAME {
                    task_update_containers(base, patch_map)
                } else {
                    Vec::new()
                };
                inner.check_metadata_set(
                    O::TYPE_NAME,
                    account_id.as_ref(),
                    SetKind::Update,
                    patch_map,
                    Some(base),
                    &containers,
                )?
            } else {
                None
            };
            // -05 §2 `metadata` has "default: {}", so a
            // `metadata/<namespace>` pointer finds its parent.
            if metadata_info.is_some() {
                base.entry("metadata")
                    .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));
            }
            let before = base.clone();
            // The value-dependent patch errors (missing parent, path through
            // an array or a Binary value) land here, after rule 3 and before rule 4 (-05 §3.2).
            apply_patch_object(base, patch_map).map_err(invalid_patch)?;
            if let Some(info) = &metadata_info {
                // -05 §3.2: "In an update, null is equivalent to {}"; the
                // patch removed the property instead.
                for property in ["metadata", "privateMetadata"] {
                    if patch_map
                        .get(property)
                        .is_some_and(serde_json::Value::is_null)
                    {
                        base.insert(
                            property.to_owned(),
                            serde_json::Value::Object(serde_json::Map::new()),
                        );
                    }
                }
                // -05 §3.2 rule 4 runs on the value as it would be stored.
                check_metadata_depth(patch_map, base, info)
                    .map_err(|e| invalid_metadata_property(e.property(), e.description()))?;
            }
            updated_props = Some(changed_properties(&before, base));
        }

        // Re-validate the patched copy against the typed object before
        // storing: a null or wrong-typed value on a required property would
        // otherwise be persisted and make every later /get fail to
        // deserialize. Name the property when the patch touches only one.
        if let Err(e) = O::deserialize(&current) {
            let mut heads: Vec<String> = patch_val
                .as_object()
                .into_iter()
                .flat_map(|m| m.keys())
                .map(|k| {
                    let head = k.split('/').next().unwrap_or(k);
                    head.replace("~1", "/").replace("~0", "~")
                })
                .collect();
            heads.sort_unstable();
            heads.dedup();
            let mut err =
                SetError::new(SetErrorType::InvalidProperties).with_description(e.to_string());
            if heads.len() == 1 {
                err = err.with_properties(heads);
            }
            return Err(BackendSetError::SetError(Box::new(err)));
        }

        // Backend-side isDraft re-check (draft-ietf-jmap-tasks-06 §4 isDraft
        // paragraph): "This may only be set to true upon creation." Compare
        // the effective post-patch value against the stored one so that any
        // path to true (including a null patch followed by true) is rejected.
        // The handler does not pre-check this (bd:JMAP-h47t.29): workspace
        // AGENTS.md "Permission enforcement: backend canonical" makes the
        // backend the only enforcement point, atomically with the mutation.
        if O::TYPE_NAME == "Task"
            && !was_draft
            && current.get("isDraft").and_then(|v| v.as_bool()) == Some(true)
        {
            return Err(BackendSetError::SetError(Box::new(
                SetError::new(SetErrorType::InvalidProperties)
                    .with_properties(vec!["isDraft".to_owned()]),
            )));
        }

        // Decision 42 (workflowStatus and progress) on the patched Task,
        // atomically with the write.
        let mut echo = false;
        if O::TYPE_NAME == Task::TYPE_NAME {
            let written: Vec<String> = patch_val
                .as_object()
                .into_iter()
                .flat_map(|m| m.keys())
                .map(|k| {
                    let head = k.split('/').next().unwrap_or(k);
                    head.replace("~1", "/").replace("~0", "~")
                })
                .collect();
            let empty = serde_json::Map::new();
            let before = previous.as_object().unwrap_or(&empty);
            echo = inner.apply_workflow(
                account_id.as_ref(),
                &mut current,
                crate::workflow::WorkflowWrite::Update {
                    before,
                    written: &written,
                },
            )?;
        }

        let new_task_list_id = if O::TYPE_NAME == "Task" {
            Inner::task_list_id_of(&current)
        } else {
            None
        };
        let echoed = if echo {
            Some(
                O::deserialize(&current)
                    .map_err(|e| BackendSetError::Other(MemoryError::serde("deserialize", &e)))?,
            )
        } else {
            None
        };

        inner.record_replace(O::TYPE_NAME, account_id, id, previous);
        let new_state = inner.bump_state(O::TYPE_NAME, account_id.as_ref());
        inner
            .objects_mut(O::TYPE_NAME, account_id.as_ref())
            .insert(id.clone(), current);
        inner
            .change_log_mut(O::TYPE_NAME, account_id.as_ref())
            .push(ChangeEntry {
                new_state,
                created: vec![],
                updated: vec![id.clone()],
                destroyed: vec![],
                restored: vec![],
                updated_props,
            });

        if O::TYPE_NAME == "Task" && old_task_list_id != new_task_list_id {
            inner.dec_task_ref(account_id.as_ref(), old_task_list_id);
            inner.inc_task_ref(account_id.as_ref(), new_task_list_id);
        }

        Ok(echoed)
    }

    /// `Task/query` over the stored tasks.
    ///
    /// Evaluates `inTaskLists`, `workflowStatus`, `progress`, `after`,
    /// `before` and the shared-metadata conditions in one `FilterCondition`;
    /// anything else, and any operator tree, is `unsupportedFilter`, as is
    /// `after` / `before` on a task whose `timeZone` is not the query's
    /// (there is no time-zone database). With `expandRecurrences` the
    /// `maxExpandedQueryDuration` cap ([`TasksBackend::limits`]) is checked
    /// again; non-recurring matches keep their ids as their single
    /// instances, and a recurring match is `cannotCalculateOccurrences`,
    /// since there is no recurrence engine. Sorting is as in
    /// [`JmapReads::query_objects`], with `start` and floating tasks read
    /// in the `timeZone` argument.
    async fn query_tasks(
        &self,
        caller: &C,
        account_id: &Id,
        params: QueryParams<'_, Task>,
        args: &TaskQueryArgs,
    ) -> Result<QueryResult, BackendQueryError<Self::Error>> {
        self.query_impl(caller, account_id, params, args).await
    }

    async fn update_task_per_user(
        &self,
        caller: &C,
        account_id: &Id,
        id: &Id,
        patch: jmap_types::PatchObject,
    ) -> Result<Option<jmap_tasks_types::Task>, BackendSetError<Self::Error>> {
        // ponytail: single-user backend (every caller is the owner), so per-user state is
        // the shared object. `update_object` never writes `updated`, which
        // keeps draft-ietf-jmap-tasks-06 §4.5.1 intact. A multi-user backend
        // stores the patch per user instead.
        self.update_object::<jmap_tasks_types::Task>(caller, account_id, id, patch)
            .await
    }

    async fn destroy_object<O: SetObject + Send + Sync>(
        &self,
        _caller: &C,
        account_id: &Id,
        id: &Id,
    ) -> Result<(), BackendSetError<Self::Error>> {
        let mut inner = self.inner.lock().await;
        inner.require_account_for_target(account_id.as_ref())?;

        let removed = inner
            .objects_mut(O::TYPE_NAME, account_id.as_ref())
            .remove(id);

        match removed {
            Some(val) => {
                inner.record_destroy(O::TYPE_NAME, account_id, id, val.clone());
                let new_state = inner.bump_state(O::TYPE_NAME, account_id.as_ref());
                inner
                    .change_log_mut(O::TYPE_NAME, account_id.as_ref())
                    .push(ChangeEntry {
                        new_state,
                        created: vec![],
                        updated: vec![],
                        destroyed: vec![id.clone()],
                        restored: vec![],
                        updated_props: None,
                    });
                if O::TYPE_NAME == "Task" {
                    inner.dec_task_ref(account_id.as_ref(), Inner::task_list_id_of(&val));
                }
                Ok(())
            }
            None => Err(BackendSetError::SetError(Box::new(SetError::new(
                SetErrorType::NotFound,
            )))),
        }
    }

    fn supports_type<O: JmapObject>(&self, _caller: &C, _account_id: &jmap_types::Id) -> bool {
        matches!(O::TYPE_NAME, "TaskList" | "Task" | "TaskNotification")
    }

    async fn task_list_has_tasks(
        &self,
        _caller: &C,
        account_id: &Id,
        task_list_id: &Id,
    ) -> Result<bool, MemoryError> {
        let inner = self.inner.lock().await;
        Ok(inner
            .aux_ref(account_id.as_ref())
            .is_some_and(|a| a.task_list_refcount.contains_key(task_list_id)))
    }
}

// ---------------------------------------------------------------------------
// ConditionalBackend (draft-ietf-jmap-conditional-02)
// ---------------------------------------------------------------------------

/// Conditional tasks Foo/set (bd JMAP-y1yu.11): the whole store is one
/// [`ScopedState`], so a scope isolates every type in every account, and an
/// atomic rollback restores objects, state strings, change logs and the
/// derived per-account indexes together, `onDestroyRemoveTasks` cascades
/// included.
///
/// Commit checks nothing beyond what the handlers already check:
/// `taskListHasTask` is judged within one TaskList/set, which moves no
/// Tasks; draft-ietf-jmap-tasks-06 sets no uniqueness rule for [`TaskList`]
/// `role`; and this backend has no cross-object caps.
impl<C: MemoryCaller> ConditionalBackend for MemoryBackend<C> {
    async fn begin_set(
        &self,
        _caller: &C,
        request: SetScopeRequest<'_>,
    ) -> Result<Box<dyn SetScope>, BeginSetError<MemoryError>> {
        Ok(self
            .inner
            .open(request, |_: &Inner, _: &Inner| Vec::new())
            .await)
    }
}

#[cfg(test)]
mod memory_error_tests {
    use super::MemoryError;

    /// The `JmapAccounts::Error` contract: "Implementations MUST NOT
    /// include ... PII shaped like an email address" in `Display`
    /// output. serde_json data errors quote the offending value, so
    /// [`MemoryError::serde`] must drop the message (bd:JMAP-510h.37).
    #[test]
    fn serde_error_display_omits_offending_value() {
        let canary = "alice@example.com";
        let e = serde_json::from_value::<u64>(serde_json::Value::String(canary.into()))
            .expect_err("a string is not a u64");
        assert!(
            e.to_string().contains(canary),
            "precondition: serde_json quotes the value"
        );

        let shown = MemoryError::serde("decode", &e).to_string();
        assert!(!shown.contains(canary), "canary leaked: {shown}");
        assert!(
            shown.contains("decode") && shown.contains("Data"),
            "{shown}"
        );
    }
}

#[cfg(test)]
mod fixture_helper_tests {
    use super::*;
    use serde_json::json;

    /// `with_account` makes the account known (RFC 8620 §3.6.2: an
    /// unknown accountId is `accountNotFound`, so `account_exists` is the
    /// observable).
    #[tokio::test]
    async fn with_account_registers_account() {
        let acc = Id::from("acc1");
        let backend = MemoryBackend::<()>::default().with_account(&acc);
        assert!(backend.account_exists(&(), &acc).await.unwrap());
        assert!(
            !backend
                .account_exists(&(), &Id::from("acc2"))
                .await
                .unwrap()
        );
    }

    /// A seeded Task counts toward its TaskList's reference index.
    #[tokio::test]
    async fn seeded_task_marks_task_list_non_empty() {
        let acc = Id::from("acc1");
        let backend = MemoryBackend::<()>::default();
        backend.seed_object(
            &acc,
            "Task",
            &Id::from("t1"),
            json!({"id": "t1", "taskListId": "tl1"}),
        );
        assert!(
            backend
                .task_list_has_tasks(&(), &acc, &Id::from("tl1"))
                .await
                .unwrap()
        );
    }

    #[test]
    #[should_panic(expected = "not one of the known")]
    fn seed_object_rejects_unknown_type_name() {
        MemoryBackend::<()>::default().seed_object(
            &Id::from("acc1"),
            "Tasklist",
            &Id::from("tl1"),
            json!({"id": "tl1"}),
        );
    }

    /// A non-object value panics at the seed call instead of surfacing
    /// later as an opaque deserialize error from get_objects.
    #[test]
    #[should_panic(expected = "must be a JSON object")]
    fn seed_object_rejects_non_object_value() {
        MemoryBackend::<()>::default().seed_object(
            &Id::from("acc1"),
            "TaskList",
            &Id::from("tl1"),
            json!(42),
        );
    }

    /// A value without an `id` field panics instead of storing a fixture
    /// whose `id` is absent on read-back.
    #[test]
    #[should_panic(expected = "must contain an `id` string field")]
    fn seed_object_rejects_value_without_id_field() {
        MemoryBackend::<()>::default().seed_object(
            &Id::from("acc1"),
            "TaskList",
            &Id::from("tl1"),
            json!({"name": "Work"}),
        );
    }

    #[test]
    #[should_panic(expected = "does not match the `id` argument")]
    fn seed_object_rejects_id_mismatch() {
        MemoryBackend::<()>::default().seed_object(
            &Id::from("acc1"),
            "TaskList",
            &Id::from("tl1"),
            json!({"id": "tl2"}),
        );
    }
}

#[cfg(all(test, debug_assertions))]
mod empty_account_id_tests {
    use super::{Id, MemoryBackend};

    /// Oracle: RFC 8620 §1.2, an Id "is a String of at least 1 and a
    /// maximum of 255 octets in size" (bd:JMAP-dx0s).
    #[test]
    #[should_panic(expected = "account_id must not be the empty string")]
    fn register_account_rejects_empty_id() {
        MemoryBackend::<()>::default().register_account(&Id::from(""));
    }
}

#[cfg(test)]
mod changes_tests {
    use super::*;
    use jmap_tasks_types::Task;

    /// Oracle: RFC 8620 §5.2 /changes rules, expected lists written by hand.
    /// "If a record has been created AND destroyed since the old state, the
    /// server SHOULD remove the id from the response entirely"; a record
    /// created then updated is reported only in `created`; one updated then
    /// destroyed is reported only in `destroyed`.
    #[tokio::test]
    async fn get_changes_dedups_ids_across_window() {
        let backend = MemoryBackend::<()>::default();
        let id = |s: &str| Id::from(s);
        {
            let mut inner = backend.inner.lock_unscoped();
            let log = inner.change_log_mut(Task::TYPE_NAME, "acc1");
            log.push(ChangeEntry {
                new_state: 1,
                created: vec![id("eph"), id("fresh")],
                updated: vec![],
                destroyed: vec![],
                restored: vec![],
                updated_props: None,
            });
            log.push(ChangeEntry {
                new_state: 2,
                created: vec![],
                updated: vec![id("fresh"), id("old"), id("doomed")],
                destroyed: vec![id("eph")],
                restored: vec![],
                updated_props: None,
            });
            log.push(ChangeEntry {
                new_state: 3,
                created: vec![],
                updated: vec![id("old")],
                destroyed: vec![id("doomed"), id("gone")],
                restored: vec![],
                updated_props: None,
            });
        }

        let changes = backend
            .get_changes::<Task>(
                &(),
                &id("acc1"),
                jmap_server::ChangesParams::new(&State::from("0")),
            )
            .await
            .expect("get_changes must succeed");

        assert_eq!(changes.created, vec![id("fresh")]);
        assert_eq!(changes.updated, vec![id("old")]);
        assert_eq!(changes.destroyed, vec![id("doomed"), id("gone")]);
    }
}

#[cfg(test)]
mod max_changes_tests {
    use super::*;
    use jmap_tasks_types::Task as T;

    const CALLER: () = ();

    /// A backend whose `T` log holds one state per element of `states`,
    /// each creating the listed ids.
    fn with_creates(states: &[&[&str]]) -> MemoryBackend<()> {
        let backend = MemoryBackend::<()>::default();
        let mut inner = backend.inner.lock_unscoped();
        for ids in states {
            let new_state = inner.bump_state(T::TYPE_NAME, "acc1");
            inner
                .change_log_mut(T::TYPE_NAME, "acc1")
                .push(ChangeEntry {
                    new_state,
                    created: ids.iter().map(|s| Id::from(*s)).collect(),
                    updated: vec![],
                    destroyed: vec![],
                    restored: vec![],
                    updated_props: None,
                });
        }
        drop(inner);
        backend
    }

    /// Oracle: RFC 8620 §5.2, expected pages written by hand: "the server
    /// MUST ensure the number of ids returned across "created", "updated",
    /// and "destroyed" does not exceed this limit. If there are more
    /// changes than this ..., the server SHOULD generate an update to take
    /// the client to an intermediate state, from which the client can
    /// continue to call "Foo/changes" until it is fully up to date." Three
    /// one-create states against `maxChanges` 2 page as states 1-2, then 3.
    #[tokio::test]
    async fn over_max_changes_pages_through_intermediate_state() {
        let backend = with_creates(&[&["a"], &["b"], &["c"]]);

        let first = changes(&backend, "0", 2).await.expect("first page");
        assert_eq!(sorted(first.created), [Id::from("a"), Id::from("b")]);
        assert!(first.has_more_changes);
        assert_eq!(first.new_state.as_ref(), "2");

        let rest = changes(&backend, "2", 2).await.expect("second page");
        assert_eq!(rest.created, [Id::from("c")]);
        assert!(!rest.has_more_changes);
        assert_eq!(rest.new_state.as_ref(), "3");
    }

    /// Oracle: RFC 8620 §5.2 "If it is unable to calculate an intermediate
    /// state, it MUST return a "cannotCalculateChanges" error response
    /// instead." One state creating three ids cannot be split under
    /// `maxChanges` 2.
    #[tokio::test]
    async fn one_state_over_max_changes_cannot_calculate() {
        let backend = with_creates(&[&["a", "b", "c"]]);
        assert!(matches!(
            changes(&backend, "0", 2).await,
            Err(BackendChangesError::TooManyChanges { limit: 2 })
        ));
    }

    fn sorted(mut ids: Vec<Id>) -> Vec<Id> {
        ids.sort_by(|a, b| a.as_ref().cmp(b.as_ref()));
        ids
    }

    async fn changes(
        backend: &MemoryBackend<()>,
        since: &str,
        max: u64,
    ) -> Result<ChangesResult, BackendChangesError<<MemoryBackend<()> as JmapAccounts>::Error>>
    {
        backend
            .get_changes::<T>(
                &CALLER,
                &Id::from("acc1"),
                jmap_server::ChangesParams::new(&State::from(since)).max_changes(Some(max)),
            )
            .await
    }
}