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