score.rs

  1//! Scoring engine for the `next` command.
  2//!
  3//! Scores ready tasks (open, no open blockers) using priority, effort,
  4//! and the transitive downstream impact through the blocker graph.
  5
  6use std::collections::{HashMap, HashSet, VecDeque};
  7
  8/// Scoring mode for ranking tasks.
  9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 10pub enum Mode {
 11    /// Critical path: downstream impact dominates.
 12    ///
 13    /// `score = (downstream + 1.0) × priority_weight / effort_weight`
 14    Impact,
 15
 16    /// Effort-weighted: effort dominates, downstream is dampened.
 17    ///
 18    /// `score = (downstream × 0.25 + 1.0) × priority_weight / effort_weight²`
 19    Effort,
 20}
 21
 22/// A lightweight snapshot of a task for scoring purposes.
 23#[derive(Debug, Clone)]
 24pub struct TaskNode {
 25    pub id: String,
 26    pub priority: i32,
 27    pub effort: i32,
 28}
 29
 30/// Scored result for a single task.
 31#[derive(Debug, Clone)]
 32pub struct ScoredTask {
 33    pub id: String,
 34    pub title: String,
 35    pub priority: i32,
 36    pub effort: i32,
 37    pub score: f64,
 38    pub downstream_score: f64,
 39    pub priority_weight: f64,
 40    pub effort_weight: f64,
 41    /// Total number of open tasks transitively blocked by this one.
 42    pub total_unblocked: usize,
 43    /// Number of tasks directly blocked by this one.
 44    pub direct_unblocked: usize,
 45}
 46
 47/// Convert DB priority (1=high, 2=medium, 3=low) to a scoring weight
 48/// where higher priority = higher weight.
 49fn priority_weight(p: i32) -> f64 {
 50    match p {
 51        1 => 3.0,
 52        2 => 2.0,
 53        3 => 1.0,
 54        _ => 2.0,
 55    }
 56}
 57
 58/// Convert DB effort (1=low, 2=medium, 3=high) to a scoring weight.
 59fn effort_weight(e: i32) -> f64 {
 60    match e {
 61        1 => 1.0,
 62        2 => 2.0,
 63        3 => 3.0,
 64        _ => 2.0,
 65    }
 66}
 67
 68/// Compute the transitive downstream score and count for a given task.
 69///
 70/// Walks the `blocks` adjacency list (task → set of tasks it blocks)
 71/// starting from `start`, summing priority weights of all reachable nodes.
 72/// Uses a visited set to handle any residual cycles defensively.
 73fn downstream(
 74    start: &str,
 75    blocks: &HashMap<String, HashSet<String>>,
 76    nodes: &HashMap<String, TaskNode>,
 77) -> (f64, usize, usize) {
 78    let mut score = 0.0;
 79    let mut total = 0usize;
 80    let mut direct = 0usize;
 81
 82    let mut visited = HashSet::new();
 83    let mut queue = VecDeque::new();
 84    visited.insert(start.to_string());
 85
 86    if let Some(dependents) = blocks.get(start) {
 87        for dep in dependents {
 88            if visited.insert(dep.clone()) {
 89                queue.push_back(dep.clone());
 90                direct += 1;
 91            }
 92        }
 93    }
 94
 95    while let Some(current) = queue.pop_front() {
 96        total += 1;
 97        if let Some(node) = nodes.get(&current) {
 98            score += priority_weight(node.priority);
 99        }
100        if let Some(dependents) = blocks.get(&current) {
101            for dep in dependents {
102                if visited.insert(dep.clone()) {
103                    queue.push_back(dep.clone());
104                }
105            }
106        }
107    }
108
109    (score, total, direct)
110}
111
112/// Score and rank ready tasks.
113///
114/// # Arguments
115/// * `open_tasks` — all open tasks (id, title, priority, effort)
116/// * `blocker_edges` — `(task_id, blocker_id)` pairs among open tasks
117/// * `exclude` — task IDs to exclude from candidates (still counted in
118///   downstream scores). Used to filter parent tasks that have open subtasks.
119/// * `mode` — scoring strategy
120/// * `limit` — maximum number of results to return
121pub fn rank(
122    open_tasks: &[(String, String, i32, i32)],
123    blocker_edges: &[(String, String)],
124    exclude: &HashSet<String>,
125    mode: Mode,
126    limit: usize,
127) -> Vec<ScoredTask> {
128    // Build node map.
129    let mut nodes: HashMap<String, TaskNode> = HashMap::new();
130    let mut titles: HashMap<String, String> = HashMap::new();
131    for (id, title, priority, effort) in open_tasks {
132        nodes.insert(
133            id.clone(),
134            TaskNode {
135                id: id.clone(),
136                priority: *priority,
137                effort: *effort,
138            },
139        );
140        titles.insert(id.clone(), title.clone());
141    }
142
143    // Build adjacency lists.
144    // blocked_by: task_id → set of blocker_ids (who blocks this task)
145    // blocks: blocker_id → set of task_ids (who this task blocks)
146    let mut blocked_by: HashMap<String, HashSet<String>> = HashMap::new();
147    let mut blocks: HashMap<String, HashSet<String>> = HashMap::new();
148
149    for (task_id, blocker_id) in blocker_edges {
150        // Only include edges where both ends are open tasks.
151        if nodes.contains_key(task_id) && nodes.contains_key(blocker_id) {
152            blocked_by
153                .entry(task_id.clone())
154                .or_default()
155                .insert(blocker_id.clone());
156            blocks
157                .entry(blocker_id.clone())
158                .or_default()
159                .insert(task_id.clone());
160        }
161    }
162
163    // Find ready tasks: open tasks with no open blockers, excluding
164    // parent tasks that still have open subtasks.
165    let ready: Vec<&TaskNode> = nodes
166        .values()
167        .filter(|n| !blocked_by.contains_key(&n.id) && !exclude.contains(&n.id))
168        .collect();
169
170    // Score each ready task.
171    let mut scored: Vec<ScoredTask> = ready
172        .iter()
173        .map(|node| {
174            let (ds, total_unblocked, direct_unblocked) = downstream(&node.id, &blocks, &nodes);
175            let pw = priority_weight(node.priority);
176            let ew = effort_weight(node.effort);
177
178            let score = match mode {
179                Mode::Impact => (ds + 1.0) * pw / ew,
180                Mode::Effort => (ds * 0.25 + 1.0) * pw / (ew * ew),
181            };
182
183            ScoredTask {
184                id: node.id.clone(),
185                title: titles.get(&node.id).cloned().unwrap_or_default(),
186                priority: node.priority,
187                effort: node.effort,
188                score,
189                downstream_score: ds,
190                priority_weight: pw,
191                effort_weight: ew,
192                total_unblocked,
193                direct_unblocked,
194            }
195        })
196        .collect();
197
198    // Sort descending by score, then by id for stability.
199    scored.sort_by(|a, b| {
200        b.score
201            .partial_cmp(&a.score)
202            .unwrap_or(std::cmp::Ordering::Equal)
203            .then_with(|| a.id.cmp(&b.id))
204    });
205
206    scored.truncate(limit);
207    scored
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    fn task(id: &str, title: &str, pri: i32, eff: i32) -> (String, String, i32, i32) {
215        (id.to_string(), title.to_string(), pri, eff)
216    }
217
218    fn edge(task_id: &str, blocker_id: &str) -> (String, String) {
219        (task_id.to_string(), blocker_id.to_string())
220    }
221
222    #[test]
223    fn single_task_no_deps() {
224        let tasks = vec![task("a", "Alpha", 1, 1)];
225        let result = rank(&tasks, &[], &HashSet::new(), Mode::Impact, 5);
226
227        assert_eq!(result.len(), 1);
228        assert_eq!(result[0].id, "a");
229        // (0 + 1.0) * 3.0 / 1.0 = 3.0
230        assert!((result[0].score - 3.0).abs() < f64::EPSILON);
231        assert_eq!(result[0].total_unblocked, 0);
232        assert_eq!(result[0].direct_unblocked, 0);
233    }
234
235    #[test]
236    fn blocker_scores_higher_than_leaf() {
237        // A blocks B. Both are ready-eligible but only A has no blockers.
238        // A is ready (blocks B), B is blocked.
239        let tasks = vec![task("a", "Blocker", 2, 2), task("b", "Blocked", 1, 1)];
240        let edges = vec![edge("b", "a")];
241        let result = rank(&tasks, &edges, &HashSet::new(), Mode::Impact, 5);
242
243        // Only A is ready.
244        assert_eq!(result.len(), 1);
245        assert_eq!(result[0].id, "a");
246        // downstream of A = priority_weight(B) = 3.0
247        // score = (3.0 + 1.0) * 2.0 / 2.0 = 4.0
248        assert!((result[0].score - 4.0).abs() < f64::EPSILON);
249        assert_eq!(result[0].total_unblocked, 1);
250        assert_eq!(result[0].direct_unblocked, 1);
251    }
252
253    #[test]
254    fn transitive_downstream_counted() {
255        // A blocks B, B blocks C. Only A is ready.
256        let tasks = vec![
257            task("a", "Root", 2, 2),
258            task("b", "Mid", 2, 2),
259            task("c", "Leaf", 1, 1),
260        ];
261        let edges = vec![edge("b", "a"), edge("c", "b")];
262        let result = rank(&tasks, &edges, &HashSet::new(), Mode::Impact, 5);
263
264        assert_eq!(result.len(), 1);
265        assert_eq!(result[0].id, "a");
266        // downstream = pw(b) + pw(c) = 2.0 + 3.0 = 5.0
267        // score = (5.0 + 1.0) * 2.0 / 2.0 = 6.0
268        assert!((result[0].score - 6.0).abs() < f64::EPSILON);
269        assert_eq!(result[0].total_unblocked, 2);
270        assert_eq!(result[0].direct_unblocked, 1);
271    }
272
273    #[test]
274    fn diamond_graph_no_double_counting() {
275        // A and B both block C. A and B are ready.
276        let tasks = vec![
277            task("a", "Left", 1, 1),
278            task("b", "Right", 2, 2),
279            task("c", "Sink", 1, 1),
280        ];
281        let edges = vec![edge("c", "a"), edge("c", "b")];
282        let result = rank(&tasks, &edges, &HashSet::new(), Mode::Impact, 5);
283
284        assert_eq!(result.len(), 2);
285        // Both A and B see C as downstream.
286        // A: downstream = pw(c) = 3.0, score = (3+1)*3/1 = 12.0
287        // B: downstream = pw(c) = 3.0, score = (3+1)*2/2 = 4.0
288        assert_eq!(result[0].id, "a");
289        assert!((result[0].score - 12.0).abs() < f64::EPSILON);
290        assert_eq!(result[1].id, "b");
291        assert!((result[1].score - 4.0).abs() < f64::EPSILON);
292    }
293
294    #[test]
295    fn effort_mode_dampens_downstream() {
296        // A blocks B. A is ready.
297        let tasks = vec![
298            task("a", "Blocker", 1, 3), // high pri, high effort
299            task("b", "Blocked", 1, 1),
300        ];
301        let edges = vec![edge("b", "a")];
302
303        let impact = rank(&tasks, &edges, &HashSet::new(), Mode::Impact, 5);
304        let effort = rank(&tasks, &edges, &HashSet::new(), Mode::Effort, 5);
305
306        // Impact: (3.0 + 1.0) * 3.0 / 3.0 = 4.0
307        assert!((impact[0].score - 4.0).abs() < f64::EPSILON);
308        // Effort: (3.0 * 0.25 + 1.0) * 3.0 / 9.0 = 1.75 * 3.0 / 9.0 ≈ 0.583
309        assert!((effort[0].score - (1.75 * 3.0 / 9.0)).abs() < f64::EPSILON);
310    }
311
312    #[test]
313    fn effort_mode_prefers_low_effort() {
314        // Two standalone tasks: A is high-effort, B is low-effort. Same priority.
315        let tasks = vec![task("a", "Heavy", 2, 3), task("b", "Light", 2, 1)];
316        let result = rank(&tasks, &[], &HashSet::new(), Mode::Effort, 5);
317
318        assert_eq!(result.len(), 2);
319        // B should rank higher (low effort).
320        assert_eq!(result[0].id, "b");
321        assert_eq!(result[1].id, "a");
322    }
323
324    #[test]
325    fn limit_truncates() {
326        let tasks = vec![
327            task("a", "A", 1, 1),
328            task("b", "B", 2, 2),
329            task("c", "C", 3, 3),
330        ];
331        let result = rank(&tasks, &[], &HashSet::new(), Mode::Impact, 2);
332        assert_eq!(result.len(), 2);
333    }
334
335    #[test]
336    fn empty_input() {
337        let result = rank(&[], &[], &HashSet::new(), Mode::Impact, 5);
338        assert!(result.is_empty());
339    }
340
341    #[test]
342    fn stable_sort_by_id() {
343        // Two tasks with identical scores should sort by id.
344        let tasks = vec![task("b", "Second", 2, 2), task("a", "First", 2, 2)];
345        let result = rank(&tasks, &[], &HashSet::new(), Mode::Impact, 5);
346        assert_eq!(result[0].id, "a");
347        assert_eq!(result[1].id, "b");
348    }
349
350    #[test]
351    fn excluded_tasks_not_candidates() {
352        // A and B are both standalone ready tasks, but A is excluded
353        // (simulating a parent with open subtasks).
354        let tasks = vec![task("a", "Parent", 1, 1), task("b", "Leaf", 2, 2)];
355        let exclude: HashSet<String> = ["a".to_string()].into();
356        let result = rank(&tasks, &[], &exclude, Mode::Impact, 5);
357
358        assert_eq!(result.len(), 1);
359        assert_eq!(result[0].id, "b");
360    }
361
362    #[test]
363    fn excluded_task_still_counted_in_downstream() {
364        // A blocks B (the excluded parent). B blocks C.
365        // A is ready. B is excluded but its downstream weight should still
366        // flow through the graph — A should see both B and C downstream.
367        let tasks = vec![
368            task("a", "Root", 2, 2),
369            task("b", "Parent", 1, 1),
370            task("c", "Leaf", 2, 2),
371        ];
372        let edges = vec![edge("b", "a"), edge("c", "b")];
373        let exclude: HashSet<String> = ["b".to_string()].into();
374        let result = rank(&tasks, &edges, &exclude, Mode::Impact, 5);
375
376        // Only A is ready (B is blocked and also excluded, C is blocked).
377        assert_eq!(result.len(), 1);
378        assert_eq!(result[0].id, "a");
379        // Downstream still includes B and C.
380        assert_eq!(result[0].total_unblocked, 2);
381    }
382
383    #[test]
384    fn parent_with_all_children_closed_remains_candidate() {
385        // A standalone task that would be in the open_tasks list but NOT
386        // in the exclude set (because all its children are closed, the
387        // caller wouldn't put it there). Verify it's still a candidate.
388        let tasks = vec![task("a", "Parent done kids", 1, 1)];
389        let result = rank(&tasks, &[], &HashSet::new(), Mode::Impact, 5);
390
391        assert_eq!(result.len(), 1);
392        assert_eq!(result[0].id, "a");
393    }
394}