Skip to main content

qualia_cooperative_core/
work_item.rs

1//! Cooperative work items — phases, epics, stories, tasks, issues, bugs, and milestones —
2//! with WBS hierarchy, PDM dependencies, and a replay-safe Kanban board.
3//!
4//! A `WorkItem` is created once (immutable core). Status transitions are separate immutable
5//! `WorkItemStatusEvent` records; the *current* status is a **derived projection** — the latest
6//! event per work item — never a mutated field. Deduping events by stable id before deriving
7//! makes the board invariant under duplicated, reordered, or replayed sync frames (plan §8.3/§8.4).
8
9use serde::{Deserialize, Serialize};
10use uuid::Uuid;
11
12use crate::record::{EpistemicStatus, EvidenceType, RecordEnvelope, SensitivityClass};
13pub use crate::work_graph::{
14    detect_semantic_conflicts, merge_dependencies, DepKind, Lag, SemanticConflict, TaskConstraint,
15    TaskRef, ThreePointEstimate, TimeEntry, WorkDependency,
16};
17
18/// The kind of work item across WBS and Agile/Kanban views.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
20#[serde(rename_all = "snake_case")]
21pub enum WorkItemType {
22    #[default]
23    Task,
24    Issue,
25    Milestone,
26    Phase,
27    Epic,
28    Story,
29    Bug,
30}
31
32/// Kanban lifecycle status. `ORDER` gives the canonical column ordering for board rendering.
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
34#[serde(rename_all = "snake_case")]
35pub enum WorkItemStatus {
36    Proposed,
37    #[default]
38    Todo,
39    InProgress,
40    Blocked,
41    InReview,
42    Done,
43    Cancelled,
44}
45
46impl WorkItemStatus {
47    /// Canonical Kanban column order.
48    pub const ORDER: [WorkItemStatus; 7] = [
49        WorkItemStatus::Proposed,
50        WorkItemStatus::Todo,
51        WorkItemStatus::InProgress,
52        WorkItemStatus::Blocked,
53        WorkItemStatus::InReview,
54        WorkItemStatus::Done,
55        WorkItemStatus::Cancelled,
56    ];
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
60#[serde(rename_all = "snake_case")]
61pub enum WorkItemPriority {
62    Low,
63    #[default]
64    Normal,
65    High,
66    Urgent,
67}
68
69/// The immutable core of a work item. Its status is derived from status events, not stored here.
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71pub struct WorkItem {
72    pub id: String,
73    pub project_id: String,
74    #[serde(default)]
75    pub item_type: WorkItemType,
76    pub title: String,
77    #[serde(default)]
78    pub description: String,
79    #[serde(default)]
80    pub priority: WorkItemPriority,
81    /// Optional parent work item ID in the WBS hierarchy.
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    pub parent_id: Option<String>,
84    /// Dotted WBS code (e.g. `"1.2.3"`).
85    #[serde(default)]
86    pub wbs: String,
87    /// WBS outline depth (`0` = root, `1` = phase/summary, etc.).
88    #[serde(default)]
89    pub outline_level: u16,
90    /// Effort estimate in whole minutes (integer discipline, plan §8.4).
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub estimate_minutes: Option<u32>,
93    /// Optional three-point PERT duration/effort estimate (`optimistic_m`, `most_likely_m`, `pessimistic_m`).
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    pub three_point_estimate: Option<ThreePointEstimate>,
96    /// Scheduling constraint (`Asap`, `Alap`, `Snet`, `Snlt`, `Fnet`, `Fnlt`, `Mso`, `Mfo`).
97    #[serde(default)]
98    pub constraint: TaskConstraint,
99    /// Optional Unix timestamp anchor for date-constrained tasks (`Snet`, `Snlt`, `Fnet`, `Fnlt`, `Mso`, `Mfo`).
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub constraint_date_unix: Option<u32>,
102    #[serde(default, skip_serializing_if = "Option::is_none")]
103    pub assignee_did: Option<String>,
104    pub created_at_unix: u32,
105}
106
107impl WorkItem {
108    /// Creates a new instance.
109    pub fn new(
110        project_id: impl Into<String>,
111        item_type: WorkItemType,
112        title: impl Into<String>,
113        created_at_unix: u32,
114    ) -> Self {
115        Self {
116            id: Uuid::new_v4().to_string(),
117            project_id: project_id.into(),
118            item_type,
119            title: title.into(),
120            description: String::new(),
121            priority: WorkItemPriority::Normal,
122            parent_id: None,
123            wbs: String::new(),
124            outline_level: 0,
125            estimate_minutes: None,
126            three_point_estimate: None,
127            constraint: TaskConstraint::Asap,
128            constraint_date_unix: None,
129            assignee_did: None,
130            created_at_unix,
131        }
132    }
133
134    /// Builder helper to set WBS hierarchy coordinates (`parent_id`, `wbs`, `outline_level`).
135    pub fn with_wbs(
136        mut self,
137        parent_id: Option<String>,
138        wbs: impl Into<String>,
139        outline_level: u16,
140    ) -> Self {
141        self.parent_id = parent_id;
142        self.wbs = wbs.into();
143        self.outline_level = outline_level;
144        self
145    }
146
147    /// Builder helper to attach a `TaskConstraint` and optional anchor timestamp.
148    pub fn with_constraint(
149        mut self,
150        constraint: TaskConstraint,
151        constraint_date_unix: Option<u32>,
152    ) -> Self {
153        self.constraint = constraint;
154        self.constraint_date_unix = constraint_date_unix;
155        self
156    }
157
158    /// Builder helper to attach a `ThreePointEstimate`.
159    pub fn with_three_point_estimate(mut self, estimate: ThreePointEstimate) -> Self {
160        self.three_point_estimate = Some(estimate);
161        self
162    }
163}
164
165/// An immutable status transition for a work item. The board derives the current status as the
166/// latest event per work item.
167#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
168pub struct WorkItemStatusEvent {
169    pub id: String,
170    pub work_item_id: String,
171    pub status: WorkItemStatus,
172    pub occurred_at_unix: u32,
173}
174
175impl WorkItemStatusEvent {
176    /// Creates a new instance.
177    pub fn new(
178        work_item_id: impl Into<String>,
179        status: WorkItemStatus,
180        occurred_at_unix: u32,
181    ) -> Self {
182        Self {
183            id: Uuid::new_v4().to_string(),
184            work_item_id: work_item_id.into(),
185            status,
186            occurred_at_unix,
187        }
188    }
189}
190
191/// `work-item-record` ID.
192pub fn work_item_record_id(uuid: &str) -> String {
193    format!("urn:qualia:work_item:{uuid}")
194}
195
196/// `work-item-status-record` ID.
197pub fn work_item_status_record_id(uuid: &str) -> String {
198    format!("urn:qualia:work_item_status:{uuid}")
199}
200
201fn cooperative_envelope(
202    id: &str,
203    owner_did: &str,
204    author_did: &str,
205    asserted_unix: u32,
206    valid_start_unix: u32,
207) -> RecordEnvelope {
208    RecordEnvelope {
209        id: id.to_string(),
210        owner_did: owner_did.to_string(),
211        author_did: author_did.to_string(),
212        proxy_did: None,
213        epistemic_status: EpistemicStatus::Asserted,
214        evidence_type: EvidenceType::SelfReported,
215        sensitivity: SensitivityClass::Restricted,
216        asserted_time_unix: asserted_unix,
217        asserted_instant: None,
218        valid_time_start_unix: Some(valid_start_unix),
219        valid_time_start_instant: None,
220        valid_time_end_unix: None,
221        valid_time_end_instant: None,
222        predecessor_id: None,
223        blob_hash: None,
224        tombstone: false,
225    }
226}
227
228/// Builds work-item-envelope.
229pub fn build_work_item_envelope(
230    item: &WorkItem,
231    owner_did: &str,
232    author_did: &str,
233    asserted_unix: u32,
234) -> RecordEnvelope {
235    cooperative_envelope(
236        &work_item_record_id(&item.id),
237        owner_did,
238        author_did,
239        asserted_unix,
240        item.created_at_unix,
241    )
242}
243
244/// Builds work-item-status-envelope.
245pub fn build_work_item_status_envelope(
246    event: &WorkItemStatusEvent,
247    owner_did: &str,
248    author_did: &str,
249    asserted_unix: u32,
250) -> RecordEnvelope {
251    cooperative_envelope(
252        &work_item_status_record_id(&event.id),
253        owner_did,
254        author_did,
255        asserted_unix,
256        event.occurred_at_unix,
257    )
258}
259
260/// Work-item summary (lossless across WBS and PDM fields).
261pub fn work_item_summary(item: &WorkItem) -> String {
262    serde_json::json!({
263        "id": item.id,
264        "project_id": item.project_id,
265        "item_type": item.item_type,
266        "title": item.title,
267        "description": item.description,
268        "priority": item.priority,
269        "parent_id": item.parent_id,
270        "wbs": item.wbs,
271        "outline_level": item.outline_level,
272        "estimate_minutes": item.estimate_minutes,
273        "three_point_estimate": item.three_point_estimate,
274        "constraint": item.constraint,
275        "constraint_date_unix": item.constraint_date_unix,
276        "assignee_did": item.assignee_did,
277        "created_at_unix": item.created_at_unix,
278    })
279    .to_string()
280}
281
282/// Work-item status summary.
283pub fn work_item_status_summary(event: &WorkItemStatusEvent) -> String {
284    serde_json::json!({
285        "id": event.id,
286        "work_item_id": event.work_item_id,
287        "status": event.status,
288        "occurred_at_unix": event.occurred_at_unix,
289    })
290    .to_string()
291}
292
293/// Reconstruct a `WorkItem` from a stored/transmitted summary JSON (fields not in the summary
294/// take their defaults). Returns `None` on malformed input.
295pub fn parse_work_item_summary(summary: &str) -> Option<WorkItem> {
296    serde_json::from_str(summary).ok()
297}
298
299/// Parses work-item-status-summary.
300pub fn parse_work_item_status_summary(summary: &str) -> Option<WorkItemStatusEvent> {
301    serde_json::from_str(summary).ok()
302}
303
304/// Merge status-event sets add-wins by stable id (never re-apply), deterministically ordered
305/// by (time, id). Idempotent and order-independent — the basis for replay-safe board derivation.
306pub fn merge_status_events(
307    existing: &[WorkItemStatusEvent],
308    incoming: &[WorkItemStatusEvent],
309) -> Vec<WorkItemStatusEvent> {
310    let mut merged: Vec<WorkItemStatusEvent> = Vec::with_capacity(existing.len() + incoming.len());
311    for ev in existing.iter().chain(incoming.iter()) {
312        if !merged.iter().any(|e| e.id == ev.id) {
313            merged.push(ev.clone());
314        }
315    }
316    merged.sort_by(|a, b| {
317        a.occurred_at_unix
318            .cmp(&b.occurred_at_unix)
319            .then_with(|| a.id.cmp(&b.id))
320    });
321    merged
322}
323
324/// The current status of a work item = the latest event (by time, then id) for it, or `Todo`
325/// if it has no status events yet. Pure over the unique-event-id set (duplicates collapse first).
326pub fn current_status(work_item_id: &str, events: &[WorkItemStatusEvent]) -> WorkItemStatus {
327    merge_status_events(events, &[])
328        .into_iter()
329        .filter(|e| e.work_item_id == work_item_id)
330        .last()
331        .map(|e| e.status)
332        .unwrap_or(WorkItemStatus::Todo)
333}
334
335/// A card as rendered on the board.
336#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
337pub struct BoardCard {
338    pub work_item_id: String,
339    pub title: String,
340    pub item_type: WorkItemType,
341    pub priority: WorkItemPriority,
342    pub status: WorkItemStatus,
343}
344
345/// A Kanban column: a status and the cards currently in it.
346#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
347pub struct BoardColumn {
348    pub status: WorkItemStatus,
349    pub cards: Vec<BoardCard>,
350}
351
352/// Derive the Kanban board for a set of work items and their status events.
353pub fn derive_board(items: &[WorkItem], events: &[WorkItemStatusEvent]) -> Vec<BoardColumn> {
354    let merged = merge_status_events(events, &[]);
355    let mut columns: Vec<BoardColumn> = WorkItemStatus::ORDER
356        .iter()
357        .map(|status| BoardColumn {
358            status: *status,
359            cards: Vec::new(),
360        })
361        .collect();
362    let mut ordered = items.to_vec();
363    ordered.sort_by(|a, b| {
364        a.created_at_unix
365            .cmp(&b.created_at_unix)
366            .then_with(|| a.id.cmp(&b.id))
367    });
368    for item in &ordered {
369        let status = current_status(&item.id, &merged);
370        if let Some(col) = columns.iter_mut().find(|c| c.status == status) {
371            col.cards.push(BoardCard {
372                work_item_id: item.id.clone(),
373                title: item.title.clone(),
374                item_type: item.item_type,
375                priority: item.priority,
376                status,
377            });
378        }
379    }
380    columns
381}
382
383#[cfg(test)]
384#[path = "work_item_tests.rs"]
385mod tests;