1use crate::backends::ExternalTask;
4use crate::engine::tasks::Task;
5use crate::store;
6use std::collections::HashMap;
7use std::fmt::Write as _;
8
9#[derive(Debug, Clone)]
11pub struct TreeNode {
12 pub id: String,
13 pub title: String,
14 pub status: String,
15 pub agent: Option<String>,
16 pub children: Vec<TreeNode>,
17}
18
19fn label_value(labels: &[String], prefix: &str) -> Option<String> {
20 labels
21 .iter()
22 .find_map(|label| label.strip_prefix(prefix).map(str::to_string))
23}
24
25impl TreeNode {
26 pub fn from_external(task: &ExternalTask) -> Self {
28 let status = label_value(&task.labels, "status:").unwrap_or_else(|| "unknown".to_string());
29 let agent = label_value(&task.labels, "agent:");
30
31 Self {
32 id: task.id.0.clone(),
33 title: task.title.clone(),
34 status,
35 agent,
36 children: Vec::new(),
37 }
38 }
39
40 pub fn from_internal(task: &store::Task) -> Self {
42 Self {
43 id: task
44 .external_id
45 .clone()
46 .unwrap_or_else(|| task.id.to_string()),
47 title: task.title.clone(),
48 status: task.status.as_str().to_string(),
49 agent: task.agent.clone(),
50 children: Vec::new(),
51 }
52 }
53}
54
55fn sort_by_numeric_id(nodes: &mut [TreeNode]) {
57 nodes.sort_by_key(|n| n.id.parse::<i64>().unwrap_or(0));
58}
59
60pub fn build_forest(tasks: &[Task]) -> Vec<TreeNode> {
66 fn build_node(
67 id: &str,
68 nodes: &HashMap<String, TreeNode>,
69 children_map: &HashMap<String, Vec<String>>,
70 ) -> Option<TreeNode> {
71 let mut node = nodes.get(id)?.clone();
72
73 if let Some(children_ids) = children_map.get(id) {
74 for child_id in children_ids {
75 if let Some(child_node) = build_node(child_id, nodes, children_map) {
76 node.children.push(child_node);
77 }
78 }
79 }
80
81 sort_by_numeric_id(&mut node.children);
83
84 Some(node)
85 }
86
87 let mut nodes: HashMap<String, TreeNode> = HashMap::new();
88 let mut parent_map: HashMap<String, Option<String>> = HashMap::new();
89
90 for task in tasks {
92 let (id, parent_id, node) = match task {
93 Task::External(ext) => {
94 let parent = label_value(&ext.labels, "parent:");
95 let node = TreeNode::from_external(ext);
96 (ext.id.0.clone(), parent, node)
97 }
98 Task::Internal(int) => {
99 let node = TreeNode::from_internal(int);
101 let id = int
102 .external_id
103 .clone()
104 .unwrap_or_else(|| int.id.to_string());
105 (id, None, node)
106 }
107 };
108
109 parent_map.insert(id.clone(), parent_id);
110 nodes.insert(id, node);
111 }
112
113 let mut root_ids: Vec<String> = Vec::new();
115 let mut children_map: HashMap<String, Vec<String>> = HashMap::new();
116
117 for (id, parent_opt) in &parent_map {
118 match parent_opt {
119 Some(parent_id) => {
120 if nodes.contains_key(parent_id) {
122 children_map
123 .entry(parent_id.clone())
124 .or_default()
125 .push(id.clone());
126 } else {
127 root_ids.push(id.clone());
129 }
130 }
131 None => {
132 root_ids.push(id.clone());
134 }
135 }
136 }
137
138 let mut roots: Vec<TreeNode> = Vec::new();
140 for root_id in root_ids {
141 if let Some(tree) = build_node(&root_id, &nodes, &children_map) {
142 roots.push(tree);
143 }
144 }
145
146 sort_by_numeric_id(&mut roots);
148
149 roots
150}
151
152pub fn render_tree(root: &TreeNode) -> String {
154 let mut output = String::new();
155 render_node(root, &mut output, "", true, true);
156 output
157}
158
159fn render_node(node: &TreeNode, output: &mut String, prefix: &str, is_last: bool, is_root: bool) {
161 let agent = node
162 .agent
163 .as_ref()
164 .map(|a| format!("({a}) "))
165 .unwrap_or_default();
166 let label = format!("#{} [{}] {}{}", node.id, node.status, agent, node.title);
167 if is_root {
168 let _ = writeln!(output, "{label}");
170 } else {
171 let branch = if is_last { "└── " } else { "├── " };
173 let _ = writeln!(output, "{prefix}{branch}{label}");
174 }
175
176 let child_prefix = if is_root {
178 prefix.to_string()
179 } else if is_last {
180 format!("{prefix} ")
181 } else {
182 format!("{prefix}│ ")
183 };
184
185 let child_count = node.children.len();
186 for (i, child) in node.children.iter().enumerate() {
187 let child_is_last = i == child_count - 1;
188 render_node(child, output, &child_prefix, child_is_last, false);
189 }
190}
191
192pub fn render_forest(roots: &[TreeNode]) -> String {
194 if roots.is_empty() {
195 return "No tasks found.".to_string();
196 }
197
198 let mut output = String::new();
199 for (i, root) in roots.iter().enumerate() {
200 output.push_str(&render_tree(root));
201
202 if i < roots.len() - 1 {
204 output.push('\n');
205 }
206 }
207
208 output
209}
210
211pub fn render_single_tree(root: &TreeNode, show_no_children_msg: bool) -> String {
213 let mut output = render_tree(root);
214
215 if root.children.is_empty() && show_no_children_msg {
216 output.push_str(" (no children)\n");
217 }
218
219 output
220}
221
222#[cfg(test)]
223mod tests {
224 use super::*;
225 use crate::backends::{ExternalId, ExternalTask};
226
227 fn create_test_task(id: &str, title: &str, _state: &str, labels: &[&str]) -> Task {
228 Task::External(ExternalTask {
229 id: ExternalId(id.to_string()),
230 title: title.to_string(),
231 body: String::new(),
232 state: "open".to_string(),
233 labels: labels.iter().map(ToString::to_string).collect(),
234 author: "test".to_string(),
235 created_at: "2026-01-01T00:00:00Z".to_string(),
236 updated_at: "2026-01-01T00:00:00Z".to_string(),
237 url: format!("https://github.com/test/test/issues/{id}"),
238 })
239 }
240
241 #[test]
242 fn test_build_forest_empty() {
243 let forest = build_forest(&[]);
244 assert!(forest.is_empty());
245 }
246
247 #[test]
248 fn test_build_forest_single_root() {
249 let tasks = vec![create_test_task(
250 "30",
251 "Implement auth",
252 "open",
253 &["status:blocked", "agent:claude"],
254 )];
255
256 let forest = build_forest(&tasks);
257 assert_eq!(forest.len(), 1);
258 assert_eq!(forest[0].id, "30");
259 assert_eq!(forest[0].status, "blocked");
260 assert_eq!(forest[0].agent, Some("claude".to_string()));
261 assert!(forest[0].children.is_empty());
262 }
263
264 #[test]
265 fn test_build_forest_with_children() {
266 let tasks = vec![
267 create_test_task(
268 "30",
269 "Implement auth",
270 "open",
271 &["status:blocked", "agent:claude"],
272 ),
273 create_test_task(
274 "31",
275 "Add user model",
276 "open",
277 &["status:done", "parent:30"],
278 ),
279 create_test_task(
280 "32",
281 "Add login API",
282 "open",
283 &["status:in_progress", "parent:30"],
284 ),
285 ];
286
287 let forest = build_forest(&tasks);
288 assert_eq!(forest.len(), 1);
289 assert_eq!(forest[0].id, "30");
290 assert_eq!(forest[0].children.len(), 2);
291
292 assert_eq!(forest[0].children[0].id, "31");
294 assert_eq!(forest[0].children[1].id, "32");
295 }
296
297 #[test]
298 fn test_build_forest_multiple_roots() {
299 let tasks = vec![
300 create_test_task("35", "Refactor DB", "open", &["status:in_progress"]),
301 create_test_task("30", "Implement auth", "open", &["status:blocked"]),
302 ];
303
304 let forest = build_forest(&tasks);
305 assert_eq!(forest.len(), 2);
306 assert_eq!(forest[0].id, "30");
308 assert_eq!(forest[1].id, "35");
309 }
310
311 #[test]
312 fn test_render_tree() {
313 let root = TreeNode {
314 id: "30".to_string(),
315 title: "Implement auth system".to_string(),
316 status: "blocked".to_string(),
317 agent: Some("claude".to_string()),
318 children: vec![
319 TreeNode {
320 id: "31".to_string(),
321 title: "Add user model".to_string(),
322 status: "done".to_string(),
323 agent: None,
324 children: vec![],
325 },
326 TreeNode {
327 id: "32".to_string(),
328 title: "Add login API".to_string(),
329 status: "in_progress".to_string(),
330 agent: Some("codex".to_string()),
331 children: vec![],
332 },
333 ],
334 };
335
336 let output = render_tree(&root);
337 assert!(output.contains("#30 [blocked] (claude) Implement auth system"));
338 assert!(output.contains("├── #31 [done] Add user model"));
339 assert!(output.contains("└── #32 [in_progress] (codex) Add login API"));
340 }
341
342 #[test]
343 fn test_render_forest() {
344 let roots = vec![TreeNode {
345 id: "35".to_string(),
346 title: "Refactor database".to_string(),
347 status: "in_progress".to_string(),
348 agent: None,
349 children: vec![],
350 }];
351
352 let output = render_forest(&roots);
353 assert!(output.contains("#35 [in_progress] Refactor database"));
354 }
355
356 #[test]
357 fn test_orphaned_child_becomes_root() {
358 let tasks = vec![create_test_task(
360 "31",
361 "Orphan task",
362 "open",
363 &["status:new", "parent:99"],
364 )];
365
366 let forest = build_forest(&tasks);
367 assert_eq!(forest.len(), 1);
368 assert_eq!(forest[0].id, "31");
369 assert!(forest[0].children.is_empty());
370 }
371
372 fn node(id: &str, status: &str, agent: Option<&str>, children: Vec<TreeNode>) -> TreeNode {
373 TreeNode {
374 id: id.to_string(),
375 title: format!("T{id}"),
376 status: status.to_string(),
377 agent: agent.map(ToString::to_string),
378 children,
379 }
380 }
381
382 #[test]
383 fn render_tree_exact_output_for_nested_tree() {
384 let root = node(
385 "1",
386 "blocked",
387 Some("claude"),
388 vec![
389 node(
390 "2",
391 "done",
392 None,
393 vec![
394 node("4", "done", Some("codex"), vec![]),
395 node("5", "new", None, vec![]),
396 ],
397 ),
398 node("3", "new", None, vec![node("6", "new", None, vec![])]),
399 ],
400 );
401
402 let expected = [
403 "#1 [blocked] (claude) T1",
404 "├── #2 [done] T2",
405 "│ ├── #4 [done] (codex) T4",
406 "│ └── #5 [new] T5",
407 "└── #3 [new] T3",
408 " └── #6 [new] T6",
409 "",
410 ]
411 .join("\n");
412 assert_eq!(render_tree(&root), expected);
413 }
414
415 #[test]
416 fn render_forest_separates_trees_with_one_blank_line() {
417 let roots = vec![
418 node("1", "new", None, vec![]),
419 node("2", "done", None, vec![]),
420 ];
421 assert_eq!(render_forest(&roots), "#1 [new] T1\n\n#2 [done] T2\n");
422 }
423
424 #[test]
425 fn render_forest_empty_says_no_tasks() {
426 assert_eq!(render_forest(&[]), "No tasks found.");
427 }
428
429 #[test]
430 fn render_single_tree_notes_missing_children_only_when_asked() {
431 let leaf = node("1", "new", None, vec![]);
432 assert_eq!(
433 render_single_tree(&leaf, true),
434 "#1 [new] T1\n (no children)\n"
435 );
436 assert_eq!(render_single_tree(&leaf, false), "#1 [new] T1\n");
437
438 let parent = node("1", "new", None, vec![node("2", "new", None, vec![])]);
439 assert_eq!(
440 render_single_tree(&parent, true),
441 "#1 [new] T1\n└── #2 [new] T2\n"
442 );
443 }
444
445 #[test]
446 fn build_forest_sorts_numerically_and_non_numeric_ids_sort_first() {
447 let tasks = vec![
448 create_test_task("10", "ten", "open", &["status:new"]),
449 create_test_task("9", "nine", "open", &["status:new"]),
450 create_test_task("abc", "word", "open", &["status:new"]),
451 create_test_task("2", "child b", "open", &["parent:10"]),
452 create_test_task("11", "child a", "open", &["parent:10"]),
453 ];
454
455 let forest = build_forest(&tasks);
456 let root_ids: Vec<&str> = forest.iter().map(|n| n.id.as_str()).collect();
457 assert_eq!(root_ids, ["abc", "9", "10"]);
458 let child_ids: Vec<&str> = forest[2].children.iter().map(|n| n.id.as_str()).collect();
459 assert_eq!(child_ids, ["2", "11"]);
460 }
461
462 #[test]
463 fn from_external_without_labels_has_unknown_status_and_no_agent() {
464 let Task::External(ext) = create_test_task("7", "x", "open", &[]) else {
465 unreachable!()
466 };
467 let node = TreeNode::from_external(&ext);
468 assert_eq!(node.status, "unknown");
469 assert_eq!(node.agent, None);
470 }
471
472 #[test]
473 fn from_external_uses_the_first_status_and_agent_label() {
474 let Task::External(ext) = create_test_task(
475 "8",
476 "x",
477 "open",
478 &[
479 "status:new",
480 "status:done",
481 "agent:claude",
482 "agent:codex",
483 "parent:1",
484 ],
485 ) else {
486 unreachable!()
487 };
488 let node = TreeNode::from_external(&ext);
489 assert_eq!(node.status, "new");
490 assert_eq!(node.agent.as_deref(), Some("claude"));
491 }
492
493 #[test]
494 fn from_external_strips_the_label_prefix() {
495 let Task::External(ext) =
496 create_test_task("8", "x", "open", &["status:in_progress", "agent:claude"])
497 else {
498 unreachable!()
499 };
500 let node = TreeNode::from_external(&ext);
501 assert_eq!(node.status, "in_progress");
502 assert_eq!(node.agent.as_deref(), Some("claude"));
503 }
504
505 #[test]
506 fn build_forest_reads_the_parent_id_from_the_parent_label() {
507 let tasks = vec![
508 create_test_task("10", "root", "open", &["status:new"]),
509 create_test_task("11", "child", "open", &["parent:10", "status:done"]),
510 ];
511 let forest = build_forest(&tasks);
512 assert_eq!(forest.len(), 1);
513 assert_eq!(forest[0].id, "10");
514 assert_eq!(forest[0].children.len(), 1);
515 assert_eq!(forest[0].children[0].id, "11");
516 assert_eq!(forest[0].children[0].status, "done");
517 }
518}