Skip to main content

adk_server/a2a/v1/
task_store.rs

1//! A2A v1.0.0 task store — trait and in-memory implementation.
2//!
3//! Defines [`TaskStore`] for persisting A2A task state (status, artifacts,
4//! history) beyond a single execution, and [`InMemoryTaskStore`] for
5//! development and testing.
6
7use std::collections::HashMap;
8
9use async_trait::async_trait;
10use chrono::Utc;
11use tokio::sync::RwLock;
12
13use super::error::A2aError;
14
15/// [`TaskStoreEntry::metadata`] key holding the authenticated user that created a task.
16///
17/// The request handler writes it when a caller is authenticated and only serves
18/// the task to that caller. It is never sent on the wire: task and status-event
19/// conversions drop it. A custom [`TaskStore`] persists it like any other metadata.
20pub const OWNER_METADATA_KEY: &str = "adk.owner";
21
22/// An entry in the task store representing a persisted A2A task.
23#[derive(Debug, Clone)]
24pub struct TaskStoreEntry {
25    /// Unique task identifier.
26    pub id: String,
27    /// Conversation context this task belongs to.
28    pub context_id: String,
29    /// Current task status (state + optional message + timestamp).
30    pub status: a2a_protocol_types::TaskStatus,
31    /// Artifacts produced by this task.
32    pub artifacts: Vec<a2a_protocol_types::Artifact>,
33    /// Historical messages exchanged during this task.
34    pub history: Vec<a2a_protocol_types::Message>,
35    /// Arbitrary metadata.
36    pub metadata: HashMap<String, serde_json::Value>,
37    /// Push notification configurations for this task.
38    pub push_configs: Vec<a2a_protocol_types::TaskPushNotificationConfig>,
39    /// Timestamp when the task was created.
40    pub created_at: chrono::DateTime<chrono::Utc>,
41    /// Timestamp when the task was last updated.
42    pub updated_at: chrono::DateTime<chrono::Utc>,
43    /// Goes up by one with each save; a store refuses a write made from an older version
44    /// ([`TaskStore::save_task_if_version`]).
45    pub version: u64,
46}
47
48impl TaskStoreEntry {
49    /// The authenticated user that created the task, or `None` for a task created
50    /// without authentication. Read from [`OWNER_METADATA_KEY`].
51    pub fn owner(&self) -> Option<&str> {
52        self.metadata.get(OWNER_METADATA_KEY).and_then(serde_json::Value::as_str)
53    }
54}
55
56/// Parameters for listing tasks with optional filtering and pagination.
57#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
58#[serde(rename_all = "camelCase", default)]
59pub struct ListTasksParams {
60    /// Filter by conversation context ID.
61    pub context_id: Option<String>,
62    /// Filter by task state.
63    pub state: Option<a2a_protocol_types::TaskState>,
64    /// Maximum number of tasks to return.
65    pub page_size: Option<u32>,
66    /// Opaque cursor for pagination.
67    pub page_token: Option<String>,
68    /// Maximum number of history messages to include per task.
69    pub history_length: Option<u32>,
70    /// Filter tasks with status timestamp after this ISO 8601 value.
71    pub status_timestamp_after: Option<String>,
72    /// Whether to include artifacts in the response.
73    pub include_artifacts: Option<bool>,
74}
75
76/// Async trait for persisting A2A task state.
77///
78/// Implementations must be `Send + Sync` for use across async boundaries.
79#[async_trait]
80pub trait TaskStore: Send + Sync {
81    /// Persists a new task entry.
82    async fn create_task(&self, entry: TaskStoreEntry) -> Result<(), A2aError>;
83
84    /// Retrieves a task by ID.
85    ///
86    /// # Errors
87    ///
88    /// Returns [`A2aError::TaskNotFound`] if the task does not exist.
89    async fn get_task(&self, task_id: &str) -> Result<TaskStoreEntry, A2aError>;
90
91    /// Updates the status of an existing task.
92    ///
93    /// # Errors
94    ///
95    /// Returns [`A2aError::TaskNotFound`] if the task does not exist.
96    async fn update_status(
97        &self,
98        task_id: &str,
99        status: a2a_protocol_types::TaskStatus,
100    ) -> Result<(), A2aError>;
101
102    /// Appends an artifact to an existing task.
103    ///
104    /// # Errors
105    ///
106    /// Returns [`A2aError::TaskNotFound`] if the task does not exist.
107    async fn add_artifact(
108        &self,
109        task_id: &str,
110        artifact: a2a_protocol_types::Artifact,
111    ) -> Result<(), A2aError>;
112
113    /// Appends a message to the task's history.
114    ///
115    /// # Errors
116    ///
117    /// Returns [`A2aError::TaskNotFound`] if the task does not exist.
118    async fn add_history_message(
119        &self,
120        task_id: &str,
121        message: a2a_protocol_types::Message,
122    ) -> Result<(), A2aError>;
123
124    /// Finds the most recently updated non-terminal task for a given contextId.
125    /// Returns None if no non-terminal task exists for the context.
126    async fn find_task_by_context(
127        &self,
128        context_id: &str,
129    ) -> Result<Option<TaskStoreEntry>, A2aError>;
130
131    /// Lists tasks matching the given parameters.
132    async fn list_tasks(&self, params: ListTasksParams) -> Result<Vec<TaskStoreEntry>, A2aError>;
133
134    /// Deletes a task by ID.
135    ///
136    /// # Errors
137    ///
138    /// Returns [`A2aError::TaskNotFound`] if the task does not exist.
139    async fn delete_task(&self, task_id: &str) -> Result<(), A2aError>;
140
141    /// Writes `entry` over the stored task with the same ID: its status, history,
142    /// artifacts, metadata and push configs together. The executor calls it while it holds
143    /// the task's lock, so a read and write-back is never interleaved with another.
144    ///
145    /// The default implementation calls [`create_task`](Self::create_task), which
146    /// overwrites a task with the same ID in the in-memory store.
147    ///
148    /// # Errors
149    ///
150    /// Returns an error if the store fails to persist the task.
151    async fn save_task(&self, entry: TaskStoreEntry) -> Result<(), A2aError> {
152        self.create_task(entry).await
153    }
154
155    /// Writes `entry` only if the stored task is still at `expected` version, as a2a-go's
156    /// task store does, so two writers never overwrite each other unseen. The executor
157    /// saves every change this way, with `entry.version` one past `expected`.
158    ///
159    /// The default implementation does not check the version and calls
160    /// [`save_task`](Self::save_task); a store shared between processes should check it.
161    ///
162    /// # Errors
163    ///
164    /// Returns [`A2aError::ConcurrentModification`] when the stored version is not
165    /// `expected`, or a store error.
166    async fn save_task_if_version(
167        &self,
168        entry: TaskStoreEntry,
169        expected: u64,
170    ) -> Result<(), A2aError> {
171        let _ = expected;
172        self.save_task(entry).await
173    }
174}
175
176/// In-memory task store for development and testing.
177///
178/// Uses a `RwLock<HashMap>` for concurrent access. Not suitable for
179/// production deployments that require persistence across restarts.
180pub struct InMemoryTaskStore {
181    tasks: RwLock<HashMap<String, TaskStoreEntry>>,
182}
183
184impl InMemoryTaskStore {
185    /// Creates a new empty in-memory task store.
186    #[must_use]
187    pub fn new() -> Self {
188        Self { tasks: RwLock::new(HashMap::new()) }
189    }
190}
191
192impl Default for InMemoryTaskStore {
193    fn default() -> Self {
194        Self::new()
195    }
196}
197
198#[async_trait]
199impl TaskStore for InMemoryTaskStore {
200    async fn save_task_if_version(
201        &self,
202        entry: TaskStoreEntry,
203        expected: u64,
204    ) -> Result<(), A2aError> {
205        let mut tasks = self.tasks.write().await;
206        let stored = tasks.get(&entry.id).map_or(0, |task| task.version);
207        if stored != expected {
208            return Err(A2aError::ConcurrentModification { task_id: entry.id });
209        }
210        tasks.insert(entry.id.clone(), entry);
211        Ok(())
212    }
213
214    async fn create_task(&self, entry: TaskStoreEntry) -> Result<(), A2aError> {
215        let mut tasks = self.tasks.write().await;
216        tasks.insert(entry.id.clone(), entry);
217        Ok(())
218    }
219
220    async fn get_task(&self, task_id: &str) -> Result<TaskStoreEntry, A2aError> {
221        let tasks = self.tasks.read().await;
222        tasks
223            .get(task_id)
224            .cloned()
225            .ok_or_else(|| A2aError::TaskNotFound { task_id: task_id.to_string() })
226    }
227
228    async fn update_status(
229        &self,
230        task_id: &str,
231        status: a2a_protocol_types::TaskStatus,
232    ) -> Result<(), A2aError> {
233        let mut tasks = self.tasks.write().await;
234        let entry = tasks
235            .get_mut(task_id)
236            .ok_or_else(|| A2aError::TaskNotFound { task_id: task_id.to_string() })?;
237        entry.status = status;
238        entry.updated_at = Utc::now();
239        Ok(())
240    }
241
242    async fn add_artifact(
243        &self,
244        task_id: &str,
245        artifact: a2a_protocol_types::Artifact,
246    ) -> Result<(), A2aError> {
247        let mut tasks = self.tasks.write().await;
248        let entry = tasks
249            .get_mut(task_id)
250            .ok_or_else(|| A2aError::TaskNotFound { task_id: task_id.to_string() })?;
251        entry.artifacts.push(artifact);
252        entry.updated_at = Utc::now();
253        Ok(())
254    }
255
256    async fn add_history_message(
257        &self,
258        task_id: &str,
259        message: a2a_protocol_types::Message,
260    ) -> Result<(), A2aError> {
261        let mut tasks = self.tasks.write().await;
262        let entry = tasks
263            .get_mut(task_id)
264            .ok_or_else(|| A2aError::TaskNotFound { task_id: task_id.to_string() })?;
265        entry.history.push(message);
266        entry.updated_at = Utc::now();
267        Ok(())
268    }
269
270    async fn find_task_by_context(
271        &self,
272        context_id: &str,
273    ) -> Result<Option<TaskStoreEntry>, A2aError> {
274        let tasks = self.tasks.read().await;
275        let result = tasks
276            .values()
277            .filter(|entry| {
278                entry.context_id == context_id
279                    && !matches!(
280                        entry.status.state,
281                        a2a_protocol_types::TaskState::Completed
282                            | a2a_protocol_types::TaskState::Failed
283                            | a2a_protocol_types::TaskState::Canceled
284                            | a2a_protocol_types::TaskState::Rejected
285                    )
286            })
287            .max_by_key(|entry| entry.updated_at)
288            .cloned();
289        Ok(result)
290    }
291
292    async fn list_tasks(&self, params: ListTasksParams) -> Result<Vec<TaskStoreEntry>, A2aError> {
293        let tasks = self.tasks.read().await;
294        let mut results: Vec<TaskStoreEntry> = tasks
295            .values()
296            .filter(|entry| {
297                if let Some(ref ctx) = params.context_id
298                    && entry.context_id != *ctx
299                {
300                    return false;
301                }
302                if let Some(ref state) = params.state
303                    && entry.status.state != *state
304                {
305                    return false;
306                }
307                true
308            })
309            .cloned()
310            .collect();
311
312        // Sort by created_at for deterministic pagination
313        results.sort_by_key(|a| a.created_at);
314
315        if let Some(page_size) = params.page_size {
316            results.truncate(page_size as usize);
317        }
318
319        Ok(results)
320    }
321
322    async fn delete_task(&self, task_id: &str) -> Result<(), A2aError> {
323        let mut tasks = self.tasks.write().await;
324        tasks
325            .remove(task_id)
326            .ok_or_else(|| A2aError::TaskNotFound { task_id: task_id.to_string() })?;
327        Ok(())
328    }
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334    use a2a_protocol_types::{
335        Artifact, ArtifactId, Message, MessageId, MessageRole, Part, TaskState, TaskStatus,
336    };
337
338    #[tokio::test]
339    async fn a_write_from_an_older_version_is_refused() {
340        let store = InMemoryTaskStore::new();
341        store.create_task(make_entry("t-v", "ctx", TaskState::Submitted)).await.unwrap();
342        let mut first = store.get_task("t-v").await.unwrap();
343        let mut second = first.clone();
344
345        first.version = 1;
346        store.save_task_if_version(first, 0).await.unwrap();
347        second.version = 1;
348        let err = store.save_task_if_version(second, 0).await.unwrap_err();
349        assert!(
350            matches!(err, A2aError::ConcurrentModification { ref task_id } if task_id == "t-v"),
351            "{err}"
352        );
353        assert_eq!(store.get_task("t-v").await.unwrap().version, 1);
354    }
355
356    #[tokio::test]
357    async fn every_executor_change_moves_the_version_on() {
358        let store: std::sync::Arc<dyn TaskStore> = std::sync::Arc::new(InMemoryTaskStore::new());
359        let executor = super::super::executor::V1Executor::new(store.clone());
360        executor.create_task("t-e", "ctx").await.unwrap();
361        executor.transition_state("t-e", "ctx", TaskState::Working, None).await.unwrap();
362        executor.transition_state("t-e", "ctx", TaskState::Completed, None).await.unwrap();
363        assert_eq!(store.get_task("t-e").await.unwrap().version, 2);
364    }
365
366    fn make_entry(id: &str, context_id: &str, state: TaskState) -> TaskStoreEntry {
367        let now = Utc::now();
368        TaskStoreEntry {
369            id: id.to_string(),
370            context_id: context_id.to_string(),
371            status: TaskStatus::new(state),
372            artifacts: Vec::new(),
373            history: Vec::new(),
374            metadata: HashMap::new(),
375            push_configs: Vec::new(),
376            created_at: now,
377            updated_at: now,
378            version: 0,
379        }
380    }
381
382    fn make_message(text: &str) -> Message {
383        Message {
384            id: MessageId::new("msg-1"),
385            role: MessageRole::User,
386            parts: vec![Part::text(text)],
387            task_id: None,
388            context_id: None,
389            reference_task_ids: None,
390            extensions: None,
391            metadata: None,
392        }
393    }
394
395    fn make_artifact(id: &str, text: &str) -> Artifact {
396        Artifact::new(ArtifactId::new(id), vec![Part::text(text)])
397    }
398
399    #[tokio::test]
400    async fn test_create_and_get_task() {
401        let store = InMemoryTaskStore::new();
402        let entry = make_entry("task-1", "ctx-1", TaskState::Submitted);
403
404        store.create_task(entry).await.unwrap();
405        let retrieved = store.get_task("task-1").await.unwrap();
406
407        assert_eq!(retrieved.id, "task-1");
408        assert_eq!(retrieved.context_id, "ctx-1");
409        assert_eq!(retrieved.status.state, TaskState::Submitted);
410    }
411
412    #[tokio::test]
413    async fn test_get_task_not_found() {
414        let store = InMemoryTaskStore::new();
415        let err = store.get_task("nonexistent").await.unwrap_err();
416        let msg = err.to_string();
417        assert!(msg.contains("nonexistent"), "error should contain task ID: {msg}");
418    }
419
420    #[tokio::test]
421    async fn test_update_status() {
422        let store = InMemoryTaskStore::new();
423        store.create_task(make_entry("task-1", "ctx-1", TaskState::Submitted)).await.unwrap();
424
425        let before = store.get_task("task-1").await.unwrap();
426        let before_updated = before.updated_at;
427
428        // Small delay to ensure timestamp differs
429        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
430
431        store.update_status("task-1", TaskStatus::new(TaskState::Working)).await.unwrap();
432
433        let after = store.get_task("task-1").await.unwrap();
434        assert_eq!(after.status.state, TaskState::Working);
435        assert!(after.updated_at >= before_updated);
436    }
437
438    #[tokio::test]
439    async fn test_update_status_not_found() {
440        let store = InMemoryTaskStore::new();
441        let err = store
442            .update_status("nonexistent", TaskStatus::new(TaskState::Working))
443            .await
444            .unwrap_err();
445        let msg = err.to_string();
446        assert!(msg.contains("nonexistent"));
447    }
448
449    #[tokio::test]
450    async fn test_add_artifact() {
451        let store = InMemoryTaskStore::new();
452        store.create_task(make_entry("task-1", "ctx-1", TaskState::Working)).await.unwrap();
453
454        store.add_artifact("task-1", make_artifact("art-1", "hello")).await.unwrap();
455
456        let task = store.get_task("task-1").await.unwrap();
457        assert_eq!(task.artifacts.len(), 1);
458        assert_eq!(task.artifacts[0].id, ArtifactId::new("art-1"));
459    }
460
461    #[tokio::test]
462    async fn test_add_artifact_not_found() {
463        let store = InMemoryTaskStore::new();
464        let err =
465            store.add_artifact("nonexistent", make_artifact("art-1", "hello")).await.unwrap_err();
466        let msg = err.to_string();
467        assert!(msg.contains("nonexistent"));
468    }
469
470    #[tokio::test]
471    async fn test_add_history_message() {
472        let store = InMemoryTaskStore::new();
473        store.create_task(make_entry("task-1", "ctx-1", TaskState::Working)).await.unwrap();
474
475        store.add_history_message("task-1", make_message("hello")).await.unwrap();
476
477        let task = store.get_task("task-1").await.unwrap();
478        assert_eq!(task.history.len(), 1);
479    }
480
481    #[tokio::test]
482    async fn test_add_history_message_not_found() {
483        let store = InMemoryTaskStore::new();
484        let err =
485            store.add_history_message("nonexistent", make_message("hello")).await.unwrap_err();
486        let msg = err.to_string();
487        assert!(msg.contains("nonexistent"));
488    }
489
490    #[tokio::test]
491    async fn test_delete_task() {
492        let store = InMemoryTaskStore::new();
493        store.create_task(make_entry("task-1", "ctx-1", TaskState::Submitted)).await.unwrap();
494
495        store.delete_task("task-1").await.unwrap();
496
497        let err = store.get_task("task-1").await.unwrap_err();
498        let msg = err.to_string();
499        assert!(msg.contains("task-1"));
500    }
501
502    #[tokio::test]
503    async fn test_delete_task_not_found() {
504        let store = InMemoryTaskStore::new();
505        let err = store.delete_task("nonexistent").await.unwrap_err();
506        let msg = err.to_string();
507        assert!(msg.contains("nonexistent"));
508    }
509
510    #[tokio::test]
511    async fn test_list_tasks_all() {
512        let store = InMemoryTaskStore::new();
513        store.create_task(make_entry("task-1", "ctx-1", TaskState::Submitted)).await.unwrap();
514        store.create_task(make_entry("task-2", "ctx-1", TaskState::Working)).await.unwrap();
515        store.create_task(make_entry("task-3", "ctx-2", TaskState::Completed)).await.unwrap();
516
517        let results = store.list_tasks(ListTasksParams::default()).await.unwrap();
518        assert_eq!(results.len(), 3);
519    }
520
521    #[tokio::test]
522    async fn test_list_tasks_filter_by_context_id() {
523        let store = InMemoryTaskStore::new();
524        store.create_task(make_entry("task-1", "ctx-1", TaskState::Submitted)).await.unwrap();
525        store.create_task(make_entry("task-2", "ctx-1", TaskState::Working)).await.unwrap();
526        store.create_task(make_entry("task-3", "ctx-2", TaskState::Completed)).await.unwrap();
527
528        let results = store
529            .list_tasks(ListTasksParams {
530                context_id: Some("ctx-1".to_string()),
531                ..Default::default()
532            })
533            .await
534            .unwrap();
535        assert_eq!(results.len(), 2);
536        assert!(results.iter().all(|t| t.context_id == "ctx-1"));
537    }
538
539    #[tokio::test]
540    async fn test_list_tasks_filter_by_state() {
541        let store = InMemoryTaskStore::new();
542        store.create_task(make_entry("task-1", "ctx-1", TaskState::Submitted)).await.unwrap();
543        store.create_task(make_entry("task-2", "ctx-1", TaskState::Working)).await.unwrap();
544        store.create_task(make_entry("task-3", "ctx-2", TaskState::Working)).await.unwrap();
545
546        let results = store
547            .list_tasks(ListTasksParams { state: Some(TaskState::Working), ..Default::default() })
548            .await
549            .unwrap();
550        assert_eq!(results.len(), 2);
551        assert!(results.iter().all(|t| t.status.state == TaskState::Working));
552    }
553
554    #[tokio::test]
555    async fn test_list_tasks_page_size() {
556        let store = InMemoryTaskStore::new();
557        store.create_task(make_entry("task-1", "ctx-1", TaskState::Submitted)).await.unwrap();
558        store.create_task(make_entry("task-2", "ctx-1", TaskState::Working)).await.unwrap();
559        store.create_task(make_entry("task-3", "ctx-2", TaskState::Completed)).await.unwrap();
560
561        let results = store
562            .list_tasks(ListTasksParams { page_size: Some(2), ..Default::default() })
563            .await
564            .unwrap();
565        assert_eq!(results.len(), 2);
566    }
567
568    #[tokio::test]
569    async fn test_list_tasks_combined_filters() {
570        let store = InMemoryTaskStore::new();
571        store.create_task(make_entry("task-1", "ctx-1", TaskState::Working)).await.unwrap();
572        store.create_task(make_entry("task-2", "ctx-1", TaskState::Submitted)).await.unwrap();
573        store.create_task(make_entry("task-3", "ctx-2", TaskState::Working)).await.unwrap();
574        store.create_task(make_entry("task-4", "ctx-1", TaskState::Working)).await.unwrap();
575
576        let results = store
577            .list_tasks(ListTasksParams {
578                context_id: Some("ctx-1".to_string()),
579                state: Some(TaskState::Working),
580                page_size: Some(1),
581                ..Default::default()
582            })
583            .await
584            .unwrap();
585        assert_eq!(results.len(), 1);
586        assert_eq!(results[0].context_id, "ctx-1");
587        assert_eq!(results[0].status.state, TaskState::Working);
588    }
589
590    #[tokio::test]
591    async fn test_list_tasks_empty_store() {
592        let store = InMemoryTaskStore::new();
593        let results = store.list_tasks(ListTasksParams::default()).await.unwrap();
594        assert!(results.is_empty());
595    }
596
597    #[tokio::test]
598    async fn test_create_overwrites_existing() {
599        let store = InMemoryTaskStore::new();
600        store.create_task(make_entry("task-1", "ctx-1", TaskState::Submitted)).await.unwrap();
601        store.create_task(make_entry("task-1", "ctx-2", TaskState::Working)).await.unwrap();
602
603        let task = store.get_task("task-1").await.unwrap();
604        assert_eq!(task.context_id, "ctx-2");
605        assert_eq!(task.status.state, TaskState::Working);
606    }
607
608    #[tokio::test]
609    async fn test_multiple_artifacts() {
610        let store = InMemoryTaskStore::new();
611        store.create_task(make_entry("task-1", "ctx-1", TaskState::Working)).await.unwrap();
612
613        store.add_artifact("task-1", make_artifact("art-1", "first")).await.unwrap();
614        store.add_artifact("task-1", make_artifact("art-2", "second")).await.unwrap();
615
616        let task = store.get_task("task-1").await.unwrap();
617        assert_eq!(task.artifacts.len(), 2);
618    }
619
620    #[tokio::test]
621    async fn test_multiple_history_messages() {
622        let store = InMemoryTaskStore::new();
623        store.create_task(make_entry("task-1", "ctx-1", TaskState::Working)).await.unwrap();
624
625        store.add_history_message("task-1", make_message("first")).await.unwrap();
626        store.add_history_message("task-1", make_message("second")).await.unwrap();
627
628        let task = store.get_task("task-1").await.unwrap();
629        assert_eq!(task.history.len(), 2);
630    }
631
632    #[tokio::test]
633    async fn test_find_task_by_context_no_match() {
634        let store = InMemoryTaskStore::new();
635        store.create_task(make_entry("task-1", "ctx-1", TaskState::Working)).await.unwrap();
636        let result = store.find_task_by_context("ctx-other").await.unwrap();
637        assert!(result.is_none());
638    }
639
640    #[tokio::test]
641    async fn test_find_task_by_context_excludes_terminal() {
642        let store = InMemoryTaskStore::new();
643        store.create_task(make_entry("task-1", "ctx-1", TaskState::Completed)).await.unwrap();
644        store.create_task(make_entry("task-2", "ctx-1", TaskState::Failed)).await.unwrap();
645        store.create_task(make_entry("task-3", "ctx-1", TaskState::Canceled)).await.unwrap();
646        store.create_task(make_entry("task-4", "ctx-1", TaskState::Rejected)).await.unwrap();
647        let result = store.find_task_by_context("ctx-1").await.unwrap();
648        assert!(result.is_none());
649    }
650
651    #[tokio::test]
652    async fn test_find_task_by_context_returns_most_recent_non_terminal() {
653        let store = InMemoryTaskStore::new();
654        store.create_task(make_entry("task-1", "ctx-1", TaskState::Working)).await.unwrap();
655        // Small delay to ensure different updated_at
656        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
657        store.create_task(make_entry("task-2", "ctx-1", TaskState::InputRequired)).await.unwrap();
658        let result = store.find_task_by_context("ctx-1").await.unwrap();
659        assert!(result.is_some());
660        assert_eq!(result.unwrap().id, "task-2");
661    }
662
663    #[tokio::test]
664    async fn test_find_task_by_context_isolates_contexts() {
665        let store = InMemoryTaskStore::new();
666        store.create_task(make_entry("task-1", "ctx-1", TaskState::Working)).await.unwrap();
667        store.create_task(make_entry("task-2", "ctx-2", TaskState::Working)).await.unwrap();
668        let result = store.find_task_by_context("ctx-1").await.unwrap();
669        assert!(result.is_some());
670        assert_eq!(result.unwrap().id, "task-1");
671    }
672}