jmap-tasks-server 0.6.0

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
//! Task/* method handlers (draft-tasks-06 §4).
//!
//! The `isDraft` immutability constraint (once false, never true again) is
//! enforced by [`crate::TasksBackend::update_object`], not by Task/set.
//!
//! # Wire-shape contract
//!
//! Every `handle_*` function in this module conforms to the canonical JMAP
//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
//! Object whose fields match the corresponding RFC 8620 §5 method shape
//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3, `/copy` → §5.4,
//! `/query` → §5.5, `/queryChanges` → §5.6), with the type-specific
//! arguments defined by draft-tasks-06 §4. The returned `Value` is the
//! corresponding method-response object per the same section refs.
//!
//! The returned `HandlerOutput::extra_invocations` carries any invocations
//! that this handler injected into the request stream (RFC 8620 §6.3).
//! For the standard `/get`, `/changes`, `/set`, `/query`, and
//! `/queryChanges` handlers in this module the vector is **always
//! empty**. `handle_task_copy` is the one exception: it MAY emit
//! `Task/set` follow-up invocations when `onSuccessDestroyOriginal` is
//! true (RFC 8620 §5.4).
//!
//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
//! §3.6.2 and §5):
//!
//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
//!   `maxObjectsInSet`;
//! - `/set`, `/copy`: `stateMismatch`;
//! - `/copy`: `fromAccountNotFound`;
//! - `/changes`, `/queryChanges`: `cannotCalculateChanges`;
//! - `/queryChanges`: `tooManyChanges`;
//! - `/query`, `/queryChanges`: `unsupportedFilter`;
//! - `/query`: `unsupportedSort`, `anchorNotFound`.
//!
//! Per-target failures inside a `/set` or `/copy` call surface in the
//! `notCreated` / `notUpdated` / `notDestroyed` maps within `Ok((Value, ...))`,
//! not as `Err`.

use std::collections::BTreeMap;

use jmap_tasks_types::{Filter, Task, TaskComparator, TaskFilter, TaskFilterCondition};
use jmap_types::{Id, Invocation, JmapError, PatchObject, UTCDate};
use serde::Deserialize;
use serde_json::{Value, json};

use crate::TasksBackend;
use crate::helpers::{
    SetAccumulators, check_metadata_entry, enforce_max_objects_in_set, extract_account_id,
    finalize_set_response, reject_unsupported_sort, resolve_refs,
};
use jmap_server::{
    HandlerOutput, QueryParams, backend_set_error_value, bool_arg, check_read_only_patch,
    filter_arg, optional_arg, query_anchor_args, reject_server_set, server_fail_from_backend,
    server_fail_value_from_backend,
};

// ---------------------------------------------------------------------------
// Task/get
// ---------------------------------------------------------------------------

/// Handle a `Task/get` method call (draft-tasks-06 §4.5).
///
/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
/// `ids`, optional `properties`); the returned `Value` is the §5.1
/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
///
/// `utcStart` and `utcDue` are returned only when `properties` names them:
/// "This is not included by default and must be requested explicitly"
/// (draft-tasks-06 §4). For each requested one,
/// [`TasksBackend::compute_utc_times`] is called per returned task and the
/// value is `UTCDate|null` (jmapio/jmap PR #464): `null` when the task has
/// no `start` (for `utcStart`) or no `due` (for `utcDue`), the computed
/// date otherwise. A task that has the local time but for which the backend
/// returns `None` (it cannot convert, e.g. the default `compute_utc_times`)
/// gets no key at all, since `null` would claim the local time is unset.
/// The local-time inputs (`start`, `due`, `timeZone`, `timeZones`) are
/// fetched for that even when `properties` leaves them out, and dropped
/// again before the response, so only the requested properties are
/// returned (RFC 8620 §5.1).
///
/// The `timeZone` argument (TimeZoneId, default `"Etc/UTC"`; jmapio/jmap
/// #456, as CalendarEvent/get, draft-ietf-jmap-calendars-34 §5.7) is the
/// zone for floating tasks: "Floating tasks will be interpreted as per the
/// time zone given as a Task/get argument" (draft-tasks-06 §4). It is
/// passed to `compute_utc_times` as `tz_hint`. A value that is neither a
/// string nor `null` is `invalidArguments`.
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]). When the backend lists Task for
/// draft-ietf-jmap-metadata-05 ([`JmapAccounts::metadata_info`](jmap_server::JmapAccounts::metadata_info)),
/// `metadata` is returned as an object, by default only with
/// `urn:ietf:params:jmap:metadata` in `using`, and with that capability
/// `properties` may hold `metadata/<namespace>` subselectors (-05 §2,
/// §3.1); see [`jmap_server::handle_get_with_metadata`].
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_task_get<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    mut args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    // Determine whether utcStart / utcDue are requested. compute_utc_times
    // needs the local-time inputs, which handle_get would otherwise project
    // away; fetch the missing ones and strip them again below.
    let mut strip: Vec<&str> = Vec::new();
    let (want_start, want_due) = match args.get_mut("properties") {
        // draft-tasks-06 §4: utcStart/utcDue are "not included by default
        // and must be requested explicitly".
        None | Some(Value::Null) => (false, false),
        Some(Value::Array(props)) => {
            let has = |name: &str| props.iter().any(|p| p == name);
            let wanted = (has("utcStart"), has("utcDue"));
            if wanted.0 || wanted.1 {
                strip = ["start", "due", "timeZone", "timeZones"]
                    .into_iter()
                    .filter(|name| !has(name))
                    .collect();
                props.extend(strip.iter().map(|name| json!(name)));
            }
            wanted
        }
        _ => (false, false),
    };

    // Peek accountId to thread through compute_utc_times (bd:JMAP-ops7.25).
    // handle_get re-extracts and re-validates idempotently below; a malformed
    // or missing accountId surfaces here as invalidArguments before the
    // delegate call.
    let account_id: Id = args
        .get("accountId")
        .and_then(|v| v.as_str())
        .ok_or_else(|| JmapError::invalid_arguments("accountId is required"))
        .and_then(|s| {
            Id::new_validated(s).map_err(|e| {
                JmapError::invalid_arguments(format!("accountId is not a valid Id: {e}"))
            })
        })?;

    // jmapio/jmap #456: a Task/get `timeZone` argument as on CalendarEvent/get
    // (draft-ietf-jmap-calendars-34 §5.7, "TimeZoneId (default:
    // "Etc/UTC")"), the zone for floating tasks' utcStart/utcDue.
    let time_zone: Option<String> = match args.as_object_mut().and_then(|a| a.remove("timeZone")) {
        None | Some(Value::Null) => None,
        Some(Value::String(s)) => Some(s),
        Some(v) => {
            return Err(JmapError::invalid_arguments(format!(
                "timeZone: expected a string, got {}",
                jmap_server::json_type_name(&v)
            )));
        }
    };

    // Delegate to the generic get handler.
    let HandlerOutput {
        primary: mut response,
        extra_invocations: tail,
        ..
    } = jmap_server::handle_get_with_metadata::<Task, B>(backend, caller, args, using).await?;

    // If utcStart or utcDue were requested, augment each returned task.
    if (want_start || want_due)
        && let Some(Value::Array(list)) = response.get_mut("list")
    {
        for item in list.iter_mut() {
            if let Ok(task) = Task::deserialize(&*item) {
                let (utc_start, utc_due) = backend
                    .compute_utc_times(caller, &account_id, &task, time_zone.as_deref())
                    .await;
                // jmapio/jmap PR #464: `UTCDate|null`, null when the local
                // time is not set.
                let pairs = [
                    (want_start, "utcStart", task.start.is_some(), utc_start),
                    (want_due, "utcDue", task.due.is_some(), utc_due),
                ];
                for (wanted, key, has_local, utc) in pairs {
                    match (wanted, has_local, utc) {
                        (true, false, _) => item[key] = Value::Null,
                        (true, true, Some(d)) => item[key] = Value::String(d.into_inner()),
                        _ => {}
                    }
                }
            }
            if let Some(obj) = item.as_object_mut() {
                for name in &strip {
                    obj.remove(*name);
                }
            }
        }
    }

    Ok(HandlerOutput::new(response).with_extra(tail))
}

// ---------------------------------------------------------------------------
// Task/changes
// ---------------------------------------------------------------------------

/// Handle a `Task/changes` method call (draft-tasks-06 §4.6).
///
/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
/// `sinceState`, optional `maxChanges`); the returned `Value` is the §5.2
/// `/changes` response shape (`accountId`, `oldState`, `newState`,
/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]); with
/// `urn:ietf:params:jmap:metadata` the request may set
/// draft-ietf-jmap-metadata-05 §3.3 `ignoreMetadataOnlyChanges`, and
/// without it metadata-only changes are left out (-05 §3).
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_task_changes<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    jmap_server::handle_changes::<Task, B>(backend, caller, args, using).await
}

// ---------------------------------------------------------------------------
// Task/set
// ---------------------------------------------------------------------------

/// The Task properties that hold the id of another record, which a client
/// may set to a `#creationId` reference (RFC 8620 §5.3).
const TASK_ID_PROPERTIES: &[&str] = &["taskListId"];

/// Handle a `Task/set` method call (draft-tasks-06 §4.7).
///
/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
/// `ifInState`, optional `create` / `update` / `destroy` maps); the
/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
/// `oldState`, `newState`, plus the per-operation result maps).
///
/// **isDraft immutability**: this handler does not check `isDraft`. The
/// backend's [`crate::TasksBackend::update_object`] MUST reject a patch that
/// sets `isDraft: true` on a Task whose stored value is not `true` with
/// `invalidProperties`, atomically with the write; the rejection is reported
/// in `notUpdated`.
///
/// **`taskListId` references**: a `#creationId` value on create or update
/// names a TaskList created earlier in the request and resolves against
/// `created_ids` (pass [`jmap_server::CallContext::created_ids`]; RFC 8620
/// §5.3). An unknown reference is `invalidProperties` naming `taskListId`.
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]): a write to `metadata` or
/// `privateMetadata` without `urn:ietf:params:jmap:metadata` is
/// `invalidProperties` (draft-ietf-jmap-metadata-05 §3), as is `null` for
/// either in a create (-05 §3.2). The backend validates the rest.
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_task_set<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    created_ids: &BTreeMap<Id, Id>,
    args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    let (account_id, mut args) = extract_account_id(args)?;

    // RFC 8620 §3.6.2: accountId not recognised → accountNotFound (method-level
    // error). Without this, a /set against an unknown accountId would silently
    // "succeed" with a fake oldState/newState envelope. Fixed in JMAP-gpt1.
    if !backend
        .account_exists(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?
    {
        return Err(JmapError::account_not_found());
    }

    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.5). Reject
    // unbounded /set batches before touching the storage layer.
    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;

    let old_state = backend
        .get_state::<Task>(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?;

    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
        && if_in_state != old_state.as_ref()
    {
        return Err(JmapError::state_mismatch());
    }

    let mut created = serde_json::Map::new();
    let mut not_created = serde_json::Map::new();
    let mut updated = serde_json::Map::new();
    let mut not_updated = serde_json::Map::new();
    let mut destroyed_list: Vec<Value> = Vec::new();
    let mut not_destroyed = serde_json::Map::new();
    let mut mutated = false;

    // -----------------------------------------------------------------------
    // create
    // -----------------------------------------------------------------------
    if let Some(Value::Object(create_map)) = args.remove("create") {
        for (create_id, mut obj_val) in create_map {
            if let Some(err) = obj_val.as_object().and_then(reject_server_set::<Task>) {
                not_created.insert(create_id, serde_json::Value::from(&err));
                continue;
            }
            if let Some(Err(err)) = obj_val
                .as_object()
                .map(|o| check_metadata_entry(o, true, using))
            {
                not_created.insert(create_id, serde_json::Value::from(&*err));
                continue;
            }
            if let Err(err) = resolve_refs(&mut obj_val, TASK_ID_PROPERTIES, created_ids) {
                not_created.insert(create_id, serde_json::Value::from(&*err));
                continue;
            }
            if let Some(prop) = obj_val
                .as_object()
                .and_then(|o| o.iter().find(|(_, v)| has_bad_person_uri(v)))
                .map(|(k, _)| k.clone())
            {
                not_created.insert(create_id, person_uri_error(&prop));
                continue;
            }
            // `Task.id` is optional, so the create parses without one and
            // `build` sets the id the backend mints.
            let mut task: Task = match serde_path_to_error::deserialize(obj_val) {
                Ok(t) => t,
                Err(e) => {
                    // RFC 8620 §5.3: invalidProperties SHOULD list the
                    // invalid properties; the first path segment is the
                    // top-level property whose value failed to parse.
                    let mut err =
                        json!({ "type": "invalidProperties", "description": e.to_string() });
                    if let Some(serde_path_to_error::Segment::Map { key }) = e.path().iter().next()
                    {
                        err["properties"] = json!([key]);
                    }
                    not_created.insert(create_id, err);
                    continue;
                }
            };

            let build = move |id: &Id| {
                task.id = Some(id.clone());
                task
            };
            match backend
                .create_object::<Task, _>(caller, &account_id, &create_id, build)
                .await
            {
                Ok((_new_id, created_obj)) => {
                    mutated = true;
                    created.insert(create_id, jmap_server::serialize_value(&created_obj)?);
                }
                Err(e) => {
                    not_created.insert(create_id, backend_set_error_value(e));
                }
            }
        }
    }

    // -----------------------------------------------------------------------
    // update
    // -----------------------------------------------------------------------
    // RFC 8620 §5.3: update keys and destroy ids may name this call's creates.
    jmap_server::resolve_set_id_refs(&mut args, created_ids, &created);
    if let Some(Value::Object(update_map)) = args.remove("update") {
        for (id_str, mut patch_val) in update_map {
            // isDraft immutability (draft-tasks-06 §4 isDraft paragraph) is
            // enforced by the backend in update_object, atomically with the
            // write (TasksBackend::update_object, bd:JMAP-h47t.29).
            let id = match jmap_server::parse_wire_id(&id_str, "id") {
                Ok(id) => id,
                Err(err) => {
                    not_updated.insert(id_str, serde_json::Value::from(&*err));
                    continue;
                }
            };

            if let Err(err) = resolve_refs(&mut patch_val, TASK_ID_PROPERTIES, created_ids) {
                not_updated.insert(id_str, serde_json::Value::from(&*err));
                continue;
            }
            if let Some(prop) = patch_val.as_object().and_then(bad_person_uri_in_patch) {
                not_updated.insert(id_str, person_uri_error(&prop));
                continue;
            }

            // Convert wire-format Value into a typed PatchObject. RFC 8620
            // §5.3 mandates a PatchObject is a JSON Object; non-object
            // values produce an `invalidPatch` SetError.
            let mut patch = match serde_json::from_value::<PatchObject>(patch_val) {
                Ok(p) => p,
                Err(e) => {
                    not_updated.insert(
                        id_str,
                        json!({ "type": "invalidPatch", "description": e.to_string() }),
                    );
                    continue;
                }
            };
            // draft-ietf-jmap-tasks-06 §4: `id`, `baseTaskId` and `isOrigin`
            // are server-set. A changed value is rejected, an identical one
            // dropped (RFC 8620 §5.3); nothing left is a no-op success.
            match check_read_only_patch::<_, Task>(
                backend,
                caller,
                &account_id,
                &id,
                patch.as_map_mut(),
            )
            .await
            {
                Ok(false) => {}
                Ok(true) => {
                    updated.insert(id_str, Value::Null);
                    continue;
                }
                Err(err) => {
                    not_updated.insert(id_str, err);
                    continue;
                }
            }

            // Route to the per-user update path when every patch key targets
            // a per-user Task property (draft-tasks-06 §4.5.1). Classified
            // after the identical server-set values are dropped above, so
            // they do not force a per-user change onto the shared path.
            //
            // PatchObject keys are RFC 6901 JSON Pointers (RFC 8620 §5.3), so a
            // per-user keyword toggle is sent as `keywords/done`, not bare
            // `keywords`. Classify on the FIRST pointer segment (the substring
            // before the first '/'), not the whole key.
            //
            // A delete-shared-property patch like `{"title": null}` is a
            // shared mutation and goes to `update_object`.
            //
            // Per-user property names (`keywords`, `color`, `freeBusyStatus`,
            // `useDefaultAlerts`, `alerts`) contain no `/` or `~`, so a plain
            // `split('/').next()` is correct without RFC 6901 unescaping.
            let is_per_user_only = patch.as_map().keys().all(|k| {
                let head = k.split('/').next().unwrap_or(k);
                jmap_tasks_types::is_per_user_task_property(head)
            });
            if let Err(err) = check_metadata_entry(patch.as_map(), false, using) {
                not_updated.insert(id_str, serde_json::Value::from(&*err));
                continue;
            }

            let update_result = if is_per_user_only {
                backend
                    .update_task_per_user(caller, &account_id, &id, patch)
                    .await
            } else {
                backend
                    .update_object::<Task>(caller, &account_id, &id, patch)
                    .await
            };

            match update_result {
                Ok(Some(obj)) => {
                    mutated = true;
                    updated.insert(id_str, jmap_server::serialize_value(&obj)?);
                }
                Ok(None) => {
                    mutated = true;
                    updated.insert(id_str, Value::Null);
                }
                Err(e) => {
                    not_updated.insert(id_str, backend_set_error_value(e));
                }
            }
        }
    }

    // -----------------------------------------------------------------------
    // destroy
    // -----------------------------------------------------------------------
    if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
        // Two-pass validation is intentional: this up-front loop fails the whole
        // request loudly; the `None => continue` arm in the inner match below
        // is unreachable BECAUSE this pre-check ran. Future contributor: do NOT
        // delete this pre-check on the reasoning that the inner match handles
        // non-string elements — silent-skip is the wrong behaviour per the
        // workspace "silent-drop is a data-integrity bug class" rule
        // (JMAP-wlip.1).
        let id_strs: Vec<&str> = destroy_arr
            .iter()
            .map(|v| {
                v.as_str().ok_or_else(|| {
                    JmapError::invalid_arguments(format!(
                        "destroy: every element must be a string Id; got {}",
                        jmap_server::json_type_name(v)
                    ))
                })
            })
            .collect::<Result<_, _>>()?;
        for id_str in id_strs {
            let id_str = id_str.to_owned();
            let id = match jmap_server::parse_wire_id(&id_str, "id") {
                Ok(id) => id,
                Err(err) => {
                    not_destroyed.insert(id_str, serde_json::Value::from(&*err));
                    continue;
                }
            };

            match backend
                .destroy_object::<Task>(caller, &account_id, &id)
                .await
            {
                Ok(()) => {
                    mutated = true;
                    destroyed_list.push(Value::String(id_str));
                }
                Err(e) => {
                    not_destroyed.insert(id_str, backend_set_error_value(e));
                }
            }
        }
    }

    finalize_set_response::<B, Task>(
        backend,
        caller,
        &account_id,
        old_state,
        mutated,
        SetAccumulators {
            created,
            updated,
            destroyed: destroyed_list,
            not_created,
            not_updated,
            not_destroyed,
        },
    )
    .await
}

// ---------------------------------------------------------------------------
// Task/copy
// ---------------------------------------------------------------------------

/// Handle a `Task/copy` method call (draft-tasks-06 §4.8).
///
/// `args` is the RFC 8620 §5.4 `/copy` request shape (`fromAccountId`,
/// optional `ifFromInState`, `accountId`, optional `ifInState`, `create`
/// map, optional `onSuccessDestroyOriginal`, optional
/// `destroyFromIfInState`); the returned `Value` is the §5.4 `/copy`
/// response shape (`fromAccountId`, `accountId`, optional `oldState`,
/// `newState`, optional `created`, optional `notCreated`).
///
/// `call_id` is the request's method-call id, used to construct any
/// follow-up `Task/set` invocations injected when
/// `onSuccessDestroyOriginal` is true (RFC 8620 §5.4 + §6.3).
///
/// Copies tasks from `fromAccountId` into the current account. The `create`
/// map keys are client-side creation ids; the backend assigns new server-side
/// ids.
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]). draft-ietf-jmap-metadata-05 §3.4:
/// the copy keeps the source's `metadata`, and its `privateMetadata` only
/// with `urn:ietf:params:jmap:metadata` in `using` and when the
/// destination supports it; neither is copied when the destination does
/// not list Task ([`JmapAccounts::metadata_info`](jmap_server::JmapAccounts::metadata_info)).
/// The create object "MAY include metadata and privateMetadata to override
/// the copied values, with the same rules as a create in Foo/set": the
/// handler rejects them without the capability and rejects `null`, and
/// [`TasksBackend::copy_object`] validates the rest against the create
/// object only: "Copied values are not revalidated against the
/// destination account".
///
/// Returns `(response_args, extra_invocations)`. The extra invocation list
/// is populated with a follow-up `Task/set` invocation when
/// `onSuccessDestroyOriginal` is true (RFC 8620 §5.4); otherwise it is
/// empty.
/// `true` when `value` holds, at any depth, a Person object
/// (draft-ietf-jmap-tasks §4.2.3 CheckItem `assignee`, §4.2.4 Comment
/// `author`) whose `uri` is a string that is not an RFC 3986 URI
/// (draft-atwood-jmap-updates-00 §7.1).
fn has_bad_person_uri(value: &Value) -> bool {
    match value {
        Value::Object(m) => {
            let bad_here = m.get("@type").and_then(Value::as_str) == Some("Person")
                && m.get("uri")
                    .and_then(Value::as_str)
                    .is_some_and(|u| jmap_types::uri::check_uri(u).is_err());
            bad_here || m.values().any(has_bad_person_uri)
        }
        Value::Array(a) => a.iter().any(has_bad_person_uri),
        _ => false,
    }
}

/// The top-level property of the first patch entry that writes a Person
/// `uri` that is not an RFC 3986 URI: a value holding such a Person, or a
/// pointer ending in `assignee/uri` or `author/uri` to a non-URI string.
fn bad_person_uri_in_patch(patch: &serde_json::Map<String, Value>) -> Option<String> {
    patch.iter().find_map(|(path, v)| {
        let direct = (path.ends_with("/assignee/uri") || path.ends_with("/author/uri"))
            && v.as_str()
                .is_some_and(|u| jmap_types::uri::check_uri(u).is_err());
        (direct || has_bad_person_uri(v)).then(|| path.split('/').next().unwrap_or(path).to_owned())
    })
}

/// The `invalidProperties` SetError for a Person `uri` under `property`.
fn person_uri_error(property: &str) -> Value {
    json!({
        "type": "invalidProperties",
        "properties": [property],
        "description": "a Person uri is not an RFC 3986 URI",
    })
}

pub async fn handle_task_copy<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
    call_id: &str,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    let (to_account_id, mut args) = extract_account_id(args)?;

    if !backend
        .account_exists(caller, &to_account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?
    {
        return Err(JmapError::account_not_found());
    }

    let from_account_id_str = args
        .remove("fromAccountId")
        .and_then(|v| v.as_str().map(|s| s.to_owned()))
        .ok_or_else(|| JmapError::invalid_arguments("fromAccountId is required"))?;
    let from_account_id = Id::new_validated(from_account_id_str)
        .map_err(|e| JmapError::invalid_arguments(format!("fromAccountId: {e}")))?;

    // RFC 8620 §5.4: fromAccountId MUST differ from accountId. The canonical
    // sibling jmap-mail-server enforces this in handle_email_copy; without it
    // a same-account "copy" silently produces a duplicate within the source
    // account, contradicting the meaning of /copy.
    if from_account_id == to_account_id {
        return Err(JmapError::invalid_arguments(
            "fromAccountId must be different from accountId",
        ));
    }

    // RFC 8620 §5.4: validate fromAccountId resolves to a real account;
    // emit the spec-canonical `fromAccountNotFound` (not the generic
    // `accountNotFound`) when it does not.
    if !backend
        .account_exists(caller, &from_account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?
    {
        return Err(JmapError::from_account_not_found());
    }

    // RFC 8620 §5.4 `ifFromInState`: if supplied, the source-account Task
    // state MUST match; otherwise abort with stateMismatch. Probed before
    // the destination state so a stale source guard fails fast.
    if let Some(if_from_in_state) = args.get("ifFromInState").and_then(|v| v.as_str()) {
        let from_state = backend
            .get_state::<Task>(caller, &from_account_id)
            .await
            .map_err(|e| server_fail_from_backend(&e))?;
        if if_from_in_state != from_state.as_ref() {
            return Err(JmapError::state_mismatch());
        }
    }

    let old_state = backend
        .get_state::<Task>(caller, &to_account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?;

    // RFC 8620 §5.4 `ifInState`: if supplied, the destination-account Task
    // state MUST match; otherwise abort with stateMismatch.
    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
        && if_in_state != old_state.as_ref()
    {
        return Err(JmapError::state_mismatch());
    }

    // RFC 8620 §5.4 `onSuccessDestroyOriginal` / `destroyFromIfInState`:
    // parsed here so the request payload is consumed in handler-local order
    // and so a clearly-shaped per-feature value is available below.
    let on_success_destroy_original: bool = bool_arg(&args, "onSuccessDestroyOriginal", false);
    let destroy_from_if_in_state: Option<String> = args
        .get("destroyFromIfInState")
        .and_then(|v| v.as_str())
        .map(|s| s.to_owned());

    let mut created = serde_json::Map::new();
    let mut not_created = serde_json::Map::new();
    let mut mutated = false;
    // (create_id, source_id) pairs for entries that succeeded — fed to the
    // implicit Task/set destroy below when onSuccessDestroyOriginal is true.
    let mut copied_source_ids: Vec<(String, Id)> = Vec::new();

    if let Some(Value::Object(create_map)) = args.remove("create") {
        for (create_id, client_val) in create_map {
            // RFC 8620 §5.4: the Foo object MUST contain an `id` property,
            // which is the id (in the fromAccount) of the record to be copied.
            // The earlier handler silently invented a "placeholder" id when
            // the client omitted one, masking the missing-id case the spec
            // treats as a hard requirement.
            let Some(source_id_str) = client_val.get("id").and_then(|v| v.as_str()) else {
                not_created.insert(
                    create_id,
                    json!({"type": "invalidProperties", "properties": ["id"]}),
                );
                continue;
            };
            let source_id: Id = match jmap_server::parse_wire_id(source_id_str, "id") {
                Ok(id) => id,
                Err(err) => {
                    not_created.insert(create_id, serde_json::Value::from(&*err));
                    continue;
                }
            };

            // Fetch the source Task from `fromAccountId`. RFC 8620 §5.4 frames
            // /copy as a read-from-source-then-create-in-destination operation;
            // unknown source ids surface as `notFound` per-entry SetErrors.
            let mut source_tasks: Vec<Task> = match backend
                .get_objects::<Task>(
                    caller,
                    &from_account_id,
                    Some(std::slice::from_ref(&source_id)),
                    None,
                )
                .await
            {
                Ok((objs, not_found)) => {
                    if !not_found.is_empty() || objs.is_empty() {
                        not_created.insert(create_id, json!({"type": "notFound"}));
                        continue;
                    }
                    objs
                }
                Err(e) => {
                    not_created.insert(create_id, server_fail_value_from_backend(&e));
                    continue;
                }
            };

            // RFC 8620 §5.4: "any other properties included [in the create
            // entry] are used instead of the current value for that property
            // on the original." Serialize the source, overlay client-supplied
            // properties, strip the source id so the backend assigns a fresh
            // server id. Pattern mirrors jmap-calendars-server event.rs:610-642.
            // draft-ietf-jmap-metadata-05 §3.4: metadata overrides follow the
            // Foo/set create rules (§3, §3.2).
            if let Some(Err(err)) = client_val
                .as_object()
                .map(|o| check_metadata_entry(o, true, using))
            {
                not_created.insert(create_id, Value::from(&*err));
                continue;
            }
            // -05 §3.4: "When the request does not use this capability, only
            // metadata is copied", "privateMetadata is not copied when the
            // destination does not support it, and neither property is
            // copied when the data type is not listed in the destination
            // account". The overrides are merged in below.
            let info = backend.metadata_info::<Task>(caller, &to_account_id);
            if !jmap_server::uses_metadata(using)
                || !info.as_ref().is_some_and(|i| i.supports_private)
            {
                source_tasks[0].private_metadata = None;
            }
            if info.is_none() {
                source_tasks[0].metadata = None;
            }
            let Ok(Value::Object(mut merged)) = serde_json::to_value(&source_tasks[0]) else {
                not_created.insert(
                    create_id,
                    json!({
                        "type": "serverFail",
                        "description": "failed to serialize source Task",
                    }),
                );
                continue;
            };
            if let Value::Object(client_props) = &client_val {
                for (k, v) in client_props {
                    if k != "id" {
                        merged.insert(k.clone(), v.clone());
                    }
                }
            }
            merged.remove("id");
            // draft-atwood-jmap-updates-00 §7.1, as for Task/set create.
            if let Some(prop) = merged
                .iter()
                .find(|(_, v)| has_bad_person_uri(v))
                .map(|(k, _)| k.clone())
            {
                not_created.insert(create_id, person_uri_error(&prop));
                continue;
            }

            let task: Task = match serde_path_to_error::deserialize(Value::Object(merged)) {
                Ok(t) => t,
                Err(e) => {
                    // RFC 8620 §5.3: invalidProperties SHOULD list the
                    // invalid properties; the first path segment is the
                    // top-level property whose value failed to parse.
                    let mut err =
                        json!({ "type": "invalidProperties", "description": e.to_string() });
                    if let Some(serde_path_to_error::Segment::Map { key }) = e.path().iter().next()
                    {
                        err["properties"] = json!([key]);
                    }
                    not_created.insert(create_id, err);
                    continue;
                }
            };

            // -05 §3.4: the backend validates only the metadata supplied in
            // the create object; the copied values are not revalidated.
            match backend
                .copy_object(caller, &from_account_id, &to_account_id, task, &client_val)
                .await
            {
                Ok((_new_id, created_task)) => {
                    mutated = true;
                    created.insert(
                        create_id.clone(),
                        jmap_server::serialize_value(&created_task)?,
                    );
                    copied_source_ids.push((create_id, source_id));
                }
                Err(e) => {
                    not_created.insert(create_id, backend_set_error_value(e));
                }
            }
        }
    }

    let new_state = if mutated {
        backend
            .get_state::<Task>(caller, &to_account_id)
            .await
            .map_err(|e| server_fail_from_backend(&e))?
    } else {
        old_state.clone()
    };

    let resp = json!({
        "fromAccountId": from_account_id.as_ref(),
        "accountId": to_account_id.as_ref(),
        "oldState": old_state.as_ref(),
        "newState": new_state.as_ref(),
        "created":    if created.is_empty()     { Value::Null } else { Value::Object(created) },
        "notCreated": if not_created.is_empty() { Value::Null } else { Value::Object(not_created) },
    });

    // RFC 8620 §5.4 `onSuccessDestroyOriginal`: after emitting the Task/copy
    // response, the server MUST make a single implicit Task/set call against
    // fromAccountId destroying each successfully copied source record.
    // `destroyFromIfInState`, if supplied, is passed through as the ifInState
    // argument on that implicit call. The dispatcher returns the extra
    // Invocation vec to the caller (RFC 8620 §6.3 chained responses).
    // Pattern mirrors jmap-mail-server email.rs:2432-2575.
    let mut extra: Vec<Invocation> = Vec::new();
    if on_success_destroy_original && !copied_source_ids.is_empty() {
        let from_old_state = backend
            .get_state::<Task>(caller, &from_account_id)
            .await
            .map_err(|e| server_fail_from_backend(&e))?;

        // Honour destroyFromIfInState on the implicit Task/set call. A
        // mismatch yields a stateMismatch top-level error on the synthesized
        // response (§5.4 inheriting §5.3 semantics on the chained call).
        let mut destroy_state_mismatch = false;
        if let Some(if_state) = destroy_from_if_in_state.as_deref()
            && if_state != from_old_state.as_ref()
        {
            destroy_state_mismatch = true;
        }

        let mut destroyed_arr: Vec<Value> = Vec::new();
        let mut not_destroyed = serde_json::Map::new();

        if !destroy_state_mismatch {
            for (_, source_id) in &copied_source_ids {
                match backend
                    .destroy_object::<Task>(caller, &from_account_id, source_id)
                    .await
                {
                    Ok(()) => {
                        destroyed_arr.push(Value::String(source_id.as_ref().to_owned()));
                    }
                    Err(e) => {
                        not_destroyed
                            .insert(source_id.as_ref().to_owned(), backend_set_error_value(e));
                    }
                }
            }
        }

        let from_new_state = backend
            .get_state::<Task>(caller, &from_account_id)
            .await
            .map_err(|e| server_fail_from_backend(&e))?;

        let set_resp = if destroy_state_mismatch {
            json!({
                "type": "stateMismatch",
            })
        } else {
            json!({
                "accountId": from_account_id.as_ref(),
                "oldState": from_old_state.as_ref(),
                "newState": from_new_state.as_ref(),
                "created": Value::Null,
                "updated": Value::Null,
                "destroyed": if destroyed_arr.is_empty() { Value::Null } else { Value::Array(destroyed_arr) },
                "notCreated": Value::Null,
                "notUpdated": Value::Null,
                "notDestroyed": if not_destroyed.is_empty() { Value::Null } else { Value::Object(not_destroyed) },
            })
        };

        let method_name = if destroy_state_mismatch {
            "error".to_owned()
        } else {
            "Task/set".to_owned()
        };
        extra.push(Invocation::new(method_name, set_resp, call_id.to_owned()));
    }

    Ok(HandlerOutput::new(resp).with_extra(extra))
}

// ---------------------------------------------------------------------------
// Task/query
// ---------------------------------------------------------------------------

/// Handle a `Task/query` method call (draft-tasks-06 §4.13).
///
/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`,
/// optional `filter`, optional `sort`, optional `position`, optional
/// `anchor`, optional `anchorOffset`, optional `limit`, optional
/// `calculateTotal`); the returned `Value` is the §5.5 `/query`
/// response shape (`accountId`, `queryState`, `canCalculateChanges`,
/// `position`, `ids`, optional `total`).
///
/// The Task/query arguments of jmapio/jmap #456, as on CalendarEvent/query
/// (draft-ietf-jmap-calendars-34 §5.11):
///
/// - `expandRecurrences`: Boolean (default `false`). "If true, the filter
///   MUST be just a FilterCondition (not a FilterOperator) and MUST include
///   both a "before" and "after" property; otherwise, the server MUST
///   reject the call with an invalidArguments error." A window longer
///   than [`TasksLimits::max_expanded_query_duration_seconds`](crate::TasksLimits::max_expanded_query_duration_seconds)
///   (`maxExpandedQueryDuration`, draft-tasks-06 §1.6.2) is the
///   `expandDurationTooLarge` method error, checked here and again by the
///   backend.
/// - `timeZone`: TimeZoneId (default `"Etc/UTC"`), the zone for the
///   `after` / `before` conditions and for floating tasks. A value that is
///   neither a string nor `null` is `invalidArguments`.
///
/// Both reach [`TasksBackend::query_tasks`] as a
/// [`TaskQueryArgs`](crate::TaskQueryArgs). The backend may also return
/// `cannotCalculateOccurrences`.
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]); without
/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-05 §3.6
/// filter condition is `unsupportedFilter` (-05 §3).
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_task_query<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    jmap_server::reject_metadata_filter_arg(
        &args,
        jmap_tasks_types::TaskFilterCondition::has_metadata_condition,
        using,
    )?;
    reject_unsupported_sort::<TaskComparator>(args.get("sort"))?;
    let (account_id, mut args) = extract_account_id(args)?;
    if !backend
        .account_exists(caller, &account_id)
        .await
        .map_err(|e| server_fail_from_backend(&e))?
    {
        return Err(JmapError::account_not_found());
    }
    // Task has no localizable properties: as in the generic /query handler,
    // a non-null `language` is invalidArguments (draft-atwood-jmap-updates-00
    // §4.2).
    jmap_server::I18nProjection::from_args::<Task>(
        &mut args,
        &[],
        backend.i18n_info(caller, &account_id).as_ref(),
    )?;

    // RFC 8620 §5.5 arguments.
    let calculate_total = bool_arg(&args, "calculateTotal", false);
    let limit: Option<u64> = match args.get("limit") {
        None | Some(Value::Null) => None,
        Some(v) => Some(v.as_u64().ok_or_else(|| {
            JmapError::invalid_arguments(format!(
                "limit: expected a non-negative integer, got {}",
                jmap_server::json_type_name(v)
            ))
        })?),
    };
    let position: i64 = match args.get("position") {
        None | Some(Value::Null) => 0,
        Some(v) => v.as_i64().ok_or_else(|| {
            JmapError::invalid_arguments(format!(
                "position: expected an integer, got {}",
                jmap_server::json_type_name(v)
            ))
        })?,
    };
    let (anchor, anchor_offset) = query_anchor_args(&args)?;
    let filter: Option<TaskFilter> = filter_arg(&mut args)?;
    let sort: Option<Vec<TaskComparator>> = optional_arg(&mut args, "sort", || {
        JmapError::invalid_arguments("sort must be an array")
    })?;

    // jmapio/jmap #456 arguments.
    let expand_recurrences = bool_arg(&args, "expandRecurrences", false);
    let time_zone: Option<String> = optional_arg(&mut args, "timeZone", || {
        JmapError::invalid_arguments("timeZone must be a string")
    })?;
    if expand_recurrences {
        let condition = match &filter {
            Some(Filter::Condition(c)) if c.before.is_some() && c.after.is_some() => c,
            _ => {
                return Err(JmapError::invalid_arguments(
                    "expandRecurrences requires a FilterCondition with both 'before' and 'after'",
                ));
            }
        };
        // Defense in depth; the backend re-checks (TasksBackend::query_tasks).
        if let Some(secs) = expand_duration_seconds(condition)
            && u64::try_from(secs).is_ok_and(|secs| {
                secs > backend
                    .limits(caller, &account_id)
                    .max_expanded_query_duration_seconds
            })
        {
            return Err(JmapError::custom("expandDurationTooLarge"));
        }
    }
    let query_args = crate::TaskQueryArgs::default()
        .with_expand_recurrences(expand_recurrences)
        .with_time_zone(time_zone);

    let result = backend
        .query_tasks(
            caller,
            &account_id,
            QueryParams::new()
                .filter(filter.as_ref())
                .sort(sort.as_deref())
                .limit(limit)
                .position(position)
                .anchor(anchor.as_ref())
                .anchor_offset(anchor_offset),
            &query_args,
        )
        .await
        .map_err(JmapError::from)?;

    let mut resp = json!({
        "accountId": account_id.as_ref(),
        "queryState": result.query_state.as_ref(),
        "canCalculateChanges": result.can_calculate_changes,
        "position": result.position,
        "ids": result.ids,
    });
    if calculate_total && let Some(t) = result.total {
        resp["total"] = json!(t);
    }
    Ok(HandlerOutput::new(resp))
}

/// `before - after` of `condition` in seconds, for the
/// `maxExpandedQueryDuration` pre-check; `None` when a bound is missing or
/// does not parse.
///
/// Both bounds are `LocalDateTime`s read in the same `timeZone`, so their
/// difference is read as if both were UTC (the calendars-server pre-check
/// does the same). A time-zone transition inside the window can make the
/// real span differ by its offset change; the backend's own check is the
/// exact one.
pub(crate) fn expand_duration_seconds(condition: &TaskFilterCondition) -> Option<i64> {
    let epoch = |local: &jmap_tasks_types::LocalDateTime| {
        UTCDate::from(format!("{local}Z")).to_epoch_seconds().ok()
    };
    Some(epoch(condition.before.as_ref()?)? - epoch(condition.after.as_ref()?)?)
}

// ---------------------------------------------------------------------------
// Task/queryChanges
// ---------------------------------------------------------------------------

/// Handle a `Task/queryChanges` method call (draft-tasks-06 §4.14).
///
/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
/// optional `filter`, optional `sort`, `sinceQueryState`, optional
/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
/// returned `Value` is the §5.6 `/queryChanges` response shape
/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
/// `removed`, `added`).
///
/// `using` is the request's capability list (pass
/// [`jmap_server::CallContext::using`]); without
/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-05 §3.6
/// filter condition is `unsupportedFilter` (-05 §3).
///
/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
pub async fn handle_task_query_changes<B: TasksBackend>(
    backend: &B,
    caller: &B::CallerCtx,
    args: Value,
    using: &[String],
) -> Result<HandlerOutput, JmapError> {
    jmap_server::reject_metadata_filter_arg(
        &args,
        jmap_tasks_types::TaskFilterCondition::has_metadata_condition,
        using,
    )?;
    reject_unsupported_sort::<TaskComparator>(args.get("sort"))?;
    jmap_server::handle_query_changes::<Task, B>(backend, caller, args).await
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    use crate::test_support::MockBackend;

    /// Oracle: RFC 8620 §5.5 `unsupportedSort`: "The sort is syntactically
    /// valid, but includes a property the server does not support sorting
    /// on". docs/specs/jmap-tasks-local.md Sorting (draft-ietf-jmap-calendars-34
    /// §5.11.2): "MUST be supported for sorting: `id`, `uid`, `start`. The
    /// following SHOULD be supported: `created`, `updated`." `title` is not
    /// among them, nor is -26's `recurrenceId`, which -34 dropped.
    #[tokio::test]
    async fn query_unlisted_sort_property_returns_unsupported_sort() {
        let backend = MockBackend::new_with_account("acc1");
        for property in ["title", "recurrenceId"] {
            let args = json!({ "accountId": "acc1", "sort": [{ "property": property }] });
            let err = handle_task_query(&backend, &(), args, &[])
                .await
                .expect_err("unlisted sort property must be rejected");
            assert_eq!(err.error_type.to_string(), "unsupportedSort", "{property}");
        }
    }

    /// Oracle: as above; `Task/queryChanges` carries the same `sort`
    /// (RFC 8620 §5.6).
    #[tokio::test]
    async fn query_changes_unlisted_sort_property_returns_unsupported_sort() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "sinceQueryState": "0",
            "sort": [{ "property": "start" }, { "property": "title" }]
        });
        let err = handle_task_query_changes(&backend, &(), args, &[])
            .await
            .expect_err("unlisted sort property must be rejected");
        assert_eq!(err.error_type.to_string(), "unsupportedSort");
    }

    /// Oracle: docs/specs/jmap-tasks-local.md Sorting: "The following
    /// properties MUST be supported for sorting: `id`, `uid`, `start`. The
    /// following SHOULD be supported: `created`, `updated`."
    #[tokio::test]
    async fn query_listed_sort_property_is_accepted() {
        let backend = MockBackend::new_with_account("acc1");
        for property in ["id", "uid", "start", "created", "updated"] {
            let args = json!({ "accountId": "acc1", "sort": [{ "property": property }] });
            handle_task_query(&backend, &(), args, &[])
                .await
                .expect("listed sort property must not be rejected");
        }
    }

    /// Oracle: Task/get with unknown accountId returns accountNotFound.
    #[tokio::test]
    async fn get_unknown_account_returns_account_not_found() {
        let backend = MockBackend::new();
        let args = json!({ "accountId": "unknown", "ids": null });
        let result = handle_task_get(&backend, &(), args, &[]).await;
        let err = result.expect_err("must return error for unknown account");
        assert_eq!(err.error_type.to_string(), "accountNotFound");
    }

    /// Oracle: Task/copy missing fromAccountId returns invalidArguments.
    #[tokio::test]
    async fn copy_missing_from_account_id_returns_invalid_arguments() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "create": {}
        });
        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
        let err = result.expect_err("must return error when fromAccountId missing");
        assert_eq!(err.error_type.to_string(), "invalidArguments");
    }

    /// Oracle: RFC 8620 §5.4 — fromAccountId MUST be different from accountId.
    /// A same-account request must be rejected with invalidArguments before
    /// any per-create work. Matches the canonical sibling jmap-mail-server
    /// at email.rs:2263-2268.
    #[tokio::test]
    async fn copy_same_account_returns_invalid_arguments() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "fromAccountId": "acc1",
            "create": {}
        });
        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
        let err = result.expect_err("must reject same-account Task/copy per RFC 8620 §5.4");
        assert_eq!(err.error_type.to_string(), "invalidArguments");
    }

    /// Oracle: RFC 8620 §5.4 — `fromAccountId` that does not resolve to a
    /// real account returns the spec-canonical `fromAccountNotFound` error,
    /// not the generic `accountNotFound`.
    #[tokio::test]
    async fn copy_unknown_from_account_returns_from_account_not_found() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "fromAccountId": "no-such-account",
            "create": {}
        });
        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
        let err = result.expect_err("must reject unknown fromAccountId");
        assert_eq!(err.error_type.to_string(), "fromAccountNotFound");
    }

    /// Oracle: RFC 8620 §5.4 — `ifFromInState` mismatch on the source
    /// account returns `stateMismatch`.
    #[tokio::test]
    async fn copy_if_from_in_state_mismatch_returns_state_mismatch() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.add_account("acc2");
        let args = json!({
            "accountId": "acc1",
            "fromAccountId": "acc2",
            "ifFromInState": "stale-source-state",
            "create": {}
        });
        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
        let err = result.expect_err("must reject stale ifFromInState");
        assert_eq!(err.error_type.to_string(), "stateMismatch");
    }

    /// Oracle: RFC 8620 §5.4 — `ifInState` mismatch on the destination
    /// account returns `stateMismatch`.
    #[tokio::test]
    async fn copy_if_in_state_mismatch_returns_state_mismatch() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.add_account("acc2");
        let args = json!({
            "accountId": "acc1",
            "fromAccountId": "acc2",
            "ifInState": "stale-destination-state",
            "create": {}
        });
        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
        let err = result.expect_err("must reject stale ifInState");
        assert_eq!(err.error_type.to_string(), "stateMismatch");
    }

    /// Oracle: RFC 8620 §5.4 — a create entry without an `id` property must
    /// produce a per-entry `invalidProperties` SetError naming `id`. The
    /// previous handler silently substituted a "placeholder" id, masking
    /// this hard requirement.
    #[tokio::test]
    async fn copy_create_entry_without_id_returns_invalid_properties() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.add_account("acc2");
        let args = json!({
            "accountId": "acc1",
            "fromAccountId": "acc2",
            "create": { "c1": {} }
        });
        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
            .await
            .expect("top-level call must succeed");
        let nc = resp["notCreated"].as_object().expect("notCreated present");
        let err = nc.get("c1").expect("c1 in notCreated");
        assert_eq!(err["type"], "invalidProperties");
        assert_eq!(err["properties"][0], "id");
    }

    /// Oracle: RFC 8620 §5.4 — when the source id does not resolve to a
    /// Task in `fromAccountId`, the per-entry result is `notFound`.
    #[tokio::test]
    async fn copy_unknown_source_id_returns_not_found() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.add_account("acc2");
        let args = json!({
            "accountId": "acc1",
            "fromAccountId": "acc2",
            "create": { "c1": { "id": "no-such-task" } }
        });
        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
            .await
            .expect("top-level call must succeed");
        let nc = resp["notCreated"].as_object().expect("notCreated present");
        assert_eq!(nc["c1"]["type"], "notFound");
    }

    /// Oracle: RFC 8620 §5.4 — the create entry's `id` selects WHAT to copy;
    /// client-supplied properties OTHER than `id` overlay the source values.
    /// Verify the handler actually round-trips through the source: seed a
    /// Task into `from_account`, request a copy that overrides `title`, and
    /// confirm the response carries the override.
    #[tokio::test]
    async fn copy_fetches_source_and_overlays_client_overrides() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.add_account("acc2");
        backend.seed_task("acc2", "src1", true); // source task in acc2

        let args = json!({
            "accountId": "acc1",
            "fromAccountId": "acc2",
            "create": {
                "c1": { "id": "src1", "title": "Overridden title" }
            }
        });
        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
            .await
            .expect("top-level call must succeed");

        // Source was fetched and the override applied: the created entry
        // carries the new title, not the source value (which had none).
        let created = resp["created"].as_object().expect("created present");
        let c1 = created.get("c1").expect("c1 in created");
        assert_eq!(
            c1["title"], "Overridden title",
            "client-supplied title must override source value: {resp}"
        );
    }

    /// Oracle: RFC 8620 §5.4 — when `onSuccessDestroyOriginal` is true, the
    /// server emits a single implicit Task/set call against fromAccountId
    /// destroying each successfully copied source. The synthesized response
    /// appears in the extra Vec<Invocation> with the same callId as the
    /// triggering Task/copy. Mirrors canonical jmap-mail-server
    /// email.rs:2432-2575.
    #[tokio::test]
    async fn copy_on_success_destroy_original_emits_implicit_task_set() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.add_account("acc2");
        backend.seed_task("acc2", "src1", true);

        let args = json!({
            "accountId": "acc1",
            "fromAccountId": "acc2",
            "onSuccessDestroyOriginal": true,
            "create": {
                "c1": { "id": "src1" }
            }
        });
        let HandlerOutput {
            extra_invocations: extra,
            ..
        } = handle_task_copy(&backend, &(), args, "c0", &[])
            .await
            .expect("top-level call must succeed");

        // Exactly one synthesized invocation: ("Task/set", response, "c0").
        assert_eq!(extra.len(), 1, "must emit one implicit Task/set: {extra:?}");
        let Invocation {
            name: method,
            arguments: val,
            call_id: ci,
        } = &extra[0];
        assert_eq!(method, "Task/set");
        assert_eq!(ci, "c0");
        assert_eq!(val["accountId"], "acc2", "implicit set targets fromAccount");
        let destroyed = val["destroyed"]
            .as_array()
            .expect("destroyed must be array");
        assert_eq!(destroyed.len(), 1);
        assert_eq!(destroyed[0], "src1");
        // Both state fields are present on the synthesized response. Their
        // bump semantics depend on the underlying backend's get_state — the
        // MockBackend here always returns "0" so we only assert presence;
        // state-advance semantics are covered by stateful integration tests.
        assert!(val.get("oldState").is_some(), "oldState must be present");
        assert!(val.get("newState").is_some(), "newState must be present");
    }

    /// Oracle: RFC 8620 §5.4 — `destroyFromIfInState` mismatch on the implicit
    /// Task/set call yields a `stateMismatch` error response in place of the
    /// normal Task/set body. The destroy MUST NOT proceed.
    #[tokio::test]
    async fn copy_destroy_from_if_in_state_mismatch_aborts_destroy() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.add_account("acc2");
        backend.seed_task("acc2", "src1", true);

        let args = json!({
            "accountId": "acc1",
            "fromAccountId": "acc2",
            "onSuccessDestroyOriginal": true,
            "destroyFromIfInState": "stale-source-state",
            "create": {
                "c1": { "id": "src1" }
            }
        });
        let HandlerOutput {
            extra_invocations: extra,
            ..
        } = handle_task_copy(&backend, &(), args, "c0", &[])
            .await
            .expect("top-level call must succeed");

        assert_eq!(extra.len(), 1);
        let Invocation { arguments: val, .. } = &extra[0];
        assert_eq!(val["type"], "stateMismatch");
    }

    /// Oracle: RFC 8620 §5.4 — when `onSuccessDestroyOriginal` is false (or
    /// absent), no implicit Task/set call is synthesized.
    #[tokio::test]
    async fn copy_without_on_success_emits_no_extra_invocations() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.add_account("acc2");
        backend.seed_task("acc2", "src1", true);

        let args = json!({
            "accountId": "acc1",
            "fromAccountId": "acc2",
            "create": {
                "c1": { "id": "src1" }
            }
        });
        let HandlerOutput {
            extra_invocations: extra,
            ..
        } = handle_task_copy(&backend, &(), args, "c0", &[])
            .await
            .expect("top-level call must succeed");
        assert!(
            extra.is_empty(),
            "no extra invocations without onSuccessDestroyOriginal: {extra:?}"
        );
    }

    /// Oracle: Task/set empty destroy returns valid response.
    #[tokio::test]
    async fn set_empty_destroy_returns_valid_response() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({ "accountId": "acc1", "destroy": [] });
        let HandlerOutput { primary: resp, .. } =
            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
                .await
                .expect("must not return top-level error");
        assert_eq!(resp["accountId"], "acc1");
    }

    // ── isDraft immutability enforcement (draft-tasks-06 §4 (isDraft paragraph)) ─

    /// Oracle: draft-tasks-06 §4 — "Once set to false, the value [isDraft]
    /// cannot be updated to true."
    /// A patch of {"isDraft": true} on a task that already has isDraft=false
    /// MUST be rejected with invalidProperties. The handler does no isDraft
    /// check, so this exercises the backend rejection reaching `notUpdated`.
    #[tokio::test]
    async fn set_is_draft_revert_rejected_when_current_is_false() {
        let mut backend = MockBackend::new_with_account("acc1");
        // Pre-seed a published (isDraft=false) task.
        backend.seed_task("acc1", "t1", false);

        let args = json!({
            "accountId": "acc1",
            "update": {
                "t1": { "isDraft": true }
            }
        });
        let HandlerOutput { primary: resp, .. } =
            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
                .await
                .expect("must not return a top-level error");

        let not_updated = resp["notUpdated"]
            .as_object()
            .expect("notUpdated must be an object");
        assert!(
            not_updated.contains_key("t1"),
            "t1 must appear in notUpdated: {resp}"
        );
        assert_eq!(
            not_updated["t1"]["type"].as_str(),
            Some("invalidProperties"),
            "error type must be invalidProperties"
        );
        assert_eq!(
            not_updated["t1"]["properties"][0].as_str(),
            Some("isDraft"),
            "properties must list isDraft"
        );
    }

    /// Oracle: draft-tasks-06 §4 — patching {"isDraft": true} on a task that
    /// is already a draft (isDraft=true) is allowed (no state transition).
    #[tokio::test]
    async fn set_is_draft_true_on_draft_task_passes_to_backend() {
        let mut backend = MockBackend::new_with_account("acc1");
        // Pre-seed a draft task (isDraft=true).
        backend.seed_task("acc1", "t2", true);

        let args = json!({
            "accountId": "acc1",
            "update": {
                "t2": { "isDraft": true }
            }
        });
        let HandlerOutput { primary: resp, .. } =
            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
                .await
                .expect("must not return a top-level error");

        // The handler passes the patch to the backend (which returns Forbidden
        // in the mock). The important thing is it is NOT pre-rejected here —
        // it must NOT appear in notUpdated with type=="invalidProperties".
        if let Some(not_updated) = resp["notUpdated"].as_object()
            && let Some(err) = not_updated.get("t2")
        {
            assert_ne!(
                err["type"].as_str(),
                Some("invalidProperties"),
                "isDraft:true on an existing draft must not produce invalidProperties"
            );
        }
    }

    /// Oracle: draft-tasks-06 §4 — patching {"isDraft": false} is always allowed
    /// (moving from draft to published is a one-way door going the right way).
    #[tokio::test]
    async fn set_is_draft_false_passes_to_backend() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.seed_task("acc1", "t3", true);

        let args = json!({
            "accountId": "acc1",
            "update": {
                "t3": { "isDraft": false }
            }
        });
        let HandlerOutput { primary: resp, .. } =
            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
                .await
                .expect("must not return a top-level error");

        // Like above: the patch must NOT be pre-rejected with invalidProperties.
        if let Some(not_updated) = resp["notUpdated"].as_object()
            && let Some(err) = not_updated.get("t3")
        {
            assert_ne!(
                err["type"].as_str(),
                Some("invalidProperties"),
                "isDraft:false must never produce invalidProperties"
            );
        }
    }

    // ── compute_utc_times / utcStart wiring (draft-tasks-06 §4 (utcStart/utcDue paragraphs)) ─

    /// Oracle: draft-tasks-06 §4 — utcStart is not returned unless explicitly
    /// requested in `properties`.  The default impl returns None so it must be
    /// absent from the response when not requested.
    #[tokio::test]
    async fn get_without_utc_properties_omits_utc_fields() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "ids": null,
            "properties": ["id", "title"]  // utcStart and utcDue NOT listed
        });
        let HandlerOutput { primary: resp, .. } = handle_task_get(&backend, &(), args, &[])
            .await
            .expect("must succeed");
        // The list is empty (no tasks seeded), but the response itself must be valid.
        assert_eq!(resp["accountId"], "acc1");
        // No utcStart or utcDue should appear in response items (list is empty so
        // this is vacuously satisfied, but the path is exercised without error).
        let list = resp["list"].as_array().expect("list must be an array");
        for item in list {
            assert!(
                item.get("utcStart").is_none(),
                "utcStart must not appear when not in properties"
            );
        }
    }

    /// Oracle: draft-tasks-06 §4 — when utcStart is in properties, the handler
    /// calls compute_utc_times. The default impl returns (None, None) so
    /// no utcStart key is injected, but no error is raised either.
    #[tokio::test]
    async fn get_with_utc_start_in_properties_does_not_error() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "ids": null,
            "properties": ["id", "utcStart", "utcDue"]
        });
        let HandlerOutput { primary: resp, .. } = handle_task_get(&backend, &(), args, &[])
            .await
            .expect("must succeed with utcStart in properties");
        assert_eq!(resp["accountId"], "acc1");
    }

    // ── per-user property routing (draft-tasks-06 §4.5.1) ──────────────────
    //
    // Routing is observable via MockBackend::per_user_calls — a counter that
    // increments inside `update_task_per_user` and stays at 0 for paths that
    // go to `update_object`. The earlier shape of these tests only asserted
    // that no `invalidProperties` error came back, which would pass even if
    // routing were inverted; tightened here to inspect the counter directly.

    /// Oracle: draft-tasks-06 §4.5.1 — a patch with only per-user properties
    /// (bare keys, no JSON Pointer sub-paths) must route to update_task_per_user.
    #[tokio::test]
    async fn set_per_user_only_patch_routes_to_per_user_update() {
        use std::sync::atomic::Ordering;
        let backend = MockBackend::new_with_account("acc1");
        // color is a per-user property (§4.5.1).
        let args = json!({
            "accountId": "acc1",
            "update": { "t1": { "color": "#ff0000" } }
        });
        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
            .await
            .expect("must not return top-level error");
        assert_eq!(
            backend.per_user_calls.load(Ordering::Relaxed),
            1,
            "per-user-only patch must route to update_task_per_user"
        );
    }

    /// Oracle: draft-tasks-06 §4.5.1 + RFC 8620 §5.3 — JSON-pointer patches on
    /// per-user properties (e.g. `keywords/done: true` to toggle a single
    /// keyword, `alerts/0/offset: null` to clear an alert sub-field) must still
    /// route to update_task_per_user. The first pointer segment is the
    /// property name; the implementation MUST classify on that segment, not
    /// on the whole key.
    #[tokio::test]
    async fn set_per_user_json_pointer_patch_routes_to_per_user_update() {
        use std::sync::atomic::Ordering;
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "update": {
                "t1": {
                    "keywords/done": true,
                    "alerts/0/offset": null
                }
            }
        });
        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
            .await
            .expect("must not return top-level error");
        assert_eq!(
            backend.per_user_calls.load(Ordering::Relaxed),
            1,
            "JSON-pointer patch on per-user properties must route to update_task_per_user"
        );
    }

    /// Oracle: RFC 8620 §5.3 "Any server-set properties MAY be included in
    /// the patch if their value is identical to the current server value"
    /// and draft-tasks-06 §4.5.1: an identical `id` is no change, so a
    /// patch of it and a per-user keyword toggle is per-user only and
    /// routes to update_task_per_user.
    #[tokio::test]
    async fn set_identical_id_with_per_user_patch_routes_to_per_user_update() {
        use std::sync::atomic::Ordering;
        let mut backend = MockBackend::new_with_account("acc1");
        backend.seed_task("acc1", "t1", false);
        let args = json!({
            "accountId": "acc1",
            "update": { "t1": { "id": "t1", "keywords/done": true } }
        });
        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
            .await
            .expect("must not return top-level error");
        assert_eq!(
            backend.per_user_calls.load(Ordering::Relaxed),
            1,
            "identical id must not move a per-user patch to update_object"
        );
    }

    /// Oracle: draft-tasks-06 §4.5.1 — a patch on a shared property (title)
    /// must route to update_object.
    #[tokio::test]
    async fn set_shared_property_patch_routes_to_update_object() {
        use std::sync::atomic::Ordering;
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "update": { "t1": { "title": "New title" } }
        });
        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
            .await
            .expect("must not return top-level error");
        assert_eq!(
            backend.per_user_calls.load(Ordering::Relaxed),
            0,
            "shared-property patch must NOT route to update_task_per_user"
        );
    }

    /// Oracle: RFC 7396 / RFC 8620 §5.3 — `{"title": null}` is a delete-shared-
    /// property mutation, NOT a per-user mutation. The previous routing
    /// short-circuited on null values, misclassifying this as per-user-only.
    #[tokio::test]
    async fn set_shared_property_null_patch_routes_to_update_object() {
        use std::sync::atomic::Ordering;
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "update": { "t1": { "title": null } }
        });
        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
            .await
            .expect("must not return top-level error");
        assert_eq!(
            backend.per_user_calls.load(Ordering::Relaxed),
            0,
            "delete-shared-property patch must NOT route to update_task_per_user"
        );
    }

    /// Oracle: draft-tasks-06 §4.5.1 — a mixed patch (per-user + shared)
    /// routes to update_object, never update_task_per_user.
    #[tokio::test]
    async fn set_mixed_patch_routes_to_update_object() {
        use std::sync::atomic::Ordering;
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "update": { "t1": { "color": "#ff0000", "title": "New" } }
        });
        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
            .await
            .expect("must not return top-level error");
        assert_eq!(
            backend.per_user_calls.load(Ordering::Relaxed),
            0,
            "mixed patch must route to update_object"
        );
    }

    /// Oracle: RFC 8620 §5.3 — an empty PatchObject is a no-op, not a per-user
    /// mutation. The previous routing classified it as per-user-only via
    /// vacuous-truth on `iter().all`.
    #[tokio::test]
    async fn set_empty_patch_routes_to_update_object() {
        use std::sync::atomic::Ordering;
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "update": { "t1": {} }
        });
        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
            .await
            .expect("must not return top-level error");
        assert_eq!(
            backend.per_user_calls.load(Ordering::Relaxed),
            0,
            "empty patch must NOT route to update_task_per_user"
        );
    }

    /// RFC 8620 §5.3 types `destroy` as "Id[]|null", so an object element
    /// is "invalidArguments: One of the arguments is of the wrong type"
    /// (§3.6.2). The description names only the JSON type: §3.6.1 reserves
    /// it for "unstructured English text suitable for displaying to a
    /// developer", so the client-supplied value is never echoed
    /// (bd JMAP-zegc).
    #[tokio::test]
    async fn set_non_string_destroy_element_does_not_echo_value() {
        let backend = MockBackend::new_with_account("acc");
        let args = json!({ "accountId": "acc", "destroy": [{ "note": "CANARY-zegc" }] });
        let err = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
            .await
            .expect_err("non-string destroy element must be a method error");
        assert_eq!(err.error_type.to_string(), "invalidArguments");
        let desc = err.description.as_deref().unwrap_or_default();
        assert!(desc.contains("got object"), "{desc}");
        assert!(!desc.contains("CANARY"), "{desc}");
    }

    /// Oracle: RFC 8620 §5.3: for `invalidProperties` "the SetError object
    /// SHOULD also have a property called `properties` of type `String[]`
    /// that lists *all* the properties that were invalid". Each create below
    /// has exactly one hand-picked bad property.
    #[tokio::test]
    async fn set_create_typed_parse_failure_names_property() {
        let backend = MockBackend::new_with_account("acc1");
        let args = json!({
            "accountId": "acc1",
            "create": {
                "badTitle": { "title": 5 },
                "badSequence": { "sequence": "x" }
            }
        });
        let HandlerOutput { primary: resp, .. } =
            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
                .await
                .expect("must not return top-level error");
        assert!(resp["created"].is_null(), "nothing may be created: {resp}");
        for (cid, prop) in [("badTitle", "title"), ("badSequence", "sequence")] {
            let err = &resp["notCreated"][cid];
            assert_eq!(err["type"], "invalidProperties", "{cid}: {resp}");
            assert_eq!(err["properties"], json!([prop]), "{cid}: {resp}");
        }
    }

    /// Oracle: RFC 8620 §5.3: for `invalidProperties` "the SetError object
    /// SHOULD also have a property called `properties` of type `String[]`
    /// that lists *all* the properties that were invalid". Each create below
    /// has exactly one hand-picked bad property override.
    #[tokio::test]
    async fn copy_typed_parse_failure_names_property() {
        let mut backend = MockBackend::new_with_account("acc1");
        backend.add_account("acc2");
        backend.seed_task("acc2", "src1", true);
        let args = json!({
            "accountId": "acc1",
            "fromAccountId": "acc2",
            "create": {
                "badTitle": { "id": "src1", "title": 5 }
            }
        });
        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
            .await
            .expect("must not return top-level error");
        assert!(resp["created"].is_null(), "nothing may be created: {resp}");
        let err = &resp["notCreated"]["badTitle"];
        assert_eq!(err["type"], "invalidProperties", "{resp}");
        assert_eq!(err["properties"], json!(["title"]), "{resp}");
    }
}