Skip to main content

jmap_tasks_server/
task.rs

1//! Task/* method handlers (draft-tasks-06 §4).
2//!
3//! The `isDraft` immutability constraint (once false, never true again) is
4//! enforced by [`crate::TasksBackend::update_object`], not by Task/set.
5//!
6//! # Wire-shape contract
7//!
8//! Every `handle_*` function in this module conforms to the canonical JMAP
9//! method shape. The `args: serde_json::Value` parameter MUST be a JSON
10//! Object whose fields match the corresponding RFC 8620 §5 method shape
11//! (`/get` → §5.1, `/changes` → §5.2, `/set` → §5.3, `/copy` → §5.4,
12//! `/query` → §5.5, `/queryChanges` → §5.6), with the type-specific
13//! arguments defined by draft-tasks-06 §4. The returned `Value` is the
14//! corresponding method-response object per the same section refs.
15//!
16//! The returned `HandlerOutput::extra_invocations` carries any invocations
17//! that this handler injected into the request stream (RFC 8620 §6.3).
18//! For the standard `/get`, `/changes`, `/set`, `/query`, and
19//! `/queryChanges` handlers in this module the vector is **always
20//! empty**. `handle_task_copy` is the one exception: it MAY emit
21//! `Task/set` follow-up invocations when `onSuccessDestroyOriginal` is
22//! true (RFC 8620 §5.4).
23//!
24//! Each handler returns `Err(JmapError)` for method-level failures (RFC 8620
25//! §3.6.2 and §5):
26//!
27//! - every handler: `accountNotFound`, `invalidArguments`, `serverFail`;
28//! - `/get`, `/set`: `requestTooLarge` past `maxObjectsInGet` /
29//!   `maxObjectsInSet`;
30//! - `/set`, `/copy`: `stateMismatch`;
31//! - `/copy`: `fromAccountNotFound`;
32//! - `/changes`, `/queryChanges`: `cannotCalculateChanges`;
33//! - `/queryChanges`: `tooManyChanges`;
34//! - `/query`, `/queryChanges`: `unsupportedFilter`;
35//! - `/query`: `unsupportedSort`, `anchorNotFound`.
36//!
37//! Per-target failures inside a `/set` or `/copy` call surface in the
38//! `notCreated` / `notUpdated` / `notDestroyed` maps within `Ok((Value, ...))`,
39//! not as `Err`.
40
41use std::collections::BTreeMap;
42
43use jmap_tasks_types::{Filter, Task, TaskComparator, TaskFilter, TaskFilterCondition};
44use jmap_types::{Id, Invocation, JmapError, PatchObject, UTCDate};
45use serde::Deserialize;
46use serde_json::{Value, json};
47
48use crate::TasksBackend;
49use crate::helpers::{
50    SetAccumulators, check_metadata_entry, enforce_max_objects_in_set, extract_account_id,
51    finalize_set_response, reject_unsupported_sort, resolve_refs,
52};
53use jmap_server::{
54    HandlerOutput, QueryParams, backend_set_error_value, bool_arg, check_read_only_patch,
55    filter_arg, optional_arg, query_anchor_args, reject_server_set, server_fail_from_backend,
56    server_fail_value_from_backend,
57};
58
59// ---------------------------------------------------------------------------
60// Task/get
61// ---------------------------------------------------------------------------
62
63/// Handle a `Task/get` method call (draft-tasks-06 §4.5).
64///
65/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
66/// `ids`, optional `properties`); the returned `Value` is the §5.1
67/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
68///
69/// `utcStart` and `utcDue` are returned only when `properties` names them:
70/// "This is not included by default and must be requested explicitly"
71/// (draft-tasks-06 §4). For each requested one,
72/// [`TasksBackend::compute_utc_times`] is called per returned task and the
73/// value is `UTCDate|null` (jmapio/jmap PR #464): `null` when the task has
74/// no `start` (for `utcStart`) or no `due` (for `utcDue`), the computed
75/// date otherwise. A task that has the local time but for which the backend
76/// returns `None` (it cannot convert, e.g. the default `compute_utc_times`)
77/// gets no key at all, since `null` would claim the local time is unset.
78/// The local-time inputs (`start`, `due`, `timeZone`, `timeZones`) are
79/// fetched for that even when `properties` leaves them out, and dropped
80/// again before the response, so only the requested properties are
81/// returned (RFC 8620 §5.1).
82///
83/// The `timeZone` argument (`TimeZoneId`, default `"Etc/UTC"`; jmapio/jmap
84/// #456, as CalendarEvent/get, draft-ietf-jmap-calendars-34 §5.7) is the
85/// zone for floating tasks: "Floating tasks will be interpreted as per the
86/// time zone given as a Task/get argument" (draft-tasks-06 §4). It is
87/// passed to `compute_utc_times` as `tz_hint`. A value that is neither a
88/// string nor `null` is `invalidArguments`.
89///
90/// `using` is the request's capability list (pass
91/// [`jmap_server::CallContext::using`]). When the backend lists Task for
92/// draft-ietf-jmap-metadata-05 ([`JmapAccounts::metadata_info`](jmap_server::JmapAccounts::metadata_info)),
93/// `metadata` is returned as an object, by default only with
94/// `urn:ietf:params:jmap:metadata` in `using`, and with that capability
95/// `properties` may hold `metadata/<namespace>` subselectors (-05 §2,
96/// §3.1); see [`jmap_server::handle_get_with_metadata`].
97///
98/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
99///
100/// # Errors
101///
102/// Returns a method-level [`JmapError`]:
103///
104/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
105///   when `ids` or `properties` is malformed, or
106///   `timeZone` is not a string;
107/// - `accountNotFound` when the backend does not know `accountId`;
108/// - `requestTooLarge` when `ids` holds more than `maxObjectsInGet` ids;
109/// - `serverFail` when the backend fails.
110pub async fn handle_task_get<B: TasksBackend>(
111    backend: &B,
112    caller: &B::CallerCtx,
113    mut args: Value,
114    using: &[String],
115) -> Result<HandlerOutput, JmapError> {
116    // Determine whether utcStart / utcDue are requested. compute_utc_times
117    // needs the local-time inputs, which handle_get would otherwise project
118    // away; fetch the missing ones and strip them again below.
119    let mut strip: Vec<&str> = Vec::new();
120    let (want_start, want_due) = match args.get_mut("properties") {
121        // draft-tasks-06 §4: utcStart/utcDue are "not included by default
122        // and must be requested explicitly".
123        None | Some(Value::Null) => (false, false),
124        Some(Value::Array(props)) => {
125            let has = |name: &str| props.iter().any(|p| p == name);
126            let wanted = (has("utcStart"), has("utcDue"));
127            if wanted.0 || wanted.1 {
128                strip = ["start", "due", "timeZone", "timeZones"]
129                    .into_iter()
130                    .filter(|name| !has(name))
131                    .collect();
132                props.extend(strip.iter().map(|name| json!(name)));
133            }
134            wanted
135        }
136        _ => (false, false),
137    };
138
139    // Peek accountId to thread through compute_utc_times (bd:JMAP-ops7.25).
140    // handle_get re-extracts and re-validates idempotently below; a malformed
141    // or missing accountId surfaces here as invalidArguments before the
142    // delegate call.
143    let account_id: Id = args
144        .get("accountId")
145        .and_then(|v| v.as_str())
146        .ok_or_else(|| JmapError::invalid_arguments("accountId is required"))
147        .and_then(|s| {
148            Id::new_validated(s).map_err(|e| {
149                JmapError::invalid_arguments(format!("accountId is not a valid Id: {e}"))
150            })
151        })?;
152
153    // jmapio/jmap #456: a Task/get `timeZone` argument as on CalendarEvent/get
154    // (draft-ietf-jmap-calendars-34 §5.7, "TimeZoneId (default:
155    // "Etc/UTC")"), the zone for floating tasks' utcStart/utcDue.
156    let time_zone: Option<String> = match args.as_object_mut().and_then(|a| a.remove("timeZone")) {
157        None | Some(Value::Null) => None,
158        Some(Value::String(s)) => Some(s),
159        Some(v) => {
160            return Err(JmapError::invalid_arguments(format!(
161                "timeZone: expected a string, got {}",
162                jmap_server::json_type_name(&v)
163            )));
164        }
165    };
166
167    // Delegate to the generic get handler.
168    let HandlerOutput {
169        primary: mut response,
170        extra_invocations: tail,
171        ..
172    } = jmap_server::handle_get_with_metadata::<Task, B>(backend, caller, args, using).await?;
173
174    // If utcStart or utcDue were requested, augment each returned task.
175    if (want_start || want_due)
176        && let Some(Value::Array(list)) = response.get_mut("list")
177    {
178        for item in list.iter_mut() {
179            if let Ok(task) = Task::deserialize(&*item) {
180                let (utc_start, utc_due) = backend
181                    .compute_utc_times(caller, &account_id, &task, time_zone.as_deref())
182                    .await;
183                // jmapio/jmap PR #464: `UTCDate|null`, null when the local
184                // time is not set.
185                let pairs = [
186                    (want_start, "utcStart", task.start.is_some(), utc_start),
187                    (want_due, "utcDue", task.due.is_some(), utc_due),
188                ];
189                for (wanted, key, has_local, utc) in pairs {
190                    match (wanted, has_local, utc) {
191                        (true, false, _) => item[key] = Value::Null,
192                        (true, true, Some(d)) => item[key] = Value::String(d.into_inner()),
193                        _ => {}
194                    }
195                }
196            }
197            if let Some(obj) = item.as_object_mut() {
198                for name in &strip {
199                    obj.remove(*name);
200                }
201            }
202        }
203    }
204
205    Ok(HandlerOutput::new(response).with_extra(tail))
206}
207
208// ---------------------------------------------------------------------------
209// Task/changes
210// ---------------------------------------------------------------------------
211
212/// Handle a `Task/changes` method call (draft-tasks-06 §4.6).
213///
214/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
215/// `sinceState`, optional `maxChanges`); the returned `Value` is the §5.2
216/// `/changes` response shape (`accountId`, `oldState`, `newState`,
217/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
218///
219/// `using` is the request's capability list (pass
220/// [`jmap_server::CallContext::using`]); with
221/// `urn:ietf:params:jmap:metadata` the request may set
222/// draft-ietf-jmap-metadata-05 §3.3 `ignoreMetadataOnlyChanges`, and
223/// without it metadata-only changes are left out (-05 §3).
224///
225/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
226///
227/// # Errors
228///
229/// Returns a method-level [`JmapError`]:
230///
231/// - `invalidArguments` when `accountId` is missing or not a valid Id,
232///   `sinceState` is missing, `maxChanges` is not a positive integer, or
233///   `ignoreMetadataOnlyChanges` is not a boolean;
234/// - `accountNotFound` when the backend does not know `accountId`;
235/// - `cannotCalculateChanges` when the backend cannot compute the changes
236///   since `sinceState`;
237/// - `serverFail` when the backend fails.
238pub async fn handle_task_changes<B: TasksBackend>(
239    backend: &B,
240    caller: &B::CallerCtx,
241    args: Value,
242    using: &[String],
243) -> Result<HandlerOutput, JmapError> {
244    jmap_server::handle_changes::<Task, B>(backend, caller, args, using).await
245}
246
247// ---------------------------------------------------------------------------
248// Task/set
249// ---------------------------------------------------------------------------
250
251/// The Task properties that hold the id of another record, which a client
252/// may set to a `#creationId` reference (RFC 8620 §5.3).
253const TASK_ID_PROPERTIES: &[&str] = &["taskListId"];
254
255/// Handle a `Task/set` method call (draft-tasks-06 §4.7).
256///
257/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
258/// `ifInState`, optional `create` / `update` / `destroy` maps); the
259/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
260/// `oldState`, `newState`, plus the per-operation result maps).
261///
262/// **isDraft immutability**: this handler does not check `isDraft`. The
263/// backend's [`crate::TasksBackend::update_object`] MUST reject a patch that
264/// sets `isDraft: true` on a Task whose stored value is not `true` with
265/// `invalidProperties`, atomically with the write; the rejection is reported
266/// in `notUpdated`.
267///
268/// **`taskListId` references**: a `#creationId` value on create or update
269/// names a `TaskList` created earlier in the request and resolves against
270/// `created_ids` (pass [`jmap_server::CallContext::created_ids`]; RFC 8620
271/// §5.3). An unknown reference is `invalidProperties` naming `taskListId`.
272///
273/// `using` is the request's capability list (pass
274/// [`jmap_server::CallContext::using`]): a write to `metadata` or
275/// `privateMetadata` without `urn:ietf:params:jmap:metadata` is
276/// `invalidProperties` (draft-ietf-jmap-metadata-05 §3), as is `null` for
277/// either in a create (-05 §3.2). The backend validates the rest.
278///
279/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
280///
281/// # Errors
282///
283/// Returns a method-level [`JmapError`]:
284///
285/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
286///   when `create`, `update` or `destroy` is malformed;
287/// - `accountNotFound` when the backend does not know `accountId`;
288/// - `requestTooLarge` when `create`, `update` and `destroy` together hold
289///   more than `maxObjectsInSet` objects;
290/// - `stateMismatch` when `ifInState` is not the current state;
291/// - `serverFail` when the backend fails.
292///
293/// A create, update or destroy that fails on its own is a [`SetError`](jmap_server::SetError) in
294/// the response, not an `Err`.
295pub async fn handle_task_set<B: TasksBackend>(
296    backend: &B,
297    caller: &B::CallerCtx,
298    created_ids: &BTreeMap<Id, Id>,
299    args: Value,
300    using: &[String],
301) -> Result<HandlerOutput, JmapError> {
302    let (account_id, mut args) = extract_account_id(args)?;
303
304    // RFC 8620 §3.6.2: accountId not recognised → accountNotFound (method-level
305    // error). Without this, a /set against an unknown accountId would silently
306    // "succeed" with a fake oldState/newState envelope. Fixed in JMAP-gpt1.
307    if !backend
308        .account_exists(caller, &account_id)
309        .await
310        .map_err(|e| server_fail_from_backend(&e))?
311    {
312        return Err(JmapError::account_not_found());
313    }
314
315    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.5). Reject
316    // unbounded /set batches before touching the storage layer.
317    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
318
319    let old_state = backend
320        .get_state::<Task>(caller, &account_id)
321        .await
322        .map_err(|e| server_fail_from_backend(&e))?;
323
324    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
325        && if_in_state != old_state.as_ref()
326    {
327        return Err(JmapError::state_mismatch());
328    }
329
330    let ctx = SetCtx {
331        backend,
332        caller,
333        account_id: &account_id,
334        created_ids,
335        using,
336    };
337    let mut acc = SetAccumulators::default();
338    let mut mutated = set_create(&ctx, &mut args, &mut acc).await?;
339    // RFC 8620 §5.3: update keys and destroy ids may name this call's creates.
340    jmap_server::resolve_set_id_refs(&mut args, created_ids, &acc.created);
341    mutated |= set_update(&ctx, &mut args, &mut acc).await?;
342    mutated |= set_destroy(&ctx, &mut args, &mut acc).await?;
343
344    finalize_set_response::<B, Task>(backend, caller, &account_id, old_state, mutated, acc).await
345}
346
347/// What every `Task/set` sub-function needs from the request
348/// (docs/design/set-handler-split.md).
349struct SetCtx<'a, B: TasksBackend> {
350    backend: &'a B,
351    caller: &'a B::CallerCtx,
352    account_id: &'a Id,
353    /// The request-wide `#creationId` map (RFC 8620 §5.3).
354    created_ids: &'a BTreeMap<Id, Id>,
355    /// The request's `using` capabilities.
356    using: &'a [String],
357}
358
359/// The `create` part of `Task/set`. Returns whether the backend was
360/// written.
361async fn set_create<B: TasksBackend>(
362    ctx: &SetCtx<'_, B>,
363    args: &mut serde_json::Map<String, Value>,
364    acc: &mut SetAccumulators,
365) -> Result<bool, JmapError> {
366    let mut mutated = false;
367    if let Some(Value::Object(create_map)) = args.remove("create") {
368        for (create_id, mut obj_val) in create_map {
369            if let Some(err) = obj_val.as_object().and_then(reject_server_set::<Task>) {
370                acc.not_created
371                    .insert(create_id, serde_json::Value::from(&err));
372                continue;
373            }
374            if let Some(Err(err)) = obj_val
375                .as_object()
376                .map(|o| check_metadata_entry(o, true, ctx.using))
377            {
378                acc.not_created
379                    .insert(create_id, serde_json::Value::from(&*err));
380                continue;
381            }
382            if let Err(err) = resolve_refs(&mut obj_val, TASK_ID_PROPERTIES, ctx.created_ids) {
383                acc.not_created
384                    .insert(create_id, serde_json::Value::from(&*err));
385                continue;
386            }
387            if let Some(prop) = obj_val
388                .as_object()
389                .and_then(|o| o.iter().find(|(_, v)| has_bad_person_uri(v)))
390                .map(|(k, _)| k.clone())
391            {
392                acc.not_created.insert(create_id, person_uri_error(&prop));
393                continue;
394            }
395            // `Task.id` is optional, so the create parses without one and
396            // `build` sets the id the backend mints.
397            let mut task: Task = match serde_path_to_error::deserialize(obj_val) {
398                Ok(t) => t,
399                Err(e) => {
400                    // RFC 8620 §5.3: invalidProperties SHOULD list the
401                    // invalid properties; the first path segment is the
402                    // top-level property whose value failed to parse.
403                    let mut err =
404                        json!({ "type": "invalidProperties", "description": e.to_string() });
405                    if let Some(serde_path_to_error::Segment::Map { key }) = e.path().iter().next()
406                    {
407                        err["properties"] = json!([key]);
408                    }
409                    acc.not_created.insert(create_id, err);
410                    continue;
411                }
412            };
413
414            let build = move |id: &Id| {
415                task.id = Some(id.clone());
416                task
417            };
418            match ctx
419                .backend
420                .create_object::<Task, _>(ctx.caller, ctx.account_id, &create_id, build)
421                .await
422            {
423                Ok((_new_id, created_obj)) => {
424                    mutated = true;
425                    acc.created
426                        .insert(create_id, jmap_server::serialize_value(&created_obj)?);
427                }
428                Err(e) => {
429                    acc.not_created
430                        .insert(create_id, backend_set_error_value(e));
431                }
432            }
433        }
434    }
435    Ok(mutated)
436}
437
438/// The `update` part of `Task/set`. Returns whether the backend was
439/// written.
440async fn set_update<B: TasksBackend>(
441    ctx: &SetCtx<'_, B>,
442    args: &mut serde_json::Map<String, Value>,
443    acc: &mut SetAccumulators,
444) -> Result<bool, JmapError> {
445    let mut mutated = false;
446    if let Some(Value::Object(update_map)) = args.remove("update") {
447        for (id_str, patch_val) in update_map {
448            mutated |= update_one(ctx, id_str, patch_val, acc).await?;
449        }
450    }
451    Ok(mutated)
452}
453
454/// One entry of the `Task/set` `update` map. Returns whether the backend
455/// was written.
456async fn update_one<B: TasksBackend>(
457    ctx: &SetCtx<'_, B>,
458    id_str: String,
459    mut patch_val: Value,
460    acc: &mut SetAccumulators,
461) -> Result<bool, JmapError> {
462    // isDraft immutability (draft-tasks-06 §4 isDraft paragraph) is
463    // enforced by the backend in update_object, atomically with the
464    // write (TasksBackend::update_object, bd:JMAP-h47t.29).
465    let id = match jmap_server::parse_wire_id(&id_str, "id") {
466        Ok(id) => id,
467        Err(err) => {
468            acc.not_updated
469                .insert(id_str, serde_json::Value::from(&*err));
470            return Ok(false);
471        }
472    };
473
474    if let Err(err) = resolve_refs(&mut patch_val, TASK_ID_PROPERTIES, ctx.created_ids) {
475        acc.not_updated
476            .insert(id_str, serde_json::Value::from(&*err));
477        return Ok(false);
478    }
479    if let Some(prop) = patch_val.as_object().and_then(bad_person_uri_in_patch) {
480        acc.not_updated.insert(id_str, person_uri_error(&prop));
481        return Ok(false);
482    }
483
484    // Convert wire-format Value into a typed PatchObject. RFC 8620
485    // §5.3 mandates a PatchObject is a JSON Object; non-object
486    // values produce an `invalidPatch` SetError.
487    let mut patch = match serde_json::from_value::<PatchObject>(patch_val) {
488        Ok(p) => p,
489        Err(e) => {
490            acc.not_updated.insert(
491                id_str,
492                json!({ "type": "invalidPatch", "description": e.to_string() }),
493            );
494            return Ok(false);
495        }
496    };
497    // draft-ietf-jmap-tasks-06 §4: `id`, `baseTaskId` and `isOrigin`
498    // are server-set. A changed value is rejected, an identical one
499    // dropped (RFC 8620 §5.3); nothing left is a no-op success.
500    match check_read_only_patch::<_, Task>(
501        ctx.backend,
502        ctx.caller,
503        ctx.account_id,
504        &id,
505        patch.as_map_mut(),
506    )
507    .await
508    {
509        Ok(false) => {}
510        Ok(true) => {
511            acc.updated.insert(id_str, Value::Null);
512            return Ok(false);
513        }
514        Err(err) => {
515            acc.not_updated.insert(id_str, err);
516            return Ok(false);
517        }
518    }
519
520    // Classified after the identical server-set values are dropped above,
521    // so they do not force a per-user change onto the shared path.
522    let is_per_user_only = patch_is_per_user_only(&patch);
523    if let Err(err) = check_metadata_entry(patch.as_map(), false, ctx.using) {
524        acc.not_updated
525            .insert(id_str, serde_json::Value::from(&*err));
526        return Ok(false);
527    }
528
529    let update_result = if is_per_user_only {
530        ctx.backend
531            .update_task_per_user(ctx.caller, ctx.account_id, &id, patch)
532            .await
533    } else {
534        ctx.backend
535            .update_object::<Task>(ctx.caller, ctx.account_id, &id, patch)
536            .await
537    };
538
539    match update_result {
540        Ok(Some(obj)) => {
541            acc.updated
542                .insert(id_str, jmap_server::serialize_value(&obj)?);
543            Ok(true)
544        }
545        Ok(None) => {
546            acc.updated.insert(id_str, Value::Null);
547            Ok(true)
548        }
549        Err(e) => {
550            acc.not_updated.insert(id_str, backend_set_error_value(e));
551            Ok(false)
552        }
553    }
554}
555
556/// Whether every key of a `Task/set` patch targets a per-user Task
557/// property, so the update goes to the per-user path
558/// (draft-tasks-06 §4.5.1).
559///
560/// [`PatchObject`] keys are RFC 6901 JSON Pointers (RFC 8620 §5.3), so a
561/// per-user keyword toggle is sent as `keywords/done`, not bare
562/// `keywords`. Classify on the FIRST pointer segment (the substring
563/// before the first '/'), not the whole key.
564///
565/// A delete-shared-property patch like `{"title": null}` is a
566/// shared mutation and goes to `update_object`.
567///
568/// Per-user property names (`keywords`, `color`, `freeBusyStatus`,
569/// `useDefaultAlerts`, `alerts`) contain no `/` or `~`, so a plain
570/// `split('/').next()` is correct without RFC 6901 unescaping.
571fn patch_is_per_user_only(patch: &PatchObject) -> bool {
572    patch.as_map().keys().all(|k| {
573        let head = k.split('/').next().unwrap_or(k);
574        jmap_tasks_types::is_per_user_task_property(head)
575    })
576}
577
578/// The `destroy` part of `Task/set`. Returns whether the backend was
579/// written.
580///
581/// # Errors
582///
583/// `invalidArguments` when an element of `destroy` is not a string.
584async fn set_destroy<B: TasksBackend>(
585    ctx: &SetCtx<'_, B>,
586    args: &mut serde_json::Map<String, Value>,
587    acc: &mut SetAccumulators,
588) -> Result<bool, JmapError> {
589    let mut mutated = false;
590    if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
591        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
592        // Two-pass validation is intentional: this up-front loop fails the whole
593        // request loudly; the `None => continue` arm in the inner match below
594        // is unreachable BECAUSE this pre-check ran. Future contributor: do NOT
595        // delete this pre-check on the reasoning that the inner match handles
596        // non-string elements — silent-skip is the wrong behaviour per the
597        // workspace "silent-drop is a data-integrity bug class" rule
598        // (JMAP-wlip.1).
599        let id_strs: Vec<&str> = destroy_arr
600            .iter()
601            .map(|v| {
602                v.as_str().ok_or_else(|| {
603                    JmapError::invalid_arguments(format!(
604                        "destroy: every element must be a string Id; got {}",
605                        jmap_server::json_type_name(v)
606                    ))
607                })
608            })
609            .collect::<Result<_, _>>()?;
610        for id_str in id_strs {
611            let id_str = id_str.to_owned();
612            let id = match jmap_server::parse_wire_id(&id_str, "id") {
613                Ok(id) => id,
614                Err(err) => {
615                    acc.not_destroyed
616                        .insert(id_str, serde_json::Value::from(&*err));
617                    continue;
618                }
619            };
620
621            match ctx
622                .backend
623                .destroy_object::<Task>(ctx.caller, ctx.account_id, &id)
624                .await
625            {
626                Ok(()) => {
627                    mutated = true;
628                    acc.destroyed.push(Value::String(id_str));
629                }
630                Err(e) => {
631                    acc.not_destroyed.insert(id_str, backend_set_error_value(e));
632                }
633            }
634        }
635    }
636    Ok(mutated)
637}
638
639// ---------------------------------------------------------------------------
640// Task/copy
641// ---------------------------------------------------------------------------
642
643/// `true` when `value` holds, at any depth, a Person object
644/// (draft-ietf-jmap-tasks §4.2.3 `CheckItem` `assignee`, §4.2.4 Comment
645/// `author`) whose `uri` is a string that is not an RFC 3986 URI
646/// (draft-atwood-jmap-updates-00 §7.1).
647fn has_bad_person_uri(value: &Value) -> bool {
648    match value {
649        Value::Object(m) => {
650            let bad_here = m.get("@type").and_then(Value::as_str) == Some("Person")
651                && m.get("uri")
652                    .and_then(Value::as_str)
653                    .is_some_and(|u| jmap_types::uri::check_uri(u).is_err());
654            bad_here || m.values().any(has_bad_person_uri)
655        }
656        Value::Array(a) => a.iter().any(has_bad_person_uri),
657        _ => false,
658    }
659}
660
661/// The top-level property of the first patch entry that writes a Person
662/// `uri` that is not an RFC 3986 URI: a value holding such a Person, or a
663/// pointer ending in `assignee/uri` or `author/uri` to a non-URI string.
664fn bad_person_uri_in_patch(patch: &serde_json::Map<String, Value>) -> Option<String> {
665    patch.iter().find_map(|(path, v)| {
666        let direct = (path.ends_with("/assignee/uri") || path.ends_with("/author/uri"))
667            && v.as_str()
668                .is_some_and(|u| jmap_types::uri::check_uri(u).is_err());
669        (direct || has_bad_person_uri(v)).then(|| path.split('/').next().unwrap_or(path).to_owned())
670    })
671}
672
673/// The `invalidProperties` `SetError` for a Person `uri` under `property`.
674fn person_uri_error(property: &str) -> Value {
675    json!({
676        "type": "invalidProperties",
677        "properties": [property],
678        "description": "a Person uri is not an RFC 3986 URI",
679    })
680}
681
682/// Handle a `Task/copy` method call (draft-tasks-06 §4.8).
683///
684/// `args` is the RFC 8620 §5.4 `/copy` request shape (`fromAccountId`,
685/// optional `ifFromInState`, `accountId`, optional `ifInState`, `create`
686/// map, optional `onSuccessDestroyOriginal`, optional
687/// `destroyFromIfInState`); the returned `Value` is the §5.4 `/copy`
688/// response shape (`fromAccountId`, `accountId`, optional `oldState`,
689/// `newState`, optional `created`, optional `notCreated`).
690///
691/// `call_id` is the request's method-call id, used to construct any
692/// follow-up `Task/set` invocations injected when
693/// `onSuccessDestroyOriginal` is true (RFC 8620 §5.4 + §6.3).
694///
695/// Copies tasks from `fromAccountId` into the current account. The `create`
696/// map keys are client-side creation ids; the backend assigns new server-side
697/// ids.
698///
699/// `using` is the request's capability list (pass
700/// [`jmap_server::CallContext::using`]). draft-ietf-jmap-metadata-05 §3.4:
701/// the copy keeps the source's `metadata`, and its `privateMetadata` only
702/// with `urn:ietf:params:jmap:metadata` in `using` and when the
703/// destination supports it; neither is copied when the destination does
704/// not list Task ([`JmapAccounts::metadata_info`](jmap_server::JmapAccounts::metadata_info)).
705/// The create object "MAY include metadata and privateMetadata to override
706/// the copied values, with the same rules as a create in Foo/set": the
707/// handler rejects them without the capability and rejects `null`, and
708/// [`TasksBackend::copy_object`] validates the rest against the create
709/// object only: "Copied values are not revalidated against the
710/// destination account".
711///
712/// Returns `(response_args, extra_invocations)`. The extra invocation list
713/// is populated with a follow-up `Task/set` invocation when
714/// `onSuccessDestroyOriginal` is true (RFC 8620 §5.4); otherwise it is
715/// empty.
716///
717/// # Errors
718///
719/// Returns a method-level [`JmapError`]:
720///
721/// - `invalidArguments` when `accountId` or `fromAccountId` is missing or not
722///   a valid Id, `fromAccountId` equals `accountId`, or `create` is missing
723///   or not an object;
724/// - `accountNotFound` when the backend does not know `accountId`;
725/// - `fromAccountNotFound` when the backend does not know `fromAccountId`;
726/// - `stateMismatch` when `ifFromInState` or `ifInState` is not the current
727///   state of its account;
728/// - `serverFail` when the backend fails.
729///
730/// An entry that fails on its own is a
731/// [`SetError`](jmap_server::SetError) in `notCreated`, not an `Err`.
732pub async fn handle_task_copy<B: TasksBackend>(
733    backend: &B,
734    caller: &B::CallerCtx,
735    args: Value,
736    call_id: &str,
737    using: &[String],
738) -> Result<HandlerOutput, JmapError> {
739    let (to_account_id, mut args) = extract_account_id(args)?;
740
741    if !backend
742        .account_exists(caller, &to_account_id)
743        .await
744        .map_err(|e| server_fail_from_backend(&e))?
745    {
746        return Err(JmapError::account_not_found());
747    }
748
749    let from_account_id_str = args
750        .remove("fromAccountId")
751        .and_then(|v| v.as_str().map(|s| s.to_owned()))
752        .ok_or_else(|| JmapError::invalid_arguments("fromAccountId is required"))?;
753    let from_account_id = Id::new_validated(from_account_id_str)
754        .map_err(|e| JmapError::invalid_arguments(format!("fromAccountId: {e}")))?;
755
756    // RFC 8620 §5.4: fromAccountId MUST differ from accountId. The canonical
757    // sibling jmap-mail-server enforces this in handle_email_copy; without it
758    // a same-account "copy" silently produces a duplicate within the source
759    // account, contradicting the meaning of /copy.
760    if from_account_id == to_account_id {
761        return Err(JmapError::invalid_arguments(
762            "fromAccountId must be different from accountId",
763        ));
764    }
765
766    // RFC 8620 §5.4: validate fromAccountId resolves to a real account;
767    // emit the spec-canonical `fromAccountNotFound` (not the generic
768    // `accountNotFound`) when it does not.
769    if !backend
770        .account_exists(caller, &from_account_id)
771        .await
772        .map_err(|e| server_fail_from_backend(&e))?
773    {
774        return Err(JmapError::from_account_not_found());
775    }
776
777    // RFC 8620 §5.4: `create` is a required argument.
778    let Some(Value::Object(create_map)) = args.remove("create") else {
779        return Err(JmapError::invalid_arguments("create is required"));
780    };
781
782    // RFC 8620 §5.4 `ifFromInState`: if supplied, the source-account Task
783    // state MUST match; otherwise abort with stateMismatch. Probed before
784    // the destination state so a stale source guard fails fast.
785    if let Some(if_from_in_state) = args.get("ifFromInState").and_then(|v| v.as_str()) {
786        let from_state = backend
787            .get_state::<Task>(caller, &from_account_id)
788            .await
789            .map_err(|e| server_fail_from_backend(&e))?;
790        if if_from_in_state != from_state.as_ref() {
791            return Err(JmapError::state_mismatch());
792        }
793    }
794
795    let old_state = backend
796        .get_state::<Task>(caller, &to_account_id)
797        .await
798        .map_err(|e| server_fail_from_backend(&e))?;
799
800    // RFC 8620 §5.4 `ifInState`: if supplied, the destination-account Task
801    // state MUST match; otherwise abort with stateMismatch.
802    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str())
803        && if_in_state != old_state.as_ref()
804    {
805        return Err(JmapError::state_mismatch());
806    }
807
808    // RFC 8620 §5.4 `onSuccessDestroyOriginal` / `destroyFromIfInState`:
809    // parsed here so the request payload is consumed in handler-local order
810    // and so a clearly-shaped per-feature value is available below.
811    let on_success_destroy_original: bool = bool_arg(&args, "onSuccessDestroyOriginal", false);
812    let destroy_from_if_in_state: Option<String> = args
813        .get("destroyFromIfInState")
814        .and_then(|v| v.as_str())
815        .map(|s| s.to_owned());
816
817    let mut created = serde_json::Map::new();
818    let mut not_created = serde_json::Map::new();
819    let mut mutated = false;
820    // (create_id, source_id) pairs for entries that succeeded — fed to the
821    // implicit Task/set destroy below when onSuccessDestroyOriginal is true.
822    let mut copied_source_ids: Vec<(String, Id)> = Vec::new();
823
824    for (create_id, client_val) in create_map {
825        // RFC 8620 §5.4: the Foo object MUST contain an `id` property,
826        // which is the id (in the fromAccount) of the record to be copied.
827        // The earlier handler silently invented a "placeholder" id when
828        // the client omitted one, masking the missing-id case the spec
829        // treats as a hard requirement.
830        let Some(source_id_str) = client_val.get("id").and_then(|v| v.as_str()) else {
831            not_created.insert(
832                create_id,
833                json!({"type": "invalidProperties", "properties": ["id"]}),
834            );
835            continue;
836        };
837        let source_id: Id = match jmap_server::parse_wire_id(source_id_str, "id") {
838            Ok(id) => id,
839            Err(err) => {
840                not_created.insert(create_id, serde_json::Value::from(&*err));
841                continue;
842            }
843        };
844
845        // Fetch the source Task from `fromAccountId`. RFC 8620 §5.4 frames
846        // /copy as a read-from-source-then-create-in-destination operation;
847        // unknown source ids surface as `notFound` per-entry SetErrors.
848        let mut source_tasks: Vec<Task> = match backend
849            .get_objects::<Task>(
850                caller,
851                &from_account_id,
852                Some(std::slice::from_ref(&source_id)),
853                None,
854            )
855            .await
856        {
857            Ok((objs, not_found)) => {
858                if !not_found.is_empty() || objs.is_empty() {
859                    not_created.insert(create_id, json!({"type": "notFound"}));
860                    continue;
861                }
862                objs
863            }
864            Err(e) => {
865                not_created.insert(create_id, server_fail_value_from_backend(&e));
866                continue;
867            }
868        };
869
870        // RFC 8620 §5.4: "any other properties included [in the create
871        // entry] are used instead of the current value for that property
872        // on the original." Serialize the source, overlay client-supplied
873        // properties, strip the source id so the backend assigns a fresh
874        // server id. Pattern mirrors jmap-calendars-server event.rs:610-642.
875        // draft-ietf-jmap-metadata-05 §3.4: metadata overrides follow the
876        // Foo/set create rules (§3, §3.2).
877        if let Some(Err(err)) = client_val
878            .as_object()
879            .map(|o| check_metadata_entry(o, true, using))
880        {
881            not_created.insert(create_id, Value::from(&*err));
882            continue;
883        }
884        // -05 §3.4: "When the request does not use this capability, only
885        // metadata is copied", "privateMetadata is not copied when the
886        // destination does not support it, and neither property is
887        // copied when the data type is not listed in the destination
888        // account". The overrides are merged in below.
889        let info = backend.metadata_info::<Task>(caller, &to_account_id);
890        if !jmap_server::uses_metadata(using) || !info.as_ref().is_some_and(|i| i.supports_private)
891        {
892            source_tasks[0].private_metadata = None;
893        }
894        if info.is_none() {
895            source_tasks[0].metadata = None;
896        }
897        let Ok(Value::Object(mut merged)) = serde_json::to_value(&source_tasks[0]) else {
898            not_created.insert(
899                create_id,
900                json!({
901                    "type": "serverFail",
902                    "description": "failed to serialize source Task",
903                }),
904            );
905            continue;
906        };
907        if let Value::Object(client_props) = &client_val {
908            for (k, v) in client_props {
909                if k != "id" {
910                    merged.insert(k.clone(), v.clone());
911                }
912            }
913        }
914        merged.remove("id");
915        // draft-atwood-jmap-updates-00 §7.1, as for Task/set create.
916        if let Some(prop) = merged
917            .iter()
918            .find(|(_, v)| has_bad_person_uri(v))
919            .map(|(k, _)| k.clone())
920        {
921            not_created.insert(create_id, person_uri_error(&prop));
922            continue;
923        }
924
925        let task: Task = match serde_path_to_error::deserialize(Value::Object(merged)) {
926            Ok(t) => t,
927            Err(e) => {
928                // RFC 8620 §5.3: invalidProperties SHOULD list the
929                // invalid properties; the first path segment is the
930                // top-level property whose value failed to parse.
931                let mut err = json!({ "type": "invalidProperties", "description": e.to_string() });
932                if let Some(serde_path_to_error::Segment::Map { key }) = e.path().iter().next() {
933                    err["properties"] = json!([key]);
934                }
935                not_created.insert(create_id, err);
936                continue;
937            }
938        };
939
940        // -05 §3.4: the backend validates only the metadata supplied in
941        // the create object; the copied values are not revalidated.
942        match backend
943            .copy_object(caller, &from_account_id, &to_account_id, task, &client_val)
944            .await
945        {
946            Ok((_new_id, created_task)) => {
947                mutated = true;
948                created.insert(
949                    create_id.clone(),
950                    jmap_server::serialize_value(&created_task)?,
951                );
952                copied_source_ids.push((create_id, source_id));
953            }
954            Err(e) => {
955                not_created.insert(create_id, backend_set_error_value(e));
956            }
957        }
958    }
959
960    let new_state = if mutated {
961        backend
962            .get_state::<Task>(caller, &to_account_id)
963            .await
964            .map_err(|e| server_fail_from_backend(&e))?
965    } else {
966        old_state.clone()
967    };
968
969    let resp = json!({
970        "fromAccountId": from_account_id.as_ref(),
971        "accountId": to_account_id.as_ref(),
972        "oldState": old_state.as_ref(),
973        "newState": new_state.as_ref(),
974        "created":    if created.is_empty()     { Value::Null } else { Value::Object(created) },
975        "notCreated": if not_created.is_empty() { Value::Null } else { Value::Object(not_created) },
976    });
977
978    // RFC 8620 §5.4 `onSuccessDestroyOriginal`: after emitting the Task/copy
979    // response, the server MUST make a single implicit Task/set call against
980    // fromAccountId destroying each successfully copied source record.
981    // `destroyFromIfInState`, if supplied, is passed through as the ifInState
982    // argument on that implicit call. The dispatcher returns the extra
983    // Invocation vec to the caller (RFC 8620 §6.3 chained responses).
984    // Pattern mirrors jmap-mail-server email.rs:2432-2575.
985    let mut extra: Vec<Invocation> = Vec::new();
986    if on_success_destroy_original && !copied_source_ids.is_empty() {
987        let from_old_state = backend
988            .get_state::<Task>(caller, &from_account_id)
989            .await
990            .map_err(|e| server_fail_from_backend(&e))?;
991
992        // Honour destroyFromIfInState on the implicit Task/set call. A
993        // mismatch yields a stateMismatch top-level error on the synthesized
994        // response (§5.4 inheriting §5.3 semantics on the chained call).
995        let mut destroy_state_mismatch = false;
996        if let Some(if_state) = destroy_from_if_in_state.as_deref()
997            && if_state != from_old_state.as_ref()
998        {
999            destroy_state_mismatch = true;
1000        }
1001
1002        let mut destroyed_arr: Vec<Value> = Vec::new();
1003        let mut not_destroyed = serde_json::Map::new();
1004
1005        if !destroy_state_mismatch {
1006            for (_, source_id) in &copied_source_ids {
1007                match backend
1008                    .destroy_object::<Task>(caller, &from_account_id, source_id)
1009                    .await
1010                {
1011                    Ok(()) => {
1012                        destroyed_arr.push(Value::String(source_id.as_ref().to_owned()));
1013                    }
1014                    Err(e) => {
1015                        not_destroyed
1016                            .insert(source_id.as_ref().to_owned(), backend_set_error_value(e));
1017                    }
1018                }
1019            }
1020        }
1021
1022        let from_new_state = backend
1023            .get_state::<Task>(caller, &from_account_id)
1024            .await
1025            .map_err(|e| server_fail_from_backend(&e))?;
1026
1027        let set_resp = if destroy_state_mismatch {
1028            json!({
1029                "type": "stateMismatch",
1030            })
1031        } else {
1032            json!({
1033                "accountId": from_account_id.as_ref(),
1034                "oldState": from_old_state.as_ref(),
1035                "newState": from_new_state.as_ref(),
1036                "created": Value::Null,
1037                "updated": Value::Null,
1038                "destroyed": if destroyed_arr.is_empty() { Value::Null } else { Value::Array(destroyed_arr) },
1039                "notCreated": Value::Null,
1040                "notUpdated": Value::Null,
1041                "notDestroyed": if not_destroyed.is_empty() { Value::Null } else { Value::Object(not_destroyed) },
1042            })
1043        };
1044
1045        let method_name = if destroy_state_mismatch {
1046            "error".to_owned()
1047        } else {
1048            "Task/set".to_owned()
1049        };
1050        extra.push(Invocation::new(method_name, set_resp, call_id.to_owned()));
1051    }
1052
1053    Ok(HandlerOutput::new(resp).with_extra(extra))
1054}
1055
1056// ---------------------------------------------------------------------------
1057// Task/query
1058// ---------------------------------------------------------------------------
1059
1060/// Handle a `Task/query` method call (draft-tasks-06 §4.13).
1061///
1062/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`,
1063/// optional `filter`, optional `sort`, optional `position`, optional
1064/// `anchor`, optional `anchorOffset`, optional `limit`, optional
1065/// `calculateTotal`); the returned `Value` is the §5.5 `/query`
1066/// response shape (`accountId`, `queryState`, `canCalculateChanges`,
1067/// `position`, `ids`, optional `total`).
1068///
1069/// The Task/query arguments of jmapio/jmap #456, as on CalendarEvent/query
1070/// (draft-ietf-jmap-calendars-34 §5.11):
1071///
1072/// - `expandRecurrences`: Boolean (default `false`). "If true, the filter
1073///   MUST be just a `FilterCondition` (not a `FilterOperator`) and MUST include
1074///   both a "before" and "after" property; otherwise, the server MUST
1075///   reject the call with an invalidArguments error." A window longer
1076///   than [`TasksLimits::max_expanded_query_duration_seconds`](crate::TasksLimits::max_expanded_query_duration_seconds)
1077///   (`maxExpandedQueryDuration`, draft-tasks-06 §1.6.2) is the
1078///   `expandDurationTooLarge` method error, checked here and again by the
1079///   backend.
1080/// - `timeZone`: `TimeZoneId` (default `"Etc/UTC"`), the zone for the
1081///   `after` / `before` conditions and for floating tasks. A value that is
1082///   neither a string nor `null` is `invalidArguments`.
1083///
1084/// Both reach [`TasksBackend::query_tasks`] as a
1085/// [`TaskQueryArgs`](crate::TaskQueryArgs). The backend may also return
1086/// `cannotCalculateOccurrences`.
1087///
1088/// `using` is the request's capability list (pass
1089/// [`jmap_server::CallContext::using`]); without
1090/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-05 §3.6
1091/// filter condition is `unsupportedFilter` (-05 §3).
1092///
1093/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
1094///
1095/// # Errors
1096///
1097/// Returns a method-level [`JmapError`]:
1098///
1099/// - `invalidArguments` when `accountId` is missing or not a valid Id, or
1100///   when `filter`, `sort`, `position`, `anchor`, `anchorOffset` or `limit`
1101///   is malformed, `timeZone` is not a string, or
1102///   `expandRecurrences` is set without a filter condition that has both
1103///   `before` and `after`;
1104/// - `accountNotFound` when the backend does not know `accountId`;
1105/// - `unsupportedFilter` when the filter does not decode as a `Task` filter or uses a metadata
1106///   condition without `urn:ietf:params:jmap:metadata` in `using`;
1107/// - `unsupportedSort` when `sort` names a property that is not supported;
1108/// - `expandDurationTooLarge` when `expandRecurrences` spans more than the
1109///   account's `maxExpandedQueryDuration`;
1110/// - `serverFail` when the backend fails, or any other RFC 8620 §5.5 error
1111///   the backend returns, such as `anchorNotFound`.
1112pub async fn handle_task_query<B: TasksBackend>(
1113    backend: &B,
1114    caller: &B::CallerCtx,
1115    args: Value,
1116    using: &[String],
1117) -> Result<HandlerOutput, JmapError> {
1118    jmap_server::reject_metadata_filter_arg(
1119        &args,
1120        jmap_tasks_types::TaskFilterCondition::has_metadata_condition,
1121        using,
1122    )?;
1123    reject_unsupported_sort::<TaskComparator>(args.get("sort"))?;
1124    let (account_id, mut args) = extract_account_id(args)?;
1125    if !backend
1126        .account_exists(caller, &account_id)
1127        .await
1128        .map_err(|e| server_fail_from_backend(&e))?
1129    {
1130        return Err(JmapError::account_not_found());
1131    }
1132    // Task has no localizable properties: as in the generic /query handler,
1133    // a non-null `language` is invalidArguments (draft-atwood-jmap-updates-00
1134    // §4.2).
1135    jmap_server::I18nProjection::from_args::<Task>(
1136        &mut args,
1137        &[],
1138        backend.i18n_info(caller, &account_id).as_ref(),
1139    )?;
1140
1141    // RFC 8620 §5.5 arguments.
1142    let calculate_total = bool_arg(&args, "calculateTotal", false);
1143    let limit: Option<u64> = match args.get("limit") {
1144        None | Some(Value::Null) => None,
1145        Some(v) => Some(v.as_u64().ok_or_else(|| {
1146            JmapError::invalid_arguments(format!(
1147                "limit: expected a non-negative integer, got {}",
1148                jmap_server::json_type_name(v)
1149            ))
1150        })?),
1151    };
1152    let position: i64 = match args.get("position") {
1153        None | Some(Value::Null) => 0,
1154        Some(v) => v.as_i64().ok_or_else(|| {
1155            JmapError::invalid_arguments(format!(
1156                "position: expected an integer, got {}",
1157                jmap_server::json_type_name(v)
1158            ))
1159        })?,
1160    };
1161    let (anchor, anchor_offset) = query_anchor_args(&args)?;
1162    let filter: Option<TaskFilter> = filter_arg(&mut args)?;
1163    let sort: Option<Vec<TaskComparator>> = optional_arg(&mut args, "sort", || {
1164        JmapError::invalid_arguments("sort must be an array")
1165    })?;
1166
1167    // jmapio/jmap #456 arguments.
1168    let expand_recurrences = bool_arg(&args, "expandRecurrences", false);
1169    let time_zone: Option<String> = optional_arg(&mut args, "timeZone", || {
1170        JmapError::invalid_arguments("timeZone must be a string")
1171    })?;
1172    if expand_recurrences {
1173        let condition = match &filter {
1174            Some(Filter::Condition(c)) if c.before.is_some() && c.after.is_some() => c,
1175            _ => {
1176                return Err(JmapError::invalid_arguments(
1177                    "expandRecurrences requires a FilterCondition with both 'before' and 'after'",
1178                ));
1179            }
1180        };
1181        // Defense in depth; the backend re-checks (TasksBackend::query_tasks).
1182        if let Some(secs) = expand_duration_seconds(condition)
1183            && u64::try_from(secs).is_ok_and(|secs| {
1184                secs > backend
1185                    .limits(caller, &account_id)
1186                    .max_expanded_query_duration_seconds
1187            })
1188        {
1189            return Err(JmapError::custom("expandDurationTooLarge"));
1190        }
1191    }
1192    let query_args = crate::TaskQueryArgs::default()
1193        .with_expand_recurrences(expand_recurrences)
1194        .with_time_zone(time_zone);
1195
1196    let result = backend
1197        .query_tasks(
1198            caller,
1199            &account_id,
1200            QueryParams::new()
1201                .filter(filter.as_ref())
1202                .sort(sort.as_deref())
1203                .limit(limit)
1204                .position(position)
1205                .anchor(anchor.as_ref())
1206                .anchor_offset(anchor_offset),
1207            &query_args,
1208        )
1209        .await
1210        .map_err(JmapError::from)?;
1211
1212    let mut resp = json!({
1213        "accountId": account_id.as_ref(),
1214        "queryState": result.query_state.as_ref(),
1215        "canCalculateChanges": result.can_calculate_changes,
1216        "position": result.position,
1217        "ids": result.ids,
1218    });
1219    if calculate_total && let Some(t) = result.total {
1220        resp["total"] = json!(t);
1221    }
1222    Ok(HandlerOutput::new(resp))
1223}
1224
1225/// `before - after` of `condition` in seconds, for the
1226/// `maxExpandedQueryDuration` pre-check; `None` when a bound is missing or
1227/// does not parse.
1228///
1229/// Both bounds are `LocalDateTime`s read in the same `timeZone`, so their
1230/// difference is read as if both were UTC (the calendars-server pre-check
1231/// does the same). A time-zone transition inside the window can make the
1232/// real span differ by its offset change; the backend's own check is the
1233/// exact one.
1234pub(crate) fn expand_duration_seconds(condition: &TaskFilterCondition) -> Option<i64> {
1235    let epoch = |local: &jmap_tasks_types::LocalDateTime| {
1236        UTCDate::from(format!("{local}Z")).to_epoch_seconds().ok()
1237    };
1238    Some(epoch(condition.before.as_ref()?)? - epoch(condition.after.as_ref()?)?)
1239}
1240
1241// ---------------------------------------------------------------------------
1242// Task/queryChanges
1243// ---------------------------------------------------------------------------
1244
1245/// Handle a `Task/queryChanges` method call (draft-tasks-06 §4.14).
1246///
1247/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
1248/// optional `filter`, optional `sort`, `sinceQueryState`, optional
1249/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
1250/// returned `Value` is the §5.6 `/queryChanges` response shape
1251/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
1252/// `removed`, `added`).
1253///
1254/// `using` is the request's capability list (pass
1255/// [`jmap_server::CallContext::using`]); without
1256/// `urn:ietf:params:jmap:metadata` a draft-ietf-jmap-metadata-05 §3.6
1257/// filter condition is `unsupportedFilter` (-05 §3).
1258///
1259/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
1260///
1261/// # Errors
1262///
1263/// Returns a method-level [`JmapError`]:
1264///
1265/// - `invalidArguments` when `accountId` is missing or not a valid Id,
1266///   `sinceQueryState` is missing, or `filter`, `sort`, `maxChanges` or
1267///   `upToId` is malformed;
1268/// - `accountNotFound` when the backend does not know `accountId`;
1269/// - `unsupportedFilter` or `unsupportedSort` as for
1270///   [`handle_task_query`];
1271/// - `cannotCalculateChanges` when `sinceQueryState` was computed in another
1272///   language or the backend cannot compute the changes since it;
1273/// - `tooManyChanges` when there are more changes than `maxChanges`;
1274/// - `serverFail` when the backend fails.
1275pub async fn handle_task_query_changes<B: TasksBackend>(
1276    backend: &B,
1277    caller: &B::CallerCtx,
1278    args: Value,
1279    using: &[String],
1280) -> Result<HandlerOutput, JmapError> {
1281    jmap_server::reject_metadata_filter_arg(
1282        &args,
1283        jmap_tasks_types::TaskFilterCondition::has_metadata_condition,
1284        using,
1285    )?;
1286    reject_unsupported_sort::<TaskComparator>(args.get("sort"))?;
1287    jmap_server::handle_query_changes::<Task, B>(backend, caller, args).await
1288}
1289
1290// ---------------------------------------------------------------------------
1291// Tests
1292// ---------------------------------------------------------------------------
1293
1294#[cfg(test)]
1295mod tests {
1296    use super::*;
1297    use serde_json::json;
1298
1299    use crate::test_support::MockBackend;
1300
1301    /// Oracle: RFC 8620 §5.5 `unsupportedSort`: "The sort is syntactically
1302    /// valid, but includes a property the server does not support sorting
1303    /// on". docs/specs/jmap-tasks-local.md Sorting (draft-ietf-jmap-calendars-34
1304    /// §5.11.2): "MUST be supported for sorting: `id`, `uid`, `start`. The
1305    /// following SHOULD be supported: `created`, `updated`." `title` is not
1306    /// among them, nor is -26's `recurrenceId`, which -34 dropped.
1307    #[tokio::test]
1308    async fn query_unlisted_sort_property_returns_unsupported_sort() {
1309        let backend = MockBackend::new_with_account("acc1");
1310        for property in ["title", "recurrenceId"] {
1311            let args = json!({ "accountId": "acc1", "sort": [{ "property": property }] });
1312            let err = handle_task_query(&backend, &(), args, &[])
1313                .await
1314                .expect_err("unlisted sort property must be rejected");
1315            assert_eq!(err.error_type.to_string(), "unsupportedSort", "{property}");
1316        }
1317    }
1318
1319    /// Oracle: as above; `Task/queryChanges` carries the same `sort`
1320    /// (RFC 8620 §5.6).
1321    #[tokio::test]
1322    async fn query_changes_unlisted_sort_property_returns_unsupported_sort() {
1323        let backend = MockBackend::new_with_account("acc1");
1324        let args = json!({
1325            "accountId": "acc1",
1326            "sinceQueryState": "0",
1327            "sort": [{ "property": "start" }, { "property": "title" }]
1328        });
1329        let err = handle_task_query_changes(&backend, &(), args, &[])
1330            .await
1331            .expect_err("unlisted sort property must be rejected");
1332        assert_eq!(err.error_type.to_string(), "unsupportedSort");
1333    }
1334
1335    /// Oracle: docs/specs/jmap-tasks-local.md Sorting: "The following
1336    /// properties MUST be supported for sorting: `id`, `uid`, `start`. The
1337    /// following SHOULD be supported: `created`, `updated`."
1338    #[tokio::test]
1339    async fn query_listed_sort_property_is_accepted() {
1340        let backend = MockBackend::new_with_account("acc1");
1341        for property in ["id", "uid", "start", "created", "updated"] {
1342            let args = json!({ "accountId": "acc1", "sort": [{ "property": property }] });
1343            handle_task_query(&backend, &(), args, &[])
1344                .await
1345                .expect("listed sort property must not be rejected");
1346        }
1347    }
1348
1349    /// Oracle: Task/get with unknown accountId returns accountNotFound.
1350    #[tokio::test]
1351    async fn get_unknown_account_returns_account_not_found() {
1352        let backend = MockBackend::new();
1353        let args = json!({ "accountId": "unknown", "ids": null });
1354        let result = handle_task_get(&backend, &(), args, &[]).await;
1355        let err = result.expect_err("must return error for unknown account");
1356        assert_eq!(err.error_type.to_string(), "accountNotFound");
1357    }
1358
1359    /// Oracle: Task/copy missing fromAccountId returns invalidArguments.
1360    #[tokio::test]
1361    async fn copy_missing_from_account_id_returns_invalid_arguments() {
1362        let backend = MockBackend::new_with_account("acc1");
1363        let args = json!({
1364            "accountId": "acc1",
1365            "create": {}
1366        });
1367        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
1368        let err = result.expect_err("must return error when fromAccountId missing");
1369        assert_eq!(err.error_type.to_string(), "invalidArguments");
1370    }
1371
1372    /// Oracle: RFC 8620 §5.4 — fromAccountId MUST be different from accountId.
1373    /// A same-account request must be rejected with invalidArguments before
1374    /// any per-create work. Matches the canonical sibling jmap-mail-server
1375    /// at email.rs:2263-2268.
1376    #[tokio::test]
1377    async fn copy_same_account_returns_invalid_arguments() {
1378        let backend = MockBackend::new_with_account("acc1");
1379        let args = json!({
1380            "accountId": "acc1",
1381            "fromAccountId": "acc1",
1382            "create": {}
1383        });
1384        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
1385        let err = result.expect_err("must reject same-account Task/copy per RFC 8620 §5.4");
1386        assert_eq!(err.error_type.to_string(), "invalidArguments");
1387    }
1388
1389    /// Oracle: RFC 8620 §5.4 lists `create` (`Id[Foo]`) among the /copy
1390    /// arguments with no default. As in the canonical `Email/copy`, a
1391    /// missing or non-object `create` is `invalidArguments`, checked after
1392    /// `fromAccountNotFound` and before `ifFromInState`.
1393    #[tokio::test]
1394    async fn copy_missing_or_malformed_create_returns_invalid_arguments() {
1395        let mut backend = MockBackend::new_with_account("acc1");
1396        backend.add_account("acc2");
1397        for create in [None, Some(json!(null)), Some(json!(["t1"]))] {
1398            let mut args = json!({
1399                "accountId": "acc2",
1400                "fromAccountId": "acc1",
1401                "ifFromInState": "stale",
1402            });
1403            if let Some(create) = create.clone() {
1404                args["create"] = create;
1405            }
1406            let err = handle_task_copy(&backend, &(), args, "c0", &[])
1407                .await
1408                .expect_err("create is required");
1409            assert_eq!(
1410                err.error_type.to_string(),
1411                "invalidArguments",
1412                "create {create:?}: {err:?}"
1413            );
1414        }
1415    }
1416
1417    /// Oracle: RFC 8620 §5.4 — `fromAccountId` that does not resolve to a
1418    /// real account returns the spec-canonical `fromAccountNotFound` error,
1419    /// not the generic `accountNotFound`.
1420    #[tokio::test]
1421    async fn copy_unknown_from_account_returns_from_account_not_found() {
1422        let backend = MockBackend::new_with_account("acc1");
1423        let args = json!({
1424            "accountId": "acc1",
1425            "fromAccountId": "no-such-account",
1426            "create": {}
1427        });
1428        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
1429        let err = result.expect_err("must reject unknown fromAccountId");
1430        assert_eq!(err.error_type.to_string(), "fromAccountNotFound");
1431    }
1432
1433    /// Oracle: RFC 8620 §5.4 — `ifFromInState` mismatch on the source
1434    /// account returns `stateMismatch`.
1435    #[tokio::test]
1436    async fn copy_if_from_in_state_mismatch_returns_state_mismatch() {
1437        let mut backend = MockBackend::new_with_account("acc1");
1438        backend.add_account("acc2");
1439        let args = json!({
1440            "accountId": "acc1",
1441            "fromAccountId": "acc2",
1442            "ifFromInState": "stale-source-state",
1443            "create": {}
1444        });
1445        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
1446        let err = result.expect_err("must reject stale ifFromInState");
1447        assert_eq!(err.error_type.to_string(), "stateMismatch");
1448    }
1449
1450    /// Oracle: RFC 8620 §5.4 — `ifInState` mismatch on the destination
1451    /// account returns `stateMismatch`.
1452    #[tokio::test]
1453    async fn copy_if_in_state_mismatch_returns_state_mismatch() {
1454        let mut backend = MockBackend::new_with_account("acc1");
1455        backend.add_account("acc2");
1456        let args = json!({
1457            "accountId": "acc1",
1458            "fromAccountId": "acc2",
1459            "ifInState": "stale-destination-state",
1460            "create": {}
1461        });
1462        let result = handle_task_copy(&backend, &(), args, "c0", &[]).await;
1463        let err = result.expect_err("must reject stale ifInState");
1464        assert_eq!(err.error_type.to_string(), "stateMismatch");
1465    }
1466
1467    /// Oracle: RFC 8620 §5.4 — a create entry without an `id` property must
1468    /// produce a per-entry `invalidProperties` SetError naming `id`. The
1469    /// previous handler silently substituted a "placeholder" id, masking
1470    /// this hard requirement.
1471    #[tokio::test]
1472    async fn copy_create_entry_without_id_returns_invalid_properties() {
1473        let mut backend = MockBackend::new_with_account("acc1");
1474        backend.add_account("acc2");
1475        let args = json!({
1476            "accountId": "acc1",
1477            "fromAccountId": "acc2",
1478            "create": { "c1": {} }
1479        });
1480        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
1481            .await
1482            .expect("top-level call must succeed");
1483        let nc = resp["notCreated"].as_object().expect("notCreated present");
1484        let err = nc.get("c1").expect("c1 in notCreated");
1485        assert_eq!(err["type"], "invalidProperties");
1486        assert_eq!(err["properties"][0], "id");
1487    }
1488
1489    /// Oracle: RFC 8620 §5.4 — when the source id does not resolve to a
1490    /// Task in `fromAccountId`, the per-entry result is `notFound`.
1491    #[tokio::test]
1492    async fn copy_unknown_source_id_returns_not_found() {
1493        let mut backend = MockBackend::new_with_account("acc1");
1494        backend.add_account("acc2");
1495        let args = json!({
1496            "accountId": "acc1",
1497            "fromAccountId": "acc2",
1498            "create": { "c1": { "id": "no-such-task" } }
1499        });
1500        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
1501            .await
1502            .expect("top-level call must succeed");
1503        let nc = resp["notCreated"].as_object().expect("notCreated present");
1504        assert_eq!(nc["c1"]["type"], "notFound");
1505    }
1506
1507    /// Oracle: RFC 8620 §5.4 — the create entry's `id` selects WHAT to copy;
1508    /// client-supplied properties OTHER than `id` overlay the source values.
1509    /// Verify the handler actually round-trips through the source: seed a
1510    /// Task into `from_account`, request a copy that overrides `title`, and
1511    /// confirm the response carries the override.
1512    #[tokio::test]
1513    async fn copy_fetches_source_and_overlays_client_overrides() {
1514        let mut backend = MockBackend::new_with_account("acc1");
1515        backend.add_account("acc2");
1516        backend.seed_task("acc2", "src1", true); // source task in acc2
1517
1518        let args = json!({
1519            "accountId": "acc1",
1520            "fromAccountId": "acc2",
1521            "create": {
1522                "c1": { "id": "src1", "title": "Overridden title" }
1523            }
1524        });
1525        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
1526            .await
1527            .expect("top-level call must succeed");
1528
1529        // Source was fetched and the override applied: the created entry
1530        // carries the new title, not the source value (which had none).
1531        let created = resp["created"].as_object().expect("created present");
1532        let c1 = created.get("c1").expect("c1 in created");
1533        assert_eq!(
1534            c1["title"], "Overridden title",
1535            "client-supplied title must override source value: {resp}"
1536        );
1537    }
1538
1539    /// Oracle: RFC 8620 §5.4 — when `onSuccessDestroyOriginal` is true, the
1540    /// server emits a single implicit Task/set call against fromAccountId
1541    /// destroying each successfully copied source. The synthesized response
1542    /// appears in the extra Vec<Invocation> with the same callId as the
1543    /// triggering Task/copy. Mirrors canonical jmap-mail-server
1544    /// email.rs:2432-2575.
1545    #[tokio::test]
1546    async fn copy_on_success_destroy_original_emits_implicit_task_set() {
1547        let mut backend = MockBackend::new_with_account("acc1");
1548        backend.add_account("acc2");
1549        backend.seed_task("acc2", "src1", true);
1550
1551        let args = json!({
1552            "accountId": "acc1",
1553            "fromAccountId": "acc2",
1554            "onSuccessDestroyOriginal": true,
1555            "create": {
1556                "c1": { "id": "src1" }
1557            }
1558        });
1559        let HandlerOutput {
1560            extra_invocations: extra,
1561            ..
1562        } = handle_task_copy(&backend, &(), args, "c0", &[])
1563            .await
1564            .expect("top-level call must succeed");
1565
1566        // Exactly one synthesized invocation: ("Task/set", response, "c0").
1567        assert_eq!(extra.len(), 1, "must emit one implicit Task/set: {extra:?}");
1568        let Invocation {
1569            name: method,
1570            arguments: val,
1571            call_id: ci,
1572        } = &extra[0];
1573        assert_eq!(method, "Task/set");
1574        assert_eq!(ci, "c0");
1575        assert_eq!(val["accountId"], "acc2", "implicit set targets fromAccount");
1576        let destroyed = val["destroyed"]
1577            .as_array()
1578            .expect("destroyed must be array");
1579        assert_eq!(destroyed.len(), 1);
1580        assert_eq!(destroyed[0], "src1");
1581        // Both state fields are present on the synthesized response. Their
1582        // bump semantics depend on the underlying backend's get_state — the
1583        // MockBackend here always returns "0" so we only assert presence;
1584        // state-advance semantics are covered by stateful integration tests.
1585        assert!(val.get("oldState").is_some(), "oldState must be present");
1586        assert!(val.get("newState").is_some(), "newState must be present");
1587    }
1588
1589    /// Oracle: RFC 8620 §5.4 — `destroyFromIfInState` mismatch on the implicit
1590    /// Task/set call yields a `stateMismatch` error response in place of the
1591    /// normal Task/set body. The destroy MUST NOT proceed.
1592    #[tokio::test]
1593    async fn copy_destroy_from_if_in_state_mismatch_aborts_destroy() {
1594        let mut backend = MockBackend::new_with_account("acc1");
1595        backend.add_account("acc2");
1596        backend.seed_task("acc2", "src1", true);
1597
1598        let args = json!({
1599            "accountId": "acc1",
1600            "fromAccountId": "acc2",
1601            "onSuccessDestroyOriginal": true,
1602            "destroyFromIfInState": "stale-source-state",
1603            "create": {
1604                "c1": { "id": "src1" }
1605            }
1606        });
1607        let HandlerOutput {
1608            extra_invocations: extra,
1609            ..
1610        } = handle_task_copy(&backend, &(), args, "c0", &[])
1611            .await
1612            .expect("top-level call must succeed");
1613
1614        assert_eq!(extra.len(), 1);
1615        let Invocation { arguments: val, .. } = &extra[0];
1616        assert_eq!(val["type"], "stateMismatch");
1617    }
1618
1619    /// Oracle: RFC 8620 §5.4 — when `onSuccessDestroyOriginal` is false (or
1620    /// absent), no implicit Task/set call is synthesized.
1621    #[tokio::test]
1622    async fn copy_without_on_success_emits_no_extra_invocations() {
1623        let mut backend = MockBackend::new_with_account("acc1");
1624        backend.add_account("acc2");
1625        backend.seed_task("acc2", "src1", true);
1626
1627        let args = json!({
1628            "accountId": "acc1",
1629            "fromAccountId": "acc2",
1630            "create": {
1631                "c1": { "id": "src1" }
1632            }
1633        });
1634        let HandlerOutput {
1635            extra_invocations: extra,
1636            ..
1637        } = handle_task_copy(&backend, &(), args, "c0", &[])
1638            .await
1639            .expect("top-level call must succeed");
1640        assert!(
1641            extra.is_empty(),
1642            "no extra invocations without onSuccessDestroyOriginal: {extra:?}"
1643        );
1644    }
1645
1646    /// Oracle: Task/set empty destroy returns valid response.
1647    #[tokio::test]
1648    async fn set_empty_destroy_returns_valid_response() {
1649        let backend = MockBackend::new_with_account("acc1");
1650        let args = json!({ "accountId": "acc1", "destroy": [] });
1651        let HandlerOutput { primary: resp, .. } =
1652            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1653                .await
1654                .expect("must not return top-level error");
1655        assert_eq!(resp["accountId"], "acc1");
1656    }
1657
1658    // ── isDraft immutability enforcement (draft-tasks-06 §4 (isDraft paragraph)) ─
1659
1660    /// Oracle: draft-tasks-06 §4 — "Once set to false, the value [isDraft]
1661    /// cannot be updated to true."
1662    /// A patch of {"isDraft": true} on a task that already has isDraft=false
1663    /// MUST be rejected with invalidProperties. The handler does no isDraft
1664    /// check, so this exercises the backend rejection reaching `notUpdated`.
1665    #[tokio::test]
1666    async fn set_is_draft_revert_rejected_when_current_is_false() {
1667        let mut backend = MockBackend::new_with_account("acc1");
1668        // Pre-seed a published (isDraft=false) task.
1669        backend.seed_task("acc1", "t1", false);
1670
1671        let args = json!({
1672            "accountId": "acc1",
1673            "update": {
1674                "t1": { "isDraft": true }
1675            }
1676        });
1677        let HandlerOutput { primary: resp, .. } =
1678            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1679                .await
1680                .expect("must not return a top-level error");
1681
1682        let not_updated = resp["notUpdated"]
1683            .as_object()
1684            .expect("notUpdated must be an object");
1685        assert!(
1686            not_updated.contains_key("t1"),
1687            "t1 must appear in notUpdated: {resp}"
1688        );
1689        assert_eq!(
1690            not_updated["t1"]["type"].as_str(),
1691            Some("invalidProperties"),
1692            "error type must be invalidProperties"
1693        );
1694        assert_eq!(
1695            not_updated["t1"]["properties"][0].as_str(),
1696            Some("isDraft"),
1697            "properties must list isDraft"
1698        );
1699    }
1700
1701    /// Oracle: draft-tasks-06 §4 — patching {"isDraft": true} on a task that
1702    /// is already a draft (isDraft=true) is allowed (no state transition).
1703    #[tokio::test]
1704    async fn set_is_draft_true_on_draft_task_passes_to_backend() {
1705        let mut backend = MockBackend::new_with_account("acc1");
1706        // Pre-seed a draft task (isDraft=true).
1707        backend.seed_task("acc1", "t2", true);
1708
1709        let args = json!({
1710            "accountId": "acc1",
1711            "update": {
1712                "t2": { "isDraft": true }
1713            }
1714        });
1715        let HandlerOutput { primary: resp, .. } =
1716            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1717                .await
1718                .expect("must not return a top-level error");
1719
1720        // The handler passes the patch to the backend (which returns Forbidden
1721        // in the mock). The important thing is it is NOT pre-rejected here —
1722        // it must NOT appear in notUpdated with type=="invalidProperties".
1723        if let Some(not_updated) = resp["notUpdated"].as_object()
1724            && let Some(err) = not_updated.get("t2")
1725        {
1726            assert_ne!(
1727                err["type"].as_str(),
1728                Some("invalidProperties"),
1729                "isDraft:true on an existing draft must not produce invalidProperties"
1730            );
1731        }
1732    }
1733
1734    /// Oracle: draft-tasks-06 §4 — patching {"isDraft": false} is always allowed
1735    /// (moving from draft to published is a one-way door going the right way).
1736    #[tokio::test]
1737    async fn set_is_draft_false_passes_to_backend() {
1738        let mut backend = MockBackend::new_with_account("acc1");
1739        backend.seed_task("acc1", "t3", true);
1740
1741        let args = json!({
1742            "accountId": "acc1",
1743            "update": {
1744                "t3": { "isDraft": false }
1745            }
1746        });
1747        let HandlerOutput { primary: resp, .. } =
1748            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1749                .await
1750                .expect("must not return a top-level error");
1751
1752        // Like above: the patch must NOT be pre-rejected with invalidProperties.
1753        if let Some(not_updated) = resp["notUpdated"].as_object()
1754            && let Some(err) = not_updated.get("t3")
1755        {
1756            assert_ne!(
1757                err["type"].as_str(),
1758                Some("invalidProperties"),
1759                "isDraft:false must never produce invalidProperties"
1760            );
1761        }
1762    }
1763
1764    // ── compute_utc_times / utcStart wiring (draft-tasks-06 §4 (utcStart/utcDue paragraphs)) ─
1765
1766    /// Oracle: draft-tasks-06 §4 — utcStart is not returned unless explicitly
1767    /// requested in `properties`.  The default impl returns None so it must be
1768    /// absent from the response when not requested.
1769    #[tokio::test]
1770    async fn get_without_utc_properties_omits_utc_fields() {
1771        let backend = MockBackend::new_with_account("acc1");
1772        let args = json!({
1773            "accountId": "acc1",
1774            "ids": null,
1775            "properties": ["id", "title"]  // utcStart and utcDue NOT listed
1776        });
1777        let HandlerOutput { primary: resp, .. } = handle_task_get(&backend, &(), args, &[])
1778            .await
1779            .expect("must succeed");
1780        // The list is empty (no tasks seeded), but the response itself must be valid.
1781        assert_eq!(resp["accountId"], "acc1");
1782        // No utcStart or utcDue should appear in response items (list is empty so
1783        // this is vacuously satisfied, but the path is exercised without error).
1784        let list = resp["list"].as_array().expect("list must be an array");
1785        for item in list {
1786            assert!(
1787                item.get("utcStart").is_none(),
1788                "utcStart must not appear when not in properties"
1789            );
1790        }
1791    }
1792
1793    /// Oracle: draft-tasks-06 §4 — when utcStart is in properties, the handler
1794    /// calls compute_utc_times. The default impl returns (None, None) so
1795    /// no utcStart key is injected, but no error is raised either.
1796    #[tokio::test]
1797    async fn get_with_utc_start_in_properties_does_not_error() {
1798        let backend = MockBackend::new_with_account("acc1");
1799        let args = json!({
1800            "accountId": "acc1",
1801            "ids": null,
1802            "properties": ["id", "utcStart", "utcDue"]
1803        });
1804        let HandlerOutput { primary: resp, .. } = handle_task_get(&backend, &(), args, &[])
1805            .await
1806            .expect("must succeed with utcStart in properties");
1807        assert_eq!(resp["accountId"], "acc1");
1808    }
1809
1810    // ── per-user property routing (draft-tasks-06 §4.5.1) ──────────────────
1811    //
1812    // Routing is observable via MockBackend::per_user_calls — a counter that
1813    // increments inside `update_task_per_user` and stays at 0 for paths that
1814    // go to `update_object`. The earlier shape of these tests only asserted
1815    // that no `invalidProperties` error came back, which would pass even if
1816    // routing were inverted; tightened here to inspect the counter directly.
1817
1818    /// Oracle: draft-tasks-06 §4.5.1 — a patch with only per-user properties
1819    /// (bare keys, no JSON Pointer sub-paths) must route to update_task_per_user.
1820    #[tokio::test]
1821    async fn set_per_user_only_patch_routes_to_per_user_update() {
1822        use std::sync::atomic::Ordering;
1823        let backend = MockBackend::new_with_account("acc1");
1824        // color is a per-user property (§4.5.1).
1825        let args = json!({
1826            "accountId": "acc1",
1827            "update": { "t1": { "color": "#ff0000" } }
1828        });
1829        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1830            .await
1831            .expect("must not return top-level error");
1832        assert_eq!(
1833            backend.per_user_calls.load(Ordering::Relaxed),
1834            1,
1835            "per-user-only patch must route to update_task_per_user"
1836        );
1837    }
1838
1839    /// Oracle: draft-tasks-06 §4.5.1 + RFC 8620 §5.3 — JSON-pointer patches on
1840    /// per-user properties (e.g. `keywords/done: true` to toggle a single
1841    /// keyword, `alerts/0/offset: null` to clear an alert sub-field) must still
1842    /// route to update_task_per_user. The first pointer segment is the
1843    /// property name; the implementation MUST classify on that segment, not
1844    /// on the whole key.
1845    #[tokio::test]
1846    async fn set_per_user_json_pointer_patch_routes_to_per_user_update() {
1847        use std::sync::atomic::Ordering;
1848        let backend = MockBackend::new_with_account("acc1");
1849        let args = json!({
1850            "accountId": "acc1",
1851            "update": {
1852                "t1": {
1853                    "keywords/done": true,
1854                    "alerts/0/offset": null
1855                }
1856            }
1857        });
1858        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1859            .await
1860            .expect("must not return top-level error");
1861        assert_eq!(
1862            backend.per_user_calls.load(Ordering::Relaxed),
1863            1,
1864            "JSON-pointer patch on per-user properties must route to update_task_per_user"
1865        );
1866    }
1867
1868    /// Oracle: RFC 8620 §5.3 "Any server-set properties MAY be included in
1869    /// the patch if their value is identical to the current server value"
1870    /// and draft-tasks-06 §4.5.1: an identical `id` is no change, so a
1871    /// patch of it and a per-user keyword toggle is per-user only and
1872    /// routes to update_task_per_user.
1873    #[tokio::test]
1874    async fn set_identical_id_with_per_user_patch_routes_to_per_user_update() {
1875        use std::sync::atomic::Ordering;
1876        let mut backend = MockBackend::new_with_account("acc1");
1877        backend.seed_task("acc1", "t1", false);
1878        let args = json!({
1879            "accountId": "acc1",
1880            "update": { "t1": { "id": "t1", "keywords/done": true } }
1881        });
1882        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1883            .await
1884            .expect("must not return top-level error");
1885        assert_eq!(
1886            backend.per_user_calls.load(Ordering::Relaxed),
1887            1,
1888            "identical id must not move a per-user patch to update_object"
1889        );
1890    }
1891
1892    /// Oracle: draft-tasks-06 §4.5.1 — a patch on a shared property (title)
1893    /// must route to update_object.
1894    #[tokio::test]
1895    async fn set_shared_property_patch_routes_to_update_object() {
1896        use std::sync::atomic::Ordering;
1897        let backend = MockBackend::new_with_account("acc1");
1898        let args = json!({
1899            "accountId": "acc1",
1900            "update": { "t1": { "title": "New title" } }
1901        });
1902        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1903            .await
1904            .expect("must not return top-level error");
1905        assert_eq!(
1906            backend.per_user_calls.load(Ordering::Relaxed),
1907            0,
1908            "shared-property patch must NOT route to update_task_per_user"
1909        );
1910    }
1911
1912    /// Oracle: RFC 7396 / RFC 8620 §5.3 — `{"title": null}` is a delete-shared-
1913    /// property mutation, NOT a per-user mutation. The previous routing
1914    /// short-circuited on null values, misclassifying this as per-user-only.
1915    #[tokio::test]
1916    async fn set_shared_property_null_patch_routes_to_update_object() {
1917        use std::sync::atomic::Ordering;
1918        let backend = MockBackend::new_with_account("acc1");
1919        let args = json!({
1920            "accountId": "acc1",
1921            "update": { "t1": { "title": null } }
1922        });
1923        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1924            .await
1925            .expect("must not return top-level error");
1926        assert_eq!(
1927            backend.per_user_calls.load(Ordering::Relaxed),
1928            0,
1929            "delete-shared-property patch must NOT route to update_task_per_user"
1930        );
1931    }
1932
1933    /// Oracle: draft-tasks-06 §4.5.1 — a mixed patch (per-user + shared)
1934    /// routes to update_object, never update_task_per_user.
1935    #[tokio::test]
1936    async fn set_mixed_patch_routes_to_update_object() {
1937        use std::sync::atomic::Ordering;
1938        let backend = MockBackend::new_with_account("acc1");
1939        let args = json!({
1940            "accountId": "acc1",
1941            "update": { "t1": { "color": "#ff0000", "title": "New" } }
1942        });
1943        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1944            .await
1945            .expect("must not return top-level error");
1946        assert_eq!(
1947            backend.per_user_calls.load(Ordering::Relaxed),
1948            0,
1949            "mixed patch must route to update_object"
1950        );
1951    }
1952
1953    /// Oracle: RFC 8620 §5.3 — an empty PatchObject is a no-op, not a per-user
1954    /// mutation. The previous routing classified it as per-user-only via
1955    /// vacuous-truth on `iter().all`.
1956    #[tokio::test]
1957    async fn set_empty_patch_routes_to_update_object() {
1958        use std::sync::atomic::Ordering;
1959        let backend = MockBackend::new_with_account("acc1");
1960        let args = json!({
1961            "accountId": "acc1",
1962            "update": { "t1": {} }
1963        });
1964        let _ = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1965            .await
1966            .expect("must not return top-level error");
1967        assert_eq!(
1968            backend.per_user_calls.load(Ordering::Relaxed),
1969            0,
1970            "empty patch must NOT route to update_task_per_user"
1971        );
1972    }
1973
1974    /// RFC 8620 §5.3 types `destroy` as "Id[]|null", so an object element
1975    /// is "invalidArguments: One of the arguments is of the wrong type"
1976    /// (§3.6.2). The description names only the JSON type: §3.6.1 reserves
1977    /// it for "unstructured English text suitable for displaying to a
1978    /// developer", so the client-supplied value is never echoed
1979    /// (bd JMAP-zegc).
1980    #[tokio::test]
1981    async fn set_non_string_destroy_element_does_not_echo_value() {
1982        let backend = MockBackend::new_with_account("acc");
1983        let args = json!({ "accountId": "acc", "destroy": [{ "note": "CANARY-zegc" }] });
1984        let err = handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
1985            .await
1986            .expect_err("non-string destroy element must be a method error");
1987        assert_eq!(err.error_type.to_string(), "invalidArguments");
1988        let desc = err.description.as_deref().unwrap_or_default();
1989        assert!(desc.contains("got object"), "{desc}");
1990        assert!(!desc.contains("CANARY"), "{desc}");
1991    }
1992
1993    /// Oracle: RFC 8620 §5.3: for `invalidProperties` "the SetError object
1994    /// SHOULD also have a property called `properties` of type `String[]`
1995    /// that lists *all* the properties that were invalid". Each create below
1996    /// has exactly one hand-picked bad property.
1997    #[tokio::test]
1998    async fn set_create_typed_parse_failure_names_property() {
1999        let backend = MockBackend::new_with_account("acc1");
2000        let args = json!({
2001            "accountId": "acc1",
2002            "create": {
2003                "badTitle": { "title": 5 },
2004                "badSequence": { "sequence": "x" }
2005            }
2006        });
2007        let HandlerOutput { primary: resp, .. } =
2008            handle_task_set(&backend, &(), &std::collections::BTreeMap::new(), args, &[])
2009                .await
2010                .expect("must not return top-level error");
2011        assert!(resp["created"].is_null(), "nothing may be created: {resp}");
2012        for (cid, prop) in [("badTitle", "title"), ("badSequence", "sequence")] {
2013            let err = &resp["notCreated"][cid];
2014            assert_eq!(err["type"], "invalidProperties", "{cid}: {resp}");
2015            assert_eq!(err["properties"], json!([prop]), "{cid}: {resp}");
2016        }
2017    }
2018
2019    /// Oracle: RFC 8620 §5.3: for `invalidProperties` "the SetError object
2020    /// SHOULD also have a property called `properties` of type `String[]`
2021    /// that lists *all* the properties that were invalid". Each create below
2022    /// has exactly one hand-picked bad property override.
2023    #[tokio::test]
2024    async fn copy_typed_parse_failure_names_property() {
2025        let mut backend = MockBackend::new_with_account("acc1");
2026        backend.add_account("acc2");
2027        backend.seed_task("acc2", "src1", true);
2028        let args = json!({
2029            "accountId": "acc1",
2030            "fromAccountId": "acc2",
2031            "create": {
2032                "badTitle": { "id": "src1", "title": 5 }
2033            }
2034        });
2035        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0", &[])
2036            .await
2037            .expect("must not return top-level error");
2038        assert!(resp["created"].is_null(), "nothing may be created: {resp}");
2039        let err = &resp["notCreated"]["badTitle"];
2040        assert_eq!(err["type"], "invalidProperties", "{resp}");
2041        assert_eq!(err["properties"], json!(["title"]), "{resp}");
2042    }
2043}