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
6use jmap_tasks_types::Task;
7use jmap_types::{Id, Invocation, JmapError, PatchObject};
8use serde::Deserialize;
9use serde_json::{json, Value};
10
11use crate::backend::{BackendSetError, TasksBackend};
12use crate::helpers::{extract_account_id, finalize_set_response, set_error_value, SetAccumulators};
13
14// ---------------------------------------------------------------------------
15// Task/get
16// ---------------------------------------------------------------------------
17
18/// Handle a `Task/get` method call (draft-tasks-06 §4.5).
19///
20/// If `"utcStart"` or `"utcDue"` appear in the requested `properties` (or if
21/// `properties` is `null` — meaning all fields), [`TasksBackend::compute_task_utc_times`]
22/// is called for each returned task and the computed values are merged in
23/// (draft-tasks-06 §4, lines 739-772).
24pub async fn handle_task_get<B: TasksBackend>(
25    backend: &B,
26    caller: &B::CallerCtx,
27    args: Value,
28) -> Result<(Value, Vec<Invocation>), JmapError> {
29    // Determine whether utcStart / utcDue are requested.
30    let want_utc = match args.get("properties") {
31        None | Some(Value::Null) => true, // all properties requested
32        Some(Value::Array(props)) => props.iter().any(|p| {
33            p.as_str()
34                .map(|s| s == "utcStart" || s == "utcDue")
35                .unwrap_or(false)
36        }),
37        _ => false,
38    };
39
40    // Delegate to the generic get handler.
41    let (mut response, tail) =
42        jmap_server::handlers::handle_get::<Task, B>(backend, caller, args).await?;
43
44    // If utcStart or utcDue were requested, augment each returned task.
45    if want_utc {
46        if let Some(Value::Array(list)) = response.get_mut("list") {
47            for item in list.iter_mut() {
48                if let Ok(task) = Task::deserialize(&*item) {
49                    let (utc_start, utc_due) = backend.compute_task_utc_times(&task, None);
50                    if let Some(s) = utc_start {
51                        item["utcStart"] = Value::String(s.into_inner());
52                    }
53                    if let Some(d) = utc_due {
54                        item["utcDue"] = Value::String(d.into_inner());
55                    }
56                }
57            }
58        }
59    }
60
61    Ok((response, tail))
62}
63
64// ---------------------------------------------------------------------------
65// Task/changes
66// ---------------------------------------------------------------------------
67
68/// Handle a `Task/changes` method call (draft-tasks-06 §4.6).
69pub async fn handle_task_changes<B: TasksBackend>(
70    backend: &B,
71    caller: &B::CallerCtx,
72    args: Value,
73) -> Result<(Value, Vec<Invocation>), JmapError> {
74    jmap_server::handlers::handle_changes::<Task, B>(backend, caller, args).await
75}
76
77// ---------------------------------------------------------------------------
78// Task/set
79// ---------------------------------------------------------------------------
80
81/// Handle a `Task/set` method call (draft-tasks-06 §4.7).
82///
83/// **isDraft immutability**: If a patch contains `"isDraft": true` and the
84/// current stored object has `isDraft = false`, the update is rejected with
85/// `invalidProperties`. The current object must be fetched from the backend
86/// to check this.
87///
88/// Note: The backend returns the current object via `get_objects` for the
89/// isDraft check. This is not done here to avoid coupling to the stored state;
90/// instead, backends are expected to enforce this constraint and return
91/// `invalidProperties` from `update_object` when the patch violates it.
92/// The handler also does a best-effort check on the patch itself.
93pub async fn handle_task_set<B: TasksBackend>(
94    backend: &B,
95    caller: &B::CallerCtx,
96    args: Value,
97) -> Result<(Value, Vec<Invocation>), JmapError> {
98    let (account_id, mut args) = extract_account_id(args)?;
99
100    // RFC 8620 §3.6.2: accountId not recognised → accountNotFound (method-level
101    // error). Without this, a /set against an unknown accountId would silently
102    // "succeed" with a fake oldState/newState envelope. Fixed in JMAP-gpt1.
103    if !backend
104        .account_exists(caller, &account_id)
105        .await
106        .map_err(|e| JmapError::server_fail(e.to_string()))?
107    {
108        return Err(JmapError::account_not_found());
109    }
110
111    let old_state = backend
112        .get_state::<Task>(caller, &account_id)
113        .await
114        .map_err(|e| JmapError::server_fail(e.to_string()))?;
115
116    if let Some(if_in_state) = args.get("ifInState").and_then(|v| v.as_str()) {
117        if if_in_state != old_state.as_ref() {
118            return Err(JmapError::state_mismatch());
119        }
120    }
121
122    let mut created = serde_json::Map::new();
123    let mut not_created = serde_json::Map::new();
124    let mut updated = serde_json::Map::new();
125    let mut not_updated = serde_json::Map::new();
126    let mut destroyed_list: Vec<Value> = Vec::new();
127    let mut not_destroyed = serde_json::Map::new();
128    let mut mutated = false;
129
130    // -----------------------------------------------------------------------
131    // create
132    // -----------------------------------------------------------------------
133    if let Some(Value::Object(create_map)) = args.remove("create") {
134        for (create_id, obj_val) in create_map {
135            // RFC 8620 §5.3: "The id property MUST NOT be set in the create
136            // object" — id is server-assigned. Any present "id" key (even
137            // null) is rejected with invalidProperties:["id"]. Fixed in
138            // JMAP-n22t. (Task/copy is a separate handler and accepts an
139            // id from the source account; this rejection applies to /set
140            // only.)
141            if obj_val.get("id").is_some() {
142                not_created.insert(
143                    create_id,
144                    json!({"type": "invalidProperties", "properties": ["id"]}),
145                );
146                continue;
147            }
148            let obj_with_id = match obj_val {
149                Value::Object(mut m) => {
150                    m.entry("id")
151                        .or_insert_with(|| Value::String("placeholder".to_owned()));
152                    Value::Object(m)
153                }
154                other => other,
155            };
156
157            let task: Task = match serde_json::from_value(obj_with_id) {
158                Ok(t) => t,
159                Err(e) => {
160                    not_created.insert(
161                        create_id,
162                        json!({ "type": "invalidProperties", "description": e.to_string() }),
163                    );
164                    continue;
165                }
166            };
167
168            match backend
169                .create_object::<Task>(caller, &account_id, &create_id, task)
170                .await
171            {
172                Ok((_new_id, created_obj)) => {
173                    mutated = true;
174                    created.insert(
175                        create_id,
176                        serde_json::to_value(&created_obj)
177                            .expect("derive(Serialize) on plain data is infallible"),
178                    );
179                }
180                Err(BackendSetError::SetError(set_err)) => {
181                    not_created.insert(create_id, set_error_value(&set_err));
182                }
183                Err(BackendSetError::Other(e)) => {
184                    not_created.insert(
185                        create_id,
186                        json!({ "type": "serverFail", "description": e.to_string() }),
187                    );
188                }
189                Err(_) => {
190                    not_created.insert(
191                        create_id,
192                        json!({
193                            "type": "serverFail",
194                            "description": "unhandled backend error variant",
195                        }),
196                    );
197                }
198            }
199        }
200    }
201
202    // -----------------------------------------------------------------------
203    // update
204    // -----------------------------------------------------------------------
205    if let Some(Value::Object(update_map)) = args.remove("update") {
206        for (id_str, patch_val) in update_map {
207            // isDraft immutability check (draft-tasks-06 §4, lines 733-737):
208            // once set to false, isDraft MUST NOT be updated back to true.
209            // We enforce this at the handler layer by fetching the current task.
210            //
211            // Fast-path: if the backend reports that it enforces this invariant
212            // atomically in update_object (via enforce_is_draft_atomically()),
213            // skip the pre-fetch get_objects call — the backend will return
214            // InvalidProperties directly.  This saves one backend round-trip per
215            // update that sets isDraft:true when the backend self-enforces.
216            if patch_val.get("isDraft").and_then(|v| v.as_bool()) == Some(true)
217                && !backend.enforce_is_draft_atomically()
218            {
219                let task_id = Id::from(id_str.as_str());
220                match backend
221                    .get_objects::<Task>(caller, &account_id, Some(&[task_id]), None)
222                    .await
223                {
224                    Ok((tasks, _)) => {
225                        if tasks.first().and_then(|t| t.is_draft) == Some(false) {
226                            // Task is already published; reverting to draft is forbidden.
227                            not_updated.insert(
228                                id_str,
229                                json!({
230                                    "type": "invalidProperties",
231                                    "properties": ["isDraft"]
232                                }),
233                            );
234                            continue;
235                        }
236                        // is_draft == Some(true) or None (no info): allow the
237                        // patch through and let the backend handle it.
238                    }
239                    Err(e) => {
240                        not_updated.insert(
241                            id_str,
242                            json!({ "type": "serverFail", "description": e.to_string() }),
243                        );
244                        continue;
245                    }
246                }
247            }
248
249            let id = Id::from(id_str.as_str());
250
251            // Route to the per-user update path if every non-null patch key is
252            // a per-user Task property (draft-tasks-06 §4.5.1).  Mixed patches
253            // (containing both per-user and shared keys) go to update_object.
254            let is_per_user_only = patch_val
255                .as_object()
256                .map(|m| {
257                    m.iter()
258                        .all(|(k, v)| v.is_null() || B::is_per_user_property(k))
259                })
260                .unwrap_or(false);
261
262            // Convert wire-format Value into a typed PatchObject. RFC 8620
263            // §5.3 mandates a PatchObject is a JSON Object; non-object
264            // values produce an `invalidPatch` SetError. Conversion runs
265            // after the isDraft and per-user-routing introspection above so
266            // those checks operate on the raw wire shape.
267            let patch = match serde_json::from_value::<PatchObject>(patch_val) {
268                Ok(p) => p,
269                Err(e) => {
270                    not_updated.insert(
271                        id_str,
272                        json!({ "type": "invalidPatch", "description": e.to_string() }),
273                    );
274                    continue;
275                }
276            };
277
278            let update_result = if is_per_user_only {
279                backend
280                    .update_task_per_user(caller, &account_id, &id, patch)
281                    .await
282            } else {
283                backend
284                    .update_object::<Task>(caller, &account_id, &id, patch)
285                    .await
286            };
287
288            match update_result {
289                Ok(Some(obj)) => {
290                    mutated = true;
291                    updated.insert(
292                        id_str,
293                        serde_json::to_value(&obj)
294                            .expect("derive(Serialize) on plain data is infallible"),
295                    );
296                }
297                Ok(None) => {
298                    mutated = true;
299                    updated.insert(id_str, Value::Null);
300                }
301                Err(BackendSetError::SetError(set_err)) => {
302                    not_updated.insert(id_str, set_error_value(&set_err));
303                }
304                Err(BackendSetError::Other(e)) => {
305                    not_updated.insert(
306                        id_str,
307                        json!({ "type": "serverFail", "description": e.to_string() }),
308                    );
309                }
310                Err(_) => {
311                    not_updated.insert(
312                        id_str,
313                        json!({
314                            "type": "serverFail",
315                            "description": "unhandled backend error variant",
316                        }),
317                    );
318                }
319            }
320        }
321    }
322
323    // -----------------------------------------------------------------------
324    // destroy
325    // -----------------------------------------------------------------------
326    if let Some(Value::Array(destroy_arr)) = args.remove("destroy") {
327        // RFC 8620 §5.3: every element of the destroy array MUST be a string Id.
328        // Reject the whole request if any element is non-string rather than
329        // silently skipping it, which would produce a misleading response.
330        if let Some(bad) = destroy_arr.iter().find(|v| !v.is_string()) {
331            return Err(JmapError::invalid_arguments(format!(
332                "destroy: every element must be a string Id; got {bad}"
333            )));
334        }
335        for id_val in destroy_arr {
336            let id_str = match id_val.as_str() {
337                Some(s) => s.to_owned(),
338                None => continue, // unreachable: validated above
339            };
340            let id = Id::from(id_str.as_str());
341
342            match backend
343                .destroy_object::<Task>(caller, &account_id, &id)
344                .await
345            {
346                Ok(()) => {
347                    mutated = true;
348                    destroyed_list.push(Value::String(id_str));
349                }
350                Err(BackendSetError::SetError(set_err)) => {
351                    not_destroyed.insert(id_str, set_error_value(&set_err));
352                }
353                Err(BackendSetError::Other(e)) => {
354                    not_destroyed.insert(
355                        id_str,
356                        json!({ "type": "serverFail", "description": e.to_string() }),
357                    );
358                }
359                Err(_) => {
360                    not_destroyed.insert(
361                        id_str,
362                        json!({
363                            "type": "serverFail",
364                            "description": "unhandled backend error variant",
365                        }),
366                    );
367                }
368            }
369        }
370    }
371
372    finalize_set_response::<B, Task>(
373        backend,
374        caller,
375        &account_id,
376        old_state,
377        mutated,
378        SetAccumulators {
379            created,
380            updated,
381            destroyed: destroyed_list,
382            not_created,
383            not_updated,
384            not_destroyed,
385        },
386    )
387    .await
388}
389
390// ---------------------------------------------------------------------------
391// Task/copy
392// ---------------------------------------------------------------------------
393
394/// Handle a `Task/copy` method call (draft-tasks-06 §4.8).
395///
396/// Copies tasks from `fromAccountId` into the current account. The `create`
397/// map keys are client-side creation ids; the backend assigns new server-side
398/// ids.
399pub async fn handle_task_copy<B: TasksBackend>(
400    backend: &B,
401    caller: &B::CallerCtx,
402    args: Value,
403) -> Result<(Value, Vec<Invocation>), JmapError> {
404    let (to_account_id, mut args) = extract_account_id(args)?;
405
406    let from_account_id_str = args
407        .remove("fromAccountId")
408        .and_then(|v| v.as_str().map(|s| s.to_owned()))
409        .ok_or_else(|| JmapError::invalid_arguments("fromAccountId is required"))?;
410    let from_account_id = Id::from(from_account_id_str.as_str());
411
412    if !backend
413        .account_exists(caller, &to_account_id)
414        .await
415        .map_err(|e| JmapError::server_fail(e.to_string()))?
416    {
417        return Err(JmapError::account_not_found());
418    }
419
420    let old_state = backend
421        .get_state::<Task>(caller, &to_account_id)
422        .await
423        .map_err(|e| JmapError::server_fail(e.to_string()))?;
424
425    let mut created = serde_json::Map::new();
426    let mut not_created = serde_json::Map::new();
427    let mut mutated = false;
428
429    if let Some(Value::Object(create_map)) = args.remove("create") {
430        for (create_id, obj_val) in create_map {
431            let obj_with_id = match obj_val {
432                Value::Object(mut m) => {
433                    m.entry("id")
434                        .or_insert_with(|| Value::String("placeholder".to_owned()));
435                    Value::Object(m)
436                }
437                other => other,
438            };
439
440            let task: Task = match serde_json::from_value(obj_with_id) {
441                Ok(t) => t,
442                Err(e) => {
443                    not_created.insert(
444                        create_id,
445                        json!({ "type": "invalidProperties", "description": e.to_string() }),
446                    );
447                    continue;
448                }
449            };
450
451            match backend
452                .copy_task(caller, &from_account_id, &to_account_id, task)
453                .await
454            {
455                Ok((_new_id, copied_task)) => {
456                    mutated = true;
457                    created.insert(
458                        create_id,
459                        serde_json::to_value(&copied_task)
460                            .expect("derive(Serialize) on plain data is infallible"),
461                    );
462                }
463                Err(BackendSetError::SetError(set_err)) => {
464                    not_created.insert(create_id, set_error_value(&set_err));
465                }
466                Err(BackendSetError::Other(e)) => {
467                    not_created.insert(
468                        create_id,
469                        json!({ "type": "serverFail", "description": e.to_string() }),
470                    );
471                }
472                Err(_) => {
473                    not_created.insert(
474                        create_id,
475                        json!({
476                            "type": "serverFail",
477                            "description": "unhandled backend error variant",
478                        }),
479                    );
480                }
481            }
482        }
483    }
484
485    let new_state = if mutated {
486        backend
487            .get_state::<Task>(caller, &to_account_id)
488            .await
489            .map_err(|e| JmapError::server_fail(e.to_string()))?
490    } else {
491        old_state.clone()
492    };
493
494    Ok((
495        json!({
496            "fromAccountId": from_account_id.as_ref(),
497            "accountId": to_account_id.as_ref(),
498            "oldState": old_state.as_ref(),
499            "newState": new_state.as_ref(),
500            "created":    if created.is_empty()     { Value::Null } else { Value::Object(created) },
501            "notCreated": if not_created.is_empty() { Value::Null } else { Value::Object(not_created) },
502        }),
503        vec![],
504    ))
505}
506
507// ---------------------------------------------------------------------------
508// Task/query
509// ---------------------------------------------------------------------------
510
511/// Handle a `Task/query` method call (draft-tasks-06 §4.13).
512pub async fn handle_task_query<B: TasksBackend>(
513    backend: &B,
514    caller: &B::CallerCtx,
515    args: Value,
516) -> Result<(Value, Vec<Invocation>), JmapError> {
517    jmap_server::handlers::handle_query::<Task, B>(backend, caller, args).await
518}
519
520// ---------------------------------------------------------------------------
521// Task/queryChanges
522// ---------------------------------------------------------------------------
523
524/// Handle a `Task/queryChanges` method call (draft-tasks-06 §4.14).
525pub async fn handle_task_query_changes<B: TasksBackend>(
526    backend: &B,
527    caller: &B::CallerCtx,
528    args: Value,
529) -> Result<(Value, Vec<Invocation>), JmapError> {
530    jmap_server::handlers::handle_query_changes::<Task, B>(backend, caller, args).await
531}
532
533// ---------------------------------------------------------------------------
534// Tests
535// ---------------------------------------------------------------------------
536
537#[cfg(test)]
538mod tests {
539    use super::*;
540    use serde_json::json;
541
542    use crate::test_support::MockBackend;
543
544    /// Oracle: Task/get with unknown accountId returns accountNotFound.
545    #[tokio::test]
546    async fn get_unknown_account_returns_account_not_found() {
547        let backend = MockBackend::new();
548        let args = json!({ "accountId": "unknown", "ids": null });
549        let result = handle_task_get(&backend, &(), args).await;
550        let err = result.expect_err("must return error for unknown account");
551        assert_eq!(err.error_type.as_str(), "accountNotFound");
552    }
553
554    /// Oracle: Task/copy missing fromAccountId returns invalidArguments.
555    #[tokio::test]
556    async fn copy_missing_from_account_id_returns_invalid_arguments() {
557        let backend = MockBackend::new_with_account("acc1");
558        let args = json!({
559            "accountId": "acc1",
560            "create": {}
561        });
562        let result = handle_task_copy(&backend, &(), args).await;
563        let err = result.expect_err("must return error when fromAccountId missing");
564        assert_eq!(err.error_type.as_str(), "invalidArguments");
565    }
566
567    /// Oracle: Task/set empty destroy returns valid response.
568    #[tokio::test]
569    async fn set_empty_destroy_returns_valid_response() {
570        let backend = MockBackend::new_with_account("acc1");
571        let args = json!({ "accountId": "acc1", "destroy": [] });
572        let (resp, _) = handle_task_set(&backend, &(), args)
573            .await
574            .expect("must not return top-level error");
575        assert_eq!(resp["accountId"], "acc1");
576    }
577
578    // ── isDraft immutability enforcement (draft-tasks-06 §4, lines 733-737) ─
579
580    /// Oracle: draft-tasks-06 §4 — "Once set to false, the value [isDraft]
581    /// cannot be updated to true."
582    /// A patch of {"isDraft": true} on a task that already has isDraft=false
583    /// MUST be rejected at the handler level with invalidProperties.
584    #[tokio::test]
585    async fn set_is_draft_revert_rejected_when_current_is_false() {
586        let mut backend = MockBackend::new_with_account("acc1");
587        // Pre-seed a published (isDraft=false) task.
588        backend.seed_task("acc1", "t1", false);
589
590        let args = json!({
591            "accountId": "acc1",
592            "update": {
593                "t1": { "isDraft": true }
594            }
595        });
596        let (resp, _) = handle_task_set(&backend, &(), args)
597            .await
598            .expect("must not return a top-level error");
599
600        let not_updated = resp["notUpdated"]
601            .as_object()
602            .expect("notUpdated must be an object");
603        assert!(
604            not_updated.contains_key("t1"),
605            "t1 must appear in notUpdated: {resp}"
606        );
607        assert_eq!(
608            not_updated["t1"]["type"].as_str(),
609            Some("invalidProperties"),
610            "error type must be invalidProperties"
611        );
612        assert_eq!(
613            not_updated["t1"]["properties"][0].as_str(),
614            Some("isDraft"),
615            "properties must list isDraft"
616        );
617    }
618
619    /// Oracle: draft-tasks-06 §4 — patching {"isDraft": true} on a task that
620    /// is already a draft (isDraft=true) is allowed (no state transition).
621    #[tokio::test]
622    async fn set_is_draft_true_on_draft_task_passes_to_backend() {
623        let mut backend = MockBackend::new_with_account("acc1");
624        // Pre-seed a draft task (isDraft=true).
625        backend.seed_task("acc1", "t2", true);
626
627        let args = json!({
628            "accountId": "acc1",
629            "update": {
630                "t2": { "isDraft": true }
631            }
632        });
633        let (resp, _) = handle_task_set(&backend, &(), args)
634            .await
635            .expect("must not return a top-level error");
636
637        // The handler passes the patch to the backend (which returns Forbidden
638        // in the mock). The important thing is it is NOT pre-rejected here —
639        // it must NOT appear in notUpdated with type=="invalidProperties".
640        if let Some(not_updated) = resp["notUpdated"].as_object() {
641            if let Some(err) = not_updated.get("t2") {
642                assert_ne!(
643                    err["type"].as_str(),
644                    Some("invalidProperties"),
645                    "isDraft:true on an existing draft must not produce invalidProperties"
646                );
647            }
648        }
649    }
650
651    /// Oracle: draft-tasks-06 §4 — patching {"isDraft": false} is always allowed
652    /// (moving from draft to published is a one-way door going the right way).
653    #[tokio::test]
654    async fn set_is_draft_false_passes_to_backend() {
655        let mut backend = MockBackend::new_with_account("acc1");
656        backend.seed_task("acc1", "t3", true);
657
658        let args = json!({
659            "accountId": "acc1",
660            "update": {
661                "t3": { "isDraft": false }
662            }
663        });
664        let (resp, _) = handle_task_set(&backend, &(), args)
665            .await
666            .expect("must not return a top-level error");
667
668        // Like above: the patch must NOT be pre-rejected with invalidProperties.
669        if let Some(not_updated) = resp["notUpdated"].as_object() {
670            if let Some(err) = not_updated.get("t3") {
671                assert_ne!(
672                    err["type"].as_str(),
673                    Some("invalidProperties"),
674                    "isDraft:false must never produce invalidProperties"
675                );
676            }
677        }
678    }
679
680    // ── compute_task_utc_times / utcStart wiring (draft-tasks-06 §4 lines 739-772) ─
681
682    /// Oracle: draft-tasks-06 §4 — utcStart is not returned unless explicitly
683    /// requested in `properties`.  The default impl returns None so it must be
684    /// absent from the response when not requested.
685    #[tokio::test]
686    async fn get_without_utc_properties_omits_utc_fields() {
687        let backend = MockBackend::new_with_account("acc1");
688        let args = json!({
689            "accountId": "acc1",
690            "ids": null,
691            "properties": ["id", "title"]  // utcStart and utcDue NOT listed
692        });
693        let (resp, _) = handle_task_get(&backend, &(), args)
694            .await
695            .expect("must succeed");
696        // The list is empty (no tasks seeded), but the response itself must be valid.
697        assert_eq!(resp["accountId"], "acc1");
698        // No utcStart or utcDue should appear in response items (list is empty so
699        // this is vacuously satisfied, but the path is exercised without error).
700        let list = resp["list"].as_array().expect("list must be an array");
701        for item in list {
702            assert!(
703                item.get("utcStart").is_none(),
704                "utcStart must not appear when not in properties"
705            );
706        }
707    }
708
709    /// Oracle: draft-tasks-06 §4 — when utcStart is in properties, the handler
710    /// calls compute_task_utc_times. The default impl returns (None, None) so
711    /// no utcStart key is injected, but no error is raised either.
712    #[tokio::test]
713    async fn get_with_utc_start_in_properties_does_not_error() {
714        let backend = MockBackend::new_with_account("acc1");
715        let args = json!({
716            "accountId": "acc1",
717            "ids": null,
718            "properties": ["id", "utcStart", "utcDue"]
719        });
720        let (resp, _) = handle_task_get(&backend, &(), args)
721            .await
722            .expect("must succeed with utcStart in properties");
723        assert_eq!(resp["accountId"], "acc1");
724    }
725
726    // ── per-user property routing (draft-tasks-06 §4.5.1) ──────────────────
727
728    /// Oracle: draft-tasks-06 §4.5.1 — a patch containing only per-user
729    /// properties must be routed to update_task_per_user. The mock backend's
730    /// update_task_per_user delegates to update_object (which returns Forbidden),
731    /// so the response is the same as a regular update — the test verifies the
732    /// handler path is reached and does not short-circuit with invalidProperties.
733    #[tokio::test]
734    async fn set_per_user_only_patch_routes_to_per_user_update() {
735        let backend = MockBackend::new_with_account("acc1");
736        // color is a per-user property (§4.5.1).
737        let args = json!({
738            "accountId": "acc1",
739            "update": { "t1": { "color": "#ff0000" } }
740        });
741        let (resp, _) = handle_task_set(&backend, &(), args)
742            .await
743            .expect("must not return top-level error");
744        // update_task_per_user → update_object → Forbidden from MockBackend.
745        // Verify: NOT in notUpdated with "invalidProperties" (the handler reached
746        // the backend path, not a pre-rejection).
747        if let Some(nu) = resp["notUpdated"].as_object() {
748            if let Some(err) = nu.get("t1") {
749                assert_ne!(
750                    err["type"].as_str(),
751                    Some("invalidProperties"),
752                    "per-user-only patch must not produce invalidProperties"
753                );
754            }
755        }
756    }
757
758    /// Oracle: draft-tasks-06 §4.5.1 — a patch containing a shared property
759    /// (title) must route to update_object, not update_task_per_user.
760    /// Same observable behaviour as above (both call update_object in mock),
761    /// but verifies the routing decision doesn't crash or misclassify.
762    #[tokio::test]
763    async fn set_shared_property_patch_routes_to_update_object() {
764        let backend = MockBackend::new_with_account("acc1");
765        let args = json!({
766            "accountId": "acc1",
767            "update": { "t1": { "title": "New title" } }
768        });
769        let (resp, _) = handle_task_set(&backend, &(), args)
770            .await
771            .expect("must not return top-level error");
772        if let Some(nu) = resp["notUpdated"].as_object() {
773            if let Some(err) = nu.get("t1") {
774                assert_ne!(
775                    err["type"].as_str(),
776                    Some("invalidProperties"),
777                    "shared-property patch must not produce invalidProperties"
778                );
779            }
780        }
781    }
782
783    /// Oracle: draft-tasks-06 §4.5.1 — a mixed patch (per-user + shared)
784    /// routes to update_object (not update_task_per_user).
785    #[tokio::test]
786    async fn set_mixed_patch_routes_to_update_object() {
787        let backend = MockBackend::new_with_account("acc1");
788        // color = per-user; title = shared → mixed patch must go to update_object.
789        let args = json!({
790            "accountId": "acc1",
791            "update": { "t1": { "color": "#ff0000", "title": "New" } }
792        });
793        let (resp, _) = handle_task_set(&backend, &(), args)
794            .await
795            .expect("must not return top-level error");
796        // Verify no crash and handler reached backend normally.
797        assert_eq!(resp["accountId"], "acc1");
798    }
799
800    // ── isDraft fast-path (enforce_is_draft_atomically) ──────────────────────
801
802    /// Oracle: when enforce_is_draft_atomically() returns true, the handler
803    /// skips the get_objects pre-fetch and delegates isDraft enforcement to
804    /// update_object.  The backend here accepts the patch (no InvalidProperties),
805    /// so the handler must not inject a pre-rejection.
806    ///
807    /// This test uses MockBackend which has enforce_is_draft_atomically() = false
808    /// by default.  We verify the fast-path flag is wired correctly by confirming
809    /// the existing behaviour is unchanged when the flag is false (pre-fetch runs).
810    #[tokio::test]
811    async fn set_is_draft_revert_rejected_with_prefetch() {
812        // Verify the pre-fetch path still works (enforce_is_draft_atomically = false).
813        let mut backend = MockBackend::new_with_account("acc1");
814        backend.seed_task("acc1", "t1", false); // published task
815
816        let args = json!({
817            "accountId": "acc1",
818            "update": { "t1": { "isDraft": true } }
819        });
820        let (resp, _) = handle_task_set(&backend, &(), args)
821            .await
822            .expect("must not return top-level error");
823
824        // Pre-fetch detected isDraft=false → rejects with invalidProperties.
825        let not_updated = resp["notUpdated"].as_object().expect("notUpdated");
826        assert_eq!(
827            not_updated["t1"]["type"], "invalidProperties",
828            "pre-fetch path must reject isDraft revert: {resp}"
829        );
830        assert_eq!(not_updated["t1"]["properties"][0], "isDraft");
831    }
832}