Skip to main content

agentstategraph_tasks/
types.rs

1//! Public data types for plans, tasks, and proofs.
2
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5
6use crate::error::TaskStoreError;
7
8/// A named container of tasks.
9#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
10pub struct Plan {
11    pub name: String,
12    pub description: Option<String>,
13    pub status: PlanStatus,
14    pub created_at: DateTime<Utc>,
15    pub created_by: String,
16    pub archived_at: Option<DateTime<Utc>>,
17    /// Closing summary, set by `close_plan`. A plan cannot be closed
18    /// without one โ€” the plan-level analog of a task's `proof`. `None`
19    /// until the plan is explicitly closed (and on legacy plans that
20    /// predate this field).
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub summary: Option<String>,
23    /// When the plan was closed via `close_plan`.
24    #[serde(default, skip_serializing_if = "Option::is_none")]
25    pub closed_at: Option<DateTime<Utc>>,
26    /// Agent that closed the plan.
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub closed_by: Option<String>,
29}
30
31/// The most a task's notes may hold: 16 KiB of UTF-8, counted in bytes.
32///
33/// Notes are a brief, decisions or links, not a document store: this is
34/// several times a long brief (the lane briefs that prompted the field run
35/// about 2 KB) and about 4,000 tokens. The cap bounds what a task costs
36/// everywhere it goes: every read of a plan's tasks reads each one whole,
37/// and every edit stores a new copy of the task that history keeps.
38pub const MAX_NOTES_BYTES: usize = 16 * 1024;
39
40/// A unit of work inside a plan.
41#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
42pub struct Task {
43    pub id: TaskId,
44    pub title: String,
45    /// Free-form notes: a brief, decisions, links. They may span lines and
46    /// hold at most [`MAX_NOTES_BYTES`]. `TaskStore::set_notes` edits them
47    /// at any status. `None` when a task has none, as every task stored
48    /// before the field existed reads.
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub notes: Option<String>,
51    pub status: TaskStatus,
52    pub priority: Priority,
53    pub parent_id: Option<TaskId>,
54    #[serde(default)]
55    pub blocked_by: Vec<TaskId>,
56    pub created_at: DateTime<Utc>,
57    pub created_by: String,
58    pub started_at: Option<DateTime<Utc>>,
59    pub started_by: Option<String>,
60    pub completed_at: Option<DateTime<Utc>>,
61    pub completed_by: Option<String>,
62    pub proof: Option<Proof>,
63    pub abandoned_at: Option<DateTime<Utc>>,
64    pub abandoned_reason: Option<String>,
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub assigned_to: Option<String>,
67    /// Opaque JSON payload attached to a task. Used by the policy
68    /// fallback pattern (POLICY_V1.md ยง22.4) to stash a deferred
69    /// `ChangeProposal` or similar state for a downstream consumer to
70    /// act on when the task completes. The `-tasks` crate does not
71    /// interpret the contents.
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub payload: Option<serde_json::Value>,
74    /// Identifier of the change this task gates. For the fallback
75    /// pattern this is the opaque spec / commit handle from the
76    /// original `ChangeProposal`. The `-tasks` crate does not resolve
77    /// it; consumers (MCP server, Lens) look it up.
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub parent_change: Option<String>,
80    /// Hook that downstream consumers should run when this task
81    /// transitions to `Done`. The `-tasks` crate serializes and
82    /// round-trips the hook but does NOT execute it.
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub on_complete: Option<OnCompleteHook>,
85}
86
87/// A hook attached to a task, run by the consumer when the task
88/// completes. The `-tasks` crate is a pure round-trip for these โ€”
89/// dispatch lives in the MCP server (phase 3) or other consumers
90/// (future Lens, CLI).
91#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
92#[serde(tag = "kind", rename_all = "snake_case")]
93pub enum OnCompleteHook {
94    /// Promote a deferred `ChangeProposal` by re-running policy
95    /// evaluation with `approval_granted: <this_task_path>` attached.
96    /// The consumer is responsible for locating the proposal โ€” usually
97    /// it lives in the task's `payload`.
98    PromoteChange,
99    /// Call an arbitrary named hook registered by the consumer.
100    /// `name` is an opaque string the consumer (e.g. the MCP server)
101    /// understands.
102    Named { name: String },
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
106#[serde(rename_all = "snake_case")]
107pub enum PlanStatus {
108    Active,
109    Completed,
110    Archived,
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
114#[serde(rename_all = "snake_case")]
115pub enum TaskStatus {
116    Pending,
117    InProgress,
118    Done,
119    Abandoned,
120}
121
122impl TaskStatus {
123    pub fn is_terminal(self) -> bool {
124        matches!(self, TaskStatus::Done | TaskStatus::Abandoned)
125    }
126}
127
128#[derive(
129    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
130)]
131#[serde(rename_all = "snake_case")]
132pub enum Priority {
133    Low,
134    #[default]
135    Medium,
136    High,
137    Critical,
138}
139
140/// A task identifier, unique within a plan. Format: "t-001", "t-002", ...
141#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
142pub struct TaskId(pub String);
143
144impl TaskId {
145    /// Construct a zero-padded id from a 1-based sequence number.
146    pub fn new(n: u32) -> Self {
147        Self(format!("t-{:03}", n))
148    }
149
150    /// Parse the numeric suffix from a `t-NNN` identifier.
151    pub fn number(&self) -> Result<u32, TaskStoreError> {
152        self.0
153            .strip_prefix("t-")
154            .and_then(|s| s.parse::<u32>().ok())
155            .ok_or_else(|| TaskStoreError::InvalidTaskId(self.0.clone()))
156    }
157
158    /// The raw string form, e.g. `"t-001"`.
159    pub fn as_str(&self) -> &str {
160        &self.0
161    }
162}
163
164impl std::fmt::Display for TaskId {
165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166        f.write_str(&self.0)
167    }
168}
169
170/// Evidence attached to a `done` task.
171#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
172pub struct Proof {
173    pub kind: ProofKind,
174    pub value: String,
175    pub note: Option<String>,
176}
177
178impl Proof {
179    pub fn commit(sha: impl Into<String>) -> Self {
180        Self {
181            kind: ProofKind::Commit,
182            value: sha.into(),
183            note: None,
184        }
185    }
186
187    pub fn file(path: impl Into<String>) -> Self {
188        Self {
189            kind: ProofKind::File,
190            value: path.into(),
191            note: None,
192        }
193    }
194
195    pub fn test(name: impl Into<String>) -> Self {
196        Self {
197            kind: ProofKind::Test,
198            value: name.into(),
199            note: None,
200        }
201    }
202
203    pub fn text(value: impl Into<String>) -> Self {
204        Self {
205            kind: ProofKind::Text,
206            value: value.into(),
207            note: None,
208        }
209    }
210
211    pub fn with_note(mut self, note: impl Into<String>) -> Self {
212        self.note = Some(note.into());
213        self
214    }
215}
216
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
218#[serde(rename_all = "snake_case")]
219pub enum ProofKind {
220    /// A git commit SHA. Verifier should check reachability.
221    Commit,
222    /// A file path. Verifier should check existence.
223    File,
224    /// A test name. Verifier should check the test exists in the suite.
225    Test,
226    /// Free-form human-attested description. Unverifiable.
227    Text,
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    #[test]
235    fn task_id_roundtrip() {
236        let id = TaskId::new(42);
237        assert_eq!(id.as_str(), "t-042");
238        assert_eq!(id.number().unwrap(), 42);
239    }
240
241    #[test]
242    fn task_id_padding() {
243        assert_eq!(TaskId::new(1).as_str(), "t-001");
244        assert_eq!(TaskId::new(999).as_str(), "t-999");
245        assert_eq!(TaskId::new(1000).as_str(), "t-1000");
246    }
247
248    #[test]
249    fn task_id_parse_invalid() {
250        assert!(TaskId("nope".to_string()).number().is_err());
251        assert!(TaskId("t-abc".to_string()).number().is_err());
252    }
253
254    #[test]
255    fn priority_ordering() {
256        assert!(Priority::Critical > Priority::High);
257        assert!(Priority::High > Priority::Medium);
258        assert!(Priority::Medium > Priority::Low);
259    }
260
261    #[test]
262    fn task_status_terminal() {
263        assert!(TaskStatus::Done.is_terminal());
264        assert!(TaskStatus::Abandoned.is_terminal());
265        assert!(!TaskStatus::Pending.is_terminal());
266        assert!(!TaskStatus::InProgress.is_terminal());
267    }
268
269    #[test]
270    fn plan_serde_roundtrip() {
271        let plan = Plan {
272            name: "website-v2".to_string(),
273            description: Some("Brand pivot".to_string()),
274            status: PlanStatus::Active,
275            created_at: Utc::now(),
276            created_by: "claude-code".to_string(),
277            archived_at: None,
278            summary: None,
279            closed_at: None,
280            closed_by: None,
281        };
282        let json = serde_json::to_value(&plan).unwrap();
283        let back: Plan = serde_json::from_value(json).unwrap();
284        assert_eq!(plan, back);
285    }
286
287    #[test]
288    fn task_serde_roundtrip() {
289        let task = Task {
290            id: TaskId::new(1),
291            title: "Rewrite hero".to_string(),
292            notes: Some("Keep the old copy.\nLink the brand doc.".to_string()),
293            status: TaskStatus::Pending,
294            priority: Priority::High,
295            parent_id: None,
296            blocked_by: vec![TaskId::new(2)],
297            created_at: Utc::now(),
298            created_by: "claude-code".to_string(),
299            started_at: None,
300            started_by: None,
301            completed_at: None,
302            completed_by: None,
303            proof: None,
304            abandoned_at: None,
305            abandoned_reason: None,
306            assigned_to: Some("codex".to_string()),
307            payload: None,
308            parent_change: None,
309            on_complete: None,
310        };
311        let json = serde_json::to_value(&task).unwrap();
312        let back: Task = serde_json::from_value(json).unwrap();
313        assert_eq!(task, back);
314    }
315
316    #[test]
317    fn a_task_stored_before_notes_reads_with_none_and_writes_back_unchanged() {
318        let stored = serde_json::json!({
319            "id": "t-001", "title": "Rewrite hero", "status": "pending",
320            "priority": "high", "parent_id": null, "blocked_by": [],
321            "created_at": "2026-10-01T00:00:00Z", "created_by": "claude-code",
322            "started_at": null, "started_by": null, "completed_at": null,
323            "completed_by": null, "proof": null, "abandoned_at": null,
324            "abandoned_reason": null,
325        });
326        let task: Task = serde_json::from_value(stored.clone()).unwrap();
327        assert_eq!(task.notes, None);
328        // No `notes` key is written for a task without notes, so the stored
329        // JSON, and the tree object it hashes to, stay as they were.
330        assert_eq!(serde_json::to_value(&task).unwrap(), stored);
331    }
332
333    #[test]
334    fn proof_constructors() {
335        let p = Proof::commit("abc123").with_note("verified");
336        assert_eq!(p.kind, ProofKind::Commit);
337        assert_eq!(p.value, "abc123");
338        assert_eq!(p.note.as_deref(), Some("verified"));
339    }
340}