Skip to content

armgit / agtx

Public Imported from GitHub
0

πŸ„πŸΌβ€β™‚οΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.

feat(mcp): add CRUD tools for task management (#68)

Pablo Speciale0160bffbfb8d
diff --git a/src/db/models.rs b/src/db/models.rs
index 02f5887..5614cf3 100644
--- a/src/db/models.rs
+++ b/src/db/models.rs
@@ -73,6 +73,7 @@ pub struct Task {
pub cycle: i32,
pub referenced_tasks: Option<String>,
pub escalation_note: Option<String>,
+ pub base_branch: Option<String>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
@@ -101,6 +102,7 @@ impl Task {
cycle: 1,
referenced_tasks: None,
escalation_note: None,
+ base_branch: None,
created_at: now,
updated_at: now,
}
diff --git a/src/db/schema.rs b/src/db/schema.rs
index 81d1fde..e227f4e 100644
--- a/src/db/schema.rs
+++ b/src/db/schema.rs
@@ -132,6 +132,9 @@ impl Database {
let _ = self
.conn
.execute("ALTER TABLE tasks ADD COLUMN escalation_note TEXT", []);
+ let _ = self
+ .conn
+ .execute("ALTER TABLE tasks ADD COLUMN base_branch TEXT", []);
// MCP transition request queue
self.conn.execute_batch(
@@ -194,8 +197,8 @@ impl Database {
pub fn create_task(&self, task: &Task) -> Result<()> {
self.conn.execute(
r#"
- INSERT INTO tasks (id, title, description, status, agent, project_id, session_name, worktree_path, branch_name, pr_number, pr_url, plugin, cycle, referenced_tasks, escalation_note, created_at, updated_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)
+ INSERT INTO tasks (id, title, description, status, agent, project_id, session_name, worktree_path, branch_name, pr_number, pr_url, plugin, cycle, referenced_tasks, escalation_note, base_branch, created_at, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18)
"#,
params![
task.id,
@@ -213,6 +216,7 @@ impl Database {
task.cycle,
task.referenced_tasks,
task.escalation_note,
+ task.base_branch,
task.created_at.to_rfc3339(),
task.updated_at.to_rfc3339(),
],
@@ -220,6 +224,40 @@ impl Database {
Ok(())
}
+ pub fn create_tasks_batch(&mut self, tasks: &[Task]) -> Result<()> {
+ let tx = self.conn.transaction()?;
+ for task in tasks {
+ tx.execute(
+ r#"
+ INSERT INTO tasks (id, title, description, status, agent, project_id, session_name, worktree_path, branch_name, pr_number, pr_url, plugin, cycle, referenced_tasks, escalation_note, base_branch, created_at, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18)
+ "#,
+ params![
+ task.id,
+ task.title,
+ task.description,
+ task.status.as_str(),
+ task.agent,
+ task.project_id,
+ task.session_name,
+ task.worktree_path,
+ task.branch_name,
+ task.pr_number,
+ task.pr_url,
+ task.plugin,
+ task.cycle,
+ task.referenced_tasks,
+ task.escalation_note,
+ task.base_branch,
+ task.created_at.to_rfc3339(),
+ task.updated_at.to_rfc3339(),
+ ],
+ )?;
+ }
+ tx.commit()?;
+ Ok(())
+ }
+
pub fn update_task(&self, task: &Task) -> Result<()> {
self.conn.execute(
r#"
@@ -237,7 +275,8 @@ impl Database {
cycle = ?12,
referenced_tasks = ?13,
escalation_note = ?14,
- updated_at = ?15
+ base_branch = ?15,
+ updated_at = ?16
WHERE id = ?1
"#,
params![
@@ -255,6 +294,7 @@ impl Database {
task.cycle,
task.referenced_tasks,
task.escalation_note,
+ task.base_branch,
task.updated_at.to_rfc3339(),
],
)?;
@@ -285,6 +325,7 @@ impl Database {
cycle: row.get("cycle").unwrap_or(1),
referenced_tasks: row.get("referenced_tasks").ok().flatten(),
escalation_note: row.get("escalation_note").ok().flatten(),
+ base_branch: row.get("base_branch").ok().flatten(),
created_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>("created_at")?)
.map(|dt| dt.with_timezone(&chrono::Utc))
.unwrap_or_else(|_| chrono::Utc::now()),
@@ -442,6 +483,16 @@ impl Database {
Ok(())
}
+ /// Directly set processed_at to an arbitrary timestamp (for testing cleanup logic only).
+ #[cfg(feature = "test-mocks")]
+ pub fn backdate_transition_processed_at(&self, id: &str, processed_at: &str) -> Result<()> {
+ self.conn.execute(
+ "UPDATE transition_requests SET processed_at = ?1 WHERE id = ?2",
+ params![processed_at, id],
+ )?;
+ Ok(())
+ }
+
fn transition_request_from_row(row: &rusqlite::Row) -> rusqlite::Result<TransitionRequest> {
Ok(TransitionRequest {
id: row.get("id")?,
diff --git a/src/mcp/server.rs b/src/mcp/server.rs
index bd66a01..9ab891d 100644
--- a/src/mcp/server.rs
+++ b/src/mcp/server.rs
@@ -10,6 +10,7 @@ use rmcp::{
};
use serde::{Deserialize, Serialize};
+use crate::config::{GlobalConfig, ProjectConfig};
use crate::db::{Database, Task, TaskStatus, TransitionRequest};
// === Parameter types ===
@@ -83,6 +84,92 @@ pub struct SendToTaskParams {
pub message: String,
}
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct CreateTaskParams {
+ /// Task title
+ #[schemars(description = "Task title")]
+ pub title: String,
+ /// Task description (what to implement, context, approach hints)
+ #[schemars(description = "Task description (what to implement, context, approach hints)")]
+ pub description: Option<String>,
+ /// Workflow plugin name (defaults to project's active plugin)
+ #[schemars(description = "Workflow plugin name (defaults to project's active plugin)")]
+ pub plugin: Option<String>,
+ /// Comma-separated task IDs that this task depends on
+ #[schemars(
+ description = "Comma-separated task IDs that this task depends on (must complete before this task starts)"
+ )]
+ pub referenced_tasks: Option<String>,
+ /// Base branch to create worktree from (defaults to project's main branch)
+ #[schemars(
+ description = "Base branch to create the worktree from (e.g. another task's branch for stacked PRs). Defaults to project's main branch."
+ )]
+ pub base_branch: Option<String>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct BatchTask {
+ /// Task title
+ #[schemars(description = "Task title")]
+ pub title: String,
+ /// Task description
+ #[schemars(description = "Task description (what to implement, context, approach hints)")]
+ pub description: Option<String>,
+ /// Workflow plugin name (defaults to project's active plugin)
+ #[schemars(description = "Workflow plugin name (defaults to project's active plugin)")]
+ pub plugin: Option<String>,
+ /// Indices (0-based) into the tasks array that this task depends on
+ #[schemars(
+ description = "Indices (0-based) into the tasks array that this task depends on. Referenced tasks must have a lower index (no forward references)."
+ )]
+ pub depends_on: Option<Vec<usize>>,
+ /// Base branch to create worktree from (defaults to project's main branch)
+ #[schemars(
+ description = "Base branch to create the worktree from (e.g. another task's branch for stacked PRs). Defaults to project's main branch."
+ )]
+ pub base_branch: Option<String>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct CreateTasksBatchParams {
+ /// Array of tasks to create, with index-based dependency wiring
+ #[schemars(description = "Array of tasks to create. Use depends_on with 0-based indices to wire dependencies between them.")]
+ pub tasks: Vec<BatchTask>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct UpdateTaskParams {
+ /// The task ID (UUID) to update
+ #[schemars(description = "The task ID (UUID) to update. Only backlog tasks can be updated.")]
+ pub task_id: String,
+ /// New title (if provided)
+ #[schemars(description = "New task title")]
+ pub title: Option<String>,
+ /// New description (if provided)
+ #[schemars(description = "New task description")]
+ pub description: Option<String>,
+ /// New plugin (if provided)
+ #[schemars(description = "New workflow plugin name")]
+ pub plugin: Option<String>,
+ /// New referenced tasks (if provided, replaces existing)
+ #[schemars(
+ description = "Comma-separated task IDs that this task depends on (replaces existing dependencies)"
+ )]
+ pub referenced_tasks: Option<String>,
+ /// New base branch (if provided)
+ #[schemars(
+ description = "Base branch to create the worktree from (e.g. another task's branch for stacked PRs)"
+ )]
+ pub base_branch: Option<String>,
+}
+
+#[derive(Debug, Deserialize, schemars::JsonSchema)]
+pub struct DeleteTaskParams {
+ /// The task ID (UUID) to delete
+ #[schemars(description = "The task ID (UUID) to delete. Only backlog tasks can be deleted.")]
+ pub task_id: String,
+}
+
// === Response types ===
#[derive(Serialize)]
@@ -181,6 +268,40 @@ struct SendToTaskResponse {
message: String,
}
+#[derive(Serialize)]
+struct CreateTaskResponse {
+ id: String,
+ title: String,
+ status: String,
+}
+
+#[derive(Serialize)]
+struct BatchTaskResponse {
+ index: usize,
+ id: String,
+ title: String,
+}
+
+#[derive(Serialize)]
+struct CreateTasksBatchResponse {
+ created: Vec<BatchTaskResponse>,
+ count: usize,
+}
+
+#[derive(Serialize)]
+struct UpdateTaskResponse {
+ id: String,
+ title: String,
+ updated_fields: Vec<String>,
+}
+
+#[derive(Serialize)]
+struct DeleteTaskResponse {
+ id: String,
+ title: String,
+ message: String,
+}
+
// === MCP Server ===
#[derive(Debug, Clone)]
@@ -206,6 +327,25 @@ impl AgtxMcpServer {
Database::open_global().map_err(|e| format!("Failed to open global database: {}", e))
}
+ /// Get the project name from the project path.
+ fn project_name(&self) -> String {
+ self.project_path
+ .file_name()
+ .map(|n| n.to_string_lossy().to_string())
+ .unwrap_or_else(|| "unknown".to_string())
+ }
+
+ /// Get the default agent and plugin from merged config.
+ fn config_defaults(&self) -> (String, Option<String>) {
+ let global = GlobalConfig::load().unwrap_or_default();
+ let project = ProjectConfig::load(&self.project_path).unwrap_or_default();
+ let agent = project
+ .default_agent
+ .unwrap_or_else(|| global.default_agent.clone());
+ let plugin = project.workflow_plugin.clone();
+ (agent, plugin)
+ }
+
/// Compute which move_task actions are valid for a task given its status and plugin rules.
fn allowed_actions(&self, task: &Task) -> Vec<String> {
let mut actions = Vec::new();
@@ -641,6 +781,245 @@ impl AgtxMcpServer {
Err(e) => format!("Error sending Enter: {}", e),
}
}
+
+ #[tool(
+ description = "Create a new task in the Backlog column. Returns the created task's ID. Use create_tasks_batch for multiple tasks with dependencies."
+ )]
+ fn create_task(&self, Parameters(params): Parameters<CreateTaskParams>) -> String {
+ let db = match self.open_project_db() {
+ Ok(db) => db,
+ Err(e) => return e,
+ };
+
+ let (default_agent, default_plugin) = self.config_defaults();
+ let project_name = self.project_name();
+
+ // Validate referenced task IDs exist
+ if let Some(ref refs) = params.referenced_tasks {
+ for ref_id in refs.split(',').map(|s| s.trim()).filter(|s| !s.is_empty()) {
+ match db.get_task(ref_id) {
+ Ok(Some(_)) => {}
+ Ok(None) => return format!("Error: referenced task not found: {}", ref_id),
+ Err(e) => return format!("Error checking referenced task: {}", e),
+ }
+ }
+ }
+
+ let mut task = Task::new(&params.title, &default_agent, &project_name);
+ task.description = params.description;
+ task.plugin = params.plugin.or(default_plugin);
+ task.referenced_tasks = params.referenced_tasks;
+ task.base_branch = params.base_branch;
+
+ match db.create_task(&task) {
+ Ok(()) => {
+ let response = CreateTaskResponse {
+ id: task.id,
+ title: task.title,
+ status: "backlog".to_string(),
+ };
+ serde_json::to_string_pretty(&response)
+ .unwrap_or_else(|e| format!("Error serializing: {}", e))
+ }
+ Err(e) => format!("Error creating task: {}", e),
+ }
+ }
+
+ #[tool(
+ description = "Create multiple tasks at once with index-based dependency wiring. Each task's depends_on field uses 0-based indices into the tasks array (no forward references). Returns all created task IDs."
+ )]
+ fn create_tasks_batch(
+ &self,
+ Parameters(params): Parameters<CreateTasksBatchParams>,
+ ) -> String {
+ if params.tasks.is_empty() {
+ return "Error: tasks array is empty".to_string();
+ }
+ if params.tasks.len() > 50 {
+ return "Error: maximum 50 tasks per batch".to_string();
+ }
+
+ // Pass 1: Validate index-based dependencies
+ for (i, batch_task) in params.tasks.iter().enumerate() {
+ if let Some(ref deps) = batch_task.depends_on {
+ let mut seen = std::collections::HashSet::new();
+ for &dep_idx in deps {
+ if dep_idx >= i {
+ return format!(
+ "Error: task[{}] '{}' has depends_on index {} which is >= its own index {}. Only backward references allowed.",
+ i, batch_task.title, dep_idx, i
+ );
+ }
+ if !seen.insert(dep_idx) {
+ return format!(
+ "Error: task[{}] '{}' has duplicate depends_on index {}.",
+ i, batch_task.title, dep_idx
+ );
+ }
+ }
+ }
+ }
+
+ let mut db = match self.open_project_db() {
+ Ok(db) => db,
+ Err(e) => return e,
+ };
+
+ let (default_agent, default_plugin) = self.config_defaults();
+ let project_name = self.project_name();
+
+ // Pass 2: Create all tasks, collect IDs
+ let mut created_tasks: Vec<Task> = Vec::with_capacity(params.tasks.len());
+ for batch_task in &params.tasks {
+ let mut task = Task::new(&batch_task.title, &default_agent, &project_name);
+ task.description = batch_task.description.clone();
+ task.plugin = batch_task.plugin.clone().or_else(|| default_plugin.clone());
+ task.base_branch = batch_task.base_branch.clone();
+ created_tasks.push(task);
+ }
+
+ // Pass 3: Resolve index-based deps to real task IDs
+ for (i, batch_task) in params.tasks.iter().enumerate() {
+ if let Some(ref deps) = batch_task.depends_on {
+ let dep_ids: Vec<String> = deps
+ .iter()
+ .map(|&idx| created_tasks[idx].id.clone())
+ .collect();
+ created_tasks[i].referenced_tasks = Some(dep_ids.join(","));
+ }
+ }
+
+ // Insert all tasks atomically β€” on any failure none are committed
+ if let Err(e) = db.create_tasks_batch(&created_tasks) {
+ return format!("Error creating tasks: {}", e);
+ }
+
+ let results: Vec<BatchTaskResponse> = created_tasks
+ .iter()
+ .enumerate()
+ .map(|(i, task)| BatchTaskResponse {
+ index: i,
+ id: task.id.clone(),
+ title: task.title.clone(),
+ })
+ .collect();
+
+ let response = CreateTasksBatchResponse {
+ count: results.len(),
+ created: results,
+ };
+ serde_json::to_string_pretty(&response)
+ .unwrap_or_else(|e| format!("Error serializing: {}", e))
+ }
+
+ #[tool(
+ description = "Update a backlog task's fields. Only tasks in Backlog status can be updated. All fields are optional β€” only provided fields are changed."
+ )]
+ fn update_task(&self, Parameters(params): Parameters<UpdateTaskParams>) -> String {
+ let db = match self.open_project_db() {
+ Ok(db) => db,
+ Err(e) => return e,
+ };
+
+ let mut task = match db.get_task(&params.task_id) {
+ Ok(Some(t)) => t,
+ Ok(None) => return format!("Task not found: {}", params.task_id),
+ Err(e) => return format!("Error getting task: {}", e),
+ };
+
+ if task.status != TaskStatus::Backlog {
+ return format!(
+ "Error: can only update Backlog tasks. Task '{}' is in {} status.",
+ task.title,
+ task.status.as_str()
+ );
+ }
+
+ let mut updated_fields = Vec::new();
+
+ if let Some(title) = params.title {
+ task.title = title;
+ updated_fields.push("title".to_string());
+ }
+ if let Some(description) = params.description {
+ task.description = Some(description);
+ updated_fields.push("description".to_string());
+ }
+ if let Some(plugin) = params.plugin {
+ task.plugin = Some(plugin);
+ updated_fields.push("plugin".to_string());
+ }
+ if let Some(ref refs) = params.referenced_tasks {
+ // Validate referenced task IDs exist
+ for ref_id in refs.split(',').map(|s| s.trim()).filter(|s| !s.is_empty()) {
+ match db.get_task(ref_id) {
+ Ok(Some(_)) => {}
+ Ok(None) => return format!("Error: referenced task not found: {}", ref_id),
+ Err(e) => return format!("Error checking referenced task: {}", e),
+ }
+ }
+ task.referenced_tasks = Some(refs.clone());
+ updated_fields.push("referenced_tasks".to_string());
+ }
+ if let Some(base_branch) = params.base_branch {
+ task.base_branch = Some(base_branch);
+ updated_fields.push("base_branch".to_string());
+ }
+
+ if updated_fields.is_empty() {
+ return "No fields to update".to_string();
+ }
+
+ match db.update_task(&task) {
+ Ok(()) => {
+ let response = UpdateTaskResponse {
+ id: task.id,
+ title: task.title,
+ updated_fields,
+ };
+ serde_json::to_string_pretty(&response)
+ .unwrap_or_else(|e| format!("Error serializing: {}", e))
+ }
+ Err(e) => format!("Error updating task: {}", e),
+ }
+ }
+
+ #[tool(
+ description = "Delete a task. Only tasks in Backlog status can be deleted."
+ )]
+ fn delete_task(&self, Parameters(params): Parameters<DeleteTaskParams>) -> String {
+ let db = match self.open_project_db() {
+ Ok(db) => db,
+ Err(e) => return e,
+ };
+
+ let task = match db.get_task(&params.task_id) {
+ Ok(Some(t)) => t,
+ Ok(None) => return format!("Task not found: {}", params.task_id),
+ Err(e) => return format!("Error getting task: {}", e),
+ };
+
+ if task.status != TaskStatus::Backlog {
+ return format!(
+ "Error: can only delete Backlog tasks. Task '{}' is in {} status.",
+ task.title,
+ task.status.as_str()
+ );
+ }
+
+ match db.delete_task(&params.task_id) {
+ Ok(()) => {
+ let response = DeleteTaskResponse {
+ id: task.id,
+ title: task.title,
+ message: "Task deleted".to_string(),
+ };
+ serde_json::to_string_pretty(&response)
+ .unwrap_or_else(|e| format!("Error serializing: {}", e))
+ }
+ Err(e) => format!("Error deleting task: {}", e),
+ }
+ }
}
#[tool_handler]
@@ -649,8 +1028,10 @@ impl ServerHandler for AgtxMcpServer {
ServerInfo {
instructions: Some(
"agtx MCP server β€” control the terminal kanban board for coding agents. \
- Use list_tasks to see current tasks, move_task to transition tasks between phases, \
- and get_transition_status to check if a transition completed."
+ Use list_tasks to see current tasks, create_task or create_tasks_batch to add new tasks \
+ (with optional dependency wiring via referenced_tasks), update_task to modify backlog \
+ task fields, move_task to transition tasks between phases, get_transition_status to \
+ check if a transition completed, and delete_task to remove backlog tasks."
.into(),
),
capabilities: ServerCapabilities::builder().enable_tools().build(),
diff --git a/src/tui/app.rs b/src/tui/app.rs
index 33b4387..c54b8ca 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -4355,7 +4355,10 @@ impl App {
let all_agents = collect_phase_agents(&self.state.config);
let project_name = self.state.project_name.clone();
let tmux_project_name = self.state.tmux_project_name.clone();
- let base_branch = self.state.config.base_branch.clone();
+ let base_branch = task
+ .base_branch
+ .clone()
+ .unwrap_or_else(|| self.state.config.base_branch.clone());
let worktree_dir = self.state.config.worktree_dir.clone();
let copy_files = self.state.config.copy_files.clone();
let init_script = self.state.config.init_script.clone();
@@ -4699,7 +4702,10 @@ impl App {
let all_agents = collect_phase_agents(&self.state.config);
let project_name = self.state.project_name.clone();
let tmux_project_name = self.state.tmux_project_name.clone();
- let base_branch = self.state.config.base_branch.clone();
+ let base_branch = task
+ .base_branch
+ .clone()
+ .unwrap_or_else(|| self.state.config.base_branch.clone());
let worktree_dir = self.state.config.worktree_dir.clone();
let copy_files = self.state.config.copy_files.clone();
let init_script = self.state.config.init_script.clone();
@@ -4899,7 +4905,10 @@ impl App {
let prompt_trigger = resolve_prompt_trigger(&plugin, "running");
let project_name = self.state.project_name.clone();
let tmux_project_name = self.state.tmux_project_name.clone();
- let base_branch = self.state.config.base_branch.clone();
+ let base_branch = task
+ .base_branch
+ .clone()
+ .unwrap_or_else(|| self.state.config.base_branch.clone());
let worktree_dir = self.state.config.worktree_dir.clone();
let copy_files = self.state.config.copy_files.clone();
let init_script = self.state.config.init_script.clone();
diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rs
index 3926771..eeb452a 100644
--- a/src/tui/app_tests.rs
+++ b/src/tui/app_tests.rs
@@ -208,6 +208,7 @@ fn test_create_pr_with_content_success() {
cycle: 1,
referenced_tasks: None,
escalation_note: None,
+ base_branch: None,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
@@ -303,6 +304,7 @@ fn test_create_pr_with_content_no_changes() {
cycle: 1,
referenced_tasks: None,
escalation_note: None,
+ base_branch: None,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
@@ -357,6 +359,7 @@ fn test_create_pr_with_content_push_failure() {
cycle: 1,
referenced_tasks: None,
escalation_note: None,
+ base_branch: None,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
@@ -417,6 +420,7 @@ fn test_push_changes_to_existing_pr_success() {
cycle: 1,
referenced_tasks: None,
escalation_note: None,
+ base_branch: None,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
@@ -471,6 +475,7 @@ fn test_push_changes_to_existing_pr_no_changes() {
cycle: 1,
referenced_tasks: None,
escalation_note: None,
+ base_branch: None,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
@@ -508,6 +513,7 @@ fn test_push_changes_to_existing_pr_no_url() {
cycle: 1,
referenced_tasks: None,
escalation_note: None,
+ base_branch: None,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
diff --git a/tests/mcp_tests.rs b/tests/mcp_tests.rs
index 9b32140..4c87bff 100644
--- a/tests/mcp_tests.rs
+++ b/tests/mcp_tests.rs
@@ -1,4 +1,4 @@
-use agtx::db::{Database, Task, TransitionRequest};
+use agtx::db::{Database, Notification, Project, Task, TaskStatus, TransitionRequest};
// === TransitionRequest Model Tests ===
@@ -148,3 +148,324 @@ fn test_transition_request_with_task() {
assert!(fetched_req.is_some());
assert_eq!(fetched_req.unwrap().task_id, task.id);
}
+
+// === Task Creation Tests (for MCP create_task / create_tasks_batch) ===
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_create_task_with_description_and_plugin() {
+ let db = Database::open_in_memory_project().unwrap();
+
+ let mut task = Task::new("Add OAuth", "claude", "my-project");
+ task.description = Some("Implement OAuth with Google".to_string());
+ task.plugin = Some("agtx".to_string());
+ db.create_task(&task).unwrap();
+
+ let fetched = db.get_task(&task.id).unwrap().unwrap();
+ assert_eq!(fetched.title, "Add OAuth");
+ assert_eq!(fetched.description.as_deref(), Some("Implement OAuth with Google"));
+ assert_eq!(fetched.plugin.as_deref(), Some("agtx"));
+ assert_eq!(fetched.status, TaskStatus::Backlog);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_create_task_with_referenced_tasks() {
+ let db = Database::open_in_memory_project().unwrap();
+
+ let task1 = Task::new("Setup DB schema", "claude", "my-project");
+ db.create_task(&task1).unwrap();
+
+ let task2 = Task::new("Setup config", "claude", "my-project");
+ db.create_task(&task2).unwrap();
+
+ let mut task3 = Task::new("Implement endpoints", "claude", "my-project");
+ task3.referenced_tasks = Some(format!("{},{}", task1.id, task2.id));
+ db.create_task(&task3).unwrap();
+
+ let fetched = db.get_task(&task3.id).unwrap().unwrap();
+ let refs = fetched.referenced_tasks.unwrap();
+ assert!(refs.contains(&task1.id));
+ assert!(refs.contains(&task2.id));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_batch_create_tasks_with_index_deps() {
+ let mut db = Database::open_in_memory_project().unwrap();
+
+ // 3 tasks where task[2] depends on task[0] and task[1]
+ let task0 = Task::new("DB schema", "claude", "my-project");
+ let task1 = Task::new("Config setup", "claude", "my-project");
+ let mut task2 = Task::new("Endpoints", "claude", "my-project");
+ task2.referenced_tasks = Some(format!("{},{}", task0.id, task1.id));
+
+ db.create_tasks_batch(&[task0.clone(), task1.clone(), task2.clone()])
+ .unwrap();
+
+ let all = db.get_all_tasks().unwrap();
+ assert_eq!(all.len(), 3);
+
+ let fetched = db.get_task(&task2.id).unwrap().unwrap();
+ let refs = fetched.referenced_tasks.unwrap();
+ assert!(refs.contains(&task0.id));
+ assert!(refs.contains(&task1.id));
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_batch_create_tasks_rolls_back_on_failure() {
+ let mut db = Database::open_in_memory_project().unwrap();
+
+ let task0 = Task::new("First task", "claude", "my-project");
+ // task1 deliberately reuses task0's ID to trigger a UNIQUE constraint violation
+ let mut task1 = Task::new("Duplicate ID task", "claude", "my-project");
+ task1.id = task0.id.clone();
+
+ let result = db.create_tasks_batch(&[task0, task1]);
+ assert!(result.is_err(), "batch insert should fail on duplicate ID");
+
+ // Nothing should have been committed
+ let all = db.get_all_tasks().unwrap();
+ assert!(all.is_empty(), "rollback should leave DB empty");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_delete_backlog_task() {
+ let db = Database::open_in_memory_project().unwrap();
+
+ let task = Task::new("Delete me", "claude", "my-project");
+ db.create_task(&task).unwrap();
+
+ db.delete_task(&task.id).unwrap();
+
+ let fetched = db.get_task(&task.id).unwrap();
+ assert!(fetched.is_none());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_update_backlog_task() {
+ let db = Database::open_in_memory_project().unwrap();
+
+ let mut task = Task::new("Original title", "claude", "my-project");
+ task.description = Some("Original desc".to_string());
+ db.create_task(&task).unwrap();
+
+ // Update title and description
+ task.title = "Updated title".to_string();
+ task.description = Some("Updated desc".to_string());
+ task.plugin = Some("gsd".to_string());
+ db.update_task(&task).unwrap();
+
+ let fetched = db.get_task(&task.id).unwrap().unwrap();
+ assert_eq!(fetched.title, "Updated title");
+ assert_eq!(fetched.description.unwrap(), "Updated desc");
+ assert_eq!(fetched.plugin.unwrap(), "gsd");
+ assert_eq!(fetched.status, TaskStatus::Backlog);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_update_task_db_allows_non_backlog_status_change() {
+ let db = Database::open_in_memory_project().unwrap();
+
+ let mut task = Task::new("My task", "claude", "my-project");
+ db.create_task(&task).unwrap();
+
+ // Move to planning status
+ task.status = TaskStatus::Planning;
+ db.update_task(&task).unwrap();
+
+ // DB layer allows update regardless of status (status guard is in MCP layer), verify status changed
+ let fetched = db.get_task(&task.id).unwrap().unwrap();
+ assert_eq!(fetched.status, TaskStatus::Planning);
+}
+
+// === get_tasks_by_status ===
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_get_tasks_by_status_filters_correctly() {
+ let db = Database::open_in_memory_project().unwrap();
+
+ let backlog = Task::new("Backlog task", "claude", "proj");
+ let mut planning = Task::new("Planning task", "claude", "proj");
+ planning.status = TaskStatus::Planning;
+ let mut running = Task::new("Running task", "claude", "proj");
+ running.status = TaskStatus::Running;
+
+ db.create_task(&backlog).unwrap();
+ db.create_task(&planning).unwrap();
+ db.create_task(&running).unwrap();
+
+ let backlog_tasks = db.get_tasks_by_status(TaskStatus::Backlog).unwrap();
+ assert_eq!(backlog_tasks.len(), 1);
+ assert_eq!(backlog_tasks[0].id, backlog.id);
+
+ let planning_tasks = db.get_tasks_by_status(TaskStatus::Planning).unwrap();
+ assert_eq!(planning_tasks.len(), 1);
+ assert_eq!(planning_tasks[0].id, planning.id);
+
+ let done_tasks = db.get_tasks_by_status(TaskStatus::Done).unwrap();
+ assert!(done_tasks.is_empty());
+}
+
+// === update_task / delete_task edge cases ===
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_update_nonexistent_task_is_silent_noop() {
+ let db = Database::open_in_memory_project().unwrap();
+ let task = Task::new("Ghost", "claude", "proj");
+ // Never inserted β€” update should succeed without error and affect nothing
+ db.update_task(&task).unwrap();
+ let fetched = db.get_task(&task.id).unwrap();
+ assert!(fetched.is_none());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_delete_nonexistent_task_is_silent_noop() {
+ let db = Database::open_in_memory_project().unwrap();
+ // Should not error
+ db.delete_task("no-such-id").unwrap();
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_create_and_get_task_with_all_none_optionals() {
+ let db = Database::open_in_memory_project().unwrap();
+ let task = Task::new("Bare task", "claude", "proj");
+ db.create_task(&task).unwrap();
+
+ let fetched = db.get_task(&task.id).unwrap().unwrap();
+ assert_eq!(fetched.title, "Bare task");
+ assert!(fetched.description.is_none());
+ assert!(fetched.plugin.is_none());
+ assert!(fetched.referenced_tasks.is_none());
+ assert!(fetched.escalation_note.is_none());
+ assert!(fetched.base_branch.is_none());
+ assert!(fetched.session_name.is_none());
+ assert!(fetched.worktree_path.is_none());
+ assert!(fetched.branch_name.is_none());
+ assert!(fetched.pr_number.is_none());
+ assert!(fetched.pr_url.is_none());
+}
+
+// === Project (global db) ===
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_upsert_and_get_project() {
+ let db = Database::open_in_memory_global().unwrap();
+
+ let project = Project::new("my-app", "/home/user/my-app");
+ db.upsert_project(&project).unwrap();
+
+ let all = db.get_all_projects().unwrap();
+ assert_eq!(all.len(), 1);
+ assert_eq!(all[0].name, "my-app");
+ assert_eq!(all[0].path, "/home/user/my-app");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_upsert_project_on_conflict_updates_name() {
+ let db = Database::open_in_memory_global().unwrap();
+
+ let mut project = Project::new("old-name", "/home/user/my-app");
+ db.upsert_project(&project).unwrap();
+
+ project.name = "new-name".to_string();
+ db.upsert_project(&project).unwrap();
+
+ let all = db.get_all_projects().unwrap();
+ assert_eq!(all.len(), 1, "upsert should not create a duplicate row");
+ assert_eq!(all[0].name, "new-name");
+}
+
+// === Notifications ===
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_peek_notifications_does_not_consume() {
+ let db = Database::open_in_memory_project().unwrap();
+
+ db.create_notification(&Notification::new("phase completed")).unwrap();
+ db.create_notification(&Notification::new("task ready")).unwrap();
+
+ let first_peek = db.peek_notifications().unwrap();
+ assert_eq!(first_peek.len(), 2);
+
+ // Peek again β€” should still be there
+ let second_peek = db.peek_notifications().unwrap();
+ assert_eq!(second_peek.len(), 2);
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_consume_notifications_clears_table() {
+ let db = Database::open_in_memory_project().unwrap();
+
+ db.create_notification(&Notification::new("event A")).unwrap();
+ db.create_notification(&Notification::new("event B")).unwrap();
+
+ let consumed = db.consume_notifications().unwrap();
+ assert_eq!(consumed.len(), 2);
+
+ // Table should now be empty
+ let after = db.peek_notifications().unwrap();
+ assert!(after.is_empty());
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_consume_notifications_returns_in_order() {
+ let db = Database::open_in_memory_project().unwrap();
+
+ db.create_notification(&Notification::new("first")).unwrap();
+ db.create_notification(&Notification::new("second")).unwrap();
+ db.create_notification(&Notification::new("third")).unwrap();
+
+ let consumed = db.consume_notifications().unwrap();
+ assert_eq!(consumed[0].message, "first");
+ assert_eq!(consumed[1].message, "second");
+ assert_eq!(consumed[2].message, "third");
+}
+
+// === cleanup_old_transition_requests actually deletes ===
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_cleanup_deletes_old_processed_requests() {
+ let db = Database::open_in_memory_project().unwrap();
+
+ let req = TransitionRequest::new("task-1", "move_forward");
+ db.create_transition_request(&req).unwrap();
+
+ // Backdate processed_at to 2 hours ago directly via SQL
+ let two_hours_ago = (chrono::Utc::now() - chrono::Duration::hours(2)).to_rfc3339();
+ db.backdate_transition_processed_at(&req.id, &two_hours_ago).unwrap();
+
+ db.cleanup_old_transition_requests().unwrap();
+
+ let fetched = db.get_transition_request(&req.id).unwrap();
+ assert!(fetched.is_none(), "request older than 1h should be deleted");
+}
+
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_cleanup_keeps_recently_processed_requests() {
+ let db = Database::open_in_memory_project().unwrap();
+
+ let req = TransitionRequest::new("task-1", "move_forward");
+ db.create_transition_request(&req).unwrap();
+ db.mark_transition_processed(&req.id, None).unwrap();
+
+ db.cleanup_old_transition_requests().unwrap();
+
+ let fetched = db.get_transition_request(&req.id).unwrap();
+ assert!(fetched.is_some(), "recently processed request should be kept");
+}