Skip to main content

lean_ctx/core/a2a/task/
store.rs

1// SPDX-License-Identifier: Apache-2.0
2
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use std::fs::{File, OpenOptions};
6use std::io::{Read, Write};
7use std::path::{Path, PathBuf};
8
9use super::authority::TaskDescriptorV1;
10use super::model::{Task, TaskPart, TaskState};
11use super::{
12    IDEMPOTENCY_RETENTION_SECONDS, MAX_DESCRIPTION_BYTES, MAX_HISTORY, MAX_ID_BYTES,
13    MAX_IDEMPOTENCY_RECORDS, MAX_MESSAGES, MAX_METADATA_ENTRIES, MAX_METADATA_VALUE_BYTES,
14    MAX_PARTS, MAX_PARTS_PER_MESSAGE, MAX_TASK_STORE_BYTES, MAX_TASKS, MAX_TEXT_BYTES,
15    TASK_DESCRIPTOR_VERSION,
16};
17
18#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
19#[serde(deny_unknown_fields)]
20pub(super) struct TaskIdempotencyRecordV1 {
21    schema_version: u32,
22    key: String,
23    sender: String,
24    recipient: String,
25    tenant_id: String,
26    project_id: String,
27    action: String,
28    key_id: String,
29    descriptor_digest: String,
30    task_id: String,
31    pub(super) created_at: DateTime<Utc>,
32}
33
34impl TaskIdempotencyRecordV1 {
35    fn matches_authority(&self, descriptor: &TaskDescriptorV1) -> bool {
36        self.sender == descriptor.sender
37            && self.recipient == descriptor.recipient
38            && self.tenant_id == descriptor.tenant_id
39            && self.project_id == descriptor.project_id
40            && self.action == descriptor.action
41            && self.key_id == descriptor.key_id
42    }
43}
44
45#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct RemoteTaskMaterialization {
47    pub task_id: String,
48    pub duplicate: bool,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize, Default)]
52pub struct TaskStore {
53    pub tasks: Vec<Task>,
54    pub updated_at: Option<DateTime<Utc>>,
55    #[serde(default)]
56    pub(super) idempotency: Vec<TaskIdempotencyRecordV1>,
57}
58
59impl TaskStore {
60    pub fn default_path() -> std::io::Result<PathBuf> {
61        task_store_path()
62    }
63
64    pub fn load() -> std::io::Result<Self> {
65        Self::load_from_path(&task_store_path()?)
66    }
67
68    pub fn save(&self) -> std::io::Result<()> {
69        let path = task_store_path()?;
70        Self::prepare_parent(&path)?;
71        let lock_path = path.with_extension("lock");
72        let _lock =
73            crate::core::agents::FileLock::acquire(&lock_path).map_err(std::io::Error::other)?;
74        self.save_to_path(&path)
75    }
76
77    pub fn scoped_path(project_root: &str) -> std::io::Result<PathBuf> {
78        let root = Path::new(project_root);
79        let metadata = std::fs::symlink_metadata(root)?;
80        if metadata.file_type().is_symlink() || !metadata.is_dir() {
81            return Err(std::io::Error::new(
82                std::io::ErrorKind::InvalidData,
83                "project root must be a real directory",
84            ));
85        }
86        Ok(root
87            .canonicalize()?
88            .join(".lean-ctx")
89            .join("a2a")
90            .join("tasks-v1.json"))
91    }
92
93    pub fn read_locked<R>(path: &Path, read: impl FnOnce(&Self) -> R) -> std::io::Result<R> {
94        Self::prepare_parent(path)?;
95        let _lock = crate::core::agents::FileLock::acquire(&path.with_extension("lock"))
96            .map_err(std::io::Error::other)?;
97        let store = Self::load_from_path(path)?;
98        Ok(read(&store))
99    }
100
101    pub fn mutate_locked<R, E>(
102        path: &Path,
103        mutate: impl FnOnce(&mut Self) -> Result<R, E>,
104    ) -> Result<R, E>
105    where
106        E: From<std::io::Error>,
107    {
108        Self::prepare_parent(path).map_err(E::from)?;
109        let _lock = crate::core::agents::FileLock::acquire(&path.with_extension("lock"))
110            .map_err(std::io::Error::other)
111            .map_err(E::from)?;
112        let mut store = Self::load_from_path(path).map_err(E::from)?;
113        let result = mutate(&mut store)?;
114        if store.tasks.len() > MAX_TASKS {
115            return Err(E::from(std::io::Error::new(
116                std::io::ErrorKind::InvalidData,
117                "task store entry limit exceeded",
118            )));
119        }
120        if store.idempotency.len() > MAX_IDEMPOTENCY_RECORDS {
121            return Err(E::from(std::io::Error::new(
122                std::io::ErrorKind::InvalidData,
123                "task idempotency entry limit exceeded",
124            )));
125        }
126        store.updated_at = Some(Utc::now());
127        store.save_to_path(path).map_err(E::from)?;
128        Ok(result)
129    }
130
131    fn prepare_parent(path: &Path) -> std::io::Result<()> {
132        let parent = path.parent().ok_or_else(|| {
133            std::io::Error::new(std::io::ErrorKind::InvalidInput, "task store has no parent")
134        })?;
135        for directory in [Some(parent), parent.parent()].into_iter().flatten() {
136            validate_existing_directory(directory)?;
137        }
138        std::fs::create_dir_all(parent)?;
139        for directory in [Some(parent), parent.parent()].into_iter().flatten() {
140            validate_existing_directory(directory)?;
141        }
142        Ok(())
143    }
144
145    fn load_from_path(path: &Path) -> std::io::Result<Self> {
146        let metadata = match std::fs::symlink_metadata(path) {
147            Ok(metadata) => metadata,
148            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
149                return Ok(Self::default());
150            }
151            Err(error) => return Err(error),
152        };
153        if metadata.file_type().is_symlink() || !metadata.is_file() {
154            return Err(std::io::Error::new(
155                std::io::ErrorKind::InvalidData,
156                "task store must be a regular file",
157            ));
158        }
159        if metadata.len() > MAX_TASK_STORE_BYTES {
160            return Err(std::io::Error::new(
161                std::io::ErrorKind::InvalidData,
162                "task store exceeds size limit",
163            ));
164        }
165        let file = open_read_nofollow(path)?;
166        let mut content = String::new();
167        file.take(MAX_TASK_STORE_BYTES + 1)
168            .read_to_string(&mut content)?;
169        if content.len() as u64 > MAX_TASK_STORE_BYTES {
170            return Err(std::io::Error::new(
171                std::io::ErrorKind::InvalidData,
172                "task store exceeds size limit",
173            ));
174        }
175        let store: Self = serde_json::from_str(&content).map_err(std::io::Error::other)?;
176        if store.idempotency.len() > MAX_IDEMPOTENCY_RECORDS {
177            return Err(std::io::Error::new(
178                std::io::ErrorKind::InvalidData,
179                "task idempotency entry limit exceeded",
180            ));
181        }
182        store.validate_restored()?;
183        Ok(store)
184    }
185
186    fn validate_restored(&self) -> std::io::Result<()> {
187        if self.tasks.len() > MAX_TASKS {
188            return invalid_data("task store entry limit exceeded");
189        }
190        let mut task_ids = std::collections::HashSet::with_capacity(self.tasks.len());
191        for task in &self.tasks {
192            validate_restored_identifier(&task.id, "task id")?;
193            if !task_ids.insert(task.id.as_str()) {
194                return invalid_data("task store contains duplicate task ids");
195            }
196            validate_restored_identifier(&task.from_agent, "from_agent")?;
197            validate_restored_identifier(&task.to_agent, "to_agent")?;
198            validate_bounded_nonempty(
199                &task.description,
200                "task description",
201                MAX_DESCRIPTION_BYTES,
202            )?;
203            if task.created_at > task.updated_at {
204                return invalid_data("task timestamps are inconsistent");
205            }
206            if task.messages.len() > MAX_MESSAGES
207                || task.artifacts.len() > MAX_PARTS
208                || task.history.is_empty()
209                || task.history.len() > MAX_HISTORY
210                || task.metadata.len() > MAX_METADATA_ENTRIES
211            {
212                return invalid_data("task collection limit exceeded");
213            }
214            for message in &task.messages {
215                validate_restored_identifier(&message.role, "message role")?;
216                if message.timestamp < task.created_at || message.timestamp > task.updated_at {
217                    return invalid_data("message timestamp is outside task lifetime");
218                }
219                if message.parts.len() > MAX_PARTS_PER_MESSAGE {
220                    return invalid_data("message part limit exceeded");
221                }
222                for part in &message.parts {
223                    validate_part(part)?;
224                }
225            }
226            for artifact in &task.artifacts {
227                validate_part(artifact)?;
228            }
229            for (key, value) in &task.metadata {
230                validate_restored_identifier(key, "metadata key")?;
231                validate_bounded(value, "metadata value", MAX_METADATA_VALUE_BYTES)?;
232            }
233            validate_history(task)?;
234        }
235        Ok(())
236    }
237
238    fn save_to_path(&self, path: &Path) -> std::io::Result<()> {
239        // Every writer must preserve the same invariants required on reload.
240        self.validate_restored()?;
241        if let Ok(metadata) = std::fs::symlink_metadata(path)
242            && (metadata.file_type().is_symlink() || !metadata.is_file())
243        {
244            return Err(std::io::Error::new(
245                std::io::ErrorKind::InvalidData,
246                "task store must be a regular file",
247            ));
248        }
249
250        let json = serde_json::to_string_pretty(self).map_err(std::io::Error::other)?;
251        if json.len() as u64 > MAX_TASK_STORE_BYTES {
252            return Err(std::io::Error::new(
253                std::io::ErrorKind::InvalidData,
254                "task store exceeds size limit",
255            ));
256        }
257        let tmp = path.with_extension(format!("tmp-{}", uuid::Uuid::new_v4()));
258        let mut options = OpenOptions::new();
259        options.write(true).create_new(true);
260        #[cfg(unix)]
261        {
262            use std::os::unix::fs::OpenOptionsExt;
263            options.mode(0o600);
264        }
265        let mut file = options.open(&tmp)?;
266        file.write_all(json.as_bytes())?;
267        file.sync_all()?;
268        drop(file);
269        std::fs::rename(&tmp, path)?;
270        sync_parent(path)?;
271        Ok(())
272    }
273
274    pub fn create_task(&mut self, from: &str, to: &str, description: &str) -> String {
275        let task = Task::new(from, to, description);
276        let id = task.id.clone();
277        self.tasks.push(task);
278        self.updated_at = Some(Utc::now());
279        id
280    }
281
282    /// Durably materialize an already-authorized remote task descriptor.
283    ///
284    /// The idempotency ledger lives in the same file as the tasks and is
285    /// written under the same lock and atomic rename, so a delivery is either
286    /// visible with its ledger entry after a restart or not at all — never
287    /// acknowledged without being stored.
288    ///
289    /// Callers MUST verify [`TaskDescriptorV1::verify_authority`] first; this
290    /// re-validates shape only, and cannot re-derive authority on its own.
291    pub fn materialize_remote_task(
292        path: &Path,
293        descriptor: &TaskDescriptorV1,
294    ) -> std::io::Result<RemoteTaskMaterialization> {
295        descriptor
296            .validate_shape()
297            .map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidInput, error))?;
298        let digest = descriptor.content_digest();
299        Self::mutate_locked(path, |store| {
300            let now = Utc::now();
301            store.prune_idempotency(now);
302            if let Some(existing) = store
303                .idempotency
304                .iter()
305                .find(|record| record.key == descriptor.idempotency_key)
306            {
307                if existing.matches_authority(descriptor) && existing.descriptor_digest == digest {
308                    return Ok(RemoteTaskMaterialization {
309                        task_id: existing.task_id.clone(),
310                        duplicate: true,
311                    });
312                }
313                return Err(std::io::Error::new(
314                    std::io::ErrorKind::AlreadyExists,
315                    "conflicting idempotency key reuse",
316                ));
317            }
318            if store.idempotency.len() >= MAX_IDEMPOTENCY_RECORDS || store.tasks.len() >= MAX_TASKS
319            {
320                return Err(std::io::Error::new(
321                    std::io::ErrorKind::InvalidData,
322                    "task idempotency entry limit exceeded",
323                ));
324            }
325            let task_id = format!("task-{}", uuid::Uuid::new_v4());
326            let task = Task::from_remote_descriptor(descriptor, task_id.clone());
327            store.tasks.push(task);
328            store.idempotency.push(TaskIdempotencyRecordV1 {
329                schema_version: TASK_DESCRIPTOR_VERSION,
330                key: descriptor.idempotency_key.clone(),
331                sender: descriptor.sender.clone(),
332                recipient: descriptor.recipient.clone(),
333                tenant_id: descriptor.tenant_id.clone(),
334                project_id: descriptor.project_id.clone(),
335                action: descriptor.action.clone(),
336                key_id: descriptor.key_id.clone(),
337                descriptor_digest: digest,
338                task_id: task_id.clone(),
339                created_at: now,
340            });
341            Ok(RemoteTaskMaterialization {
342                task_id,
343                duplicate: false,
344            })
345        })
346    }
347
348    /// Drop idempotency records that no live descriptor can still reference.
349    ///
350    /// A descriptor may live at most [`MAX_TASK_LIFETIME_SECONDS`] and is
351    /// rejected once expired, so a record older than that plus the accepted
352    /// clock skew can never turn a replay into a duplicate. Records with a
353    /// creation time in the future (clock moved backwards) are kept.
354    fn prune_idempotency(&mut self, now: DateTime<Utc>) {
355        let cutoff = now - chrono::Duration::seconds(IDEMPOTENCY_RETENTION_SECONDS);
356        self.idempotency.retain(|record| record.created_at > cutoff);
357    }
358
359    pub fn get_task(&self, task_id: &str) -> Option<&Task> {
360        self.tasks.iter().find(|t| t.id == task_id)
361    }
362
363    pub fn get_task_mut(&mut self, task_id: &str) -> Option<&mut Task> {
364        self.tasks.iter_mut().find(|t| t.id == task_id)
365    }
366
367    pub fn tasks_for_agent(&self, agent_id: &str) -> Vec<&Task> {
368        self.tasks
369            .iter()
370            .filter(|t| t.to_agent == agent_id || t.from_agent == agent_id)
371            .collect()
372    }
373
374    pub fn pending_tasks_for(&self, agent_id: &str) -> Vec<&Task> {
375        self.tasks
376            .iter()
377            .filter(|t| t.to_agent == agent_id && !t.state.is_terminal())
378            .collect()
379    }
380
381    pub fn cleanup_old(&mut self, max_age_hours: u64) {
382        let now = Utc::now();
383        let cutoff = now - chrono::Duration::hours(max_age_hours as i64);
384        self.tasks
385            .retain(|t| !t.state.is_terminal() || t.updated_at > cutoff);
386        self.prune_idempotency(now);
387    }
388}
389
390fn invalid_data<T>(message: &str) -> std::io::Result<T> {
391    Err(std::io::Error::new(
392        std::io::ErrorKind::InvalidData,
393        message,
394    ))
395}
396
397fn validate_bounded(value: &str, field: &str, max_bytes: usize) -> std::io::Result<()> {
398    if value.len() > max_bytes {
399        return invalid_data(&format!("invalid {field}"));
400    }
401    Ok(())
402}
403
404fn validate_restored_identifier(value: &str, field: &str) -> std::io::Result<()> {
405    validate_bounded_nonempty(value, field, MAX_ID_BYTES)?;
406    if value.chars().any(char::is_control) {
407        return invalid_data(&format!("invalid {field}"));
408    }
409    Ok(())
410}
411
412fn validate_bounded_nonempty(value: &str, field: &str, max_bytes: usize) -> std::io::Result<()> {
413    if value.is_empty() {
414        return invalid_data(&format!("invalid {field}"));
415    }
416    validate_bounded(value, field, max_bytes)
417}
418
419fn validate_part(part: &TaskPart) -> std::io::Result<()> {
420    match part {
421        TaskPart::Text { text } => validate_bounded(text, "text part", MAX_TEXT_BYTES),
422        TaskPart::Data { mime_type, data } => {
423            validate_restored_identifier(mime_type, "data mime_type")?;
424            validate_bounded(data, "data part", MAX_TEXT_BYTES)
425        }
426        TaskPart::File {
427            name,
428            mime_type,
429            data,
430            uri,
431        } => {
432            validate_restored_identifier(name, "file name")?;
433            if let Some(value) = mime_type {
434                validate_restored_identifier(value, "file mime_type")?;
435            }
436            if let Some(value) = data {
437                validate_bounded(value, "file data", MAX_TEXT_BYTES)?;
438            }
439            if let Some(value) = uri {
440                validate_bounded_nonempty(value, "file uri", MAX_TEXT_BYTES)?;
441            }
442            if data.is_none() && uri.is_none() {
443                return invalid_data("file part requires data or uri");
444            }
445            Ok(())
446        }
447    }
448}
449
450fn validate_history(task: &Task) -> std::io::Result<()> {
451    let first = &task.history[0];
452    if first.from != TaskState::Created || first.to != TaskState::Created {
453        return invalid_data("task history has invalid origin");
454    }
455    if let Some(reason) = &first.reason {
456        validate_bounded(reason, "transition reason", MAX_DESCRIPTION_BYTES)?;
457    }
458    let mut state = TaskState::Created;
459    let mut timestamp = first.timestamp;
460    for transition in task.history.iter().skip(1) {
461        if transition.from != state
462            || !transition.from.can_transition_to(&transition.to)
463            || transition.timestamp < timestamp
464        {
465            return invalid_data("task history is inconsistent");
466        }
467        if let Some(reason) = &transition.reason {
468            validate_bounded(reason, "transition reason", MAX_DESCRIPTION_BYTES)?;
469        }
470        state = transition.to.clone();
471        timestamp = transition.timestamp;
472    }
473    if state != task.state || first.timestamp < task.created_at || timestamp > task.updated_at {
474        return invalid_data("task state does not match history");
475    }
476    Ok(())
477}
478
479fn task_store_path() -> std::io::Result<PathBuf> {
480    // GH #439: the A2A task store is agent DATA — resolve through the typed dir
481    // so a post-split install writes to $XDG_DATA_HOME/lean-ctx/agents instead
482    // of a re-created ~/.lean-ctx. Legacy single-dir installs resolve in place.
483    crate::core::data_dir::lean_ctx_data_dir()
484        .map(|d| d.join("agents").join("tasks.json"))
485        .map_err(std::io::Error::other)
486}
487
488fn open_read_nofollow(path: &Path) -> std::io::Result<File> {
489    let mut options = OpenOptions::new();
490    options.read(true);
491    #[cfg(unix)]
492    {
493        use std::os::unix::fs::OpenOptionsExt;
494        options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK | libc::O_CLOEXEC);
495    }
496    let file = options.open(path)?;
497    if !file.metadata()?.is_file() {
498        return Err(std::io::Error::new(
499            std::io::ErrorKind::InvalidData,
500            "task store must be a regular file",
501        ));
502    }
503    Ok(file)
504}
505
506fn validate_existing_directory(path: &Path) -> std::io::Result<()> {
507    match std::fs::symlink_metadata(path) {
508        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_dir() => {
509            Err(std::io::Error::new(
510                std::io::ErrorKind::InvalidData,
511                "task store path components must be real directories",
512            ))
513        }
514        Ok(_) => Ok(()),
515        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
516        Err(error) => Err(error),
517    }
518}
519
520#[cfg_attr(not(unix), allow(unused_variables))] // only the unix branch reads it
521fn sync_parent(path: &Path) -> std::io::Result<()> {
522    #[cfg(unix)]
523    if let Some(parent) = path.parent() {
524        File::open(parent)?.sync_all()?;
525    }
526    Ok(())
527}