๐๐ผโโ๏ธ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.
Rust adeai-agentsclaudeclaude-codecodexcursorgeminigrokopencodespec-driven-developmentvibe-codingvim
feat(tui): dependency-graph visualization with batch-move (Shift+D) (#124)
Valentin Palkovice214855a8f6f
diff --git a/src/tui/app.rs b/src/tui/app.rsindex f2dcfe7..e936c3d 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -5,7 +5,8 @@ use crossterm::{terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},};use ratatui::{prelude::*, widgets::*};-use std::collections::{HashMap, HashSet};+use std::cell::Cell;+use std::collections::{HashMap, HashSet, VecDeque};use std::io::{self, Stdout};use std::path::{Path, PathBuf};use std::sync::{@@ -49,7 +50,7 @@ fn build_footer_text(" [j/k] navigate [Enter] open [l] board [e] hide sidebar [q] quit ".to_string()} else {match selected_column {- 0 => " [o] new [/] search [Enter] open [x] del [d] diff [R] research [m] plan [M] run [e] sidebar [q] quit".to_string(),+ 0 => " [o] new [/] search [Enter] open [x] del [d] diff [D] deps [R] research [m] plan [M] run [e] sidebar [q] quit".to_string(),1 => if fullscreen_on_enter {" [o] new [/] search [Enter] open [x] del [d] diff [m] run [e] sidebar [q] quit".to_string()} else {@@ -315,9 +316,31 @@ struct AppState {session_refresh_rx: Option<mpsc::Receiver<SessionRefreshResult>>,// Cache of dependency satisfaction per task ID (refreshed with tasks)deps_satisfied_cache: HashMap<String, bool>,+ // Full-screen dependency-graph overlay (Shift+D)+ dep_graph_popup: Option<DepGraphPopup>,+ // Queue of task IDs awaiting serialized worktree setup (batch-move from the+ // dependency view). Worktree setup runs one-at-a-time via `setup_rx`; this+ // queue is drained as each setup completes.+ setup_queue: VecDeque<String>,instance_id: String,}+/// State for the dependency-graph overlay.+struct DepGraphPopup {+ graph: crate::tui::dep_graph::DepGraph,+ /// Cursor index into `graph.nodes`.+ selected: usize,+ /// Task IDs marked for batch-move (only unblocked nodes are markable).+ marked: HashSet<String>,+ /// Horizontal scroll offset, in levels (columns), for wide graphs. Owned and+ /// corrected by the draw pass each frame so the selected node stays on+ /// screen; the key handler only moves `selected` and lets render re-clamp.+ scroll_levels: Cell<usize>,+ /// Number of level-columns that fit on screen, recorded by the last draw.+ /// Used only for the footer hint. Starts at 1, corrected on first render.+ visible_levels: Cell<usize>,+}+/// State for confirming move to Done#[derive(Debug, Clone)]struct DoneConfirmPopup {@@ -671,6 +694,8 @@ impl App {orchestrator_last_check: Instant::now(),session_refresh_rx: None,deps_satisfied_cache: HashMap::new(),+ dep_graph_popup: None,+ setup_queue: VecDeque::new(),instance_id: uuid::Uuid::new_v4().to_string(),},};@@ -856,6 +881,8 @@ impl App {orchestrator_last_check: Instant::now(),session_refresh_rx: None,deps_satisfied_cache: HashMap::new(),+ dep_graph_popup: None,+ setup_queue: VecDeque::new(),instance_id: uuid::Uuid::new_v4().to_string(),},})@@ -925,6 +952,8 @@ impl App {}self.refresh_tasks()?;}+ // This setup finished; start the next queued batch task (if any).+ self.try_start_next_queued_setup()?;}}@@ -2218,6 +2247,238 @@ impl App {);frame.render_widget(footer, popup_chunks[2]);}++ // Dependency-graph overlay+ if let Some(ref popup) = state.dep_graph_popup {+ Self::draw_dependency_graph(popup, frame, area, &state.config.theme);+ }+ }++ /// Render the dependency-graph overlay: topological columns of task cards,+ /// with unblocked Backlog tasks in green and marked tasks reversed.+ fn draw_dependency_graph(+ popup: &DepGraphPopup,+ frame: &mut Frame,+ area: Rect,+ theme: &ThemeConfig,+ ) {+ let popup_area = centered_rect(90, 90, area);+ frame.render_widget(Clear, popup_area);++ let chunks = Layout::default()+ .direction(Direction::Vertical)+ .constraints([+ Constraint::Length(1), // Title bar+ Constraint::Min(0), // Columns+ Constraint::Length(1), // Footer+ ])+ .split(popup_area);++ // Title bar.+ let unblocked_count = popup.graph.nodes.iter().filter(|n| n.unblocked).count();+ let title = format!(+ " Dependency Graph โ {} tasks, {} unblocked ",+ popup.graph.nodes.len(),+ unblocked_count+ );+ let title_bar = Paragraph::new(title).style(+ Style::default()+ .fg(Color::Black)+ .bg(hex_to_color(&theme.color_popup_header)),+ );+ frame.render_widget(title_bar, chunks[0]);++ let body = chunks[1];+ let level_count = popup.graph.level_count();+ if level_count == 0 {+ let empty = Paragraph::new("No tasks").block(+ Block::default().borders(Borders::ALL).border_style(+ Style::default().fg(hex_to_color(&theme.color_popup_border)),+ ),+ );+ frame.render_widget(empty, body);+ } else {+ // Fit as many columns as possible at a fixed minimum width, starting+ // from the horizontal scroll offset.+ const COL_WIDTH: u16 = 26;+ let max_visible = (body.width / COL_WIDTH).max(1) as usize;+ // Record the viewport width so the key handler can keep the cursor in+ // view when scrolling horizontally.+ popup.visible_levels.set(max_visible);+ // Honor the stored offset, but always keep the selected node's level+ // on screen โ covers the initial open (cursor may start in a far+ // level) and every navigation (the key handler just moves the cursor+ // and lets this clamp re-scroll).+ let sel_level = popup+ .graph+ .nodes+ .get(popup.selected)+ .map_or(0, |n| n.level);+ let start = clamp_scroll_to_selected(+ popup.scroll_levels.get(),+ sel_level,+ max_visible,+ level_count,+ );+ // Persist the corrected offset so the footer hint stays in sync.+ popup.scroll_levels.set(start);+ let visible_cols = max_visible.min(level_count - start);+ let end = (start + visible_cols).min(level_count);++ let col_constraints: Vec<Constraint> = (start..end)+ .map(|_| Constraint::Ratio(1, (end - start) as u32))+ .collect();+ let col_areas = Layout::default()+ .direction(Direction::Horizontal)+ .constraints(col_constraints)+ .split(body);++ for (slot, level) in (start..end).enumerate() {+ let col_area = col_areas[slot];+ Self::draw_dep_level_column(popup, frame, col_area, level, theme);+ }+ }++ // Footer.+ let scroll_hint = if level_count > 0 {+ let scroll = popup.scroll_levels.get();+ let first = scroll + 1;+ let last = (scroll + popup.visible_levels.get()).min(level_count);+ format!(" cols {first}-{last}/{level_count} ")+ } else {+ String::new()+ };+ let footer_text = format!(+ " [hjkl] move [Space] mark [a] all unblocked [c] clear [Enter] move {} โresearch [q] close {}",+ popup.marked.len(),+ scroll_hint+ );+ let footer = Paragraph::new(footer_text).style(+ Style::default()+ .fg(Color::Black)+ .bg(hex_to_color(&theme.color_dimmed)),+ );+ frame.render_widget(footer, chunks[2]);+ }++ /// Render a single topological column (level) of the dependency graph.+ fn draw_dep_level_column(+ popup: &DepGraphPopup,+ frame: &mut Frame,+ area: Rect,+ level: usize,+ theme: &ThemeConfig,+ ) {+ let Some(indices) = popup.graph.levels.get(level) else {+ return;+ };++ // Column header.+ let header = Paragraph::new(format!("Level {level}"))+ .style(+ Style::default()+ .fg(hex_to_color(&theme.color_column_header))+ .bold(),+ )+ .alignment(Alignment::Center);+ let header_area = Rect { height: 1, ..area };+ frame.render_widget(header, header_area);++ // Each card is 4 rows tall (border + title + status + hint).+ const CARD_HEIGHT: u16 = 4;+ let mut y = area.y + 1;+ for &idx in indices {+ if y + CARD_HEIGHT > area.y + area.height {+ break;+ }+ let Some(node) = popup.graph.nodes.get(idx) else {+ continue;+ };+ let card_area = Rect {+ x: area.x,+ y,+ width: area.width,+ height: CARD_HEIGHT,+ };+ let is_cursor = idx == popup.selected;+ let is_marked = popup.marked.contains(&node.task_id);++ // Choose the node color by status / unblocked state.+ let base_color = if node.unblocked {+ Color::Green+ } else if matches!(node.status, TaskStatus::Done) {+ hex_to_color(&theme.color_dimmed)+ } else if matches!(node.status, TaskStatus::Backlog) {+ // Blocked Backlog (deps not satisfied).+ hex_to_color(&theme.color_dimmed)+ } else {+ hex_to_color(&theme.color_normal)+ };++ let border_style = if is_cursor {+ Style::default().fg(hex_to_color(&theme.color_selected))+ } else {+ Style::default().fg(base_color)+ };+ let border_type = if is_cursor {+ BorderType::Thick+ } else {+ BorderType::Plain+ };++ let block = Block::default()+ .borders(Borders::ALL)+ .border_style(border_style)+ .border_type(border_type);+ let inner = block.inner(card_area);+ frame.render_widget(block, card_area);++ // Marker glyph: โ done, โ blocked Backlog, โ unblocked, else space.+ let marker = if node.unblocked {+ "\u{25cf} " // โ+ } else if matches!(node.status, TaskStatus::Done) {+ "\u{2713} " // โ+ } else if matches!(node.status, TaskStatus::Backlog) {+ "\u{2298} " // โ blocked+ } else {+ " "+ };++ let mut title_style = Style::default().fg(base_color);+ if is_marked {+ title_style = title_style.add_modifier(Modifier::REVERSED).bold();+ } else if is_cursor {+ title_style = title_style.bold();+ }++ // Title line (marker + truncated title).+ let title_text = truncate_str(&node.title, inner.width.saturating_sub(2) as usize);+ let title_line = Line::from(vec![+ Span::styled(marker, title_style),+ Span::styled(title_text, title_style),+ ]);+ // Status line.+ let status_line = Line::from(Span::styled(+ format!("[{}]", node.status.as_str()),+ Style::default().fg(hex_to_color(&theme.color_description)),+ ));+ // Dependency hint line.+ let hint = if node.dep_titles.is_empty() {+ String::new()+ } else {+ let joined = node.dep_titles.join(", ");+ format!("\u{2190} {}", truncate_str(&joined, inner.width.saturating_sub(2) as usize))+ };+ let hint_line = Line::from(Span::styled(+ hint,+ Style::default().fg(hex_to_color(&theme.color_dimmed)),+ ));++ let para = Paragraph::new(vec![title_line, status_line, hint_line]);+ frame.render_widget(para, inner);++ y += CARD_HEIGHT;+ }}fn draw_shell_popup(popup: &ShellPopup, frame: &mut Frame, area: Rect, theme: &ThemeConfig) {@@ -2617,6 +2878,11 @@ impl App {return self.handle_diff_popup_key(key);}+ // Handle dependency-graph overlay if open+ if self.state.dep_graph_popup.is_some() {+ return self.handle_dep_graph_key(key);+ }+// Handle PR confirmation popup if openif self.state.pr_confirm_popup.is_some() {return self.handle_pr_confirm_key(key);@@ -3539,6 +3805,7 @@ impl App {}KeyCode::Char('x') => self.delete_selected_task()?,KeyCode::Char('d') => self.show_task_diff()?,+ KeyCode::Char('D') => self.show_dependency_graph()?,KeyCode::Char('m') => self.move_task_right()?,KeyCode::Char('M') => self.move_backlog_to_running()?,KeyCode::Char('R') => {@@ -5118,6 +5385,233 @@ impl App {Ok(())}+ /// Build and open the dependency-graph overlay for the current project's tasks.+ fn show_dependency_graph(&mut self) -> Result<()> {+ let Some(db) = self.state.db.as_ref() else {+ return Ok(());+ };+ let tasks = db.get_all_tasks().unwrap_or_default();+ if tasks.is_empty() {+ self.state.warning_message =+ Some(("No tasks to show in the dependency view".to_string(), Instant::now()));+ return Ok(());+ }+ let graph = crate::tui::dep_graph::build_dep_graph(&tasks, |t| db.deps_satisfied(t));+ // Start the cursor on the first unblocked node if there is one.+ let selected = graph+ .nodes+ .iter()+ .position(|n| n.unblocked)+ .unwrap_or(0);+ self.state.dep_graph_popup = Some(DepGraphPopup {+ graph,+ selected,+ marked: HashSet::new(),+ scroll_levels: Cell::new(0),+ visible_levels: Cell::new(1),+ });+ Ok(())+ }++ /// Key handling for the dependency-graph overlay.+ fn handle_dep_graph_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {+ let Some(popup) = self.state.dep_graph_popup.as_mut() else {+ return Ok(());+ };+ match key.code {+ KeyCode::Esc | KeyCode::Char('q') => {+ self.state.dep_graph_popup = None;+ }+ KeyCode::Char('j') | KeyCode::Down => {+ Self::dep_graph_move_vertical(popup, 1);+ }+ KeyCode::Char('k') | KeyCode::Up => {+ Self::dep_graph_move_vertical(popup, -1);+ }+ KeyCode::Char('l') | KeyCode::Right => {+ Self::dep_graph_move_horizontal(popup, 1);+ }+ KeyCode::Char('h') | KeyCode::Left => {+ Self::dep_graph_move_horizontal(popup, -1);+ }+ KeyCode::Char(' ') => {+ // Toggle mark on the selected node, only if it is unblocked.+ if let Some(node) = popup.graph.nodes.get(popup.selected) {+ if node.unblocked {+ let id = node.task_id.clone();+ if !popup.marked.remove(&id) {+ popup.marked.insert(id);+ }+ }+ }+ }+ KeyCode::Char('a') => {+ // Mark all unblocked nodes.+ for id in popup.graph.unblocked_ids() {+ popup.marked.insert(id);+ }+ }+ KeyCode::Char('c') => {+ popup.marked.clear();+ }+ KeyCode::Enter => {+ // Collect targets: marked nodes, or the selected node if nothing+ // is marked and it is unblocked.+ let mut targets: Vec<String> = popup+ .graph+ .nodes+ .iter()+ .filter(|n| n.unblocked && popup.marked.contains(&n.task_id))+ .map(|n| n.task_id.clone())+ .collect();+ if targets.is_empty() {+ if let Some(node) = popup.graph.nodes.get(popup.selected) {+ if node.unblocked {+ targets.push(node.task_id.clone());+ }+ }+ }+ if targets.is_empty() {+ self.state.warning_message = Some((+ "No unblocked tasks selected โ press Space to mark one".to_string(),+ Instant::now(),+ ));+ return Ok(());+ }+ self.state.dep_graph_popup = None;+ self.batch_move_unblocked(targets)?;+ }+ _ => {}+ }+ Ok(())+ }++ /// Move the cursor up/down within the current level (column).+ fn dep_graph_move_vertical(popup: &mut DepGraphPopup, delta: i32) {+ let Some(node) = popup.graph.nodes.get(popup.selected) else {+ return;+ };+ let level = node.level;+ let Some(col) = popup.graph.levels.get(level) else {+ return;+ };+ let pos = col.iter().position(|&i| i == popup.selected).unwrap_or(0);+ let new_pos = (pos as i32 + delta).clamp(0, col.len() as i32 - 1) as usize;+ if let Some(&idx) = col.get(new_pos) {+ popup.selected = idx;+ }+ }++ /// Move the cursor left/right across levels, keeping a similar row position.+ fn dep_graph_move_horizontal(popup: &mut DepGraphPopup, delta: i32) {+ let Some(node) = popup.graph.nodes.get(popup.selected) else {+ return;+ };+ let level = node.level;+ let cur_pos = popup+ .graph+ .levels+ .get(level)+ .and_then(|col| col.iter().position(|&i| i == popup.selected))+ .unwrap_or(0);+ let new_level = (level as i32 + delta).clamp(0, popup.graph.level_count() as i32 - 1);+ if new_level < 0 {+ return;+ }+ let new_level = new_level as usize;+ if let Some(col) = popup.graph.levels.get(new_level) {+ if !col.is_empty() {+ let new_pos = cur_pos.min(col.len() - 1);+ popup.selected = col[new_pos];+ }+ }+ // Scrolling is handled by the draw pass, which re-clamps `scroll_levels`+ // each frame to keep the selected node on screen.+ }++ /// Enqueue unblocked tasks for serialized worktree setup, then kick off the first.+ fn batch_move_unblocked(&mut self, task_ids: Vec<String>) -> Result<()> {+ for id in task_ids {+ if !self.state.setup_queue.contains(&id) {+ self.state.setup_queue.push_back(id);+ }+ }+ self.try_start_next_queued_setup()+ }++ /// If no worktree setup is currently running, start the next queued batch task.+ /// Routes each task to research when its plugin supports it, else to planning.+ fn try_start_next_queued_setup(&mut self) -> Result<()> {+ // A setup is in progress โ it will call back here when it completes.+ if self.state.setup_rx.is_some() {+ return Ok(());+ }+ while let Some(task_id) = self.state.setup_queue.pop_front() {+ // Re-validate: the task may have changed status or deps since queuing.+ let Some(db) = self.state.db.as_ref() else {+ continue;+ };+ let Some(task) = db.get_task(&task_id).ok().flatten() else {+ continue;+ };+ if task.status != TaskStatus::Backlog || !db.deps_satisfied(&task) {+ continue;+ }++ // Prefer research if the plugin defines a research/preresearch command.+ let plugin = self.load_task_plugin(&task);+ let has_research_cmd = plugin.as_ref().map_or(false, |p| {+ p.commands.research.is_some() || p.commands.preresearch.is_some()+ });++ if has_research_cmd {+ self.start_research(&task_id)?;+ } else {+ self.start_planning_from_backlog(&task_id)?;+ }++ // start_research / start_planning_from_backlog set setup_rx when they+ // spawn a background setup. If so, stop draining โ the completion+ // handler will resume the queue. If not (no-op), keep draining.+ if self.state.setup_rx.is_some() {+ break;+ }+ }+ self.refresh_tasks()?;+ Ok(())+ }++ /// Move a Backlog task into Planning (the planning fallback for plugins with+ /// no research phase). Mirrors `move_task_right`'s BacklogโPlanning branch.+ fn start_planning_from_backlog(&mut self, task_id: &str) -> Result<()> {+ if self.state.setup_rx.is_some() {+ return Ok(());+ }+ let (mut task, project_path) = match (+ self.state.db.as_ref().and_then(|db| db.get_task(task_id).ok().flatten()),+ self.state.project_path.clone(),+ ) {+ (Some(t), Some(p)) => (t, p),+ _ => return Ok(()),+ };+ if task.status != TaskStatus::Backlog {+ return Ok(());+ }+ let handled = self.transition_to_planning(&mut task, &project_path)?;+ if !handled {+ task.status = TaskStatus::Planning;+ task.updated_at = chrono::Utc::now();+ task.escalation_note = None;+ if let Some(db) = &self.state.db {+ db.update_task(&task)?;+ }+ self.state.stuck_task_notified.remove(&task.id);+ self.state.stuck_task_idle_since.remove(&task.id);+ self.state.phase_status_cache.remove(&task.id);+ }+ Ok(())+ }+/// Move task directly from Backlog to Running (skip Planning)fn move_backlog_to_running(&mut self) -> Result<()> {let task_id = match self.state.board.selected_task() {@@ -7209,6 +7703,49 @@ fn collect_task_diff(}/// Helper function to create a centered rect+/// Clamp a horizontal scroll offset (in level-columns) so the selected level is+/// visible within a viewport `visible` columns wide. Returns the new offset.+///+/// - If the selection is left of the window, scroll left to it.+/// - If it is at/past the right edge, scroll right so it sits on the last+/// visible column.+/// - The offset never exceeds what keeps the last column flush with the right+/// edge (no blank trailing space when the graph is wider than the viewport).+fn clamp_scroll_to_selected(+ scroll: usize,+ sel_level: usize,+ visible: usize,+ level_count: usize,+) -> usize {+ let visible = visible.max(1);+ let mut start = scroll.min(level_count.saturating_sub(1));+ if sel_level < start {+ start = sel_level;+ } else if sel_level >= start + visible {+ start = sel_level + 1 - visible;+ }+ // Don't scroll past the point where the final column is at the right edge.+ let max_start = level_count.saturating_sub(visible);+ start.min(max_start)+}++/// Truncate a string to at most `max` characters, appending an ellipsis when+/// it was shortened. Operates on chars so it is UTF-8 safe.+fn truncate_str(s: &str, max: usize) -> String {+ if max == 0 {+ return String::new();+ }+ let char_count = s.chars().count();+ if char_count <= max {+ return s.to_string();+ }+ if max == 1 {+ return "\u{2026}".to_string();+ }+ let taken: String = s.chars().take(max - 1).collect();+ format!("{taken}\u{2026}")+}+fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {let popup_layout = Layout::default().direction(Direction::Vertical)diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rsindex 19ae59c..ac7a486 100644--- a/src/tui/app_tests.rs+++ b/src/tui/app_tests.rs@@ -10290,3 +10290,51 @@ fn test_switch_to_project_reloads_config() {// Config should now reflect the new project's settingsassert_eq!(app.state.config.agent_for_phase("review"), "codex");}++// === Dependency-graph horizontal scroll clamp ===++#[test]+fn dep_scroll_no_change_when_selection_already_visible() {+ // 10 levels, viewport shows 4, scroll at 0, selection at level 2 -> stays.+ assert_eq!(clamp_scroll_to_selected(0, 2, 4, 10), 0);+}++#[test]+fn dep_scroll_right_when_selection_past_right_edge() {+ // Viewport [0,4): selecting level 4 must scroll so 4 is the last visible col.+ assert_eq!(clamp_scroll_to_selected(0, 4, 4, 10), 1);+ // Selecting level 6 from scroll 0 -> start = 6 + 1 - 4 = 3.+ assert_eq!(clamp_scroll_to_selected(0, 6, 4, 10), 3);+}++#[test]+fn dep_scroll_left_when_selection_before_left_edge() {+ // Window starts at 5, selecting level 2 -> scroll left to 2.+ assert_eq!(clamp_scroll_to_selected(5, 2, 4, 10), 2);+}++#[test]+fn dep_scroll_reaches_last_level() {+ // The final level (9) must become visible: start = 9 + 1 - 4 = 6.+ assert_eq!(clamp_scroll_to_selected(0, 9, 4, 10), 6);+}++#[test]+fn dep_scroll_never_overshoots_past_end() {+ // A stale large scroll is clamped so the last column stays flush right.+ // max_start = level_count - visible = 10 - 4 = 6.+ assert_eq!(clamp_scroll_to_selected(99, 9, 4, 10), 6);+}++#[test]+fn dep_scroll_handles_fewer_levels_than_viewport() {+ // 3 levels, viewport fits 5 -> never scrolls; offset stays 0.+ assert_eq!(clamp_scroll_to_selected(0, 2, 5, 3), 0);+ assert_eq!(clamp_scroll_to_selected(2, 0, 5, 3), 0);+}++#[test]+fn dep_scroll_zero_visible_treated_as_one() {+ // Defensive: a zero viewport width must not panic (treated as 1 column).+ assert_eq!(clamp_scroll_to_selected(0, 5, 0, 10), 5);+}diff --git a/src/tui/dep_graph.rs b/src/tui/dep_graph.rsnew file mode 100644index 0000000..543f513--- /dev/null+++ b/src/tui/dep_graph.rs@@ -0,0 +1,363 @@+//! Pure, TUI-independent dependency-graph model.+//!+//! Builds a topologically-leveled view of task dependencies from the+//! `referenced_tasks` field. Each task becomes a [`DepNode`] assigned to a+//! `level` (column): level 0 holds tasks with no in-graph dependencies, and a+//! task's level is one past the maximum level of its dependencies.+//!+//! The module is deliberately free of any ratatui/database types so it can be+//! unit-tested in isolation. The caller supplies a `deps_satisfied` closure so+//! the "unblocked" rule stays consistent with the board's move-gating+//! (`Database::deps_satisfied`).++use crate::db::{Task, TaskStatus};+use std::collections::{HashMap, HashSet, VecDeque};++/// A single task rendered in the dependency graph.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct DepNode {+ pub task_id: String,+ pub title: String,+ pub status: TaskStatus,+ /// True when the task is in Backlog and all its dependencies are satisfied+ /// (in Review/Done) โ i.e. it is actionable and can be batch-moved.+ pub unblocked: bool,+ /// Topological column index (0 = no in-graph dependencies).+ pub level: usize,+ /// Titles of the task's (in-graph) dependencies, for the per-node hint line.+ pub dep_titles: Vec<String>,+}++/// The full dependency graph: nodes plus the level groupings used for layout.+#[derive(Debug, Clone, Default)]+pub struct DepGraph {+ /// All nodes, ordered by `(level, title)`.+ pub nodes: Vec<DepNode>,+ /// Directed edges `(dependency_id, dependent_id)`.+ pub edges: Vec<(String, String)>,+ /// Indices into `nodes`, grouped by level. `levels[l]` lists every node at+ /// column `l`, already sorted by title.+ pub levels: Vec<Vec<usize>>,+}++impl DepGraph {+ pub fn is_empty(&self) -> bool {+ self.nodes.is_empty()+ }++ /// Number of topological columns.+ pub fn level_count(&self) -> usize {+ self.levels.len()+ }++ /// Every node currently flagged as unblocked (actionable Backlog tasks).+ pub fn unblocked_ids(&self) -> Vec<String> {+ self.nodes+ .iter()+ .filter(|n| n.unblocked)+ .map(|n| n.task_id.clone())+ .collect()+ }+}++/// Parse the comma-separated `referenced_tasks` field into dependency IDs.+fn parse_refs(refs: &Option<String>) -> Vec<String> {+ match refs.as_deref() {+ Some(s) => s+ .split(',')+ .map(|p| p.trim())+ .filter(|p| !p.is_empty())+ .map(|p| p.to_string())+ .collect(),+ None => Vec::new(),+ }+}++/// Build the dependency graph from a project's tasks.+///+/// `deps_satisfied` should return true when every dependency of the given task+/// is in Review/Done (the same rule `Database::deps_satisfied` applies). It is+/// passed as a closure so this function stays database-free and testable.+///+/// References to tasks that are not present in `tasks` (deleted/unknown) are+/// dropped, matching `deps_satisfied`'s treatment of missing deps as satisfied.+/// Cycles are tolerated: any nodes that cannot be topologically resolved are+/// placed in a column after the resolvable maximum, so the view never hangs.+pub fn build_dep_graph(tasks: &[Task], deps_satisfied: impl Fn(&Task) -> bool) -> DepGraph {+ // Known task ids, so we can drop dangling references.+ let known: HashSet<&str> = tasks.iter().map(|t| t.id.as_str()).collect();+ let title_of: HashMap<&str, &str> =+ tasks.iter().map(|t| (t.id.as_str(), t.title.as_str())).collect();++ // dependency_id -> dependent_id edges, restricted to known tasks.+ let mut edges: Vec<(String, String)> = Vec::new();+ // For each task: its in-graph dependency ids.+ let mut deps: HashMap<String, Vec<String>> = HashMap::new();+ for task in tasks {+ let refs: Vec<String> = parse_refs(&task.referenced_tasks)+ .into_iter()+ .filter(|r| known.contains(r.as_str()))+ .collect();+ for dep in &refs {+ edges.push((dep.clone(), task.id.clone()));+ }+ deps.insert(task.id.clone(), refs);+ }++ // Kahn-style level assignment. in_degree counts unresolved dependencies.+ let mut in_degree: HashMap<String, usize> =+ deps.iter().map(|(id, d)| (id.clone(), d.len())).collect();+ // dependency_id -> dependents, to decrement when a dependency is resolved.+ let mut dependents: HashMap<String, Vec<String>> = HashMap::new();+ for (dep, dependent) in &edges {+ dependents.entry(dep.clone()).or_default().push(dependent.clone());+ }++ let mut level_of: HashMap<String, usize> = HashMap::new();+ let mut queue: VecDeque<String> = in_degree+ .iter()+ .filter(|(_, &d)| d == 0)+ .map(|(id, _)| id.clone())+ .collect();+ for id in &queue {+ level_of.insert(id.clone(), 0);+ }++ while let Some(id) = queue.pop_front() {+ let lvl = *level_of.get(&id).unwrap_or(&0);+ if let Some(children) = dependents.get(&id) {+ for child in children {+ // Child sits at least one column past this dependency.+ let entry = level_of.entry(child.clone()).or_insert(0);+ if lvl + 1 > *entry {+ *entry = lvl + 1;+ }+ if let Some(d) = in_degree.get_mut(child) {+ *d = d.saturating_sub(1);+ if *d == 0 {+ queue.push_back(child.clone());+ }+ }+ }+ }+ }++ // Anything left with in_degree > 0 is part of a cycle. Place it after the+ // resolved maximum so rendering is total and never loops.+ let resolved_max = level_of.values().copied().max().unwrap_or(0);+ let cycle_level = if level_of.len() == tasks.len() {+ resolved_max+ } else {+ resolved_max + 1+ };+ for task in tasks {+ level_of.entry(task.id.clone()).or_insert(cycle_level);+ }++ // Build nodes.+ let mut nodes: Vec<DepNode> = tasks+ .iter()+ .map(|task| {+ let level = *level_of.get(&task.id).unwrap_or(&0);+ let unblocked =+ task.status == TaskStatus::Backlog && deps_satisfied(task);+ let dep_titles = deps+ .get(&task.id)+ .map(|d| {+ d.iter()+ .filter_map(|id| title_of.get(id.as_str()).map(|t| t.to_string()))+ .collect()+ })+ .unwrap_or_default();+ DepNode {+ task_id: task.id.clone(),+ title: task.title.clone(),+ status: task.status,+ unblocked,+ level,+ dep_titles,+ }+ })+ .collect();++ // Stable ordering: by level, then title, then id.+ nodes.sort_by(|a, b| {+ a.level+ .cmp(&b.level)+ .then_with(|| a.title.cmp(&b.title))+ .then_with(|| a.task_id.cmp(&b.task_id))+ });++ // Group indices by level.+ let max_level = nodes.iter().map(|n| n.level).max().unwrap_or(0);+ let mut levels: Vec<Vec<usize>> = vec![Vec::new(); if nodes.is_empty() { 0 } else { max_level + 1 }];+ for (idx, node) in nodes.iter().enumerate() {+ levels[node.level].push(idx);+ }++ DepGraph { nodes, edges, levels }+}++#[cfg(test)]+mod tests {+ use super::*;+ use chrono::Utc;++ fn task(id: &str, status: TaskStatus, refs: Option<&str>) -> Task {+ Task {+ id: id.to_string(),+ title: format!("Task {id}"),+ description: None,+ status,+ agent: "claude".to_string(),+ project_id: "proj".to_string(),+ session_name: None,+ worktree_path: None,+ branch_name: None,+ pr_number: None,+ pr_url: None,+ plugin: None,+ cycle: 0,+ referenced_tasks: refs.map(|s| s.to_string()),+ escalation_note: None,+ base_branch: None,+ created_at: Utc::now(),+ updated_at: Utc::now(),+ }+ }++ /// Mirror of Database::deps_satisfied for tests: deps satisfied when every+ /// referenced task in `tasks` is Review/Done (missing => satisfied).+ fn satisfied_fn(tasks: Vec<Task>) -> impl Fn(&Task) -> bool {+ move |t: &Task| {+ let refs = parse_refs(&t.referenced_tasks);+ refs.iter().all(|rid| {+ tasks+ .iter()+ .find(|x| &x.id == rid)+ .map_or(true, |dep| {+ matches!(dep.status, TaskStatus::Review | TaskStatus::Done)+ })+ })+ }+ }++ fn node<'a>(g: &'a DepGraph, id: &str) -> &'a DepNode {+ g.nodes.iter().find(|n| n.task_id == id).expect("node exists")+ }++ #[test]+ fn linear_chain_levels_increase() {+ // a -> b -> c (c depends on b depends on a)+ let tasks = vec![+ task("a", TaskStatus::Done, None),+ task("b", TaskStatus::Backlog, Some("a")),+ task("c", TaskStatus::Backlog, Some("b")),+ ];+ let g = build_dep_graph(&tasks, satisfied_fn(tasks.clone()));+ assert_eq!(node(&g, "a").level, 0);+ assert_eq!(node(&g, "b").level, 1);+ assert_eq!(node(&g, "c").level, 2);+ assert_eq!(g.level_count(), 3);+ }++ #[test]+ fn diamond_shared_dependency() {+ // a -> b, a -> c, b -> d, c -> d. d must be 2 columns past a.+ let tasks = vec![+ task("a", TaskStatus::Done, None),+ task("b", TaskStatus::Backlog, Some("a")),+ task("c", TaskStatus::Backlog, Some("a")),+ task("d", TaskStatus::Backlog, Some("b,c")),+ ];+ let g = build_dep_graph(&tasks, satisfied_fn(tasks.clone()));+ assert_eq!(node(&g, "a").level, 0);+ assert_eq!(node(&g, "b").level, 1);+ assert_eq!(node(&g, "c").level, 1);+ assert_eq!(node(&g, "d").level, 2);+ }++ #[test]+ fn multiple_roots_at_level_zero() {+ let tasks = vec![+ task("a", TaskStatus::Done, None),+ task("b", TaskStatus::Backlog, None),+ task("c", TaskStatus::Backlog, Some("a,b")),+ ];+ let g = build_dep_graph(&tasks, satisfied_fn(tasks.clone()));+ assert_eq!(node(&g, "a").level, 0);+ assert_eq!(node(&g, "b").level, 0);+ assert_eq!(node(&g, "c").level, 1);+ assert_eq!(g.levels[0].len(), 2);+ }++ #[test]+ fn cycle_does_not_panic_or_hang() {+ // a -> b -> a (mutual). Both should still appear with finite levels.+ let tasks = vec![+ task("a", TaskStatus::Backlog, Some("b")),+ task("b", TaskStatus::Backlog, Some("a")),+ ];+ let g = build_dep_graph(&tasks, satisfied_fn(tasks.clone()));+ assert_eq!(g.nodes.len(), 2);+ // Neither node is dropped.+ assert!(g.nodes.iter().any(|n| n.task_id == "a"));+ assert!(g.nodes.iter().any(|n| n.task_id == "b"));+ }++ #[test]+ fn missing_reference_is_dropped() {+ // b references a deleted task "ghost" plus real "a".+ let tasks = vec![+ task("a", TaskStatus::Done, None),+ task("b", TaskStatus::Backlog, Some("a,ghost")),+ ];+ let g = build_dep_graph(&tasks, satisfied_fn(tasks.clone()));+ // Only the edge a->b survives; b stays at level 1.+ assert_eq!(node(&g, "b").level, 1);+ assert_eq!(g.edges.len(), 1);+ assert_eq!(g.edges[0], ("a".to_string(), "b".to_string()));+ // dep_titles only lists the known dependency.+ assert_eq!(node(&g, "b").dep_titles, vec!["Task a".to_string()]);+ }++ #[test]+ fn unblocked_only_for_backlog_with_satisfied_deps() {+ let tasks = vec![+ // satisfied dependency (Done)+ task("done_dep", TaskStatus::Done, None),+ // unsatisfied dependency (Backlog)+ task("open_dep", TaskStatus::Backlog, None),+ // Backlog + dep satisfied => unblocked+ task("ready", TaskStatus::Backlog, Some("done_dep")),+ // Backlog + dep NOT satisfied => blocked+ task("blocked", TaskStatus::Backlog, Some("open_dep")),+ // Backlog, no deps => unblocked+ task("free", TaskStatus::Backlog, None),+ // Already in progress => not "unblocked" even with satisfied deps+ task("running", TaskStatus::Running, Some("done_dep")),+ ];+ let g = build_dep_graph(&tasks, satisfied_fn(tasks.clone()));+ assert!(node(&g, "ready").unblocked);+ assert!(node(&g, "free").unblocked);+ assert!(!node(&g, "blocked").unblocked);+ assert!(!node(&g, "running").unblocked);+ assert!(!node(&g, "done_dep").unblocked);+ // open_dep is itself a Backlog task with no deps, so it too is unblocked.+ assert!(node(&g, "open_dep").unblocked);++ let mut unblocked = g.unblocked_ids();+ unblocked.sort();+ assert_eq!(+ unblocked,+ vec!["free".to_string(), "open_dep".to_string(), "ready".to_string()]+ );+ }++ #[test]+ fn empty_input_yields_empty_graph() {+ let g = build_dep_graph(&[], |_| true);+ assert!(g.is_empty());+ assert_eq!(g.level_count(), 0);+ }+}diff --git a/src/tui/mod.rs b/src/tui/mod.rsindex d041e94..873dff0 100644--- a/src/tui/mod.rs+++ b/src/tui/mod.rs@@ -1,5 +1,6 @@mod app;pub mod board;+pub mod dep_graph;mod input;pub mod shell_popup;diff --git a/tests/db_tests.rs b/tests/db_tests.rsindex 462b76b..d9ca312 100644--- a/tests/db_tests.rs+++ b/tests/db_tests.rs@@ -558,3 +558,85 @@ fn test_global_db_file_permissions_are_0600() {assert_eq!(mode, 0o600, "Global DB file should be owner-only read/write");}}++// === Dependency-graph integration tests (real Database + deps_satisfied) ===++use agtx::tui::dep_graph::build_dep_graph;++/// Build a dependency graph from a real in-memory database, exercising the+/// same `deps_satisfied` rule the board uses. This complements the pure-model+/// unit tests in src/tui/dep_graph.rs.+#[test]+fn test_dep_graph_levels_and_unblocked_from_db() {+ let db = Database::open_in_memory_project().unwrap();++ // Level 0: a completed dependency.+ let mut base = Task::new("Base", "claude", "proj");+ base.status = TaskStatus::Done;+ db.create_task(&base).unwrap();++ // Level 1: a Backlog task whose only dep (base) is Done -> unblocked.+ let mut api = Task::new("API", "claude", "proj");+ api.referenced_tasks = Some(base.id.clone());+ db.create_task(&api).unwrap();++ // Level 2: a Backlog task depending on API (still Backlog) -> blocked.+ let mut ui = Task::new("UI", "claude", "proj");+ ui.referenced_tasks = Some(api.id.clone());+ db.create_task(&ui).unwrap();++ let tasks = db.get_all_tasks().unwrap();+ let graph = build_dep_graph(&tasks, |t| db.deps_satisfied(t));++ let node = |id: &str| {+ graph+ .nodes+ .iter()+ .find(|n| n.task_id == id)+ .expect("node present")+ };++ // Topological columns.+ assert_eq!(node(&base.id).level, 0);+ assert_eq!(node(&api.id).level, 1);+ assert_eq!(node(&ui.id).level, 2);++ // Only API is an actionable (unblocked) Backlog task: its dep is Done.+ assert!(node(&api.id).unblocked);+ // UI's dep (API) is still in Backlog, so UI is blocked.+ assert!(!node(&ui.id).unblocked);+ // Base is Done, so it is not "unblocked" (not actionable).+ assert!(!node(&base.id).unblocked);++ let unblocked = graph.unblocked_ids();+ assert_eq!(unblocked, vec![api.id.clone()]);+}++#[test]+fn test_dep_graph_unblocks_chain_as_deps_complete() {+ let db = Database::open_in_memory_project().unwrap();++ // a (Backlog) -> b (Backlog): b depends on a.+ let a = Task::new("A", "claude", "proj");+ db.create_task(&a).unwrap();+ let mut b = Task::new("B", "claude", "proj");+ b.referenced_tasks = Some(a.id.clone());+ db.create_task(&b).unwrap();++ // Initially only A is unblocked (no deps); B is blocked on A.+ let tasks = db.get_all_tasks().unwrap();+ let graph = build_dep_graph(&tasks, |t| db.deps_satisfied(t));+ let mut unblocked = graph.unblocked_ids();+ unblocked.sort();+ assert_eq!(unblocked, vec![a.id.clone()]);++ // Complete A (move to Review). Now B should become unblocked.+ let mut a_done = db.get_task(&a.id).unwrap().unwrap();+ a_done.status = TaskStatus::Review;+ db.update_task(&a_done).unwrap();++ let tasks = db.get_all_tasks().unwrap();+ let graph = build_dep_graph(&tasks, |t| db.deps_satisfied(t));+ // A is no longer Backlog, so it drops out of the unblocked set; B enters it.+ assert_eq!(graph.unblocked_ids(), vec![b.id.clone()]);+}