Skip to main content

lean_ctx_tasks/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Local project tasks: the Cloud task model
3//! ([`TaskV1`](lean_ctx_protocol::cloud::tasks::TaskV1), [`TaskState`]) kept
4//! per project on this machine, so tasks work without Cloud (owner decision
5//! 2026-11-04: everything a project has works locally in the Instance; Cloud
6//! only adds sharing).
7//!
8//! ```text
9//! proposed --accept--> open --claim--> claimed --submit--> submitted --verify accept--> done
10//!    |                  ^ ^               |  |                  |
11//!    +--decline--> rejected +--release----+  +--submit failed--> failed
12//!                           +--------------------- verify reject ---+
13//! proposed/open/claimed --stop--> cancelled
14//! ```
15//!
16//! The rules ([`board`]):
17//! - anyone (an agent or a person) may accept or decline a proposal, the
18//!   proposer included;
19//! - only an agent claims, the proposer included; a claim lasts its minutes
20//!   and is renewed by the holder's claim again or update; an expired claim
21//!   opens the task again;
22//! - the holder updates, submits or releases; a person may release too;
23//! - a result is verified by a person or by another agent, never by the
24//!   agent that submitted it; `reject` opens the task again;
25//! - a person (never an agent) stops a proposed, open or claimed task, with a reason;
26//! - every transition is recorded with who and when, on the task and in the
27//!   store's journal ([`store`]).
28//!
29//! Text rules (lengths, one-line summaries, evidence kinds) are Cloud's: each
30//! write is checked with the matching Cloud request type's `validate`.
31//!
32//! This crate never posts on the bus or decides whether a project is linked
33//! to a vault: every write returns its [`Change`]s, and the caller announces
34//! them (lean-ctx-cloud `tasks::local`).
35
36pub mod board;
37pub mod store;
38
39#[cfg(test)]
40mod tests;
41
42use serde::{Deserialize, Serialize};
43
44use lean_ctx_protocol::UtcTimestamp;
45use lean_ctx_protocol::cloud::tasks::{TaskActorKind, TaskActorV1, TaskState};
46
47pub use board::{Amendment, Board, LocalTask, Proposal, SharedRef, Submission, Transition};
48pub use store::Store;
49
50/// The `vault_id` every local task carries (it lives in no vault).
51pub const LOCAL_VAULT: &str = "local";
52/// Claim length when the caller names none.
53pub const DEFAULT_CLAIM_MINUTES: u32 = 60;
54pub const MIN_CLAIM_MINUTES: u32 = 5;
55/// No keeper renews a local claim: the holder renews it by working on it.
56pub const MAX_CLAIM_MINUTES: u32 = 240;
57
58/// Who acts on a task.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum Actor {
61    /// A bus agent (its id) and how it is shown.
62    Agent { id: String, label: Option<String> },
63    /// A person on this machine (Cloud Desktop, the CLI).
64    Person { label: String },
65}
66
67impl Actor {
68    pub fn agent(id: impl Into<String>) -> Self {
69        Self::Agent {
70            id: id.into(),
71            label: None,
72        }
73    }
74
75    pub fn person(label: impl Into<String>) -> Self {
76        Self::Person {
77            label: label.into(),
78        }
79    }
80
81    /// The bus agent id, for an agent.
82    pub fn agent_id(&self) -> Option<&str> {
83        match self {
84            Self::Agent { id, .. } => Some(id),
85            Self::Person { .. } => None,
86        }
87    }
88
89    /// The actor as a task view names it (`mine` is the reader's, set when
90    /// a view is rendered).
91    pub fn view(&self) -> TaskActorV1 {
92        match self {
93            Self::Agent { id, label } => TaskActorV1 {
94                kind: TaskActorKind::Instance,
95                label: label.clone().unwrap_or_else(|| id.clone()),
96                agent: Some(id.clone()),
97                owner: None,
98                model: None,
99                mine: false,
100                profile_id: None,
101                own: None,
102            },
103            Self::Person { label } => TaskActorV1 {
104                kind: TaskActorKind::Person,
105                label: label.clone(),
106                agent: None,
107                owner: None,
108                model: None,
109                mine: false,
110                profile_id: None,
111                own: None,
112            },
113        }
114    }
115
116    /// Whether `actor` (a view) is this actor.
117    fn is(&self, actor: &TaskActorV1) -> bool {
118        match self {
119            Self::Agent { id, .. } => actor.agent.as_deref() == Some(id.as_str()),
120            Self::Person { .. } => actor.kind == TaskActorKind::Person,
121        }
122    }
123
124    /// Whether `actor` is this actor by name too: a person by its label
125    /// (two people on one machine stay apart).
126    fn is_exactly(&self, actor: &TaskActorV1) -> bool {
127        match self {
128            Self::Agent { .. } => self.is(actor),
129            Self::Person { label } => actor.kind == TaskActorKind::Person && actor.label == *label,
130        }
131    }
132}
133
134/// What happened to a task; the bus key names it (`task:<n>:<event>`).
135#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
136#[serde(rename_all = "snake_case")]
137pub enum TaskEvent {
138    Proposed,
139    Accepted,
140    Declined,
141    Claimed,
142    Updated,
143    Released,
144    Submitted,
145    Failed,
146    Verified,
147    Rejected,
148    Stopped,
149    /// The submitter amended its result (no state change).
150    Amended,
151    /// Brought into a Cloud vault (no state change, no bus notice).
152    Shared,
153    /// Priority and/or labels set (no state change, no bus notice).
154    Fields,
155}
156
157impl TaskEvent {
158    pub fn as_str(self) -> &'static str {
159        match self {
160            Self::Proposed => "proposed",
161            Self::Accepted => "accepted",
162            Self::Declined => "declined",
163            Self::Claimed => "claimed",
164            Self::Updated => "updated",
165            Self::Released => "released",
166            Self::Submitted => "submitted",
167            Self::Failed => "failed",
168            Self::Verified => "verified",
169            Self::Rejected => "rejected",
170            Self::Stopped => "stopped",
171            Self::Amended => "amended",
172            Self::Shared => "shared",
173            Self::Fields => "fields",
174        }
175    }
176}
177
178/// One recorded transition, as a write returns it for its notices.
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct Change {
181    /// The store's journal sequence of this transition (unique per store).
182    pub seq: u64,
183    pub number: u64,
184    pub event: TaskEvent,
185    pub state: TaskState,
186    /// The agent the event is about when it must not be told: the worker
187    /// whose result waits for a check.
188    pub worker: Option<String>,
189}
190
191/// Why a write was refused. `reason` codes follow Cloud's (`task_claimed`,
192/// `task_not_open`, `task_closed`, `not_submitted`, `self_verify`, …).
193#[derive(Debug, Clone, PartialEq, Eq)]
194pub enum TaskError {
195    NotFound(u64),
196    /// The task's state does not allow the write.
197    InvalidState {
198        number: u64,
199        reason: &'static str,
200    },
201    /// The actor may not make the write.
202    Forbidden {
203        number: u64,
204        reason: &'static str,
205    },
206    /// The request is malformed (text rules, missing fields).
207    Invalid(String),
208    /// The store could not be read, locked or written.
209    Store(String),
210}
211
212impl TaskError {
213    /// A stable code: `not_found`, `invalid_state`, `forbidden`,
214    /// `invalid_argument`, `unavailable`.
215    pub fn code(&self) -> &'static str {
216        match self {
217            Self::NotFound(_) => "not_found",
218            Self::InvalidState { .. } => "invalid_state",
219            Self::Forbidden { .. } => "forbidden",
220            Self::Invalid(_) => "invalid_argument",
221            Self::Store(_) => "unavailable",
222        }
223    }
224
225    /// The Cloud-style reason, for state and right refusals.
226    pub fn reason(&self) -> Option<&'static str> {
227        match self {
228            Self::InvalidState { reason, .. } | Self::Forbidden { reason, .. } => Some(reason),
229            _ => None,
230        }
231    }
232}
233
234impl std::fmt::Display for TaskError {
235    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
236        match self {
237            Self::NotFound(n) => write!(f, "task #{n} does not exist"),
238            Self::InvalidState { number, reason } | Self::Forbidden { number, reason } => {
239                write!(f, "task #{number}: {}", describe(reason))
240            }
241            Self::Invalid(message) | Self::Store(message) => f.write_str(message),
242        }
243    }
244}
245
246impl std::error::Error for TaskError {}
247
248fn describe(reason: &str) -> &'static str {
249    match reason {
250        "task_claimed" => "another agent holds its claim (task_claimed)",
251        "task_not_open" => "it is not open (task_not_open)",
252        "not_proposed" => "it is not a proposal (not_proposed)",
253        "not_claimed" => "it is not claimed (not_claimed)",
254        "task_closed" => "it is closed (task_closed)",
255        "not_submitted" => "no result waits for a check (not_submitted)",
256        "self_verify" => {
257            "the agent that submitted the result never checks it; a person or another agent does (self_verify)"
258        }
259        "not_holder" => "only the agent holding its claim does that (not_holder)",
260        "agents_claim" => "only an agent claims a task (agents_claim)",
261        "task_submitted" => "its result waits for a check; verify it instead (task_submitted)",
262        "agents_stop" => "only a person stops a task (agents_stop)",
263        "already_shared" => "it was already brought into a vault (already_shared)",
264        "too_many_tasks" => "the project holds too many unfinished tasks (too_many_tasks)",
265        "not_submitter" => {
266            "only the agent that submitted its result corrects it; a merge record also a person or a coordinator session (not_submitter)"
267        }
268        "not_merger" => {
269            "the reviewer never records the merge; the submitter, a person or a coordinator session does (not_merger)"
270        }
271        "not_amendable" => "it has no submitted or done result to amend (not_amendable)",
272        "record_merge_only" => {
273            "it is done: it only takes its merge record, --merge <sha> (record_merge_only)"
274        }
275        "not_merged_yet" => {
276            "its result waits for a check; a merge is recorded once it is done (not_merged_yet)"
277        }
278        "merge_recorded" => "its merge is already recorded (merge_recorded)",
279        _ => "refused",
280    }
281}
282
283/// Whole-second UTC, as Cloud writes task times.
284pub fn timestamp(at: lean_ctx_time::UtcDateTime) -> UtcTimestamp {
285    UtcTimestamp::new(at.format("%Y-%m-%dT%H:%M:%SZ").to_string())
286        .unwrap_or_else(|_| unreachable_timestamp())
287}
288
289#[cold]
290fn unreachable_timestamp() -> UtcTimestamp {
291    // `%Y-%m-%dT%H:%M:%SZ` of a chrono time is always canonical.
292    UtcTimestamp::new("1970-01-01T00:00:00Z").unwrap_or_else(|_| unreachable!())
293}