Skip to main content

mlua_swarm/store/task/
mod.rs

1//! `TaskStore` — persistence for `Task` records.
2//!
3//! Part of the issue #13 ID-hierarchy reconciliation: Blueprint -> Task ->
4//! Run -> Step -> Attempt. A `Task` is the **work-item identity**: one row
5//! per unit of work ("resolve issue #10" + a Blueprint ref snapshot + an
6//! input ctx), created once when the work is submitted (e.g.
7//! `POST /v1/tasks`). A single Task can be kicked N times; each kick mints
8//! a [`RunId`](crate::types::RunId) and is tracked by the sibling
9//! [`crate::store::run`] store — this module owns only the 1-row-per-Task
10//! identity and its coarse lifecycle status.
11//!
12//! Current scope:
13//!
14//! - [`InMemoryTaskStore`] — process-volatile default.
15//! - [`SqliteTaskStore`] — file-backed persistence via `rusqlite-isle`
16//!   (thread-isolated `Connection`, single-writer FIFO discipline; same
17//!   shape as [`crate::store::issue::sqlite::SqliteIssueStore`]).
18//! - Other persistent backends (Git / mini-app / …) are future carries.
19
20use crate::types::TaskId;
21use async_trait::async_trait;
22use serde::{Deserialize, Serialize};
23use std::collections::HashMap;
24use std::sync::Mutex;
25use thiserror::Error;
26
27pub mod inmemory;
28pub mod sqlite;
29pub use inmemory::InMemoryTaskStore;
30pub use sqlite::SqliteTaskStore;
31
32// ──────────────────────────────────────────────────────────────────────────
33// TaskRecordStatus / TaskRecord
34// ──────────────────────────────────────────────────────────────────────────
35
36/// Lifecycle status of a [`TaskRecord`].
37///
38/// Coarser than [`crate::store::run::RunStatus`]: a Task's status tracks
39/// "is there work in flight / did the most recent kick finish", while a
40/// Run's status tracks one specific kick's own outcome.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
42#[serde(rename_all = "snake_case")]
43pub enum TaskRecordStatus {
44    /// Created, no [`crate::store::run::RunRecord`] started yet.
45    Pending,
46    /// A Run is currently in flight for this Task.
47    Running,
48    /// The Task's most recent Run completed successfully.
49    Done,
50    /// The Task's most recent Run failed.
51    Failed,
52}
53
54/// One persisted `Task` row — the work-item identity.
55#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
56pub struct TaskRecord {
57    /// Task identifier.
58    #[schemars(with = "String")]
59    pub id: TaskId,
60    /// Human-facing goal / description (e.g. "resolve issue #10").
61    pub goal: String,
62    /// Snapshot of the Blueprint selector supplied at creation (the
63    /// `POST /v1/tasks` body's `BlueprintSelector`). Kept as a bare
64    /// `serde_json::Value` so the store layer does not depend on the
65    /// selector's Rust type — callers decode/encode at the API boundary.
66    #[schemars(with = "serde_json::Value")]
67    pub blueprint_ref: serde_json::Value,
68    /// Input context supplied at task creation.
69    #[schemars(with = "serde_json::Value")]
70    pub input_ctx: serde_json::Value,
71    /// Issue #19 ST4: Task-level canonical fields (`project_root` /
72    /// `work_dir` / `task_metadata`) snapshot for rekick, stored as JSON
73    /// (a serialized `TaskInputSpec`) — same "bare `Value`, no Rust-type
74    /// dependency" rationale as [`Self::blueprint_ref`] /
75    /// [`Self::input_ctx`]. `None` for every pre-#19 `TaskRecord`
76    /// (backward compat) and for callers whose request carried no
77    /// Task-level fields at all.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    #[schemars(with = "Option<serde_json::Value>")]
80    pub task_input_spec: Option<serde_json::Value>,
81    /// Current lifecycle status.
82    pub status: TaskRecordStatus,
83    /// Unix epoch seconds — creation time.
84    pub created_at: u64,
85    /// Unix epoch seconds — last update time.
86    pub updated_at: u64,
87}
88
89/// Errors surfaced by a [`TaskStore`] implementation.
90#[derive(Debug, Error)]
91pub enum TaskStoreError {
92    /// No Task exists for the given id.
93    #[error("task not found: {0}")]
94    NotFound(TaskId),
95
96    /// `create` was called with an id that is already stored.
97    #[error("task already exists: {0}")]
98    Duplicate(TaskId),
99
100    /// Backend-specific failure not covered by the other variants.
101    #[error("other: {0}")]
102    Other(String),
103}
104
105// ──────────────────────────────────────────────────────────────────────────
106// TaskStore trait
107// ──────────────────────────────────────────────────────────────────────────
108
109/// Persistence interface for `Task` records — the work-item identity
110/// layer of the issue #13 ID hierarchy.
111#[async_trait]
112pub trait TaskStore: Send + Sync {
113    /// Backend name — for diagnostics/logging.
114    fn name(&self) -> &str;
115
116    /// Create a new Task row. Returns `Duplicate` if `record.id` is
117    /// already stored.
118    async fn create(&self, record: TaskRecord) -> Result<(), TaskStoreError>;
119
120    /// Fetch a Task by id.
121    async fn get(&self, id: &TaskId) -> Result<TaskRecord, TaskStoreError>;
122
123    /// List every Task, newest first (descending `created_at`).
124    async fn list(&self) -> Result<Vec<TaskRecord>, TaskStoreError>;
125
126    /// Update a Task's status, bumping `updated_at` to now.
127    async fn update_status(
128        &self,
129        id: &TaskId,
130        status: TaskRecordStatus,
131    ) -> Result<(), TaskStoreError>;
132}
133
134// ──────────────────────────────────────────────────────────────────────────
135// Shared inner state used by the InMemory backend.
136// ──────────────────────────────────────────────────────────────────────────
137
138#[derive(Default)]
139pub(crate) struct Inner {
140    /// Insertion order — used as a stable tie-break under `list()`.
141    pub(crate) order: Vec<TaskId>,
142    pub(crate) records: HashMap<TaskId, TaskRecord>,
143}
144
145pub(crate) type SharedInner = Mutex<Inner>;