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(¤t) {
98 score += priority_weight(node.priority);
99 }
100 if let Some(dependents) = blocks.get(¤t) {
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/// * `mode` — scoring strategy
118/// * `limit` — maximum number of results to return
119pub fn rank(
120 open_tasks: &[(String, String, i32, i32)],
121 blocker_edges: &[(String, String)],
122 mode: Mode,
123 limit: usize,
124) -> Vec<ScoredTask> {
125 // Build node map.
126 let mut nodes: HashMap<String, TaskNode> = HashMap::new();
127 let mut titles: HashMap<String, String> = HashMap::new();
128 for (id, title, priority, effort) in open_tasks {
129 nodes.insert(
130 id.clone(),
131 TaskNode {
132 id: id.clone(),
133 priority: *priority,
134 effort: *effort,
135 },
136 );
137 titles.insert(id.clone(), title.clone());
138 }
139
140 // Build adjacency lists.
141 // blocked_by: task_id → set of blocker_ids (who blocks this task)
142 // blocks: blocker_id → set of task_ids (who this task blocks)
143 let mut blocked_by: HashMap<String, HashSet<String>> = HashMap::new();
144 let mut blocks: HashMap<String, HashSet<String>> = HashMap::new();
145
146 for (task_id, blocker_id) in blocker_edges {
147 // Only include edges where both ends are open tasks.
148 if nodes.contains_key(task_id) && nodes.contains_key(blocker_id) {
149 blocked_by
150 .entry(task_id.clone())
151 .or_default()
152 .insert(blocker_id.clone());
153 blocks
154 .entry(blocker_id.clone())
155 .or_default()
156 .insert(task_id.clone());
157 }
158 }
159
160 // Find ready tasks: open tasks with no open blockers.
161 let ready: Vec<&TaskNode> = nodes
162 .values()
163 .filter(|n| !blocked_by.contains_key(&n.id))
164 .collect();
165
166 // Score each ready task.
167 let mut scored: Vec<ScoredTask> = ready
168 .iter()
169 .map(|node| {
170 let (ds, total_unblocked, direct_unblocked) = downstream(&node.id, &blocks, &nodes);
171 let pw = priority_weight(node.priority);
172 let ew = effort_weight(node.effort);
173
174 let score = match mode {
175 Mode::Impact => (ds + 1.0) * pw / ew,
176 Mode::Effort => (ds * 0.25 + 1.0) * pw / (ew * ew),
177 };
178
179 ScoredTask {
180 id: node.id.clone(),
181 title: titles.get(&node.id).cloned().unwrap_or_default(),
182 priority: node.priority,
183 effort: node.effort,
184 score,
185 downstream_score: ds,
186 priority_weight: pw,
187 effort_weight: ew,
188 total_unblocked,
189 direct_unblocked,
190 }
191 })
192 .collect();
193
194 // Sort descending by score, then by id for stability.
195 scored.sort_by(|a, b| {
196 b.score
197 .partial_cmp(&a.score)
198 .unwrap_or(std::cmp::Ordering::Equal)
199 .then_with(|| a.id.cmp(&b.id))
200 });
201
202 scored.truncate(limit);
203 scored
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209
210 fn task(id: &str, title: &str, pri: i32, eff: i32) -> (String, String, i32, i32) {
211 (id.to_string(), title.to_string(), pri, eff)
212 }
213
214 fn edge(task_id: &str, blocker_id: &str) -> (String, String) {
215 (task_id.to_string(), blocker_id.to_string())
216 }
217
218 #[test]
219 fn single_task_no_deps() {
220 let tasks = vec![task("a", "Alpha", 1, 1)];
221 let result = rank(&tasks, &[], Mode::Impact, 5);
222
223 assert_eq!(result.len(), 1);
224 assert_eq!(result[0].id, "a");
225 // (0 + 1.0) * 3.0 / 1.0 = 3.0
226 assert!((result[0].score - 3.0).abs() < f64::EPSILON);
227 assert_eq!(result[0].total_unblocked, 0);
228 assert_eq!(result[0].direct_unblocked, 0);
229 }
230
231 #[test]
232 fn blocker_scores_higher_than_leaf() {
233 // A blocks B. Both are ready-eligible but only A has no blockers.
234 // A is ready (blocks B), B is blocked.
235 let tasks = vec![task("a", "Blocker", 2, 2), task("b", "Blocked", 1, 1)];
236 let edges = vec![edge("b", "a")];
237 let result = rank(&tasks, &edges, Mode::Impact, 5);
238
239 // Only A is ready.
240 assert_eq!(result.len(), 1);
241 assert_eq!(result[0].id, "a");
242 // downstream of A = priority_weight(B) = 3.0
243 // score = (3.0 + 1.0) * 2.0 / 2.0 = 4.0
244 assert!((result[0].score - 4.0).abs() < f64::EPSILON);
245 assert_eq!(result[0].total_unblocked, 1);
246 assert_eq!(result[0].direct_unblocked, 1);
247 }
248
249 #[test]
250 fn transitive_downstream_counted() {
251 // A blocks B, B blocks C. Only A is ready.
252 let tasks = vec![
253 task("a", "Root", 2, 2),
254 task("b", "Mid", 2, 2),
255 task("c", "Leaf", 1, 1),
256 ];
257 let edges = vec![edge("b", "a"), edge("c", "b")];
258 let result = rank(&tasks, &edges, Mode::Impact, 5);
259
260 assert_eq!(result.len(), 1);
261 assert_eq!(result[0].id, "a");
262 // downstream = pw(b) + pw(c) = 2.0 + 3.0 = 5.0
263 // score = (5.0 + 1.0) * 2.0 / 2.0 = 6.0
264 assert!((result[0].score - 6.0).abs() < f64::EPSILON);
265 assert_eq!(result[0].total_unblocked, 2);
266 assert_eq!(result[0].direct_unblocked, 1);
267 }
268
269 #[test]
270 fn diamond_graph_no_double_counting() {
271 // A and B both block C. A and B are ready.
272 let tasks = vec![
273 task("a", "Left", 1, 1),
274 task("b", "Right", 2, 2),
275 task("c", "Sink", 1, 1),
276 ];
277 let edges = vec![edge("c", "a"), edge("c", "b")];
278 let result = rank(&tasks, &edges, Mode::Impact, 5);
279
280 assert_eq!(result.len(), 2);
281 // Both A and B see C as downstream.
282 // A: downstream = pw(c) = 3.0, score = (3+1)*3/1 = 12.0
283 // B: downstream = pw(c) = 3.0, score = (3+1)*2/2 = 4.0
284 assert_eq!(result[0].id, "a");
285 assert!((result[0].score - 12.0).abs() < f64::EPSILON);
286 assert_eq!(result[1].id, "b");
287 assert!((result[1].score - 4.0).abs() < f64::EPSILON);
288 }
289
290 #[test]
291 fn effort_mode_dampens_downstream() {
292 // A blocks B. A is ready.
293 let tasks = vec![
294 task("a", "Blocker", 1, 3), // high pri, high effort
295 task("b", "Blocked", 1, 1),
296 ];
297 let edges = vec![edge("b", "a")];
298
299 let impact = rank(&tasks, &edges, Mode::Impact, 5);
300 let effort = rank(&tasks, &edges, Mode::Effort, 5);
301
302 // Impact: (3.0 + 1.0) * 3.0 / 3.0 = 4.0
303 assert!((impact[0].score - 4.0).abs() < f64::EPSILON);
304 // Effort: (3.0 * 0.25 + 1.0) * 3.0 / 9.0 = 1.75 * 3.0 / 9.0 ≈ 0.583
305 assert!((effort[0].score - (1.75 * 3.0 / 9.0)).abs() < f64::EPSILON);
306 }
307
308 #[test]
309 fn effort_mode_prefers_low_effort() {
310 // Two standalone tasks: A is high-effort, B is low-effort. Same priority.
311 let tasks = vec![task("a", "Heavy", 2, 3), task("b", "Light", 2, 1)];
312 let result = rank(&tasks, &[], Mode::Effort, 5);
313
314 assert_eq!(result.len(), 2);
315 // B should rank higher (low effort).
316 assert_eq!(result[0].id, "b");
317 assert_eq!(result[1].id, "a");
318 }
319
320 #[test]
321 fn limit_truncates() {
322 let tasks = vec![
323 task("a", "A", 1, 1),
324 task("b", "B", 2, 2),
325 task("c", "C", 3, 3),
326 ];
327 let result = rank(&tasks, &[], Mode::Impact, 2);
328 assert_eq!(result.len(), 2);
329 }
330
331 #[test]
332 fn empty_input() {
333 let result = rank(&[], &[], Mode::Impact, 5);
334 assert!(result.is_empty());
335 }
336
337 #[test]
338 fn stable_sort_by_id() {
339 // Two tasks with identical scores should sort by id.
340 let tasks = vec![task("b", "Second", 2, 2), task("a", "First", 2, 2)];
341 let result = rank(&tasks, &[], Mode::Impact, 5);
342 assert_eq!(result[0].id, "a");
343 assert_eq!(result[1].id, "b");
344 }
345}