Skip to main content

qualia_cooperative_core/
work_graph.rs

1//! Enriched WBS / PDM Work Graph: Dependencies (`FS`/`SS`/`FF`/`SF`), `Lag`, `TaskRef`,
2//! `TaskConstraint`, `ThreePointEstimate`, `TimeEntry` (producing Stage 2 `ActivityAndResources`
3//! records), and post-merge `SemanticConflict` detection.
4
5use std::collections::{HashMap, HashSet};
6
7use serde::{Deserialize, Serialize};
8use uuid::Uuid;
9
10use crate::contribution_lifecycle::ActivityAndResources;
11use crate::record::{q_hash_str, InstantBridge, NQuin, SensitivityClass};
12use crate::work_item::WorkItem;
13
14/// Precedence Diagramming Method (PDM) relationship kind.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
16pub enum DepKind {
17    /// Finish-to-Start (default).
18    #[default]
19    FS,
20    /// Start-to-Start.
21    SS,
22    /// Finish-to-Finish.
23    FF,
24    /// Start-to-Finish.
25    SF,
26}
27
28/// Lead/lag offset on a PDM dependency link.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
30#[serde(tag = "kind", content = "value", rename_all = "snake_case")]
31pub enum Lag {
32    #[default]
33    None,
34    WorkingMinutes(i64),
35    ElapsedMinutes(i64),
36    Percent(i32),
37}
38
39/// Reference to a predecessor or successor task — either within the current project
40/// or across projects (`External`).
41#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
42#[serde(tag = "scope", content = "ref", rename_all = "snake_case")]
43pub enum TaskRef {
44    Local(String),
45    External {
46        project_id: String,
47        work_item_id: String,
48    },
49}
50
51impl TaskRef {
52    /// Returns the local `work_item_id` when `Local`, or the target `work_item_id` when `External`.
53    pub fn work_item_id(&self) -> &str {
54        match self {
55            Self::Local(id) => id,
56            Self::External { work_item_id, .. } => work_item_id,
57        }
58    }
59}
60
61/// An immutable PDM dependency edge between two tasks.
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63pub struct WorkDependency {
64    pub id: String,
65    pub project_id: String,
66    pub predecessor: TaskRef,
67    pub successor: TaskRef,
68    pub kind: DepKind,
69    pub lag: Lag,
70    pub created_at_unix: u32,
71}
72
73impl WorkDependency {
74    /// Construct a new local `FS` dependency with optional lag.
75    pub fn new_local(
76        project_id: impl Into<String>,
77        predecessor_id: impl Into<String>,
78        successor_id: impl Into<String>,
79        kind: DepKind,
80        lag: Lag,
81        created_at_unix: u32,
82    ) -> Self {
83        Self {
84            id: Uuid::new_v4().to_string(),
85            project_id: project_id.into(),
86            predecessor: TaskRef::Local(predecessor_id.into()),
87            successor: TaskRef::Local(successor_id.into()),
88            kind,
89            lag,
90            created_at_unix,
91        }
92    }
93
94    /// Zero-heap compilation into 48-byte `NQuin`s.
95    pub fn compile_to_quins(&self, out: &mut [NQuin]) -> usize {
96        if out.is_empty() {
97            return 0;
98        }
99        let s = q_hash_str(self.predecessor.work_item_id());
100        let p = q_hash_str("https://vocab.Burst.net.au/coop#precedesTask");
101        let o = q_hash_str(self.successor.work_item_id());
102        let ctx = q_hash_str(&self.project_id);
103        let meta = SensitivityClass::Restricted.to_metadata_mask() | (self.created_at_unix as u64);
104        out[0] = NQuin::new(s, p, o, ctx, meta);
105        1
106    }
107}
108
109/// Replay-safe, order-independent union of `WorkDependency` records by stable `id`
110/// (also deduplicating identical `(predecessor, successor, kind, lag)` tuples).
111pub fn merge_dependencies(
112    existing: &[WorkDependency],
113    incoming: &[WorkDependency],
114) -> Vec<WorkDependency> {
115    let mut merged: Vec<WorkDependency> = Vec::with_capacity(existing.len() + incoming.len());
116    for dep in existing.iter().chain(incoming.iter()) {
117        let duplicate = merged.iter().any(|d| {
118            d.id == dep.id
119                || (d.project_id == dep.project_id
120                    && d.predecessor == dep.predecessor
121                    && d.successor == dep.successor
122                    && d.kind == dep.kind
123                    && d.lag == dep.lag)
124        });
125        if !duplicate {
126            merged.push(dep.clone());
127        }
128    }
129    merged.sort_by(|a, b| {
130        a.created_at_unix
131            .cmp(&b.created_at_unix)
132            .then_with(|| a.id.cmp(&b.id))
133    });
134    merged
135}
136
137/// Scheduling constraint type for CPM/PDM planning.
138#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
139#[serde(rename_all = "snake_case")]
140pub enum TaskConstraint {
141    /// As Soon As Possible (default).
142    #[default]
143    Asap,
144    /// As Late As Possible.
145    Alap,
146    /// Start No Earlier Than.
147    Snet,
148    /// Start No Later Than.
149    Snlt,
150    /// Finish No Earlier Than.
151    Fnet,
152    /// Finish No Later Than.
153    Fnlt,
154    /// Must Start On.
155    Mso,
156    /// Must Finish On.
157    Mfo,
158}
159
160impl TaskConstraint {
161    /// True when the constraint requires a companion `constraint_date_unix` timestamp.
162    pub const fn requires_anchor_date(&self) -> bool {
163        matches!(
164            self,
165            Self::Snet | Self::Snlt | Self::Fnet | Self::Fnlt | Self::Mso | Self::Mfo
166        )
167    }
168}
169
170/// Three-point PERT duration/effort estimate in integer minutes.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
172pub struct ThreePointEstimate {
173    pub optimistic_m: u32,
174    pub most_likely_m: u32,
175    pub pessimistic_m: u32,
176}
177
178impl ThreePointEstimate {
179    /// Construct a new three-point estimate.
180    pub const fn new(optimistic_m: u32, most_likely_m: u32, pessimistic_m: u32) -> Self {
181        Self {
182            optimistic_m,
183            most_likely_m,
184            pessimistic_m,
185        }
186    }
187
188    /// True if `optimistic_m <= most_likely_m <= pessimistic_m`.
189    pub const fn is_valid(&self) -> bool {
190        self.optimistic_m <= self.most_likely_m && self.most_likely_m <= self.pessimistic_m
191    }
192
193    /// Expected PERT duration `(O + 4M + P) / 6` in integer minutes.
194    pub const fn pert_expected_minutes(&self) -> u32 {
195        let weighted = (self.optimistic_m as u64)
196            + 4 * (self.most_likely_m as u64)
197            + (self.pessimistic_m as u64);
198        ((weighted + 3) / 6) as u32
199    }
200
201    /// Standard deviation `(P - O) / 6` in integer minutes.
202    pub const fn pert_std_dev_minutes(&self) -> u32 {
203        if self.pessimistic_m <= self.optimistic_m {
204            0
205        } else {
206            (self.pessimistic_m - self.optimistic_m) / 6
207        }
208    }
209}
210
211/// Logged time/expense against a work item. Produces a Stage 2 `ActivityAndResources` record
212/// (and NEVER directly mints a payable `LifecycleObligation` without the 9-stage lifecycle).
213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
214pub struct TimeEntry {
215    pub id: String,
216    pub project_id: String,
217    pub work_item_id: String,
218    pub contributor_did: String,
219    #[serde(default, skip_serializing_if = "Option::is_none")]
220    pub agreement_id: Option<String>,
221    pub minutes: u32,
222    pub reimbursable_expense_cents: i64,
223    pub note: String,
224    pub logged_at_unix: u32,
225}
226
227impl TimeEntry {
228    /// Convert this `TimeEntry` into a Stage 2 `ActivityAndResources` record.
229    pub fn to_activity_record(&self) -> ActivityAndResources {
230        ActivityAndResources {
231            id: format!("act:{}", self.id),
232            project_id: self.project_id.clone(),
233            contributor_did: self.contributor_did.clone(),
234            agreement_id: self.agreement_id.clone(),
235            work_item_id: Some(self.work_item_id.clone()),
236            effort_minutes: self.minutes,
237            reimbursable_expense_cents: self.reimbursable_expense_cents,
238            capital_advanced_cents: 0,
239            occurred_at_unix: self.logged_at_unix,
240            occurred_at_instant: Some(InstantBridge::from_coarse(self.logged_at_unix)),
241        }
242    }
243}
244
245/// Post-merge semantic conflicts detected across a project's WBS/PDM graph.
246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247#[serde(tag = "kind", rename_all = "snake_case")]
248pub enum SemanticConflict {
249    DependencyCycle {
250        cycle_task_ids: Vec<String>,
251    },
252    ConstraintViolation {
253        work_item_id: String,
254        constraint: TaskConstraint,
255        reason: String,
256    },
257    Overallocation {
258        assignee_did: String,
259        total_assigned_minutes: u32,
260        capacity_minutes: u32,
261    },
262}
263
264/// Detect post-merge semantic conflicts (`DependencyCycle`, `ConstraintViolation`, `Overallocation`)
265/// across a set of work items and dependencies.
266pub fn detect_semantic_conflicts(
267    items: &[WorkItem],
268    dependencies: &[WorkDependency],
269    capacity_minutes_per_assignee: u32,
270) -> Vec<SemanticConflict> {
271    let mut conflicts = Vec::new();
272
273    // 1. Cycle detection over local dependencies using Kahn's topological in-degree elimination.
274    let mut adj: HashMap<&str, Vec<&str>> = HashMap::new();
275    let mut in_deg: HashMap<&str, usize> = HashMap::new();
276    let mut nodes: HashSet<&str> = HashSet::new();
277    for dep in dependencies {
278        if let (TaskRef::Local(u), TaskRef::Local(v)) = (&dep.predecessor, &dep.successor) {
279            nodes.insert(u.as_str());
280            nodes.insert(v.as_str());
281            adj.entry(u.as_str()).or_default().push(v.as_str());
282            *in_deg.entry(v.as_str()).or_insert(0) += 1;
283            in_deg.entry(u.as_str()).or_insert(0);
284        }
285    }
286    let mut queue: Vec<&str> = in_deg
287        .iter()
288        .filter_map(|(&node, &deg)| if deg == 0 { Some(node) } else { None })
289        .collect();
290    let mut visited = 0usize;
291    while let Some(u) = queue.pop() {
292        visited += 1;
293        if let Some(neighbors) = adj.get(u) {
294            for &v in neighbors {
295                if let Some(d) = in_deg.get_mut(v) {
296                    *d -= 1;
297                    if *d == 0 {
298                        queue.push(v);
299                    }
300                }
301            }
302        }
303    }
304    if visited < nodes.len() {
305        let mut cycle_nodes: Vec<String> = in_deg
306            .into_iter()
307            .filter_map(|(k, deg)| if deg > 0 { Some(k.to_string()) } else { None })
308            .collect();
309        cycle_nodes.sort();
310        conflicts.push(SemanticConflict::DependencyCycle {
311            cycle_task_ids: cycle_nodes,
312        });
313    }
314
315    // 2. ConstraintViolation detection (missing anchor date on date-anchored constraint, or invalid PERT).
316    for item in items {
317        if item.constraint.requires_anchor_date() && item.constraint_date_unix.is_none() {
318            conflicts.push(SemanticConflict::ConstraintViolation {
319                work_item_id: item.id.clone(),
320                constraint: item.constraint,
321                reason: "date-anchored constraint is missing constraint_date_unix".to_string(),
322            });
323        } else if let Some(anchor) = item.constraint_date_unix {
324            if matches!(item.constraint, TaskConstraint::Snlt | TaskConstraint::Fnlt | TaskConstraint::Mfo)
325                && anchor < item.created_at_unix
326            {
327                conflicts.push(SemanticConflict::ConstraintViolation {
328                    work_item_id: item.id.clone(),
329                    constraint: item.constraint,
330                    reason: format!(
331                        "constraint anchor ({anchor}) precedes item creation ({})",
332                        item.created_at_unix
333                    ),
334                });
335            }
336        }
337        if let Some(est) = item.three_point_estimate {
338            if !est.is_valid() {
339                conflicts.push(SemanticConflict::ConstraintViolation {
340                    work_item_id: item.id.clone(),
341                    constraint: item.constraint,
342                    reason: "three-point estimate violates optimistic <= most_likely <= pessimistic"
343                        .to_string(),
344                });
345            }
346        }
347    }
348
349    // 3. Overallocation detection per assignee_did.
350    if capacity_minutes_per_assignee > 0 {
351        let mut by_assignee: HashMap<&str, u32> = HashMap::new();
352        for item in items {
353            if let Some(did) = item.assignee_did.as_deref() {
354                let mins = item
355                    .estimate_minutes
356                    .or_else(|| item.three_point_estimate.map(|e| e.pert_expected_minutes()))
357                    .unwrap_or(0);
358                *by_assignee.entry(did).or_insert(0) =
359                    by_assignee.get(did).copied().unwrap_or(0).saturating_add(mins);
360            }
361        }
362        let mut assignees: Vec<(&str, u32)> = by_assignee.into_iter().collect();
363        assignees.sort_by(|a, b| a.0.cmp(b.0));
364        for (did, total_m) in assignees {
365            if total_m > capacity_minutes_per_assignee {
366                conflicts.push(SemanticConflict::Overallocation {
367                    assignee_did: did.to_string(),
368                    total_assigned_minutes: total_m,
369                    capacity_minutes: capacity_minutes_per_assignee,
370                });
371            }
372        }
373    }
374
375    conflicts
376}