Skip to main content

jmap_tasks_server/
task.rs

1//! Task/* method handlers (draft-tasks-06 §4).
2//!
3//! Task/set enforces the `isDraft` immutability constraint: once set to false,
4//! it cannot be set back to true.
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
25//! (`accountNotFound`, `invalidArguments`, `stateMismatch`, `serverFail`,
26//! `unsupportedFilter`, `unsupportedSort`, `cannotCalculateChanges` —
27//! per RFC 8620 §3.6 and §5). Per-target failures inside a `/set` or
28//! `/copy` call surface in the `notCreated` / `notUpdated` /
29//! `notDestroyed` maps within `Ok((Value, ...))`, not as `Err`.
30
31use jmap_tasks_types::Task;
32use jmap_types::{Id, Invocation, JmapError, PatchObject};
33use serde::Deserialize;
34use serde_json::{json, Value};
35
36use crate::backend::{BackendSetError, TasksBackend};
37use crate::helpers::{
38    enforce_max_objects_in_set, extract_account_id, finalize_set_response, set_error_value,
39    SetAccumulators,
40};
41use jmap_server::{server_fail_from_backend, server_fail_value_from_backend, HandlerOutput};
42
43// ---------------------------------------------------------------------------
44// Task/get
45// ---------------------------------------------------------------------------
46
47/// Handle a `Task/get` method call (draft-tasks-06 §4.5).
48///
49/// `args` is the RFC 8620 §5.1 `/get` request shape (`accountId`, optional
50/// `ids`, optional `properties`); the returned `Value` is the §5.1
51/// `/get` response shape (`accountId`, `state`, `list`, `notFound`).
52///
53/// If `"utcStart"` or `"utcDue"` appear in the requested `properties` (or if
54/// `properties` is `null` — meaning all fields), [`TasksBackend::compute_utc_times`]
55/// is called for each returned task and the computed values are merged in
56/// (draft-tasks-06 §4, utcStart/utcDue paragraphs).
57///
58/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
59pub async fn handle_task_get<B: TasksBackend>(
60    backend: &B,
61    caller: &B::CallerCtx,
62    args: Value,
63) -> Result<HandlerOutput, JmapError> {
64    // Determine whether utcStart / utcDue are requested.
65    let want_utc = match args.get("properties") {
66        None | Some(Value::Null) => true, // all properties requested
67        Some(Value::Array(props)) => props
68            .iter()
69            .any(|p| p.as_str().is_some_and(|s| s == "utcStart" || s == "utcDue")),
70        _ => false,
71    };
72
73    // Peek accountId to thread through compute_utc_times (bd:JMAP-ops7.25).
74    // handle_get re-extracts and re-validates idempotently below; a malformed
75    // or missing accountId surfaces here as invalidArguments before the
76    // delegate call.
77    let account_id: Id = args
78        .get("accountId")
79        .and_then(|v| v.as_str())
80        .ok_or_else(|| JmapError::invalid_arguments("accountId is required"))
81        .and_then(|s| {
82            Id::new_validated(s).map_err(|e| {
83                JmapError::invalid_arguments(format!("accountId is not a valid Id: {e}"))
84            })
85        })?;
86
87    // Delegate to the generic get handler.
88    let HandlerOutput {
89        primary: mut response,
90        extra_invocations: tail,
91        ..
92    } = jmap_server::handlers::handle_get::<Task, B>(backend, caller, args).await?;
93
94    // If utcStart or utcDue were requested, augment each returned task.
95    if want_utc {
96        if let Some(Value::Array(list)) = response.get_mut("list") {
97            for item in list.iter_mut() {
98                if let Ok(task) = Task::deserialize(&*item) {
99                    let (utc_start, utc_due) = backend
100                        .compute_utc_times(caller, &account_id, &task, None)
101                        .await;
102                    if let Some(s) = utc_start {
103                        item["utcStart"] = Value::String(s.into_inner());
104                    }
105                    if let Some(d) = utc_due {
106                        item["utcDue"] = Value::String(d.into_inner());
107                    }
108                }
109            }
110        }
111    }
112
113    Ok(HandlerOutput::new(response).with_extra(tail))
114}
115
116// ---------------------------------------------------------------------------
117// Task/changes
118// ---------------------------------------------------------------------------
119
120/// Handle a `Task/changes` method call (draft-tasks-06 §4.6).
121///
122/// `args` is the RFC 8620 §5.2 `/changes` request shape (`accountId`,
123/// `sinceState`, optional `maxChanges`); the returned `Value` is the §5.2
124/// `/changes` response shape (`accountId`, `oldState`, `newState`,
125/// `hasMoreChanges`, `created`, `updated`, `destroyed`).
126///
127/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
128pub async fn handle_task_changes<B: TasksBackend>(
129    backend: &B,
130    caller: &B::CallerCtx,
131    args: Value,
132) -> Result<HandlerOutput, JmapError> {
133    jmap_server::handlers::handle_changes::<Task, B>(backend, caller, args).await
134}
135
136// ---------------------------------------------------------------------------
137// Task/set
138// ---------------------------------------------------------------------------
139
140/// Handle a `Task/set` method call (draft-tasks-06 §4.7).
141///
142/// `args` is the RFC 8620 §5.3 `/set` request shape (`accountId`, optional
143/// `ifInState`, optional `create` / `update` / `destroy` maps); the
144/// returned `Value` is the §5.3 `/set` response shape (`accountId`,
145/// `oldState`, `newState`, plus the per-operation result maps).
146///
147/// **isDraft immutability**: If a patch contains `"isDraft": true` and the
148/// current stored object does not have `isDraft = true`, the update is rejected with
149/// `invalidProperties`. The current object must be fetched from the backend
150/// to check this.
151///
152/// Note: The backend returns the current object via `get_objects` for the
153/// isDraft check. This is not done here to avoid coupling to the stored state;
154/// instead, backends are expected to enforce this constraint and return
155/// `invalidProperties` from `update_object` when the patch violates it.
156/// The handler also does a best-effort check on the patch itself.
157///
158/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
159pub async fn handle_task_set<B: TasksBackend>(
160    backend: &B,
161    caller: &B::CallerCtx,
162    args: Value,
163) -> Result<HandlerOutput, JmapError> {
164    let (account_id, mut args) = extract_account_id(args)?;
165
166    // RFC 8620 §3.6.2: accountId not recognised → accountNotFound (method-level
167    // error). Without this, a /set against an unknown accountId would silently
168    // "succeed" with a fake oldState/newState envelope. Fixed in JMAP-gpt1.
169    if !backend
170        .account_exists(caller, &account_id)
171        .await
172        .map_err(|e| server_fail_from_backend(&e))?
173    {
174        return Err(JmapError::account_not_found());
175    }
176
177    // RFC 8620 §5.3 maxObjectsInSet (bd:JMAP-ayoz.41.5). Reject
178    // unbounded /set batches before touching the storage layer.
179    enforce_max_objects_in_set(&args, backend.max_objects_in_set(caller, &account_id))?;
180
181    let old_state = backend
182        .get_state::<Task>(caller, &account_id)
183        .await
184        .map_err(|e| server_fail_from_backend(&e))?;
185
186    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str()) {
187        if if_in_state != old_state.as_ref() {
188            return Err(JmapError::state_mismatch());
189        }
190    }
191
192    let mut created = serde_json::Map::new();
193    let mut not_created = serde_json::Map::new();
194    let mut updated = serde_json::Map::new();
195    let mut not_updated = serde_json::Map::new();
196    let mut destroyed_list: Vec<Value> = Vec::new();
197    let mut not_destroyed = serde_json::Map::new();
198    let mut mutated = false;
199
200    // -----------------------------------------------------------------------
201    // create
202    // -----------------------------------------------------------------------
203    if let Some(Value::Object(create_map)) = args.remove("create") {
204        for (create_id, obj_val) in create_map {
205            // RFC 8620 §5.3: "The id property MUST NOT be set in the create
206            // object" — id is server-assigned. Any present "id" key (even
207            // null) is rejected with invalidProperties:["id"]. Fixed in
208            // JMAP-n22t. (Task/copy is a separate handler and accepts an
209            // id from the source account; this rejection applies to /set
210            // only.)
211            if obj_val.get("id").is_some() {
212                not_created.insert(
213                    create_id,
214                    json!({"type": "invalidProperties", "properties": ["id"]}),
215                );
216                continue;
217            }
218            let obj_with_id = match obj_val {
219                Value::Object(mut m) => {
220                    m.entry("id").or_insert_with(|| {
221                        Value::String(crate::helpers::PLACEHOLDER_ID.to_owned())
222                    });
223                    Value::Object(m)
224                }
225                other => other,
226            };
227
228            let task: Task = match serde_json::from_value(obj_with_id) {
229                Ok(t) => t,
230                Err(e) => {
231                    not_created.insert(
232                        create_id,
233                        json!({ "type": "invalidProperties", "description": e.to_string() }),
234                    );
235                    continue;
236                }
237            };
238
239            match backend
240                .create_object::<Task>(caller, &account_id, &create_id, task)
241                .await
242            {
243                Ok((_new_id, created_obj)) => {
244                    mutated = true;
245                    created.insert(
246                        create_id,
247                        serde_json::to_value(&created_obj)
248                            .expect("derive(Serialize) on plain data is infallible"),
249                    );
250                }
251                Err(BackendSetError::SetError(set_err)) => {
252                    not_created.insert(create_id, set_error_value(&set_err));
253                }
254                Err(BackendSetError::Other(e)) => {
255                    not_created.insert(create_id, server_fail_value_from_backend(&e));
256                }
257                Err(other) => {
258                    not_created.insert(create_id, server_fail_value_from_backend(&other));
259                }
260            }
261        }
262    }
263
264    // -----------------------------------------------------------------------
265    // update
266    // -----------------------------------------------------------------------
267    if let Some(Value::Object(update_map)) = args.remove("update") {
268        for (id_str, patch_val) in update_map {
269            // isDraft immutability check (draft-tasks-06 §4 (isDraft paragraph)):
270            // once set to false, isDraft MUST NOT be updated back to true.
271            // We enforce this at the handler layer by fetching the current task.
272            //
273            // Fast-path: if the backend reports that it enforces this invariant
274            // atomically in update_object (via enforce_is_draft_atomically()),
275            // skip the pre-fetch get_objects call — the backend will return
276            // InvalidProperties directly.  This saves one backend round-trip per
277            // update that sets isDraft:true when the backend self-enforces.
278            if patch_val.get("isDraft").and_then(|v| v.as_bool()) == Some(true)
279                && !backend.enforce_is_draft_atomically()
280            {
281                // Id::from: wire-boundary validation deferred to JMAP-k9va; backend rejects unknown IDs.
282                let task_id = Id::from(id_str.as_str());
283                match backend
284                    .get_objects::<Task>(caller, &account_id, Some(&[task_id]), None)
285                    .await
286                {
287                    Ok((tasks, _)) => {
288                        // draft-tasks-06 §4: isDraft "may only be set to true
289                        // upon creation", so reject unless it is already true
290                        // (absent counts: a prior null patch must not reopen it).
291                        if tasks.first().is_some_and(|t| t.is_draft != Some(true)) {
292                            not_updated.insert(
293                                id_str,
294                                json!({
295                                    "type": "invalidProperties",
296                                    "properties": ["isDraft"]
297                                }),
298                            );
299                            continue;
300                        }
301                        // Already a draft, or task not found: let the backend
302                        // handle it.
303                    }
304                    Err(e) => {
305                        not_updated.insert(id_str, server_fail_value_from_backend(&e));
306                        continue;
307                    }
308                }
309            }
310
311            let id = Id::from(id_str.as_str());
312
313            // Route to the per-user update path when every patch key targets
314            // a per-user Task property (draft-tasks-06 §4.5.1).
315            //
316            // PatchObject keys are RFC 6901 JSON Pointers (RFC 8620 §5.3), so a
317            // per-user keyword toggle is sent as `keywords/done`, not bare
318            // `keywords`. Classify on the FIRST pointer segment (the substring
319            // before the first '/'), not the whole key.
320            //
321            // The null short-circuit that was here previously (`v.is_null() ||
322            // ...`) misclassified a delete-shared-property patch like
323            // `{"title": null}` as per-user-only, and an empty patch object as
324            // per-user-only via vacuous-truth on `iter().all`. Both go to
325            // `update_object` now: deletions are shared mutations, and an
326            // empty patch is a no-op that should not bump per-user state.
327            //
328            // Per-user property names (`keywords`, `color`, `freeBusyStatus`,
329            // `useDefaultAlerts`, `alerts`) contain no `/` or `~`, so a plain
330            // `split('/').next()` is correct without RFC 6901 unescaping.
331            let is_per_user_only = patch_val.as_object().is_some_and(|m| {
332                !m.is_empty()
333                    && m.keys().all(|k| {
334                        let head = k.split('/').next().unwrap_or(k);
335                        jmap_tasks_types::is_per_user_task_property(head)
336                    })
337            });
338
339            // Convert wire-format Value into a typed PatchObject. RFC 8620
340            // §5.3 mandates a PatchObject is a JSON Object; non-object
341            // values produce an `invalidPatch` SetError. Conversion runs
342            // after the isDraft and per-user-routing introspection above so
343            // those checks operate on the raw wire shape.
344            let patch = match serde_json::from_value::<PatchObject>(patch_val) {
345                Ok(p) => p,
346                Err(e) => {
347                    not_updated.insert(
348                        id_str,
349                        json!({ "type": "invalidPatch", "description": e.to_string() }),
350                    );
351                    continue;
352                }
353            };
354
355            let update_result = if is_per_user_only {
356                backend
357                    .update_task_per_user(caller, &account_id, &id, patch)
358                    .await
359            } else {
360                backend
361                    .update_object::<Task>(caller, &account_id, &id, patch)
362                    .await
363            };
364
365            match update_result {
366                Ok(Some(obj)) => {
367                    mutated = true;
368                    updated.insert(
369                        id_str,
370                        serde_json::to_value(&obj)
371                            .expect("derive(Serialize) on plain data is infallible"),
372                    );
373                }
374                Ok(None) => {
375                    mutated = true;
376                    updated.insert(id_str, Value::Null);
377                }
378                Err(BackendSetError::SetError(set_err)) => {
379                    not_updated.insert(id_str, set_error_value(&set_err));
380                }
381                Err(BackendSetError::Other(e)) => {
382                    not_updated.insert(id_str, server_fail_value_from_backend(&e));
383                }
384                Err(other) => {
385                    not_updated.insert(id_str, server_fail_value_from_backend(&other));
386                }
387            }
388        }
389    }
390
391    // -----------------------------------------------------------------------
392    // destroy
393    // -----------------------------------------------------------------------
394    if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
395        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
396        // Two-pass validation is intentional: this up-front loop fails the whole
397        // request loudly; the `None => continue` arm in the inner match below
398        // is unreachable BECAUSE this pre-check ran. Future contributor: do NOT
399        // delete this pre-check on the reasoning that the inner match handles
400        // non-string elements — silent-skip is the wrong behaviour per the
401        // workspace "silent-drop is a data-integrity bug class" rule
402        // (JMAP-wlip.1).
403        if let Some(bad) = destroy_arr.iter().find(|v| !v.is_string()) {
404            return Err(JmapError::invalid_arguments(format!(
405                "destroy: every element must be a string Id; got {bad}"
406            )));
407        }
408        for id_val in destroy_arr {
409            let id_str = match id_val.as_str() {
410                Some(s) => s.to_owned(),
411                None => continue, // unreachable: validated above
412            };
413            let id = Id::from(id_str.as_str());
414
415            match backend
416                .destroy_object::<Task>(caller, &account_id, &id)
417                .await
418            {
419                Ok(()) => {
420                    mutated = true;
421                    destroyed_list.push(Value::String(id_str));
422                }
423                Err(BackendSetError::SetError(set_err)) => {
424                    not_destroyed.insert(id_str, set_error_value(&set_err));
425                }
426                Err(BackendSetError::Other(e)) => {
427                    not_destroyed.insert(id_str, server_fail_value_from_backend(&e));
428                }
429                Err(other) => {
430                    not_destroyed.insert(id_str, server_fail_value_from_backend(&other));
431                }
432            }
433        }
434    }
435
436    finalize_set_response::<B, Task>(
437        backend,
438        caller,
439        &account_id,
440        old_state,
441        mutated,
442        SetAccumulators {
443            created,
444            updated,
445            destroyed: destroyed_list,
446            not_created,
447            not_updated,
448            not_destroyed,
449        },
450    )
451    .await
452}
453
454// ---------------------------------------------------------------------------
455// Task/copy
456// ---------------------------------------------------------------------------
457
458/// Handle a `Task/copy` method call (draft-tasks-06 §4.8).
459///
460/// `args` is the RFC 8620 §5.4 `/copy` request shape (`fromAccountId`,
461/// optional `ifFromInState`, `accountId`, optional `ifInState`, `create`
462/// map, optional `onSuccessDestroyOriginal`, optional
463/// `destroyFromIfInState`); the returned `Value` is the §5.4 `/copy`
464/// response shape (`fromAccountId`, `accountId`, optional `oldState`,
465/// `newState`, optional `created`, optional `notCreated`).
466///
467/// `call_id` is the request's method-call id, used to construct any
468/// follow-up `Task/set` invocations injected when
469/// `onSuccessDestroyOriginal` is true (RFC 8620 §5.4 + §6.3).
470///
471/// Copies tasks from `fromAccountId` into the current account. The `create`
472/// map keys are client-side creation ids; the backend assigns new server-side
473/// ids.
474///
475/// Returns `(response_args, extra_invocations)`. The extra invocation list
476/// is populated with a follow-up `Task/set` invocation when
477/// `onSuccessDestroyOriginal` is true (RFC 8620 §5.4); otherwise it is
478/// empty.
479pub async fn handle_task_copy<B: TasksBackend>(
480    backend: &B,
481    caller: &B::CallerCtx,
482    args: Value,
483    call_id: &str,
484) -> Result<HandlerOutput, JmapError> {
485    let (to_account_id, mut args) = extract_account_id(args)?;
486
487    if !backend
488        .account_exists(caller, &to_account_id)
489        .await
490        .map_err(|e| server_fail_from_backend(&e))?
491    {
492        return Err(JmapError::account_not_found());
493    }
494
495    let from_account_id_str = args
496        .remove("fromAccountId")
497        .and_then(|v| v.as_str().map(|s| s.to_owned()))
498        .ok_or_else(|| JmapError::invalid_arguments("fromAccountId is required"))?;
499    let from_account_id = Id::from(from_account_id_str.as_str());
500
501    // RFC 8620 §5.4: fromAccountId MUST differ from accountId. The canonical
502    // sibling jmap-mail-server enforces this in handle_email_copy; without it
503    // a same-account "copy" silently produces a duplicate within the source
504    // account, contradicting the meaning of /copy.
505    if from_account_id == to_account_id {
506        return Err(JmapError::invalid_arguments(
507            "fromAccountId must be different from accountId",
508        ));
509    }
510
511    // RFC 8620 §5.4: validate fromAccountId resolves to a real account;
512    // emit the spec-canonical `fromAccountNotFound` (not the generic
513    // `accountNotFound`) when it does not.
514    if !backend
515        .account_exists(caller, &from_account_id)
516        .await
517        .map_err(|e| server_fail_from_backend(&e))?
518    {
519        return Err(JmapError::from_account_not_found());
520    }
521
522    // RFC 8620 §5.4 `ifFromInState`: if supplied, the source-account Task
523    // state MUST match; otherwise abort with stateMismatch. Probed before
524    // the destination state so a stale source guard fails fast.
525    if let Some(if_from_in_state) = args.get("ifFromInState").and_then(|v| v.as_str()) {
526        let from_state = backend
527            .get_state::<Task>(caller, &from_account_id)
528            .await
529            .map_err(|e| server_fail_from_backend(&e))?;
530        if if_from_in_state != from_state.as_ref() {
531            return Err(JmapError::state_mismatch());
532        }
533    }
534
535    let old_state = backend
536        .get_state::<Task>(caller, &to_account_id)
537        .await
538        .map_err(|e| server_fail_from_backend(&e))?;
539
540    // RFC 8620 §5.4 `ifInState`: if supplied, the destination-account Task
541    // state MUST match; otherwise abort with stateMismatch.
542    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str()) {
543        if if_in_state != old_state.as_ref() {
544            return Err(JmapError::state_mismatch());
545        }
546    }
547
548    // RFC 8620 §5.4 `onSuccessDestroyOriginal` / `destroyFromIfInState`:
549    // parsed here so the request payload is consumed in handler-local order
550    // and so a clearly-shaped per-feature value is available below.
551    let on_success_destroy_original: bool = args
552        .get("onSuccessDestroyOriginal")
553        .and_then(|v| v.as_bool())
554        .unwrap_or(false);
555    let destroy_from_if_in_state: Option<String> = args
556        .get("destroyFromIfInState")
557        .and_then(|v| v.as_str())
558        .map(|s| s.to_owned());
559
560    let mut created = serde_json::Map::new();
561    let mut not_created = serde_json::Map::new();
562    let mut mutated = false;
563    // (create_id, source_id) pairs for entries that succeeded — fed to the
564    // implicit Task/set destroy below when onSuccessDestroyOriginal is true.
565    let mut copied_source_ids: Vec<(String, Id)> = Vec::new();
566
567    if let Some(Value::Object(create_map)) = args.remove("create") {
568        for (create_id, client_val) in create_map {
569            // RFC 8620 §5.4: the Foo object MUST contain an `id` property,
570            // which is the id (in the fromAccount) of the record to be copied.
571            // The earlier handler silently invented a "placeholder" id when
572            // the client omitted one, masking the missing-id case the spec
573            // treats as a hard requirement.
574            let Some(source_id_str) = client_val.get("id").and_then(|v| v.as_str()) else {
575                not_created.insert(
576                    create_id,
577                    json!({"type": "invalidProperties", "properties": ["id"]}),
578                );
579                continue;
580            };
581            let source_id: Id = Id::from(source_id_str);
582
583            // Fetch the source Task from `fromAccountId`. RFC 8620 §5.4 frames
584            // /copy as a read-from-source-then-create-in-destination operation;
585            // unknown source ids surface as `notFound` per-entry SetErrors.
586            let source_tasks: Vec<Task> = match backend
587                .get_objects::<Task>(
588                    caller,
589                    &from_account_id,
590                    Some(std::slice::from_ref(&source_id)),
591                    None,
592                )
593                .await
594            {
595                Ok((objs, not_found)) => {
596                    if !not_found.is_empty() || objs.is_empty() {
597                        not_created.insert(create_id, json!({"type": "notFound"}));
598                        continue;
599                    }
600                    objs
601                }
602                Err(e) => {
603                    not_created.insert(create_id, server_fail_value_from_backend(&e));
604                    continue;
605                }
606            };
607
608            // RFC 8620 §5.4: "any other properties included [in the create
609            // entry] are used instead of the current value for that property
610            // on the original." Serialize the source, overlay client-supplied
611            // properties, strip the source id so the backend assigns a fresh
612            // server id. Pattern mirrors jmap-calendars-server event.rs:610-642.
613            let Ok(Value::Object(mut merged)) = serde_json::to_value(&source_tasks[0]) else {
614                not_created.insert(
615                    create_id,
616                    json!({
617                        "type": "serverFail",
618                        "description": "failed to serialize source Task",
619                    }),
620                );
621                continue;
622            };
623            if let Value::Object(client_props) = client_val {
624                for (k, v) in client_props {
625                    if k != "id" {
626                        merged.insert(k, v);
627                    }
628                }
629            }
630            merged.remove("id");
631
632            let task: Task = match serde_json::from_value(Value::Object(merged)) {
633                Ok(t) => t,
634                Err(e) => {
635                    not_created.insert(
636                        create_id,
637                        json!({ "type": "invalidProperties", "description": e.to_string() }),
638                    );
639                    continue;
640                }
641            };
642
643            match backend
644                .create_object::<Task>(caller, &to_account_id, &create_id, task)
645                .await
646            {
647                Ok((_new_id, created_task)) => {
648                    mutated = true;
649                    created.insert(
650                        create_id.clone(),
651                        serde_json::to_value(&created_task)
652                            .expect("derive(Serialize) on plain data is infallible"),
653                    );
654                    copied_source_ids.push((create_id, source_id));
655                }
656                Err(BackendSetError::SetError(set_err)) => {
657                    not_created.insert(create_id, set_error_value(&set_err));
658                }
659                Err(BackendSetError::Other(e)) => {
660                    not_created.insert(create_id, server_fail_value_from_backend(&e));
661                }
662                Err(other) => {
663                    not_created.insert(create_id, server_fail_value_from_backend(&other));
664                }
665            }
666        }
667    }
668
669    let new_state = if mutated {
670        backend
671            .get_state::<Task>(caller, &to_account_id)
672            .await
673            .map_err(|e| server_fail_from_backend(&e))?
674    } else {
675        old_state.clone()
676    };
677
678    let resp = json!({
679        "fromAccountId": from_account_id.as_ref(),
680        "accountId": to_account_id.as_ref(),
681        "oldState": old_state.as_ref(),
682        "newState": new_state.as_ref(),
683        "created":    if created.is_empty()     { Value::Null } else { Value::Object(created) },
684        "notCreated": if not_created.is_empty() { Value::Null } else { Value::Object(not_created) },
685    });
686
687    // RFC 8620 §5.4 `onSuccessDestroyOriginal`: after emitting the Task/copy
688    // response, the server MUST make a single implicit Task/set call against
689    // fromAccountId destroying each successfully copied source record.
690    // `destroyFromIfInState`, if supplied, is passed through as the ifInState
691    // argument on that implicit call. The dispatcher returns the extra
692    // Invocation vec to the caller (RFC 8620 §6.3 chained responses).
693    // Pattern mirrors jmap-mail-server email.rs:2432-2575.
694    let mut extra: Vec<Invocation> = Vec::new();
695    if on_success_destroy_original && !copied_source_ids.is_empty() {
696        let from_old_state = backend
697            .get_state::<Task>(caller, &from_account_id)
698            .await
699            .map_err(|e| server_fail_from_backend(&e))?;
700
701        // Honour destroyFromIfInState on the implicit Task/set call. A
702        // mismatch yields a stateMismatch top-level error on the synthesized
703        // response (§5.4 inheriting §5.3 semantics on the chained call).
704        let mut destroy_state_mismatch = false;
705        if let Some(if_state) = destroy_from_if_in_state.as_deref() {
706            if if_state != from_old_state.as_ref() {
707                destroy_state_mismatch = true;
708            }
709        }
710
711        let mut destroyed_arr: Vec<Value> = Vec::new();
712        let mut not_destroyed = serde_json::Map::new();
713
714        if !destroy_state_mismatch {
715            for (_, source_id) in &copied_source_ids {
716                match backend
717                    .destroy_object::<Task>(caller, &from_account_id, source_id)
718                    .await
719                {
720                    Ok(()) => {
721                        destroyed_arr.push(Value::String(source_id.as_ref().to_owned()));
722                    }
723                    Err(BackendSetError::SetError(set_err)) => {
724                        not_destroyed
725                            .insert(source_id.as_ref().to_owned(), set_error_value(&set_err));
726                    }
727                    Err(BackendSetError::Other(e)) => {
728                        not_destroyed.insert(
729                            source_id.as_ref().to_owned(),
730                            server_fail_value_from_backend(&e),
731                        );
732                    }
733                    Err(other) => {
734                        not_destroyed.insert(
735                            source_id.as_ref().to_owned(),
736                            server_fail_value_from_backend(&other),
737                        );
738                    }
739                }
740            }
741        }
742
743        let from_new_state = backend
744            .get_state::<Task>(caller, &from_account_id)
745            .await
746            .map_err(|e| server_fail_from_backend(&e))?;
747
748        let set_resp = if destroy_state_mismatch {
749            json!({
750                "type": "stateMismatch",
751            })
752        } else {
753            json!({
754                "accountId": from_account_id.as_ref(),
755                "oldState": from_old_state.as_ref(),
756                "newState": from_new_state.as_ref(),
757                "created": Value::Null,
758                "updated": Value::Null,
759                "destroyed": if destroyed_arr.is_empty() { Value::Null } else { Value::Array(destroyed_arr) },
760                "notCreated": Value::Null,
761                "notUpdated": Value::Null,
762                "notDestroyed": if not_destroyed.is_empty() { Value::Null } else { Value::Object(not_destroyed) },
763            })
764        };
765
766        let method_name = if destroy_state_mismatch {
767            "error".to_owned()
768        } else {
769            "Task/set".to_owned()
770        };
771        extra.push(Invocation::new(method_name, set_resp, call_id.to_owned()));
772    }
773
774    Ok(HandlerOutput::new(resp).with_extra(extra))
775}
776
777// ---------------------------------------------------------------------------
778// Task/query
779// ---------------------------------------------------------------------------
780
781/// Handle a `Task/query` method call (draft-tasks-06 §4.13).
782///
783/// `args` is the RFC 8620 §5.5 `/query` request shape (`accountId`,
784/// optional `filter`, optional `sort`, optional `position`, optional
785/// `anchor`, optional `anchorOffset`, optional `limit`, optional
786/// `calculateTotal`); the returned `Value` is the §5.5 `/query`
787/// response shape (`accountId`, `queryState`, `canCalculateChanges`,
788/// `position`, `ids`, optional `total`).
789///
790/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
791pub async fn handle_task_query<B: TasksBackend>(
792    backend: &B,
793    caller: &B::CallerCtx,
794    args: Value,
795) -> Result<HandlerOutput, JmapError> {
796    jmap_server::handlers::handle_query::<Task, B>(backend, caller, args).await
797}
798
799// ---------------------------------------------------------------------------
800// Task/queryChanges
801// ---------------------------------------------------------------------------
802
803/// Handle a `Task/queryChanges` method call (draft-tasks-06 §4.14).
804///
805/// `args` is the RFC 8620 §5.6 `/queryChanges` request shape (`accountId`,
806/// optional `filter`, optional `sort`, `sinceQueryState`, optional
807/// `maxChanges`, optional `upToId`, optional `calculateTotal`); the
808/// returned `Value` is the §5.6 `/queryChanges` response shape
809/// (`accountId`, `oldQueryState`, `newQueryState`, optional `total`,
810/// `removed`, `added`).
811///
812/// Returns `(response_args, extra_invocations)`. The extra list is always empty.
813pub async fn handle_task_query_changes<B: TasksBackend>(
814    backend: &B,
815    caller: &B::CallerCtx,
816    args: Value,
817) -> Result<HandlerOutput, JmapError> {
818    jmap_server::handlers::handle_query_changes::<Task, B>(backend, caller, args).await
819}
820
821// ---------------------------------------------------------------------------
822// Tests
823// ---------------------------------------------------------------------------
824
825#[cfg(test)]
826mod tests {
827    use super::*;
828    use serde_json::json;
829
830    use crate::test_support::MockBackend;
831
832    /// Oracle: Task/get with unknown accountId returns accountNotFound.
833    #[tokio::test]
834    async fn get_unknown_account_returns_account_not_found() {
835        let backend = MockBackend::new();
836        let args = json!({ "accountId": "unknown", "ids": null });
837        let result = handle_task_get(&backend, &(), args).await;
838        let err = result.expect_err("must return error for unknown account");
839        assert_eq!(err.error_type.as_str(), "accountNotFound");
840    }
841
842    /// Oracle: Task/copy missing fromAccountId returns invalidArguments.
843    #[tokio::test]
844    async fn copy_missing_from_account_id_returns_invalid_arguments() {
845        let backend = MockBackend::new_with_account("acc1");
846        let args = json!({
847            "accountId": "acc1",
848            "create": {}
849        });
850        let result = handle_task_copy(&backend, &(), args, "c0").await;
851        let err = result.expect_err("must return error when fromAccountId missing");
852        assert_eq!(err.error_type.as_str(), "invalidArguments");
853    }
854
855    /// Oracle: RFC 8620 §5.4 — fromAccountId MUST be different from accountId.
856    /// A same-account request must be rejected with invalidArguments before
857    /// any per-create work. Matches the canonical sibling jmap-mail-server
858    /// at email.rs:2263-2268.
859    #[tokio::test]
860    async fn copy_same_account_returns_invalid_arguments() {
861        let backend = MockBackend::new_with_account("acc1");
862        let args = json!({
863            "accountId": "acc1",
864            "fromAccountId": "acc1",
865            "create": {}
866        });
867        let result = handle_task_copy(&backend, &(), args, "c0").await;
868        let err = result.expect_err("must reject same-account Task/copy per RFC 8620 §5.4");
869        assert_eq!(err.error_type.as_str(), "invalidArguments");
870    }
871
872    /// Oracle: RFC 8620 §5.4 — `fromAccountId` that does not resolve to a
873    /// real account returns the spec-canonical `fromAccountNotFound` error,
874    /// not the generic `accountNotFound`.
875    #[tokio::test]
876    async fn copy_unknown_from_account_returns_from_account_not_found() {
877        let backend = MockBackend::new_with_account("acc1");
878        let args = json!({
879            "accountId": "acc1",
880            "fromAccountId": "no-such-account",
881            "create": {}
882        });
883        let result = handle_task_copy(&backend, &(), args, "c0").await;
884        let err = result.expect_err("must reject unknown fromAccountId");
885        assert_eq!(err.error_type.as_str(), "fromAccountNotFound");
886    }
887
888    /// Oracle: RFC 8620 §5.4 — `ifFromInState` mismatch on the source
889    /// account returns `stateMismatch`.
890    #[tokio::test]
891    async fn copy_if_from_in_state_mismatch_returns_state_mismatch() {
892        let mut backend = MockBackend::new_with_account("acc1");
893        backend.add_account("acc2");
894        let args = json!({
895            "accountId": "acc1",
896            "fromAccountId": "acc2",
897            "ifFromInState": "stale-source-state",
898            "create": {}
899        });
900        let result = handle_task_copy(&backend, &(), args, "c0").await;
901        let err = result.expect_err("must reject stale ifFromInState");
902        assert_eq!(err.error_type.as_str(), "stateMismatch");
903    }
904
905    /// Oracle: RFC 8620 §5.4 — `ifInState` mismatch on the destination
906    /// account returns `stateMismatch`.
907    #[tokio::test]
908    async fn copy_if_in_state_mismatch_returns_state_mismatch() {
909        let mut backend = MockBackend::new_with_account("acc1");
910        backend.add_account("acc2");
911        let args = json!({
912            "accountId": "acc1",
913            "fromAccountId": "acc2",
914            "ifInState": "stale-destination-state",
915            "create": {}
916        });
917        let result = handle_task_copy(&backend, &(), args, "c0").await;
918        let err = result.expect_err("must reject stale ifInState");
919        assert_eq!(err.error_type.as_str(), "stateMismatch");
920    }
921
922    /// Oracle: RFC 8620 §5.4 — a create entry without an `id` property must
923    /// produce a per-entry `invalidProperties` SetError naming `id`. The
924    /// previous handler silently substituted a "placeholder" id, masking
925    /// this hard requirement.
926    #[tokio::test]
927    async fn copy_create_entry_without_id_returns_invalid_properties() {
928        let mut backend = MockBackend::new_with_account("acc1");
929        backend.add_account("acc2");
930        let args = json!({
931            "accountId": "acc1",
932            "fromAccountId": "acc2",
933            "create": { "c1": {} }
934        });
935        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0")
936            .await
937            .expect("top-level call must succeed");
938        let nc = resp["notCreated"].as_object().expect("notCreated present");
939        let err = nc.get("c1").expect("c1 in notCreated");
940        assert_eq!(err["type"], "invalidProperties");
941        assert_eq!(err["properties"][0], "id");
942    }
943
944    /// Oracle: RFC 8620 §5.4 — when the source id does not resolve to a
945    /// Task in `fromAccountId`, the per-entry result is `notFound`.
946    #[tokio::test]
947    async fn copy_unknown_source_id_returns_not_found() {
948        let mut backend = MockBackend::new_with_account("acc1");
949        backend.add_account("acc2");
950        let args = json!({
951            "accountId": "acc1",
952            "fromAccountId": "acc2",
953            "create": { "c1": { "id": "no-such-task" } }
954        });
955        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0")
956            .await
957            .expect("top-level call must succeed");
958        let nc = resp["notCreated"].as_object().expect("notCreated present");
959        assert_eq!(nc["c1"]["type"], "notFound");
960    }
961
962    /// Oracle: RFC 8620 §5.4 — the create entry's `id` selects WHAT to copy;
963    /// client-supplied properties OTHER than `id` overlay the source values.
964    /// Verify the handler actually round-trips through the source: seed a
965    /// Task into `from_account`, request a copy that overrides `title`, and
966    /// confirm the response carries the override.
967    #[tokio::test]
968    async fn copy_fetches_source_and_overlays_client_overrides() {
969        let mut backend = MockBackend::new_with_account("acc1");
970        backend.add_account("acc2");
971        backend.seed_task("acc2", "src1", true); // source task in acc2
972
973        let args = json!({
974            "accountId": "acc1",
975            "fromAccountId": "acc2",
976            "create": {
977                "c1": { "id": "src1", "title": "Overridden title" }
978            }
979        });
980        let HandlerOutput { primary: resp, .. } = handle_task_copy(&backend, &(), args, "c0")
981            .await
982            .expect("top-level call must succeed");
983
984        // Source was fetched and the override applied: the created entry
985        // carries the new title, not the source value (which had none).
986        let created = resp["created"].as_object().expect("created present");
987        let c1 = created.get("c1").expect("c1 in created");
988        assert_eq!(
989            c1["title"], "Overridden title",
990            "client-supplied title must override source value: {resp}"
991        );
992    }
993
994    /// Oracle: RFC 8620 §5.4 — when `onSuccessDestroyOriginal` is true, the
995    /// server emits a single implicit Task/set call against fromAccountId
996    /// destroying each successfully copied source. The synthesized response
997    /// appears in the extra Vec<Invocation> with the same callId as the
998    /// triggering Task/copy. Mirrors canonical jmap-mail-server
999    /// email.rs:2432-2575.
1000    #[tokio::test]
1001    async fn copy_on_success_destroy_original_emits_implicit_task_set() {
1002        let mut backend = MockBackend::new_with_account("acc1");
1003        backend.add_account("acc2");
1004        backend.seed_task("acc2", "src1", true);
1005
1006        let args = json!({
1007            "accountId": "acc1",
1008            "fromAccountId": "acc2",
1009            "onSuccessDestroyOriginal": true,
1010            "create": {
1011                "c1": { "id": "src1" }
1012            }
1013        });
1014        let HandlerOutput {
1015            extra_invocations: extra,
1016            ..
1017        } = handle_task_copy(&backend, &(), args, "c0")
1018            .await
1019            .expect("top-level call must succeed");
1020
1021        // Exactly one synthesized invocation: ("Task/set", response, "c0").
1022        assert_eq!(extra.len(), 1, "must emit one implicit Task/set: {extra:?}");
1023        let Invocation {
1024            name: method,
1025            arguments: val,
1026            call_id: ci,
1027        } = &extra[0];
1028        assert_eq!(method, "Task/set");
1029        assert_eq!(ci, "c0");
1030        assert_eq!(val["accountId"], "acc2", "implicit set targets fromAccount");
1031        let destroyed = val["destroyed"]
1032            .as_array()
1033            .expect("destroyed must be array");
1034        assert_eq!(destroyed.len(), 1);
1035        assert_eq!(destroyed[0], "src1");
1036        // Both state fields are present on the synthesized response. Their
1037        // bump semantics depend on the underlying backend's get_state — the
1038        // MockBackend here always returns "0" so we only assert presence;
1039        // state-advance semantics are covered by stateful integration tests.
1040        assert!(val.get("oldState").is_some(), "oldState must be present");
1041        assert!(val.get("newState").is_some(), "newState must be present");
1042    }
1043
1044    /// Oracle: RFC 8620 §5.4 — `destroyFromIfInState` mismatch on the implicit
1045    /// Task/set call yields a `stateMismatch` error response in place of the
1046    /// normal Task/set body. The destroy MUST NOT proceed.
1047    #[tokio::test]
1048    async fn copy_destroy_from_if_in_state_mismatch_aborts_destroy() {
1049        let mut backend = MockBackend::new_with_account("acc1");
1050        backend.add_account("acc2");
1051        backend.seed_task("acc2", "src1", true);
1052
1053        let args = json!({
1054            "accountId": "acc1",
1055            "fromAccountId": "acc2",
1056            "onSuccessDestroyOriginal": true,
1057            "destroyFromIfInState": "stale-source-state",
1058            "create": {
1059                "c1": { "id": "src1" }
1060            }
1061        });
1062        let HandlerOutput {
1063            extra_invocations: extra,
1064            ..
1065        } = handle_task_copy(&backend, &(), args, "c0")
1066            .await
1067            .expect("top-level call must succeed");
1068
1069        assert_eq!(extra.len(), 1);
1070        let Invocation { arguments: val, .. } = &extra[0];
1071        assert_eq!(val["type"], "stateMismatch");
1072    }
1073
1074    /// Oracle: RFC 8620 §5.4 — when `onSuccessDestroyOriginal` is false (or
1075    /// absent), no implicit Task/set call is synthesized.
1076    #[tokio::test]
1077    async fn copy_without_on_success_emits_no_extra_invocations() {
1078        let mut backend = MockBackend::new_with_account("acc1");
1079        backend.add_account("acc2");
1080        backend.seed_task("acc2", "src1", true);
1081
1082        let args = json!({
1083            "accountId": "acc1",
1084            "fromAccountId": "acc2",
1085            "create": {
1086                "c1": { "id": "src1" }
1087            }
1088        });
1089        let HandlerOutput {
1090            extra_invocations: extra,
1091            ..
1092        } = handle_task_copy(&backend, &(), args, "c0")
1093            .await
1094            .expect("top-level call must succeed");
1095        assert!(
1096            extra.is_empty(),
1097            "no extra invocations without onSuccessDestroyOriginal: {extra:?}"
1098        );
1099    }
1100
1101    /// Oracle: Task/set empty destroy returns valid response.
1102    #[tokio::test]
1103    async fn set_empty_destroy_returns_valid_response() {
1104        let backend = MockBackend::new_with_account("acc1");
1105        let args = json!({ "accountId": "acc1", "destroy": [] });
1106        let HandlerOutput { primary: resp, .. } = handle_task_set(&backend, &(), args)
1107            .await
1108            .expect("must not return top-level error");
1109        assert_eq!(resp["accountId"], "acc1");
1110    }
1111
1112    // ── isDraft immutability enforcement (draft-tasks-06 §4 (isDraft paragraph)) ─
1113
1114    /// Oracle: draft-tasks-06 §4 — "Once set to false, the value [isDraft]
1115    /// cannot be updated to true."
1116    /// A patch of {"isDraft": true} on a task that already has isDraft=false
1117    /// MUST be rejected at the handler level with invalidProperties.
1118    #[tokio::test]
1119    async fn set_is_draft_revert_rejected_when_current_is_false() {
1120        let mut backend = MockBackend::new_with_account("acc1");
1121        // Pre-seed a published (isDraft=false) task.
1122        backend.seed_task("acc1", "t1", false);
1123
1124        let args = json!({
1125            "accountId": "acc1",
1126            "update": {
1127                "t1": { "isDraft": true }
1128            }
1129        });
1130        let HandlerOutput { primary: resp, .. } = handle_task_set(&backend, &(), args)
1131            .await
1132            .expect("must not return a top-level error");
1133
1134        let not_updated = resp["notUpdated"]
1135            .as_object()
1136            .expect("notUpdated must be an object");
1137        assert!(
1138            not_updated.contains_key("t1"),
1139            "t1 must appear in notUpdated: {resp}"
1140        );
1141        assert_eq!(
1142            not_updated["t1"]["type"].as_str(),
1143            Some("invalidProperties"),
1144            "error type must be invalidProperties"
1145        );
1146        assert_eq!(
1147            not_updated["t1"]["properties"][0].as_str(),
1148            Some("isDraft"),
1149            "properties must list isDraft"
1150        );
1151    }
1152
1153    /// Oracle: draft-tasks-06 §4 — patching {"isDraft": true} on a task that
1154    /// is already a draft (isDraft=true) is allowed (no state transition).
1155    #[tokio::test]
1156    async fn set_is_draft_true_on_draft_task_passes_to_backend() {
1157        let mut backend = MockBackend::new_with_account("acc1");
1158        // Pre-seed a draft task (isDraft=true).
1159        backend.seed_task("acc1", "t2", true);
1160
1161        let args = json!({
1162            "accountId": "acc1",
1163            "update": {
1164                "t2": { "isDraft": true }
1165            }
1166        });
1167        let HandlerOutput { primary: resp, .. } = handle_task_set(&backend, &(), args)
1168            .await
1169            .expect("must not return a top-level error");
1170
1171        // The handler passes the patch to the backend (which returns Forbidden
1172        // in the mock). The important thing is it is NOT pre-rejected here —
1173        // it must NOT appear in notUpdated with type=="invalidProperties".
1174        if let Some(not_updated) = resp["notUpdated"].as_object() {
1175            if let Some(err) = not_updated.get("t2") {
1176                assert_ne!(
1177                    err["type"].as_str(),
1178                    Some("invalidProperties"),
1179                    "isDraft:true on an existing draft must not produce invalidProperties"
1180                );
1181            }
1182        }
1183    }
1184
1185    /// Oracle: draft-tasks-06 §4 — patching {"isDraft": false} is always allowed
1186    /// (moving from draft to published is a one-way door going the right way).
1187    #[tokio::test]
1188    async fn set_is_draft_false_passes_to_backend() {
1189        let mut backend = MockBackend::new_with_account("acc1");
1190        backend.seed_task("acc1", "t3", true);
1191
1192        let args = json!({
1193            "accountId": "acc1",
1194            "update": {
1195                "t3": { "isDraft": false }
1196            }
1197        });
1198        let HandlerOutput { primary: resp, .. } = handle_task_set(&backend, &(), args)
1199            .await
1200            .expect("must not return a top-level error");
1201
1202        // Like above: the patch must NOT be pre-rejected with invalidProperties.
1203        if let Some(not_updated) = resp["notUpdated"].as_object() {
1204            if let Some(err) = not_updated.get("t3") {
1205                assert_ne!(
1206                    err["type"].as_str(),
1207                    Some("invalidProperties"),
1208                    "isDraft:false must never produce invalidProperties"
1209                );
1210            }
1211        }
1212    }
1213
1214    // ── compute_utc_times / utcStart wiring (draft-tasks-06 §4 (utcStart/utcDue paragraphs)) ─
1215
1216    /// Oracle: draft-tasks-06 §4 — utcStart is not returned unless explicitly
1217    /// requested in `properties`.  The default impl returns None so it must be
1218    /// absent from the response when not requested.
1219    #[tokio::test]
1220    async fn get_without_utc_properties_omits_utc_fields() {
1221        let backend = MockBackend::new_with_account("acc1");
1222        let args = json!({
1223            "accountId": "acc1",
1224            "ids": null,
1225            "properties": ["id", "title"]  // utcStart and utcDue NOT listed
1226        });
1227        let HandlerOutput { primary: resp, .. } = handle_task_get(&backend, &(), args)
1228            .await
1229            .expect("must succeed");
1230        // The list is empty (no tasks seeded), but the response itself must be valid.
1231        assert_eq!(resp["accountId"], "acc1");
1232        // No utcStart or utcDue should appear in response items (list is empty so
1233        // this is vacuously satisfied, but the path is exercised without error).
1234        let list = resp["list"].as_array().expect("list must be an array");
1235        for item in list {
1236            assert!(
1237                item.get("utcStart").is_none(),
1238                "utcStart must not appear when not in properties"
1239            );
1240        }
1241    }
1242
1243    /// Oracle: draft-tasks-06 §4 — when utcStart is in properties, the handler
1244    /// calls compute_utc_times. The default impl returns (None, None) so
1245    /// no utcStart key is injected, but no error is raised either.
1246    #[tokio::test]
1247    async fn get_with_utc_start_in_properties_does_not_error() {
1248        let backend = MockBackend::new_with_account("acc1");
1249        let args = json!({
1250            "accountId": "acc1",
1251            "ids": null,
1252            "properties": ["id", "utcStart", "utcDue"]
1253        });
1254        let HandlerOutput { primary: resp, .. } = handle_task_get(&backend, &(), args)
1255            .await
1256            .expect("must succeed with utcStart in properties");
1257        assert_eq!(resp["accountId"], "acc1");
1258    }
1259
1260    // ── per-user property routing (draft-tasks-06 §4.5.1) ──────────────────
1261    //
1262    // Routing is observable via MockBackend::per_user_calls — a counter that
1263    // increments inside `update_task_per_user` and stays at 0 for paths that
1264    // go to `update_object`. The earlier shape of these tests only asserted
1265    // that no `invalidProperties` error came back, which would pass even if
1266    // routing were inverted; tightened here to inspect the counter directly.
1267
1268    /// Oracle: draft-tasks-06 §4.5.1 — a patch with only per-user properties
1269    /// (bare keys, no JSON Pointer sub-paths) must route to update_task_per_user.
1270    #[tokio::test]
1271    async fn set_per_user_only_patch_routes_to_per_user_update() {
1272        use std::sync::atomic::Ordering;
1273        let backend = MockBackend::new_with_account("acc1");
1274        // color is a per-user property (§4.5.1).
1275        let args = json!({
1276            "accountId": "acc1",
1277            "update": { "t1": { "color": "#ff0000" } }
1278        });
1279        let _ = handle_task_set(&backend, &(), args)
1280            .await
1281            .expect("must not return top-level error");
1282        assert_eq!(
1283            backend.per_user_calls.load(Ordering::Relaxed),
1284            1,
1285            "per-user-only patch must route to update_task_per_user"
1286        );
1287    }
1288
1289    /// Oracle: draft-tasks-06 §4.5.1 + RFC 8620 §5.3 — JSON-pointer patches on
1290    /// per-user properties (e.g. `keywords/done: true` to toggle a single
1291    /// keyword, `alerts/0/offset: null` to clear an alert sub-field) must still
1292    /// route to update_task_per_user. The first pointer segment is the
1293    /// property name; the implementation MUST classify on that segment, not
1294    /// on the whole key.
1295    #[tokio::test]
1296    async fn set_per_user_json_pointer_patch_routes_to_per_user_update() {
1297        use std::sync::atomic::Ordering;
1298        let backend = MockBackend::new_with_account("acc1");
1299        let args = json!({
1300            "accountId": "acc1",
1301            "update": {
1302                "t1": {
1303                    "keywords/done": true,
1304                    "alerts/0/offset": null
1305                }
1306            }
1307        });
1308        let _ = handle_task_set(&backend, &(), args)
1309            .await
1310            .expect("must not return top-level error");
1311        assert_eq!(
1312            backend.per_user_calls.load(Ordering::Relaxed),
1313            1,
1314            "JSON-pointer patch on per-user properties must route to update_task_per_user"
1315        );
1316    }
1317
1318    /// Oracle: draft-tasks-06 §4.5.1 — a patch on a shared property (title)
1319    /// must route to update_object.
1320    #[tokio::test]
1321    async fn set_shared_property_patch_routes_to_update_object() {
1322        use std::sync::atomic::Ordering;
1323        let backend = MockBackend::new_with_account("acc1");
1324        let args = json!({
1325            "accountId": "acc1",
1326            "update": { "t1": { "title": "New title" } }
1327        });
1328        let _ = handle_task_set(&backend, &(), args)
1329            .await
1330            .expect("must not return top-level error");
1331        assert_eq!(
1332            backend.per_user_calls.load(Ordering::Relaxed),
1333            0,
1334            "shared-property patch must NOT route to update_task_per_user"
1335        );
1336    }
1337
1338    /// Oracle: RFC 7396 / RFC 8620 §5.3 — `{"title": null}` is a delete-shared-
1339    /// property mutation, NOT a per-user mutation. The previous routing
1340    /// short-circuited on null values, misclassifying this as per-user-only.
1341    #[tokio::test]
1342    async fn set_shared_property_null_patch_routes_to_update_object() {
1343        use std::sync::atomic::Ordering;
1344        let backend = MockBackend::new_with_account("acc1");
1345        let args = json!({
1346            "accountId": "acc1",
1347            "update": { "t1": { "title": null } }
1348        });
1349        let _ = handle_task_set(&backend, &(), args)
1350            .await
1351            .expect("must not return top-level error");
1352        assert_eq!(
1353            backend.per_user_calls.load(Ordering::Relaxed),
1354            0,
1355            "delete-shared-property patch must NOT route to update_task_per_user"
1356        );
1357    }
1358
1359    /// Oracle: draft-tasks-06 §4.5.1 — a mixed patch (per-user + shared)
1360    /// routes to update_object, never update_task_per_user.
1361    #[tokio::test]
1362    async fn set_mixed_patch_routes_to_update_object() {
1363        use std::sync::atomic::Ordering;
1364        let backend = MockBackend::new_with_account("acc1");
1365        let args = json!({
1366            "accountId": "acc1",
1367            "update": { "t1": { "color": "#ff0000", "title": "New" } }
1368        });
1369        let _ = handle_task_set(&backend, &(), args)
1370            .await
1371            .expect("must not return top-level error");
1372        assert_eq!(
1373            backend.per_user_calls.load(Ordering::Relaxed),
1374            0,
1375            "mixed patch must route to update_object"
1376        );
1377    }
1378
1379    /// Oracle: RFC 8620 §5.3 — an empty PatchObject is a no-op, not a per-user
1380    /// mutation. The previous routing classified it as per-user-only via
1381    /// vacuous-truth on `iter().all`.
1382    #[tokio::test]
1383    async fn set_empty_patch_routes_to_update_object() {
1384        use std::sync::atomic::Ordering;
1385        let backend = MockBackend::new_with_account("acc1");
1386        let args = json!({
1387            "accountId": "acc1",
1388            "update": { "t1": {} }
1389        });
1390        let _ = handle_task_set(&backend, &(), args)
1391            .await
1392            .expect("must not return top-level error");
1393        assert_eq!(
1394            backend.per_user_calls.load(Ordering::Relaxed),
1395            0,
1396            "empty patch must NOT route to update_task_per_user"
1397        );
1398    }
1399
1400    // ── isDraft fast-path (enforce_is_draft_atomically) ──────────────────────
1401
1402    /// Oracle: when enforce_is_draft_atomically() returns true, the handler
1403    /// skips the get_objects pre-fetch and delegates isDraft enforcement to
1404    /// update_object.  The backend here accepts the patch (no InvalidProperties),
1405    /// so the handler must not inject a pre-rejection.
1406    ///
1407    /// This test uses MockBackend which has enforce_is_draft_atomically() = false
1408    /// by default.  We verify the fast-path flag is wired correctly by confirming
1409    /// the existing behaviour is unchanged when the flag is false (pre-fetch runs).
1410    #[tokio::test]
1411    async fn set_is_draft_revert_rejected_with_prefetch() {
1412        // Verify the pre-fetch path still works (enforce_is_draft_atomically = false).
1413        let mut backend = MockBackend::new_with_account("acc1");
1414        backend.seed_task("acc1", "t1", false); // published task
1415
1416        let args = json!({
1417            "accountId": "acc1",
1418            "update": { "t1": { "isDraft": true } }
1419        });
1420        let HandlerOutput { primary: resp, .. } = handle_task_set(&backend, &(), args)
1421            .await
1422            .expect("must not return top-level error");
1423
1424        // Pre-fetch detected isDraft=false → rejects with invalidProperties.
1425        let not_updated = resp["notUpdated"].as_object().expect("notUpdated");
1426        assert_eq!(
1427            not_updated["t1"]["type"], "invalidProperties",
1428            "pre-fetch path must reject isDraft revert: {resp}"
1429        );
1430        assert_eq!(not_updated["t1"]["properties"][0], "isDraft");
1431    }
1432
1433    /// Oracle: draft-tasks-06 §4 — isDraft "may only be set to true upon
1434    /// creation." A task whose isDraft is absent (e.g. after a prior
1435    /// `{"isDraft": null}` patch) MUST NOT be updated to true; the pre-fetch
1436    /// path rejects it exactly like a false → true revert.
1437    #[tokio::test]
1438    async fn set_is_draft_true_rejected_when_current_is_absent() {
1439        let mut backend = MockBackend::new_with_account("acc1");
1440        // Seeds "task1" with no isDraft property.
1441        backend.add_task_list_with_task("acc1", "list1");
1442
1443        let args = json!({
1444            "accountId": "acc1",
1445            "update": { "task1": { "isDraft": true } }
1446        });
1447        let HandlerOutput { primary: resp, .. } = handle_task_set(&backend, &(), args)
1448            .await
1449            .expect("must not return top-level error");
1450
1451        let not_updated = resp["notUpdated"].as_object().expect("notUpdated");
1452        assert_eq!(
1453            not_updated["task1"]["type"], "invalidProperties",
1454            "pre-fetch path must reject absent → true: {resp}"
1455        );
1456        assert_eq!(not_updated["task1"]["properties"][0], "isDraft");
1457    }
1458}