ππΌββοΈ 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: add orchestrator agent (#36)
Fynn FlΓΌgge93910f240309
diff --git a/CLAUDE.md b/CLAUDE.mdindex 142e912..8b00a05 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -13,14 +13,17 @@ cargo build --release# Or run in dashboard mode (no git project required)./target/release/agtx -g++# Enable experimental features (orchestrator agent)+./target/release/agtx --experimental```## Architecture```src/-βββ main.rs # Entry point, CLI arg parsing, AppMode enum-βββ lib.rs # Module exports for integration tests+βββ main.rs # Entry point, CLI arg parsing, AppMode enum, FeatureFlags+βββ lib.rs # Module exports, AppMode, FeatureFlagsβββ skills.rs # Skill constants, agent-native paths, plugin command translationβββ tui/β βββ mod.rs # Re-exports@@ -32,7 +35,7 @@ src/βββ db/β βββ mod.rs # Re-exportsβ βββ schema.rs # Database struct, SQLite operations-β βββ models.rs # Task, Project, TaskStatus enums+β βββ models.rs # Task, Project, TaskStatus, Notification enumsβββ tmux/β βββ mod.rs # Tmux server "agtx", session managementβ βββ operations.rs # TmuxOperations trait (mockable for testing)@@ -44,6 +47,9 @@ src/βββ agent/β βββ mod.rs # Agent definitions, detection, spawn argsβ βββ operations.rs # AgentOperations/CodingAgent traits (mockable)+βββ mcp/+β βββ mod.rs # Re-exports+β βββ server.rs # MCP server (JSON-RPC over stdio) for orchestratorβββ config/βββ mod.rs # GlobalConfig, ProjectConfig, ThemeConfig, WorkflowPlugin@@ -54,7 +60,9 @@ skills/ # Built-in skill files (embedded at compile time)βββ research.md # Research phase instructionsplugins/ # Bundled plugin configs (embedded at compile time)-βββ agtx/plugin.toml # Default workflow with skills and prompts+βββ agtx/+β βββ plugin.toml # Default workflow with skills and prompts+β βββ skills/orchestrate.md # Orchestrator agent skill (experimental)βββ gsd/plugin.toml # Get Shit Done workflowβββ spec-kit/plugin.toml # GitHub spec-kit workflowβββ openspec/plugin.toml # OpenSpec specification framework@@ -68,6 +76,7 @@ tests/βββ board_tests.rs # Board navigation testsβββ git_tests.rs # Git worktree testsβββ agent_tests.rs # Agent detection and spawn args tests+βββ mcp_tests.rs # MCP server testsβββ mock_infrastructure_tests.rs # Mock infrastructure testsβββ shell_popup_tests.rs # Shell popup logic tests```@@ -103,11 +112,11 @@ Plugins customize the task lifecycle per phase. A plugin is a TOML file (`plugin- **supported_agents**: Agent whitelist (empty = all supported)- **auto_dismiss**: Rules to auto-dismiss interactive prompts before sending the task prompt-Phase gating is derived from the config: if a phase's command or prompt contains `{task}`, the phase can be entered directly from Backlog. Otherwise, it requires a prior phase artifact. This replaces the old `research_required` flag β all behavior is now inferred from the plugin TOML.+Phase gating is derived from the config: if a phase's command or prompt contains `{task}`, the phase can be entered directly from Backlog. Otherwise, it requires a prior phase artifact. If a phase has no command AND no prompt (e.g. void plugin), it is ungated and can be entered freely. This replaces the old `research_required` flag β all behavior is now inferred from the plugin TOML.-Plugin resolution: project-local `.agtx/plugins/{name}/` β global `~/.config/agtx/plugins/{name}/` β bundled.+Plugin resolution: project-local `.agtx/plugins/{name}/` β global `~/.config/agtx/plugins/{name}/` β bundled. `load_task_plugin` falls back to bundled plugins when disk load fails, so tasks always resolve their plugin correctly even if the on-disk copy is missing.-Each task stores its plugin name in the database at creation time. Switching the project plugin only affects new tasks.+Each task stores its plugin name explicitly in the database at creation time (e.g. `Some("agtx")`, `Some("gsd")`). Switching the project plugin only affects new tasks.### Skill SystemSkills are markdown files with YAML frontmatter deployed to agent-native discovery paths in worktrees:@@ -168,6 +177,30 @@ Structure:- View sessions: `tmux -L agtx list-windows -a`- Attach: `tmux -L agtx attach`+### Orchestrator Agent (Experimental)+A dedicated Claude Code agent that autonomously manages the kanban board. Enabled with `--experimental`, toggled with `O`.++```+βββββββββββββββ MCP (stdio) ββββββββββββββββ SQLite βββββββ+β Orchestrator β ββββββββββββββββββββ β MCP Server β ββββββββββββββ β DB β+β (Claude Code)β β (agtx serve) β ββββ¬βββ+ββββββββ¬ββββββββ ββββββββββββββββ β+ β send_keys (push-when-idle) β+ββββββββ΄ββββββββ β+β TUI (agtx) β ββββββββββββββββββββββββββββββββββββββββββββββββββββββ+ββββββββββββββββ+```++- **Orchestrator β TUI**: `transition_requests` DB table (commands like "move task X forward")+- **TUI β Orchestrator**: `notifications` DB table, pushed via `send_keys` when orchestrator is idle+- MCP registered per-session via `claude mcp add-json --scope local`, cleaned up on exit+- Orchestrator only manages Planning and Running phases; the user triages Backlog/Research manually and handles merging in Review/Done+- Orchestrator is a coordinator, not a reviewer β it moves tasks forward immediately when phases complete, without inspecting output+- Only "completed phase" notifications are sent (no "entered phase" notifications)+- On startup, if an orchestrator tmux session already exists, it is detected and reconnected; catch-up notifications are created for tasks that completed phases while the TUI was down (deduplicated via `peek_notifications`)++**MCP tools**: `list_tasks`, `get_task` (includes `allowed_actions`), `move_task`, `get_transition_status`, `check_conflicts`, `get_notifications`+### Theme ConfigurationColors configurable via `~/.config/agtx/config.toml`:```toml@@ -198,6 +231,7 @@ color_popup_header = "#69fae7" # Popup headers (light cyan)| `r` | Resume task (Review β Running) || `/` | Search tasks (jumps to and opens task) || `P` | Select workflow plugin |+| `O` | Toggle orchestrator agent (experimental) || `e` | Toggle project sidebar || `q` | Quit |@@ -373,4 +407,5 @@ Detected automatically via `known_agents()` in order of preference:## Future Enhancements- Reopen Done tasks (recreate worktree from preserved branch)-- Notification when agent finishes work+- Orchestrator: support non-Claude agents as orchestrator+- Orchestrator: task deletion notificationsdiff --git a/Cargo.lock b/Cargo.lockindex 9a81f8a..34c177a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -12,6 +12,7 @@ dependencies = ["directories","mockall","ratatui",+ "rmcp","rusqlite","serde","serde_json",@@ -59,6 +60,17 @@ version = "1.0.101"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5f0e0fee31ef5ed1ba1316088939cea399010ed7731dba877ed44aeb407a75ea"+[[package]]+name = "async-trait"+version = "0.1.89"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]+[[package]]name = "atomic"version = "0.6.1"@@ -381,6 +393,12 @@ version = "0.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1"+[[package]]+name = "dyn-clone"+version = "1.0.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"+[[package]]name = "either"version = "1.15.0"@@ -499,6 +517,94 @@ version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "28dd6caf6059519a65843af8fe2a3ae298b14b80179855aeb4adc2c1934ee619"+[[package]]+name = "futures"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-executor",+ "futures-io",+ "futures-sink",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-channel"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"+dependencies = [+ "futures-core",+ "futures-sink",+]++[[package]]+name = "futures-core"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"++[[package]]+name = "futures-executor"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"+dependencies = [+ "futures-core",+ "futures-task",+ "futures-util",+]++[[package]]+name = "futures-io"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"++[[package]]+name = "futures-macro"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "futures-sink"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"++[[package]]+name = "futures-task"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"++[[package]]+name = "futures-util"+version = "0.3.32"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"+dependencies = [+ "futures-channel",+ "futures-core",+ "futures-io",+ "futures-macro",+ "futures-sink",+ "futures-task",+ "memchr",+ "pin-project-lite",+ "slab",+]+[[package]]name = "generic-array"version = "0.14.7"@@ -932,6 +1038,12 @@ dependencies = ["windows-link",]+[[package]]+name = "pastey"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b867cad97c0791bbd3aaa6472142568c6c9e8f71937e98379f584cfb0cf35bec"+[[package]]name = "pest"version = "2.8.6"@@ -1221,6 +1333,26 @@ dependencies = ["thiserror 2.0.18",]+[[package]]+name = "ref-cast"+version = "1.0.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d"+dependencies = [+ "ref-cast-impl",+]++[[package]]+name = "ref-cast-impl"+version = "1.0.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]+[[package]]name = "regex"version = "1.12.3"@@ -1250,6 +1382,41 @@ version = "0.8.9"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c"+[[package]]+name = "rmcp"+version = "0.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4c9c94680f75470ee8083a0667988b5d7b5beb70b9f998a8e51de7c682ce60"+dependencies = [+ "async-trait",+ "base64",+ "chrono",+ "futures",+ "pastey",+ "pin-project-lite",+ "rmcp-macros",+ "schemars",+ "serde",+ "serde_json",+ "thiserror 2.0.18",+ "tokio",+ "tokio-util",+ "tracing",+]++[[package]]+name = "rmcp-macros"+version = "0.16.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90c23c8f26cae4da838fbc3eadfaecf2d549d97c04b558e7bd90526a9c28b42a"+dependencies = [+ "darling",+ "proc-macro2",+ "quote",+ "serde_json",+ "syn 2.0.114",+]+[[package]]name = "rusqlite"version = "0.34.0"@@ -1298,6 +1465,32 @@ version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a50f4cf475b65d88e057964e0e9bb1f0aa9bbb2036dc65c64596b42932536984"+[[package]]+name = "schemars"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2b42f36aa1cd011945615b92222f6bf73c599a102a300334cd7f8dbeec726cc"+dependencies = [+ "chrono",+ "dyn-clone",+ "ref-cast",+ "schemars_derive",+ "serde",+ "serde_json",+]++[[package]]+name = "schemars_derive"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d115b50f4aaeea07e79c1912f645c7513d81715d0420f8bc77a18c6260b307f"+dependencies = [+ "proc-macro2",+ "quote",+ "serde_derive_internals",+ "syn 2.0.114",+]+[[package]]name = "scopeguard"version = "1.2.0"@@ -1340,6 +1533,17 @@ dependencies = ["syn 2.0.114",]+[[package]]+name = "serde_derive_internals"+version = "0.29.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]+[[package]]name = "serde_json"version = "1.0.149"@@ -1416,6 +1620,12 @@ version = "1.0.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b2aa850e253778c88a04c3d7323b043aeda9d3e30d5971937c1855769763678e"+[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"+[[package]]name = "smallvec"version = "1.15.1"@@ -1658,6 +1868,19 @@ dependencies = ["syn 2.0.114",]+[[package]]+name = "tokio-util"+version = "0.7.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"+dependencies = [+ "bytes",+ "futures-core",+ "futures-sink",+ "pin-project-lite",+ "tokio",+]+[[package]]name = "toml"version = "0.8.23"@@ -1699,6 +1922,37 @@ version = "0.1.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"+[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "pin-project-lite",+ "tracing-attributes",+ "tracing-core",+]++[[package]]+name = "tracing-attributes"+version = "0.1.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.114",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+]+[[package]]name = "typenum"version = "1.19.0"diff --git a/Cargo.toml b/Cargo.tomlindex 97fe8b1..61239cc 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -33,7 +33,8 @@ directories = "6.0"chrono = { version = "0.4", features = ["serde"] }uuid = { version = "1.16", features = ["v4"] }-+# MCP server+rmcp = { version = "0.16", features = ["server", "macros", "transport-io"] }[features]default = []diff --git a/README.md b/README.mdindex ada31d2..8aad251 100644--- a/README.md+++ b/README.md@@ -3,15 +3,13 @@[//]: <img src="https://github.com/user-attachments/assets/54ac039b-085e-490b-aacc-36c8e244e313" width="428" /># agtx-### Run and manage multi-agent AI coding workflows in the terminal-Let different AI coding agents collaborate on the same task.+#### An AI agent that manages other coding agents in a terminal kanban board-**Gemini β research**-**Claude β implement**-**Codex β review**+Let different AI coding agents collaborate on the same task, e.g.+**Gemini β research** | **Claude β implement** | **Codex β review**-Plug in any existing spec-driven development framework or specify a custom plugin with per-phase skills,-prompts, artifact tracking and autonomous execution.+Add tasks. Press one key. An orchestrator agent picks it up, plans, and delegates<br/>+to multiple coding agents running in parallel. Come back to changes ready to merge.<br/>@@ -27,48 +25,57 @@ prompts, artifact tracking and autonomous execution.</div>+## Why agtx?-## Features+AI coding tools give you one agent, one task, one terminal. agtx gives you a **kanban board where multiple coding agents work in parallel** β each in its own git worktree, each in its own tmux window, each running autonomously through a spec-driven workflow managed by an orchestrator agent.-- **Multi-project dashboard**: Manage and orchestrate coding agent sessions across all your projects-- **Multi-agent task lifecycle**: Configure different agents per workflow phase β e.g. Gemini for planning, Claude for implementation, Codex for review β with automatic agent switching in the same tmux window-- **Git worktree and tmux isolation**: Each task gets its own worktree and tmux window, keeping work separated-- **Spec-driven development plugins**: Plug in any spec-driven development framework or select from a predefined set of plugins like GSD, Spec-kit or OpenSpec β or define custom skills, prompts and artifact tracking - with automatic execution and tracking at each phase-- **Supported coding agents**: [Claude Code](https://github.com/anthropics/claude-code), [Codex](https://github.com/openai/codex), [Gemini](https://github.com/google-gemini/gemini-cli), [OpenCode](https://github.com/sst/opencode), [Copilot](https://github.com/github/copilot-cli)+With the orchestrator, you don't even manage the board yourself. **An AI agent picks up tasks, delegates work, and ensures getting things done** through planning, implementation, review and resolving conflicts β while you focus on what matters: research, defining tasks, and merging changes.-## Installation+## Features-### Quick Install+- **Orchestrator agent**: A dedicated AI agent that autonomously manages your kanban board via [MCP](https://modelcontextprotocol.io) β delegates to coding agents, advances phases, checks for merge conflicts ([experimental](#orchestrator-agent-experimental))+- **Multi-agent task lifecycle**: Configure different agents per workflow phase β e.g. Gemini for research, Claude for implementation, Codex for review β with automatic agent switching+- **Parallel execution**: Every task gets its own git worktree and tmux window β run as many agents as you want, simultaneously+- **Spec-driven plugins**: Plug in [GSD](https://github.com/fynnfluegge/get-shit-done-cc), [Spec-kit](https://github.com/github/spec-kit), [OpenSpec](https://github.com/Fission-AI/OpenSpec), [BMAD](https://github.com/bmad-code-org/BMAD-METHOD), [Superpowers](https://github.com/obra/superpowers) β or define your own with a single TOML file+- **Multi-project dashboard**: Manage agent sessions across all your projects from one place+- **Works with**: [Claude Code](https://github.com/anthropics/claude-code) | [Codex](https://github.com/openai/codex) | [Gemini CLI](https://github.com/google-gemini/gemini-cli) | [OpenCode](https://github.com/sst/opencode) | [Copilot](https://github.com/github/copilot-cli)++## Quick Start```bash+# Installcurl -fsSL https://raw.githubusercontent.com/fynnfluegge/agtx/main/install.sh | bash++# Run in any git repository+cd your-project && agtx```-### From Source+That's it. Add tasks, press `m` to start agents, watch them work.```bash-cargo build --release-cp target/release/agtx ~/.local/bin/-```+# Dashboard mode β manage all projects+agtx -g-### Requirements+# Orchestrator mode β let an AI manage the board for you+agtx --experimental+```-- **tmux** - Agent sessions run in a dedicated tmux server-- **gh** (optional) - GitHub CLI for PR operations+> [!NOTE]+> Add `.agtx/` to your project's `.gitignore` to avoid committing worktrees and local task data.-## Quick Start+<details>+<summary>Install from source</summary>```bash-# Run in any git repository-cd your-project-agtx--# Or run in dashboard mode (manage all projects)-agtx -g+cargo build --release+cp target/release/agtx ~/.local/bin/```+</details>-> [!NOTE]-> Add `.agtx/` to your project's `.gitignore` to avoid committing worktrees and local task data.+### Requirements++- **tmux** β agent sessions run in a dedicated tmux server+- **gh** (optional) β GitHub CLI for PR operations## Usage@@ -88,6 +95,7 @@ agtx -g| `x` | Delete task || `/` | Search tasks || `P` | Select spec-driven workflow plugin |+| `O` | Toggle orchestrator agent (`--experimental`) || `e` | Toggle project sidebar || `q` | Quit |@@ -159,13 +167,11 @@ review = "codex"running = "codex"```-## Spec-driven Development Plugins--agtx ships with a fully declarative plugin framework β a single TOML file is all it takes to integrate any spec-driven development framework into the task lifecycle.+## Plugins-A plugin defines commands, prompts and artifacts β agtx handles the rest: phase gating, artifact polling, worktree sync, agent switching, and autonomous execution.+One TOML file. That's all it takes to plug any spec-driven framework into the task lifecycle. Define commands, prompts, and artifacts β agtx handles phase gating, artifact polling, worktree sync, agent switching, and autonomous execution.-Press `P` to activate a plugin for the current project. The active plugin is shown in the header bar.+Press `P` to switch plugins. Ships with 7 built-in:| Plugin | Description ||--------|-------------|@@ -197,7 +203,8 @@ Commands are written once in canonical format and automatically translated per aβ Skills, commands, and prompts fully supported Β· π‘ Prompt only, no interactive skill support Β· β Not supported-### Creating a Plugin+<details>+<summary><b>Creating a Plugin</b></summary>Place your plugin at `.agtx/plugins/<name>/plugin.toml` in your project root (or `~/.config/agtx/plugins/<name>/plugin.toml` for global use). It will appear in the plugin selector automatically.@@ -327,6 +334,8 @@ response = "2\nEnter"These override the built-in agtx skills and are automatically deployed to each agent's native discovery path (`.claude/commands/`, `.codex/skills/`, `.gemini/commands/`, etc.) in every worktree.+</details>+## How It Works### Architecture@@ -394,6 +403,56 @@ tmux -L agtx attach- **Worktrees**: `.agtx/worktrees/` in each project- **Tmux**: Dedicated server `agtx` with per-project sessions+## Orchestrator Agent (Experimental)++> Press `O` and walk away. Come back to changes ready to merge.++The orchestrator is an AI agent that **drives other AI agents to completion**. You triage tasks into Planning or Running β the orchestrator takes over from there, advancing each task through its phases until it lands in Review, ready for you to merge.++```bash+agtx --experimental # then press O+```++**What it does:**+- Monitors tasks in Planning and Running+- Advances tasks automatically as phases complete (Planning β Running β Review)+- Respects plugin phase rules β checks `allowed_actions` before each transition++**You triage. It executes.** Move tasks from Backlog into Planning or Running β the orchestrator handles the rest. Merging is your call.++### MCP Integration++The orchestrator communicates with agtx through the [Model Context Protocol (MCP)](https://modelcontextprotocol.io). agtx ships with a built-in MCP server (`agtx serve`) that exposes the kanban board as a set of tools over JSON-RPC via stdio.++```+ββββββββββββββ-β MCP (stdio) ββββββββββββββββ SQLite βββββββ+β Orchestrator β βββββββββββββββββββ β MCP Server β ββββββββββββββ β DB β+β (Claude Code)β β (agtx serve) β ββββ¬βββ+ββββββββ¬ββββββββ ββββββββββββββββ β+ β push-when-idle notifications β+ββββββββ΄ββββββββ β+β TUI (agtx) β ββββββββββββββββββββββββββββββββββββββββββββββββββββ--ββ+ββββββββββββββββ+```++**MCP tools available to the orchestrator:**++| Tool | Description |+|------|-------------|+| `list_tasks` | List all tasks, optionally filtered by status |+| `get_task` | Get task details including `allowed_actions` for valid transitions |+| `move_task` | Queue a state transition (the TUI executes it with full side effects) |+| `get_transition_status` | Check if a queued transition completed or errored |+| `check_conflicts` | Non-destructive merge conflict detection against the default branch |+| `get_notifications` | Manually fetch pending notifications (backup β usually pushed automatically) |++**How it works:**+1. When you press `O`, the TUI registers the MCP server with the orchestrator agent via `claude mcp add-json --scope local`+2. The orchestrator receives phase completion notifications pushed to its tmux pane when idle+3. It reacts by calling `get_task` to check `allowed_actions`, then `move_task` to advance the task+4. The TUI processes the transition request, executes all side effects (agent switching, skill deployment, prompt sending), and updates the database+5. MCP registration is cleaned up when the orchestrator is stopped+## DevelopmentSee [CLAUDE.md](CLAUDE.md) for development documentation.diff --git a/plugins/agtx/skills/orchestrate.md b/plugins/agtx/skills/orchestrate.mdnew file mode 100644index 0000000..3cbf1b0--- /dev/null+++ b/plugins/agtx/skills/orchestrate.md@@ -0,0 +1,82 @@+---+name: agtx-orchestrate+description: Orchestrate the agtx kanban board β advance tasks through planning and running phases, monitor completions, and coordinate multiple agents working in parallel.+---++# Orchestrator Agent++You are the **orchestrator** for an agtx kanban board. Your job is to advance tasks+through the **Planning** and **Running** phases until they reach **Review**.++The user manages the Backlog and Research columns. Once a task lands in Planning,+you take over and drive it to Review β that's where your responsibility ends.++## Available MCP Tools++You have access to these agtx MCP tools:++- **list_tasks** β List all tasks, optionally filtered by status+- **get_task** β Get full details of a specific task. Includes `allowed_actions`+ showing which transitions are valid given the task's status and plugin rules.+- **move_task** β Queue a task state transition (the TUI executes it with full side effects)+ - Actions: `move_forward`+- **get_transition_status** β Check if a queued transition completed+- **get_notifications** β Manually fetch pending notifications (usually not needed β+ notifications are pushed to you automatically when you are idle).++## How You Receive Updates++Notifications are **pushed to you automatically** when you are idle (waiting for input).+You will receive messages like:++```+[agtx] Task "fix-auth-bug" (abc12345) completed phase: planning+```++This is the **only** type of notification you receive β a phase has completed and the+task is ready to advance. Simply react by moving the task forward.+If multiple events happened at once, they are combined with `|` separators in a single message.++## Task Lifecycle++```+Backlog β Research β Planning β Running β Review+ ^^^^^^^^ ^^^^^^^+ you manage these two phases+```++- The user moves tasks from Backlog/Research into Planning (or directly into Running).+- Once a task is in Planning or Running, you are responsible for advancing it.+- Use `move_task` with action `move_forward` to advance a task to its next phase.+- **Review is the final state you manage.** Do not move tasks to Done β the user+ handles merging and cleanup manually.++## Strategy++1. **On startup:** Call `list_tasks` to understand the current board state.+ Check for tasks in Planning or Running that may need advancing.+2. **When notified a task entered Planning:** Note it. Wait for its planning phase+ to complete before advancing.+3. **When notified of phase completion:**+ - Read the task details with `get_task`+ - Check `allowed_actions` β only use actions listed there+ - If the task is in Planning and planning is complete β `move_forward` to Running+ - If the task is in Running and running is complete β `move_forward` to Review+ - If the task is already in Review, your job is done for that task+4. **Concurrency:** Don't worry about how many tasks are active β the user controls+ what enters Planning/Running. Just advance what's there.+5. **Error handling:** If `get_transition_status` shows an error, investigate+ and try a different approach.+6. **When idle:** After processing all current work, simply wait for the next+ notification to arrive. Do not poll in a loop.++## Rules++- **You are a coordinator, not a reviewer.** Your job is to move tasks between phases.+ Do not read, evaluate, or critique the code or plans produced by coding agents.+ A separate agent handles review in the Review phase.+- When a phase completes, advance the task immediately β do not inspect the output.+- Only act on tasks in Planning or Running β never touch Backlog or Research tasks.+- Always check `allowed_actions` before choosing a transition.+- Do not move tasks beyond Review β merging is the user's responsibility.+- When idle with no pending work, just wait β notifications will be pushed to you.diff --git a/src/config/mod.rs b/src/config/mod.rsindex fdc601f..beab35d 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -480,22 +480,27 @@ impl WorkflowPlugin {/// Check if a phase's command or prompt contains `{task}`, meaning the phase/// can receive task context directly and can be entered from Backlog./// If neither command nor prompt has `{task}`, the phase depends on a prior phase.+ /// If no command AND no prompt exist at all (e.g. void plugin), the phase is ungated.pub fn phase_accepts_task(&self, phase: &str) -> bool {- let cmd_has_task = match phase {+ let cmd = match phase {"planning" => self.commands.planning.as_deref(),"running" => self.commands.running.as_deref(),_ => None,- }- .map_or(false, |c| c.contains("{task}"));+ };- let prompt_has_task = match phase {+ let prompt = match phase {"planning" => self.prompts.planning.as_deref(),"running" => self.prompts.running.as_deref(),_ => None,+ };++ // No command and no prompt β ungated (e.g. void plugin)+ if cmd.is_none() && prompt.is_none() {+ return true;}- .map_or(false, |p| p.contains("{task}"));- cmd_has_task || prompt_has_task+ cmd.map_or(false, |c| c.contains("{task}"))+ || prompt.map_or(false, |p| p.contains("{task}"))}/// Check if the given agent is supported by this plugin.diff --git a/src/db/models.rs b/src/db/models.rsindex f4fa69c..8315fd8 100644--- a/src/db/models.rs+++ b/src/db/models.rs@@ -143,6 +143,31 @@ impl Project {}}+/// A queued request for a task state transition (used by MCP server).+/// The TUI polls this table and executes transitions with full side effects.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TransitionRequest {+ pub id: String,+ pub task_id: String,+ pub action: String,+ pub requested_at: DateTime<Utc>,+ pub processed_at: Option<DateTime<Utc>>,+ pub error: Option<String>,+}++impl TransitionRequest {+ pub fn new(task_id: impl Into<String>, action: impl Into<String>) -> Self {+ Self {+ id: uuid::Uuid::new_v4().to_string(),+ task_id: task_id.into(),+ action: action.into(),+ requested_at: Utc::now(),+ processed_at: None,+ error: None,+ }+ }+}+/// Represents a running agent session#[derive(Debug, Clone, Serialize, Deserialize)]pub struct RunningAgent {@@ -171,6 +196,25 @@ impl AgentStatus {}}+/// A notification for the orchestrator agent (pull-based).+/// Events are written to the DB by the TUI and fetched by the orchestrator via MCP.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct Notification {+ pub id: String,+ pub message: String,+ pub created_at: DateTime<Utc>,+}++impl Notification {+ pub fn new(message: impl Into<String>) -> Self {+ Self {+ id: uuid::Uuid::new_v4().to_string(),+ message: message.into(),+ created_at: Utc::now(),+ }+ }+}+/// Phase completion status (runtime-only, not persisted to DB)#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum PhaseStatus {diff --git a/src/db/schema.rs b/src/db/schema.rsindex 3e26d8a..cbecf56 100644--- a/src/db/schema.rs+++ b/src/db/schema.rs@@ -2,7 +2,7 @@ use anyhow::{Context, Result};use rusqlite::{params, Connection};use std::path::Path;-use super::models::{Project, Task, TaskStatus};+use super::models::{Notification, Project, Task, TaskStatus, TransitionRequest};/// Database wrapper for SQLite operationspub struct Database {@@ -117,6 +117,26 @@ impl Database {let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN cycle INTEGER NOT NULL DEFAULT 1", []);let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN referenced_tasks TEXT", []);+ // MCP transition request queue+ self.conn.execute_batch(+ r#"+ CREATE TABLE IF NOT EXISTS transition_requests (+ id TEXT PRIMARY KEY,+ task_id TEXT NOT NULL,+ action TEXT NOT NULL,+ requested_at TEXT NOT NULL,+ processed_at TEXT,+ error TEXT+ );++ CREATE TABLE IF NOT EXISTS notifications (+ id TEXT PRIMARY KEY,+ message TEXT NOT NULL,+ created_at TEXT NOT NULL+ );+ "#,+ )?;+Ok(())}@@ -337,4 +357,147 @@ impl Database {Ok(projects)}++ // === Transition Request Operations (MCP command queue) ===++ pub fn create_transition_request(&self, req: &TransitionRequest) -> Result<()> {+ self.conn.execute(+ r#"+ INSERT INTO transition_requests (id, task_id, action, requested_at, processed_at, error)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6)+ "#,+ params![+ req.id,+ req.task_id,+ req.action,+ req.requested_at.to_rfc3339(),+ req.processed_at.map(|dt| dt.to_rfc3339()),+ req.error,+ ],+ )?;+ Ok(())+ }++ pub fn get_transition_request(&self, id: &str) -> Result<Option<TransitionRequest>> {+ let mut stmt = self+ .conn+ .prepare("SELECT * FROM transition_requests WHERE id = ?1")?;++ let req = stmt+ .query_row(params![id], Self::transition_request_from_row)+ .ok();++ Ok(req)+ }++ pub fn get_pending_transition_requests(&self) -> Result<Vec<TransitionRequest>> {+ let mut stmt = self.conn.prepare(+ "SELECT * FROM transition_requests WHERE processed_at IS NULL ORDER BY requested_at ASC",+ )?;++ let requests = stmt+ .query_map([], Self::transition_request_from_row)?+ .filter_map(|r| r.ok())+ .collect();++ Ok(requests)+ }++ pub fn mark_transition_processed(&self, id: &str, error: Option<&str>) -> Result<()> {+ self.conn.execute(+ "UPDATE transition_requests SET processed_at = ?1, error = ?2 WHERE id = ?3",+ params![chrono::Utc::now().to_rfc3339(), error, id],+ )?;+ Ok(())+ }++ pub fn cleanup_old_transition_requests(&self) -> Result<()> {+ let cutoff = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();+ self.conn.execute(+ "DELETE FROM transition_requests WHERE processed_at IS NOT NULL AND processed_at < ?1",+ params![cutoff],+ )?;+ Ok(())+ }++ fn transition_request_from_row(row: &rusqlite::Row) -> rusqlite::Result<TransitionRequest> {+ Ok(TransitionRequest {+ id: row.get("id")?,+ task_id: row.get("task_id")?,+ action: row.get("action")?,+ requested_at: chrono::DateTime::parse_from_rfc3339(+ &row.get::<_, String>("requested_at")?,+ )+ .map(|dt| dt.with_timezone(&chrono::Utc))+ .unwrap_or_else(|_| chrono::Utc::now()),+ processed_at: row+ .get::<_, Option<String>>("processed_at")?+ .and_then(|s| {+ chrono::DateTime::parse_from_rfc3339(&s)+ .map(|dt| dt.with_timezone(&chrono::Utc))+ .ok()+ }),+ error: row.get("error")?,+ })+ }++ // ββ Notifications βββββββββββββββββββββββββββββββββββββββββββββββββββ++ pub fn create_notification(&self, notif: &Notification) -> Result<()> {+ self.conn.execute(+ "INSERT INTO notifications (id, message, created_at) VALUES (?1, ?2, ?3)",+ params![notif.id, notif.message, notif.created_at.to_rfc3339()],+ )?;+ Ok(())+ }++ /// Peek at pending notifications without consuming them.+ pub fn peek_notifications(&self) -> Result<Vec<Notification>> {+ let mut stmt = self+ .conn+ .prepare("SELECT * FROM notifications ORDER BY created_at ASC")?;++ let notifs: Vec<Notification> = stmt+ .query_map([], |row| {+ Ok(Notification {+ id: row.get("id")?,+ message: row.get("message")?,+ 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()),+ })+ })?+ .filter_map(|r| r.ok())+ .collect();++ Ok(notifs)+ }++ /// Fetch and delete all pending notifications (atomic consume).+ pub fn consume_notifications(&self) -> Result<Vec<Notification>> {+ let mut stmt = self+ .conn+ .prepare("SELECT * FROM notifications ORDER BY created_at ASC")?;++ let notifs: Vec<Notification> = stmt+ .query_map([], |row| {+ Ok(Notification {+ id: row.get("id")?,+ message: row.get("message")?,+ 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()),+ })+ })?+ .filter_map(|r| r.ok())+ .collect();++ self.conn.execute("DELETE FROM notifications", [])?;++ Ok(notifs)+ }}diff --git a/src/git/mod.rs b/src/git/mod.rsindex 19f716e..ee2f2e1 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -91,6 +91,47 @@ pub fn merge_branch(path: &Path, branch: &str, message: &str) -> Result<()> {Ok(())}+/// Check if merging a branch into the base branch would produce conflicts.+/// Uses `git merge-tree --write-tree` (Git 2.38+) for a non-destructive check.+/// Returns Ok((has_conflicts, conflicting_files)).+pub fn check_merge_conflicts(path: &Path, base: &str, branch: &str) -> Result<(bool, Vec<String>)> {+ let output = Command::new("git")+ .current_dir(path)+ .args(["merge-tree", "--write-tree", base, branch])+ .output()+ .context("Failed to run git merge-tree")?;++ if output.status.success() {+ return Ok((false, vec![]));+ }++ // Non-zero exit: parse structured output for conflicting files.+ // git merge-tree outputs lines like "100644 <hash> <stage> <tab><filename>"+ // where stage 1/2/3 indicates conflict (base/ours/theirs).+ // This format is locale-independent (unlike the human-readable CONFLICT messages).+ let stdout = String::from_utf8_lossy(&output.stdout);+ let mut seen = std::collections::HashSet::new();+ let conflicting_files: Vec<String> = stdout+ .lines()+ .filter_map(|line| {+ // Match lines like: "100644 abc123 1\tpath/to/file" or "100644 abc123 2\tpath/to/file"+ let parts: Vec<&str> = line.splitn(4, |c: char| c.is_whitespace()).collect();+ if parts.len() == 4 {+ let stage = parts[2];+ if matches!(stage, "1" | "2" | "3") {+ let filename = parts[3].trim();+ if !filename.is_empty() && seen.insert(filename.to_string()) {+ return Some(filename.to_string());+ }+ }+ }+ None+ })+ .collect();++ Ok((true, conflicting_files))+}+/// Delete a branchpub fn delete_branch(path: &Path, branch: &str, force: bool) -> Result<()> {let flag = if force { "-D" } else { "-d" };diff --git a/src/git/worktree.rs b/src/git/worktree.rsindex 761bf38..a6c7d7d 100644--- a/src/git/worktree.rs+++ b/src/git/worktree.rs@@ -183,7 +183,7 @@ pub fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {}/// Detect the main branch name (main or master)-fn detect_main_branch(project_path: &Path) -> Result<String> {+pub fn detect_main_branch(project_path: &Path) -> Result<String> {// Check if 'main' existslet output = Command::new("git").current_dir(project_path)diff --git a/src/lib.rs b/src/lib.rsindex d0c57bb..f4b738a 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -2,6 +2,7 @@ pub mod agent;pub mod config;pub mod db;pub mod git;+pub mod mcp;pub mod skills;pub mod tmux;pub mod tui;@@ -13,3 +14,10 @@ pub enum AppMode {Dashboard,Project(PathBuf),}++/// Feature flags parsed from CLI arguments+#[derive(Debug, Clone, Default)]+pub struct FeatureFlags {+ /// Enable experimental features (orchestrator agent, etc.)+ pub experimental: bool,+}diff --git a/src/main.rs b/src/main.rsindex 360c412..ab6abdb 100644--- a/src/main.rs+++ b/src/main.rs@@ -1,4 +1,4 @@-use agtx::{agent, config::{self, GlobalConfig}, git, tui, AppMode};+use agtx::{agent, config::{self, GlobalConfig}, git, tui, AppMode, FeatureFlags};use anyhow::Result;use crossterm::{cursor,@@ -14,7 +14,26 @@ async fn main() -> Result<()> {// Parse command line argumentslet args: Vec<String> = std::env::args().collect();- let mode = match args.get(1).map(|s| s.as_str()) {+ // Extract flags (--experimental) from any position+ let experimental = args.iter().any(|a| a == "--experimental");+ let positional_args: Vec<&str> = args.iter()+ .skip(1)+ .filter(|a| !a.starts_with("--"))+ .map(|s| s.as_str())+ .collect();++ let mode = match positional_args.first().copied() {+ Some("mcp-serve") => {+ let project_path = positional_args+ .get(1)+ .map(PathBuf::from)+ .unwrap_or(std::env::current_dir()?);+ let project_path = project_path.canonicalize()?;+ if !git::is_git_repo(&project_path) {+ anyhow::bail!("mcp-serve requires a git project directory");+ }+ return agtx::mcp::serve(project_path).await;+ }Some("-g") => AppMode::Dashboard,Some(".") => AppMode::Project(std::env::current_dir()?),Some(path) => AppMode::Project(PathBuf::from(path)),@@ -29,6 +48,8 @@ async fn main() -> Result<()> {}};+ let flags = FeatureFlags { experimental };+// First-run: determine action based on config/data statelet config_path = GlobalConfig::config_path()?;let config_exists = config_path.exists();@@ -58,7 +79,7 @@ async fn main() -> Result<()> {}// Initialize and run the app- let mut app = tui::App::new(mode)?;+ let mut app = tui::App::new(mode, flags)?;app.run().await?;Ok(())diff --git a/src/mcp/mod.rs b/src/mcp/mod.rsnew file mode 100644index 0000000..06234c7--- /dev/null+++ b/src/mcp/mod.rs@@ -0,0 +1,3 @@+mod server;++pub use server::serve;diff --git a/src/mcp/server.rs b/src/mcp/server.rsnew file mode 100644index 0000000..76b7b27--- /dev/null+++ b/src/mcp/server.rs@@ -0,0 +1,494 @@+use std::path::PathBuf;++use rmcp::{+ ServerHandler, ServiceExt,+ handler::server::{router::tool::ToolRouter, wrapper::Parameters},+ model::{ServerCapabilities, ServerInfo},+ schemars,+ tool, tool_handler, tool_router,+ transport::io::stdio,+};+use serde::{Deserialize, Serialize};++use crate::db::{Database, Task, TaskStatus, TransitionRequest};++// === Parameter types ===++#[derive(Debug, Deserialize, schemars::JsonSchema)]+pub struct ListProjectsParams {}++#[derive(Debug, Deserialize, schemars::JsonSchema)]+pub struct ListTasksParams {+ /// Filter by status: "backlog", "planning", "running", "review", "done". Omit for all tasks.+ #[schemars(description = "Filter by status: backlog, planning, running, review, done")]+ pub status: Option<String>,+}++#[derive(Debug, Deserialize, schemars::JsonSchema)]+pub struct GetTaskParams {+ /// The task ID (UUID)+ #[schemars(description = "The task ID (UUID)")]+ pub task_id: String,+}++#[derive(Debug, Deserialize, schemars::JsonSchema)]+pub struct MoveTaskParams {+ /// The task ID (UUID)+ #[schemars(description = "The task ID (UUID)")]+ pub task_id: String,+ /// Action: "research", "move_forward", "move_to_planning", "move_to_running", "move_to_review", "move_to_done", "resume"+ #[schemars(+ description = "Action: research (start research for backlog task), move_forward, move_to_planning, move_to_running, move_to_review, move_to_done, resume"+ )]+ pub action: String,+}++#[derive(Debug, Deserialize, schemars::JsonSchema)]+pub struct GetTransitionStatusParams {+ /// The transition request ID returned by move_task+ #[schemars(description = "The transition request ID returned by move_task")]+ pub request_id: String,+}++#[derive(Debug, Deserialize, schemars::JsonSchema)]+pub struct CheckConflictsParams {+ /// Optional task ID. If omitted, checks all tasks in Review status.+ #[schemars(description = "Optional task ID. If omitted, checks all tasks in Review status.")]+ pub task_id: Option<String>,+}++#[derive(Debug, Deserialize, schemars::JsonSchema)]+pub struct GetNotificationsParams {}++// === Response types ===++#[derive(Serialize)]+struct ProjectSummary {+ id: String,+ name: String,+ path: String,+}++#[derive(Serialize)]+struct TaskSummary {+ id: String,+ title: String,+ description: Option<String>,+ status: String,+ agent: String,+ branch_name: Option<String>,+ pr_url: Option<String>,+ plugin: Option<String>,+}++#[derive(Serialize)]+struct TaskDetail {+ id: String,+ title: String,+ description: Option<String>,+ status: String,+ agent: String,+ project_id: String,+ session_name: Option<String>,+ worktree_path: Option<String>,+ branch_name: Option<String>,+ pr_number: Option<i32>,+ pr_url: Option<String>,+ plugin: Option<String>,+ cycle: i32,+ created_at: String,+ updated_at: String,+ /// Actions the orchestrator can take on this task given its current status and plugin rules.+ allowed_actions: Vec<String>,+}++#[derive(Serialize)]+struct MoveTaskResult {+ request_id: String,+ message: String,+}++#[derive(Serialize)]+struct TransitionStatusResult {+ request_id: String,+ status: String,+ error: Option<String>,+}++#[derive(Serialize)]+struct ConflictCheckResult {+ task_id: String,+ title: String,+ branch_name: Option<String>,+ has_conflicts: bool,+ conflicting_files: Vec<String>,+ error: Option<String>,+}++#[derive(Serialize)]+struct CheckConflictsResponse {+ main_branch: String,+ results: Vec<ConflictCheckResult>,+}++#[derive(Serialize)]+struct NotificationItem {+ message: String,+ created_at: String,+}++#[derive(Serialize)]+struct GetNotificationsResponse {+ notifications: Vec<NotificationItem>,+}++// === MCP Server ===++#[derive(Debug, Clone)]+pub struct AgtxMcpServer {+ project_path: PathBuf,+ tool_router: ToolRouter<Self>,+}++impl AgtxMcpServer {+ fn new(project_path: PathBuf) -> Self {+ Self {+ project_path,+ tool_router: Self::tool_router(),+ }+ }++ fn open_project_db(&self) -> Result<Database, String> {+ Database::open_project(&self.project_path).map_err(|e| format!("Failed to open project database: {}", e))+ }++ fn open_global_db(&self) -> Result<Database, String> {+ Database::open_global().map_err(|e| format!("Failed to open global database: {}", e))+ }++ /// 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();++ let plugin = match &task.plugin {+ Some(name) => crate::config::WorkflowPlugin::load(name, Some(&self.project_path))+ .ok()+ .or_else(|| crate::skills::load_bundled_plugin(name)),+ None => crate::skills::load_bundled_plugin("agtx"),+ };++ match task.status {+ TaskStatus::Backlog => {+ // Orchestrator does not manage Backlog β user triages manually+ }+ TaskStatus::Planning => {+ actions.push("move_forward".to_string());+ }+ TaskStatus::Running => {+ actions.push("move_forward".to_string());+ }+ TaskStatus::Review => {+ actions.push("move_to_done".to_string());+ actions.push("resume".to_string());+ }+ TaskStatus::Done => {}+ }++ actions+ }+}++#[tool_router]+impl AgtxMcpServer {+ #[tool(description = "List all projects indexed by agtx")]+ fn list_projects(&self, _params: Parameters<ListProjectsParams>) -> String {+ match self.open_global_db() {+ Ok(db) => match db.get_all_projects() {+ Ok(projects) => {+ let summaries: Vec<ProjectSummary> = projects+ .into_iter()+ .map(|p| ProjectSummary {+ id: p.id,+ name: p.name,+ path: p.path,+ })+ .collect();+ serde_json::to_string_pretty(&summaries).unwrap_or_else(|e| format!("Error serializing: {}", e))+ }+ Err(e) => format!("Error listing projects: {}", e),+ },+ Err(e) => e,+ }+ }++ #[tool(description = "List tasks for the current project, optionally filtered by status (backlog, planning, running, review, done)")]+ fn list_tasks(&self, Parameters(params): Parameters<ListTasksParams>) -> String {+ match self.open_project_db() {+ Ok(db) => {+ let tasks_result = if let Some(status_str) = ¶ms.status {+ match TaskStatus::from_str(status_str) {+ Some(status) => db.get_tasks_by_status(status),+ None => return format!("Invalid status: '{}'. Valid values: backlog, planning, running, review, done", status_str),+ }+ } else {+ db.get_all_tasks()+ };+ match tasks_result {+ Ok(tasks) => {+ let summaries: Vec<TaskSummary> = tasks+ .into_iter()+ .map(|t| TaskSummary {+ id: t.id,+ title: t.title,+ description: t.description,+ status: t.status.as_str().to_string(),+ agent: t.agent,+ branch_name: t.branch_name,+ pr_url: t.pr_url,+ plugin: t.plugin,+ })+ .collect();+ serde_json::to_string_pretty(&summaries).unwrap_or_else(|e| format!("Error serializing: {}", e))+ }+ Err(e) => format!("Error listing tasks: {}", e),+ }+ }+ Err(e) => e,+ }+ }++ #[tool(description = "Get full details of a specific task by its ID. Includes allowed_actions based on the task's current status and plugin rules.")]+ fn get_task(&self, Parameters(params): Parameters<GetTaskParams>) -> String {+ match self.open_project_db() {+ Ok(db) => match db.get_task(¶ms.task_id) {+ Ok(Some(t)) => {+ let allowed = self.allowed_actions(&t);+ let detail = TaskDetail {+ id: t.id,+ title: t.title,+ description: t.description,+ status: t.status.as_str().to_string(),+ agent: t.agent,+ project_id: t.project_id,+ session_name: t.session_name,+ worktree_path: t.worktree_path,+ branch_name: t.branch_name,+ pr_number: t.pr_number,+ pr_url: t.pr_url,+ plugin: t.plugin,+ cycle: t.cycle,+ created_at: t.created_at.to_rfc3339(),+ updated_at: t.updated_at.to_rfc3339(),+ allowed_actions: allowed,+ };+ serde_json::to_string_pretty(&detail).unwrap_or_else(|e| format!("Error serializing: {}", e))+ }+ Ok(None) => format!("Task not found: {}", params.task_id),+ Err(e) => format!("Error getting task: {}", e),+ },+ Err(e) => e,+ }+ }++ #[tool(description = "Queue a task state transition. The agtx TUI will process it and execute all side effects (worktree creation, agent spawning, etc). Use get_transition_status to check completion. Actions: research (start research phase for backlog task), move_forward, move_to_planning, move_to_running, move_to_review, move_to_done, resume")]+ fn move_task(&self, Parameters(params): Parameters<MoveTaskParams>) -> String {+ let valid_actions = [+ "research",+ "move_forward",+ "move_to_planning",+ "move_to_running",+ "move_to_review",+ "move_to_done",+ "resume",+ ];+ if !valid_actions.contains(¶ms.action.as_str()) {+ return format!(+ "Invalid action: '{}'. Valid actions: {}",+ params.action,+ valid_actions.join(", ")+ );+ }++ match self.open_project_db() {+ Ok(db) => {+ // Verify task exists+ match db.get_task(¶ms.task_id) {+ Ok(Some(_)) => {}+ Ok(None) => return format!("Task not found: {}", params.task_id),+ Err(e) => return format!("Error checking task: {}", e),+ }++ let req = TransitionRequest::new(¶ms.task_id, ¶ms.action);+ let request_id = req.id.clone();++ match db.create_transition_request(&req) {+ Ok(()) => {+ let result = MoveTaskResult {+ request_id,+ message: format!(+ "Transition '{}' queued for task {}. The agtx TUI will process it shortly.",+ params.action, params.task_id+ ),+ };+ serde_json::to_string_pretty(&result)+ .unwrap_or_else(|e| format!("Error serializing: {}", e))+ }+ Err(e) => format!("Error creating transition request: {}", e),+ }+ }+ Err(e) => e,+ }+ }++ #[tool(description = "Check the status of a queued transition request. Returns pending, completed, or error with details.")]+ fn get_transition_status(+ &self,+ Parameters(params): Parameters<GetTransitionStatusParams>,+ ) -> String {+ match self.open_project_db() {+ Ok(db) => match db.get_transition_request(¶ms.request_id) {+ Ok(Some(req)) => {+ let status = if req.processed_at.is_some() {+ if req.error.is_some() {+ "error"+ } else {+ "completed"+ }+ } else {+ "pending"+ };+ let result = TransitionStatusResult {+ request_id: req.id,+ status: status.to_string(),+ error: req.error,+ };+ serde_json::to_string_pretty(&result)+ .unwrap_or_else(|e| format!("Error serializing: {}", e))+ }+ Ok(None) => format!("Transition request not found: {}", params.request_id),+ Err(e) => format!("Error getting transition status: {}", e),+ },+ Err(e) => e,+ }+ }++ #[tool(description = "Check if task branches have merge conflicts with the main branch. Pass a task_id to check one task, or omit it to check all Review tasks. Uses a read-only git check β no files are modified.")]+ fn check_conflicts(&self, Parameters(params): Parameters<CheckConflictsParams>) -> String {+ let main_branch = match crate::git::detect_main_branch(&self.project_path) {+ Ok(b) => b,+ Err(e) => return format!("Failed to detect main branch: {}", e),+ };++ let tasks = match self.open_project_db() {+ Ok(db) => {+ if let Some(task_id) = ¶ms.task_id {+ match db.get_task(task_id) {+ Ok(Some(t)) => vec![t],+ Ok(None) => return format!("Task not found: {}", task_id),+ Err(e) => return format!("Error getting task: {}", e),+ }+ } else {+ match db.get_tasks_by_status(TaskStatus::Review) {+ Ok(tasks) => tasks,+ Err(e) => return format!("Error listing review tasks: {}", e),+ }+ }+ }+ Err(e) => return e,+ };++ let results: Vec<ConflictCheckResult> = tasks+ .into_iter()+ .map(|t| {+ let branch = match &t.branch_name {+ Some(b) => b.clone(),+ None => {+ return ConflictCheckResult {+ task_id: t.id,+ title: t.title,+ branch_name: None,+ has_conflicts: false,+ conflicting_files: vec![],+ error: Some("No branch name set for this task".to_string()),+ };+ }+ };++ match crate::git::check_merge_conflicts(&self.project_path, &main_branch, &branch) {+ Ok((has_conflicts, files)) => ConflictCheckResult {+ task_id: t.id,+ title: t.title,+ branch_name: Some(branch),+ has_conflicts,+ conflicting_files: files,+ error: None,+ },+ Err(e) => ConflictCheckResult {+ task_id: t.id,+ title: t.title,+ branch_name: Some(branch),+ has_conflicts: false,+ conflicting_files: vec![],+ error: Some(format!("{}", e)),+ },+ }+ })+ .collect();++ let response = CheckConflictsResponse {+ main_branch,+ results,+ };+ serde_json::to_string_pretty(&response).unwrap_or_else(|e| format!("Error serializing: {}", e))+ }++ #[tool(description = "Fetch and consume pending notifications. Returns new events (task created, phase completed, etc.) and removes them from the queue. Note: notifications are also pushed to your input automatically when you are idle, so you usually don't need to call this manually.")]+ fn get_notifications(&self, _params: Parameters<GetNotificationsParams>) -> String {+ match self.open_project_db() {+ Ok(db) => match db.consume_notifications() {+ Ok(notifs) => {+ let items: Vec<NotificationItem> = notifs+ .into_iter()+ .map(|n| NotificationItem {+ message: n.message,+ created_at: n.created_at.to_rfc3339(),+ })+ .collect();+ let response = GetNotificationsResponse {+ notifications: items,+ };+ serde_json::to_string_pretty(&response)+ .unwrap_or_else(|e| format!("Error serializing: {}", e))+ }+ Err(e) => format!("Error fetching notifications: {}", e),+ },+ Err(e) => e,+ }+ }+}++#[tool_handler]+impl ServerHandler for AgtxMcpServer {+ fn get_info(&self) -> ServerInfo {+ 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."+ .into(),+ ),+ capabilities: ServerCapabilities::builder().enable_tools().build(),+ ..Default::default()+ }+ }+}++pub async fn serve(project_path: PathBuf) -> anyhow::Result<()> {+ // Validate project DB can be opened+ Database::open_project(&project_path)?;++ let server = AgtxMcpServer::new(project_path);+ let service = server.serve(stdio()).await?;+ service.waiting().await?;+ Ok(())+}diff --git a/src/skills.rs b/src/skills.rsindex 6e529fe..31d4447 100644--- a/src/skills.rs+++ b/src/skills.rs@@ -6,6 +6,7 @@ pub const RESEARCH_SKILL: &str = include_str!("../plugins/agtx/skills/research.mpub const PLAN_SKILL: &str = include_str!("../plugins/agtx/skills/plan.md");pub const EXECUTE_SKILL: &str = include_str!("../plugins/agtx/skills/execute.md");pub const REVIEW_SKILL: &str = include_str!("../plugins/agtx/skills/review.md");+pub const ORCHESTRATE_SKILL: &str = include_str!("../plugins/agtx/skills/orchestrate.md");pub const MERGE_CONFLICTS_SKILL: &str = include_str!("../plugins/agtx/skills/merge-conflicts.md");/// Default built-in skills: (directory_name, SKILL.md content)@@ -15,6 +16,7 @@ pub const BUILTIN_SKILLS: &[(&str, &str)] = &[("agtx-plan", PLAN_SKILL),("agtx-execute", EXECUTE_SKILL),("agtx-review", REVIEW_SKILL),+ ("agtx-orchestrate", ORCHESTRATE_SKILL),("agtx-merge-conflicts", MERGE_CONFLICTS_SKILL),];diff --git a/src/tui/app.rs b/src/tui/app.rsindex db5a46c..1fc25e9 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -13,7 +13,7 @@ use std::time::Instant;use crate::agent::{self, AgentOperations};use crate::config::{GlobalConfig, MergedConfig, ProjectConfig, ThemeConfig, WorkflowPlugin};-use crate::db::{Database, PhaseStatus, Task, TaskStatus};+use crate::db::{Database, PhaseStatus, Task, TaskStatus, TransitionRequest};use crate::git::{self, GitOperations, GitProviderOperations, PullRequestState, RealGitHubOps, RealGitOps};use crate::skills;use crate::tmux::{self, RealTmuxOps, TmuxOperations};@@ -158,6 +158,7 @@ const SHELL_POPUP_HEIGHT_PERCENT: u16 = 75; // Percentage of terminal height/// Application state (separate from terminal for borrow checker)struct AppState {mode: AppMode,+ flags: crate::FeatureFlags,should_quit: bool,board: BoardState,input_mode: InputMode,@@ -239,6 +240,12 @@ struct AppState {warning_message: Option<(String, Instant)>,// Plugin selection popupplugin_select_popup: Option<PluginSelectPopup>,+ // Orchestrator agent tmux target (e.g. "project:orchestrator")+ orchestrator_session: Option<String>,+ // Orchestrator idle detection for push notifications+ orchestrator_last_content: String,+ orchestrator_stable_since: Option<Instant>,+ orchestrator_last_check: Instant,// Background session refresh channel (non-blocking phase status polling)session_refresh_rx: Option<mpsc::Receiver<SessionRefreshResult>>,}@@ -431,9 +438,10 @@ pub struct App {}impl App {- pub fn new(mode: AppMode) -> Result<Self> {+ pub fn new(mode: AppMode, flags: crate::FeatureFlags) -> Result<Self> {Self::with_ops(mode,+ flags,Arc::new(RealTmuxOps),Arc::new(RealGitOps),Arc::new(RealGitHubOps),@@ -443,6 +451,7 @@ impl App {pub fn with_ops(mode: AppMode,+ flags: crate::FeatureFlags,tmux_ops: Arc<dyn TmuxOperations>,git_ops: Arc<dyn GitOperations>,git_provider_ops: Arc<dyn GitProviderOperations>,@@ -492,6 +501,7 @@ impl App {terminal,state: AppState {mode,+ flags,should_quit: false,board: BoardState::new(),input_mode: InputMode::Normal,@@ -542,6 +552,10 @@ impl App {cached_plugin: None,warning_message: None,plugin_select_popup: None,+ orchestrator_session: None,+ orchestrator_last_content: String::new(),+ orchestrator_stable_since: None,+ orchestrator_last_check: Instant::now(),session_refresh_rx: None,},};@@ -557,6 +571,47 @@ impl App {// Load projects from global databaseapp.refresh_projects()?;+ // Detect existing orchestrator session (survives agtx restarts)+ if app.state.flags.experimental {+ let orch_target = format!("{}:orchestrator", app.state.project_name);+ if app.state.tmux_ops.window_exists(&orch_target).unwrap_or(false) {+ app.state.orchestrator_session = Some(orch_target);++ // Catch up: notify orchestrator about tasks that completed while TUI was down+ if let Some(ref db) = app.state.db {+ // Check existing notifications to avoid duplicates+ let existing: HashSet<String> = db.peek_notifications()+ .unwrap_or_default()+ .into_iter()+ .map(|n| n.message)+ .collect();++ for task in &app.state.board.tasks {+ if !matches!(task.status, TaskStatus::Planning | TaskStatus::Running) {+ continue;+ }+ let plugin = match &task.plugin {+ Some(name) => WorkflowPlugin::load(name, app.state.project_path.as_deref()).ok(),+ None => skills::load_bundled_plugin("agtx"),+ };+ if let Some(ref wt) = task.worktree_path {+ if phase_artifact_exists(wt, task.status, &plugin, task.cycle) {+ let short_id = if task.id.len() >= 8 { &task.id[..8] } else { &task.id };+ let message = format!(+ "Task \"{}\" ({}) completed phase: {}",+ task.title, short_id, task.status.as_str()+ );+ if !existing.contains(&message) {+ let notif = crate::db::Notification::new(message);+ let _ = db.create_notification(¬if);+ }+ }+ }+ }+ }+ }+ }+Ok(app)}@@ -592,6 +647,7 @@ impl App {terminal,state: AppState {mode,+ flags: crate::FeatureFlags::default(),should_quit: false,board: BoardState::new(),input_mode: InputMode::Normal,@@ -642,6 +698,10 @@ impl App {cached_plugin: None,warning_message: None,plugin_select_popup: None,+ orchestrator_session: None,+ orchestrator_last_content: String::new(),+ orchestrator_stable_since: None,+ orchestrator_last_check: Instant::now(),session_refresh_rx: None,},})@@ -714,6 +774,9 @@ impl App {}}+ // Process MCP transition requests from the command queue+ self.process_transition_requests()?;+if event::poll(std::time::Duration::from_millis(100))? {if let Event::Key(key) = event::read()? {if key.kind == KeyEventKind::Press {@@ -744,6 +807,9 @@ impl App {// Spawn background refresh if not already running and cache expiredself.maybe_spawn_session_refresh();+ // Deliver queued notifications to orchestrator when idle+ self.deliver_orchestrator_notifications();+// Clear expired warning messagesif let Some((_, created)) = &self.state.warning_message {if created.elapsed() >= std::time::Duration::from_secs(5) {@@ -811,11 +877,19 @@ impl App {// Headerlet plugin_label = state.config.workflow_plugin.as_deref().unwrap_or("agtx");let left = Span::styled(format!(" {} ", state.project_name), Style::default().fg(Color::Cyan).bold());- let right_spans: Vec<Span> = vec![+ let mut right_spans: Vec<Span> = Vec::new();+ if state.flags.experimental {+ let orch_active = state.orchestrator_session.is_some();+ if orch_active {+ right_spans.push(Span::styled("β ", Style::default().fg(Color::Green)));+ right_spans.push(Span::styled("orchestrator ", Style::default().fg(Color::Green)));+ }+ right_spans.push(Span::styled("[O] ", Style::default().fg(hex_to_color(&state.config.theme.color_dimmed))));+ }+ right_spans.extend([Span::styled(format!("{} ", plugin_label), Style::default().fg(hex_to_color(&state.config.theme.color_accent))),Span::styled("[P] ", Style::default().fg(hex_to_color(&state.config.theme.color_dimmed))),- Span::styled("Plugins ", Style::default().fg(hex_to_color(&state.config.theme.color_dimmed))),- ];+ ]);let left_len = state.project_name.len() + 2;let right_len: usize = right_spans.iter().map(|s| s.content.len()).sum();let padding = (chunks[0].width as usize).saturating_sub(left_len + right_len + 2); // 2 for borders@@ -2089,12 +2163,12 @@ impl App {}fn open_plugin_select_popup(&mut self) {- let current = self.state.config.workflow_plugin.as_deref().unwrap_or("");+ let current = self.state.config.workflow_plugin.as_deref().unwrap_or("agtx");let mut options = vec![PluginOption {- name: String::new(),+ name: "agtx".to_string(),label: "agtx".to_string(),description: "Built-in workflow with skills and prompts".to_string(),- active: current.is_empty(),+ active: current == "agtx",}];for (name, desc, _content) in skills::BUNDLED_PLUGINS {if *name == "agtx" { continue; }@@ -2144,8 +2218,8 @@ impl App {// Load current project configlet mut project_config = ProjectConfig::load(&project_path).unwrap_or_default();- if plugin_name.is_empty() {- // Clear plugin+ if plugin_name.is_empty() || plugin_name == "agtx" {+ // agtx is the default β clear explicit settingproject_config.workflow_plugin = None;} else {// Find bundled plugin content and write it@@ -2767,6 +2841,10 @@ impl App {// Open plugin selection popupself.open_plugin_select_popup();}+ KeyCode::Char('O') if self.state.flags.experimental => {+ // Toggle orchestrator agent (experimental)+ self.toggle_orchestrator()?;+ }_ => {}}Ok(())@@ -3285,6 +3363,8 @@ impl App {task.referenced_tasks = refs;// Task starts in Backlog without tmux windowdb.create_task(&task)?;++ // No orchestrator notification for Backlog β orchestrator only manages Planning/Running}self.refresh_tasks()?;}@@ -3298,18 +3378,18 @@ impl App {.and_then(|db| db.get_task(task_id).ok().flatten()).and_then(|t| t.plugin.clone()).or_else(|| self.state.config.workflow_plugin.clone())- .unwrap_or_default()+ .unwrap_or_else(|| "agtx".to_string())} else {- self.state.config.workflow_plugin.as_deref().unwrap_or("").to_string()+ self.state.config.workflow_plugin.as_deref().unwrap_or("agtx").to_string()};let selected_agent_name = &self.state.config.default_agent;let mut options = vec![PluginOption {- name: String::new(),+ name: "agtx".to_string(),label: "agtx".to_string(),description: "Built-in workflow with skills and prompts".to_string(),- active: current.is_empty(),+ active: current == "agtx",}];for (name, desc, content) in skills::BUNDLED_PLUGINS {if *name == "agtx" { continue; }@@ -3466,6 +3546,7 @@ impl App {db.update_task(&task)?;}}+}self.refresh_tasks()?;Ok(())@@ -3902,11 +3983,21 @@ impl App {/// 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() {+ Some(t) if t.status == TaskStatus::Backlog => t.id.clone(),+ _ => return Ok(()),+ };+ self.move_backlog_to_running_by_id(&task_id)+ }++ fn move_backlog_to_running_by_id(&mut self, task_id: &str) -> Result<()> {// Don't start if a setup is already in progress- if self.state.setup_rx.is_some() { return Ok(()) }+ if self.state.setup_rx.is_some() {+ anyhow::bail!("Another task setup is already in progress, try again shortly");+ }let (mut task, project_path) = match (- self.state.board.selected_task().cloned(),+ 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),@@ -3914,7 +4005,7 @@ impl App {};if task.status != TaskStatus::Backlog {- return Ok(());+ anyhow::bail!("Task must be in Backlog to move to Running (current: {})", task.status.as_str());}// Stamp plugin on task before checking research requirement@@ -4137,6 +4228,310 @@ impl App {Ok(())}+ // === MCP Transition Request Processing ===++ /// Poll the transition_requests table for unprocessed requests and execute them.+ fn process_transition_requests(&mut self) -> Result<()> {+ let Some(db) = &self.state.db else { return Ok(()) };+ let pending = db.get_pending_transition_requests()?;+ if pending.is_empty() {+ return Ok(());+ }++ for req in pending {+ let result = self.execute_transition_request(&req);+ if let Some(db) = &self.state.db {+ match &result {+ Ok(()) => {+ let _ = db.mark_transition_processed(&req.id, None);+ }+ Err(e) => {+ let _ = db.mark_transition_processed(&req.id, Some(&e.to_string()));+ }+ }+ }+ self.refresh_tasks()?;+ }++ // Periodically clean up old processed requests+ if let Some(db) = &self.state.db {+ let _ = db.cleanup_old_transition_requests();+ }++ Ok(())+ }++ fn execute_transition_request(&mut self, req: &TransitionRequest) -> Result<()> {+ let Some(db) = &self.state.db else {+ anyhow::bail!("No project database");+ };+ let Some(project_path) = self.state.project_path.clone() else {+ anyhow::bail!("No project path");+ };++ let mut task = db+ .get_task(&req.task_id)?+ .ok_or_else(|| anyhow::anyhow!("Task not found: {}", req.task_id))?;++ match req.action.as_str() {+ "research" => {+ if task.status != TaskStatus::Backlog {+ anyhow::bail!(+ "Task must be in Backlog to start research (current: {})",+ task.status.as_str()+ );+ }+ if task.session_name.is_some() {+ anyhow::bail!("Task already has an active session (research may already be running)");+ }+ self.start_research(&req.task_id)?;+ }+ "move_forward" => {+ self.execute_forward_transition(&mut task, &project_path)?;+ }+ "move_to_planning" => {+ if task.status != TaskStatus::Backlog {+ anyhow::bail!(+ "Task must be in Backlog to move to Planning (current: {})",+ task.status.as_str()+ );+ }+ self.execute_forward_transition(&mut task, &project_path)?;+ }+ "move_to_running" => {+ if task.status != TaskStatus::Planning && task.status != TaskStatus::Backlog {+ anyhow::bail!(+ "Task must be in Backlog or Planning to move to Running (current: {})",+ task.status.as_str()+ );+ }+ if task.status == TaskStatus::Backlog {+ self.move_backlog_to_running_by_id(&req.task_id)?;+ } else {+ self.execute_forward_transition(&mut task, &project_path)?;+ }+ }+ "move_to_review" => {+ if task.status != TaskStatus::Running {+ anyhow::bail!(+ "Task must be in Running to move to Review (current: {})",+ task.status.as_str()+ );+ }+ self.mcp_transition_to_review(&mut task)?;+ }+ "move_to_done" => {+ if task.status != TaskStatus::Review {+ anyhow::bail!(+ "Task must be in Review to move to Done (current: {})",+ task.status.as_str()+ );+ }+ self.force_move_to_done(&task.id)?;+ }+ "resume" => {+ if task.status != TaskStatus::Review {+ anyhow::bail!(+ "Task must be in Review to resume (current: {})",+ task.status.as_str()+ );+ }+ self.move_review_to_running(&req.task_id)?;+ }+ other => {+ anyhow::bail!("Unknown action: {}", other);+ }+ }++ Ok(())+ }++ /// Execute a forward transition (next column), mirroring move_task_right logic.+ fn execute_forward_transition(&mut self, task: &mut Task, project_path: &Path) -> Result<()> {+ let next_status = match task.status {+ TaskStatus::Backlog => TaskStatus::Planning,+ TaskStatus::Planning => TaskStatus::Running,+ TaskStatus::Running => TaskStatus::Review,+ TaskStatus::Review => TaskStatus::Done,+ TaskStatus::Done => anyhow::bail!("Task is already Done"),+ };++ // Skip the phase-incomplete confirmation for MCP requests+ let handled = match (task.status, next_status) {+ (TaskStatus::Backlog, TaskStatus::Planning) => {+ if self.state.setup_rx.is_some() {+ anyhow::bail!("Another task setup is already in progress, try again shortly");+ }+ self.transition_to_planning(task, project_path)?+ }+ (TaskStatus::Planning, TaskStatus::Running) => self.transition_to_running(task)?,+ (TaskStatus::Running, TaskStatus::Review) => {+ self.mcp_transition_to_review(task)?;+ return Ok(());+ }+ (TaskStatus::Review, TaskStatus::Done) => {+ self.force_move_to_done(&task.id)?;+ return Ok(());+ }+ _ => false,+ };++ if !handled {+ task.status = next_status;+ task.updated_at = chrono::Utc::now();+ if let Some(db) = &self.state.db {+ db.update_task(task)?;+ }+ }++ Ok(())+ }++ /// MCP version of transition_to_review: sends review prompt but skips PR popup.+ fn mcp_transition_to_review(&mut self, task: &mut Task) -> Result<()> {+ let (review_agent, agent_switch) = needs_agent_switch(&self.state.config, task, "review");+ if let Some(session_name) = &task.session_name {+ let plugin = self.load_task_plugin(task);+ let task_content = task.content_text();+ let skill_cmd =+ resolve_skill_command(&plugin, "review", &review_agent, &task_content, task.cycle);+ let prompt =+ resolve_prompt(&plugin, "review", &task_content, &task.id, task.cycle);+ let prompt_trigger = resolve_prompt_trigger(&plugin, "review");+ let auto_dismiss = plugin+ .as_ref()+ .map_or_else(Vec::new, |p| p.auto_dismiss.clone());+ spawn_send_to_agent(+ Arc::clone(&self.state.tmux_ops),+ Arc::clone(&self.state.agent_registry),+ session_name.clone(),+ task.agent.clone(),+ review_agent.clone(),+ agent_switch,+ skill_cmd,+ prompt,+ prompt_trigger,+ task_content,+ auto_dismiss,+ );+ }+ task.agent = review_agent;+ task.status = TaskStatus::Review;+ task.updated_at = chrono::Utc::now();+ if let Some(db) = &self.state.db {+ db.update_task(task)?;+ }+ Ok(())+ }++ /// Toggle orchestrator agent: spawn if not running, view if running.+ fn toggle_orchestrator(&mut self) -> Result<()> {+ let project_path = match &self.state.project_path {+ Some(p) => p.clone(),+ None => {+ self.state.warning_message = Some((+ "Orchestrator requires a project (not dashboard mode)".to_string(),+ Instant::now(),+ ));+ return Ok(());+ }+ };++ let project_name = self.state.project_name.clone();+ let window_name = "orchestrator";+ let orch_target = format!("{}:{}", project_name, window_name);++ // If orchestrator is running, open the popup to view it+ if let Some(ref orch_target) = self.state.orchestrator_session {+ if self.state.tmux_ops.window_exists(orch_target).unwrap_or(false) {+ let mut popup = ShellPopup::new("Orchestrator".to_string(), orch_target.clone());+ if let Ok((_term_width, term_height)) = crossterm::terminal::size() {+ let pane_width = SHELL_POPUP_CONTENT_WIDTH;+ let popup_height = (term_height as u32 * SHELL_POPUP_HEIGHT_PERCENT as u32 / 100) as u16;+ let pane_height = popup_height.saturating_sub(4);+ let _ = self.state.tmux_ops.resize_window(orch_target, pane_width, pane_height);+ popup.last_pane_size = Some((pane_width, pane_height));+ std::thread::sleep(std::time::Duration::from_millis(200));+ }+ popup.cached_content = capture_tmux_pane_with_history(orch_target, 500, self.state.tmux_ops.as_ref());+ self.state.shell_popup = Some(popup);+ return Ok(());+ } else {+ // Window gone, clear the session+ self.state.orchestrator_session = None;+ }+ }++ // Spawn new orchestrator+ let default_agent = self.state.config.default_agent.clone();+ let agent = self.state.agent_registry.get(&default_agent);+ let project_path_str = project_path.to_string_lossy().to_string();++ // Build MCP registration JSON for the agtx server+ let agtx_bin = std::env::current_exe()+ .unwrap_or_else(|_| PathBuf::from("agtx"))+ .to_string_lossy()+ .to_string();+ let mcp_json = serde_json::json!({+ "type": "stdio",+ "command": agtx_bin,+ "args": ["mcp-serve", &project_path_str]+ });+ let mcp_json_str = mcp_json.to_string().replace('\'', "'\\''");++ // Build agent command: register MCP in local scope, launch agent, clean up on exit+ // --scope local stores in ~/.claude.json tied to project path (not in project files)+ let agent_base = agent.build_interactive_command("");+ let agent_cmd = match default_agent.as_str() {+ "claude" => format!(+ "claude mcp add-json agtx '{}' --scope local && {}; claude mcp remove agtx --scope local",+ mcp_json_str, agent_base+ ),+ _ => agent_base,+ };++ // Ensure project tmux session exists+ ensure_project_tmux_session(&project_name, &project_path, self.state.tmux_ops.as_ref());++ // Create orchestrator tmux window in the project root (no worktree)+ self.state.tmux_ops.create_window(+ &project_name,+ window_name,+ &project_path_str,+ Some(agent_cmd),+ )?;++ self.state.orchestrator_session = Some(orch_target.clone());++ // Open the popup immediately so the user can see the orchestrator starting+ let mut popup = ShellPopup::new("Orchestrator".to_string(), orch_target.clone());+ if let Ok((_term_width, term_height)) = crossterm::terminal::size() {+ let pane_width = SHELL_POPUP_CONTENT_WIDTH;+ let popup_height = (term_height as u32 * SHELL_POPUP_HEIGHT_PERCENT as u32 / 100) as u16;+ let pane_height = popup_height.saturating_sub(4);+ let _ = self.state.tmux_ops.resize_window(&orch_target, pane_width, pane_height);+ popup.last_pane_size = Some((pane_width, pane_height));+ }+ popup.cached_content = capture_tmux_pane_with_history(&orch_target, 500, self.state.tmux_ops.as_ref());+ self.state.shell_popup = Some(popup);++ // Deploy orchestrate skill to project root so the agent can discover it+ deploy_skill(&project_path, "agtx-orchestrate", skills::ORCHESTRATE_SKILL, &default_agent);++ // Send the /agtx:orchestrate command once the agent is ready+ let skill_cmd = skills::transform_plugin_command("/agtx:orchestrate", &default_agent)+ .unwrap_or_else(|| "/agtx:orchestrate".to_string());+ let tmux_ops = Arc::clone(&self.state.tmux_ops);+ let target = orch_target;+ std::thread::spawn(move || {+ if let Some(ready_target) = wait_for_agent_ready(&tmux_ops, &target) {+ let _ = tmux_ops.send_keys(&ready_target, &skill_cmd);+ }+ });++ Ok(())+ }+fn open_selected_task(&mut self) -> Result<()> {if let Some(task) = self.state.board.selected_task() {if let Some(window_name) = &task.session_name.clone() {@@ -4208,6 +4603,70 @@ impl App {Ok(())}+ /// Push queued notifications to the orchestrator's tmux pane, but only when idle.+ /// Runs every 2s. Idle = pane content unchanged for β₯3s.+ fn deliver_orchestrator_notifications(&mut self) {+ // Only check every 2 seconds+ if self.state.orchestrator_last_check.elapsed() < std::time::Duration::from_secs(2) {+ return;+ }+ self.state.orchestrator_last_check = Instant::now();++ let orch_target = match &self.state.orchestrator_session {+ Some(t) => t.clone(),+ None => return,+ };++ // Check window still exists+ if !self.state.tmux_ops.window_exists(&orch_target).unwrap_or(false) {+ return;+ }++ // Capture current pane content (bottom portion for comparison)+ let current_content = self.state.tmux_ops+ .capture_pane(&orch_target)+ .unwrap_or_default();++ if current_content != self.state.orchestrator_last_content {+ // Content changed β agent is working, reset idle timer+ self.state.orchestrator_last_content = current_content;+ self.state.orchestrator_stable_since = Some(Instant::now());+ return;+ }++ // Content unchanged β check if stable long enough (β₯3s)+ let stable_since = match self.state.orchestrator_stable_since {+ Some(t) => t,+ None => {+ self.state.orchestrator_stable_since = Some(Instant::now());+ return;+ }+ };++ if stable_since.elapsed() < std::time::Duration::from_secs(3) {+ return;+ }++ // Orchestrator is idle β deliver pending notifications+ let db = match &self.state.db {+ Some(db) => db,+ None => return,+ };++ let notifications = match db.consume_notifications() {+ Ok(n) if !n.is_empty() => n,+ _ => return,+ };++ let messages: Vec<String> = notifications.iter().map(|n| n.message.clone()).collect();+ let combined = format!("[agtx] {}", messages.join(" | "));+ let _ = self.state.tmux_ops.send_keys(&orch_target, &combined);++ // Reset idle tracking since we just sent input+ self.state.orchestrator_last_content.clear();+ self.state.orchestrator_stable_since = None;+ }+/// Spawn a background thread to check phase statuses if no refresh is already running/// and the cache has expired for at least one task.fn maybe_spawn_session_refresh(&mut self) {@@ -4232,8 +4691,10 @@ impl App {.map_or(true, |(_, ts)| now.duration_since(*ts) >= CACHE_TTL)}).map(|t| {+ // was_ready: true if previously Ready OR not in cache yet (first poll after startup).+ // This avoids false "newly ready" notifications for tasks that were already done before restart.let was_ready = self.state.phase_status_cache.get(&t.id)- .map_or(false, |(prev, _)| *prev == PhaseStatus::Ready);+ .map_or(true, |(prev, _)| *prev == PhaseStatus::Ready);(t.id.clone(), t.status, t.worktree_path.clone(), t.plugin.clone(), t.session_name.clone(), t.cycle, was_ready, t.agent.clone())}).collect();@@ -4363,11 +4824,30 @@ impl App {self.state.pane_content_hashes.remove(&task_status.task_id);}+ let newly_ready = phase == PhaseStatus::Ready && !task_status.was_ready;self.state.phase_status_cache.insert(task_status.task_id.clone(), (phase, now));+ // Notify orchestrator when a phase completes (newly Ready)+ if newly_ready {+ if self.state.orchestrator_session.is_some() {+ if let Some(db) = &self.state.db {+ let task_title = self.state.board.tasks.iter()+ .find(|t| t.id == task_status.task_id)+ .map(|t| t.title.as_str())+ .unwrap_or("unknown");+ let phase_name = if task_status.status == TaskStatus::Backlog { "research" } else { task_status.status.as_str() };+ let short_id = if task_status.task_id.len() >= 8 { &task_status.task_id[..8] } else { &task_status.task_id };+ let notif = crate::db::Notification::new(format!(+ "Task \"{}\" ({}) completed phase: {}",+ task_title, short_id, phase_name+ ));+ let _ = db.create_notification(¬if);+ }+ }+ }+// Auto merge-conflict check for Review tasksif task_status.status == TaskStatus::Review && !self.state.merge_conflict_checked.contains(&task_status.task_id) {- let newly_ready = phase == PhaseStatus::Ready && !task_status.was_ready;let should_check = match phase {PhaseStatus::Ready => newly_ready,PhaseStatus::Idle => {@@ -5938,9 +6418,12 @@ fn wait_for_agent_ready(tmux_ops: &Arc<dyn TmuxOperations>, target: &str) -> Opt}/// Load the workflow plugin for a task, checking agent compatibility.+/// Tries disk first (project-local β global), then falls back to bundled plugins.fn load_task_plugin(task: &Task, project_path: Option<&Path>, default_agent: &str) -> Option<WorkflowPlugin> {let plugin = match &task.plugin {- Some(name) => WorkflowPlugin::load(name, project_path).ok(),+ Some(name) => WorkflowPlugin::load(name, project_path)+ .ok()+ .or_else(|| skills::load_bundled_plugin(name)),None => skills::load_bundled_plugin("agtx"),};if let Some(ref p) = plugin {@@ -6056,6 +6539,51 @@ fn write_skills_to_worktree(worktree_path: &str, project_path: &Path, plugin: &O}}+/// Deploy a single skill to a target directory for the given agent.+/// Writes both the canonical `.agtx/skills/` copy and the agent-native discovery path.+fn deploy_skill(target_dir: &Path, skill_name: &str, content: &str, agent_name: &str) {+ // Write canonical copy+ let canonical_dir = target_dir.join(".agtx/skills").join(skill_name);+ let _ = std::fs::create_dir_all(&canonical_dir);+ let _ = std::fs::write(canonical_dir.join("SKILL.md"), content);++ // Write to agent-native discovery path+ if let Some((base_dir, namespace)) = skills::agent_native_skill_dir(agent_name) {+ let native_dir = if namespace.is_empty() {+ target_dir.join(base_dir)+ } else {+ target_dir.join(base_dir).join(namespace)+ };+ let _ = std::fs::create_dir_all(&native_dir);++ match agent_name {+ "claude" | "copilot" => {+ let transformed = transform_skill_frontmatter(content);+ let filename = skills::skill_dir_to_filename(skill_name, agent_name);+ let _ = std::fs::write(native_dir.join(&filename), transformed);+ }+ "gemini" => {+ let description = skills::extract_description(content)+ .unwrap_or_else(|| format!("agtx {} skill", skill_name));+ let toml_content = skills::skill_to_gemini_toml(&description, content);+ let filename = skills::skill_dir_to_filename(skill_name, agent_name);+ let _ = std::fs::write(native_dir.join(&filename), toml_content);+ }+ "codex" => {+ let skill_subdir = native_dir.join(skill_name);+ let _ = std::fs::create_dir_all(&skill_subdir);+ let _ = std::fs::write(skill_subdir.join("SKILL.md"), content);+ }+ "opencode" => {+ let oc_content = transform_skill_for_opencode(content);+ let filename = skills::skill_dir_to_filename(skill_name, agent_name);+ let _ = std::fs::write(native_dir.join(&filename), oc_content);+ }+ _ => {}+ }+ }+}+/// Transform YAML frontmatter `name: agtx-plan` β `name: agtx:plan` for agent commandsfn transform_skill_frontmatter(content: &str) -> String {if let Some(start) = content.find("name: agtx-") {diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rsindex 615bc8b..ed41fe5 100644--- a/src/tui/app_tests.rs+++ b/src/tui/app_tests.rs@@ -1819,12 +1819,13 @@ fn test_agtx_plugin_has_commands() {#[test]fn test_enumerate_available_skills_claude() {let skills = skills::enumerate_available_skills("claude");- assert_eq!(skills.len(), 5);+ assert_eq!(skills.len(), 6);let commands: Vec<&str> = skills.iter().map(|(c, _)| c.as_str()).collect();assert!(commands.contains(&"/agtx:research"));assert!(commands.contains(&"/agtx:plan"));assert!(commands.contains(&"/agtx:execute"));assert!(commands.contains(&"/agtx:review"));+ assert!(commands.contains(&"/agtx:orchestrate"));assert!(commands.contains(&"/agtx:merge-conflicts"));// Each should have a descriptionfor (_, desc) in &skills {@@ -3264,6 +3265,71 @@ fn test_load_task_plugin_nonexistent_returns_none() {assert!(plugin.is_none());}+#[test]+fn test_load_task_plugin_bundled_fallback() {+ // When a bundled plugin name is set but not on disk, falls back to bundled+ let mut task = crate::db::Task::new("Test", "claude", "proj");+ task.plugin = Some("agtx".to_string());+ // Pass a path where no .agtx/plugins/agtx/ exists+ let dir = tempfile::tempdir().unwrap();+ let plugin = load_task_plugin(&task, Some(dir.path()), "claude");+ assert!(plugin.is_some(), "should fall back to bundled agtx plugin");+ assert_eq!(plugin.unwrap().name, "agtx");+}++#[test]+fn test_phase_accepts_task_with_task_placeholder() {+ use crate::config::WorkflowPlugin;+ let plugin: WorkflowPlugin = toml::from_str(r#"+ name = "test"+ [commands]+ planning = "/test:plan {task}"+ [prompts]+ [artifacts]+ "#).unwrap();+ assert!(plugin.phase_accepts_task("planning"), "command with {{task}} should be accepted");+}++#[test]+fn test_phase_accepts_task_without_task_placeholder() {+ use crate::config::WorkflowPlugin;+ let plugin: WorkflowPlugin = toml::from_str(r#"+ name = "test"+ [commands]+ planning = "/test:plan {phase}"+ [prompts]+ [artifacts]+ "#).unwrap();+ assert!(!plugin.phase_accepts_task("planning"), "command without {{task}} should be blocked");+}++#[test]+fn test_phase_accepts_task_void_plugin_ungated() {+ use crate::config::WorkflowPlugin;+ // Void plugin: no commands, no prompts β should be ungated+ let plugin: WorkflowPlugin = toml::from_str(r#"+ name = "void"+ [commands]+ [prompts]+ [artifacts]+ "#).unwrap();+ assert!(plugin.phase_accepts_task("planning"), "void plugin should be ungated for planning");+ assert!(plugin.phase_accepts_task("running"), "void plugin should be ungated for running");+}++#[test]+fn test_phase_accepts_task_prompt_with_task() {+ use crate::config::WorkflowPlugin;+ let plugin: WorkflowPlugin = toml::from_str(r#"+ name = "test"+ [commands]+ [prompts]+ planning = "Task: {task}"+ [artifacts]+ "#).unwrap();+ assert!(plugin.phase_accepts_task("planning"), "prompt with {{task}} should be accepted");+}+// === App Integration Tests ===#[cfg(feature = "test-mocks")]@@ -3646,11 +3712,29 @@ fn test_wizard_saves_with_selected_plugin() {let tasks = app.state.board.tasks.clone();assert_eq!(tasks.len(), 1);- if selected_plugin.is_empty() {- assert!(tasks[0].plugin.is_none());- } else {- assert_eq!(tasks[0].plugin.as_deref(), Some(selected_plugin.as_str()));- }+ assert_eq!(tasks[0].plugin.as_deref(), Some(selected_plugin.as_str()));+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_wizard_default_plugin_saves_agtx() {+ let mut app = make_test_app_with_agents();+ press_key(&mut app, KeyCode::Char('o'));+ type_str(&mut app, "Default plugin task");+ press_key(&mut app, KeyCode::Enter);+ assert_eq!(app.state.input_mode, InputMode::SelectPlugin);++ // Keep default selection (index 0 = agtx) and advance+ assert_eq!(app.state.wizard_selected_plugin, 0);+ assert_eq!(app.state.wizard_plugin_options[0].name, "agtx");+ press_key(&mut app, KeyCode::Enter);+ assert_eq!(app.state.input_mode, InputMode::InputDescription);+ press_key(&mut app, KeyCode::Enter); // save with no description++ let tasks = app.state.board.tasks.clone();+ assert_eq!(tasks.len(), 1);+ // agtx should be explicitly saved, not None+ assert_eq!(tasks[0].plugin.as_deref(), Some("agtx"));}#[test]diff --git a/tests/db_tests.rs b/tests/db_tests.rsindex b62e387..350d7e3 100644--- a/tests/db_tests.rs+++ b/tests/db_tests.rs@@ -1,4 +1,4 @@-use agtx::db::{Database, Task, TaskStatus, Project};+use agtx::db::{Database, Notification, Task, TaskStatus, Project};// === TaskStatus Tests ===@@ -192,3 +192,34 @@ fn test_in_memory_dbs_are_isolated() {let tasks = db2.get_tasks_by_status(TaskStatus::Backlog).unwrap();assert_eq!(tasks.len(), 0);}++// === Notification Tests ===++#[test]+#[cfg(feature = "test-mocks")]+fn test_notifications_create_and_consume() {+ let db = Database::open_in_memory_project().unwrap();++ let n1 = Notification::new("Task created: foo");+ let n2 = Notification::new("Phase completed: bar");+ db.create_notification(&n1).unwrap();+ db.create_notification(&n2).unwrap();++ // First consume returns both+ let notifs = db.consume_notifications().unwrap();+ assert_eq!(notifs.len(), 2);+ assert_eq!(notifs[0].message, "Task created: foo");+ assert_eq!(notifs[1].message, "Phase completed: bar");++ // Second consume returns empty (they were deleted)+ let notifs = db.consume_notifications().unwrap();+ assert_eq!(notifs.len(), 0);+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_notifications_empty_queue() {+ let db = Database::open_in_memory_project().unwrap();+ let notifs = db.consume_notifications().unwrap();+ assert_eq!(notifs.len(), 0);+}diff --git a/tests/git_tests.rs b/tests/git_tests.rsindex 6a41843..3c503df 100644--- a/tests/git_tests.rs+++ b/tests/git_tests.rs@@ -471,3 +471,74 @@ fn test_initialize_worktree_copy_directory_supported() {let content = std::fs::read_to_string(worktree_path.join("config").join("app.toml")).unwrap();assert_eq!(content, "key = 1");}++// =============================================================================+// Conflict detection tests+// =============================================================================++#[test]+fn test_check_merge_conflicts_no_conflict() {+ let temp_dir = setup_git_repo();+ let path = temp_dir.path();++ // Create a feature branch with a non-conflicting change+ Command::new("git")+ .current_dir(path)+ .args(["checkout", "-b", "task/feature"])+ .output()+ .unwrap();++ std::fs::write(path.join("new_file.txt"), "feature content").unwrap();+ Command::new("git").current_dir(path).args(["add", "."]).output().unwrap();+ Command::new("git").current_dir(path).args(["commit", "-m", "add new file"]).output().unwrap();++ // Switch back to main+ Command::new("git").current_dir(path).args(["checkout", "main"]).output().unwrap();++ let (has_conflicts, files) = git::check_merge_conflicts(path, "main", "task/feature").unwrap();+ assert!(!has_conflicts);+ assert!(files.is_empty());+}++#[test]+fn test_check_merge_conflicts_with_conflict() {+ let temp_dir = setup_git_repo();+ let path = temp_dir.path();++ // Create a feature branch that modifies README.md+ Command::new("git")+ .current_dir(path)+ .args(["checkout", "-b", "task/feature"])+ .output()+ .unwrap();++ std::fs::write(path.join("README.md"), "# Feature branch change").unwrap();+ Command::new("git").current_dir(path).args(["add", "."]).output().unwrap();+ Command::new("git").current_dir(path).args(["commit", "-m", "modify readme on feature"]).output().unwrap();++ // Switch back to main and make a conflicting change+ Command::new("git").current_dir(path).args(["checkout", "main"]).output().unwrap();++ std::fs::write(path.join("README.md"), "# Main branch change").unwrap();+ Command::new("git").current_dir(path).args(["add", "."]).output().unwrap();+ Command::new("git").current_dir(path).args(["commit", "-m", "modify readme on main"]).output().unwrap();++ let (has_conflicts, files) = git::check_merge_conflicts(path, "main", "task/feature").unwrap();+ assert!(has_conflicts);+ assert!(files.iter().any(|f| f.contains("README.md")));+}++#[test]+fn test_check_merge_conflicts_nonexistent_branch() {+ let temp_dir = setup_git_repo();+ let result = git::check_merge_conflicts(temp_dir.path(), "main", "nonexistent");+ // Should return error (git merge-tree fails on non-existent ref)+ assert!(result.is_err() || result.unwrap().0);+}++#[test]+fn test_detect_main_branch_public() {+ let temp_dir = setup_git_repo();+ let branch = git::detect_main_branch(temp_dir.path()).unwrap();+ assert_eq!(branch, "main");+}diff --git a/tests/mcp_tests.rs b/tests/mcp_tests.rsnew file mode 100644index 0000000..9b32140--- /dev/null+++ b/tests/mcp_tests.rs@@ -0,0 +1,150 @@+use agtx::db::{Database, Task, TransitionRequest};++// === TransitionRequest Model Tests ===++#[test]+fn test_transition_request_new() {+ let req = TransitionRequest::new("task-123", "move_forward");+ assert!(!req.id.is_empty());+ assert_eq!(req.task_id, "task-123");+ assert_eq!(req.action, "move_forward");+ assert!(req.processed_at.is_none());+ assert!(req.error.is_none());+}++// === Database CRUD Tests ===++#[test]+#[cfg(feature = "test-mocks")]+fn test_create_and_get_transition_request() {+ let db = Database::open_in_memory_project().unwrap();+ let req = TransitionRequest::new("task-1", "move_to_planning");++ db.create_transition_request(&req).unwrap();++ let fetched = db.get_transition_request(&req.id).unwrap();+ assert!(fetched.is_some());+ let fetched = fetched.unwrap();+ assert_eq!(fetched.id, req.id);+ assert_eq!(fetched.task_id, "task-1");+ assert_eq!(fetched.action, "move_to_planning");+ assert!(fetched.processed_at.is_none());+ assert!(fetched.error.is_none());+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_get_transition_request_not_found() {+ let db = Database::open_in_memory_project().unwrap();+ let fetched = db.get_transition_request("nonexistent").unwrap();+ assert!(fetched.is_none());+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_get_pending_transition_requests() {+ let db = Database::open_in_memory_project().unwrap();++ let req1 = TransitionRequest::new("task-1", "move_forward");+ let req2 = TransitionRequest::new("task-2", "move_to_running");+ let req3 = TransitionRequest::new("task-3", "resume");++ db.create_transition_request(&req1).unwrap();+ db.create_transition_request(&req2).unwrap();+ db.create_transition_request(&req3).unwrap();++ // Mark req2 as processed+ db.mark_transition_processed(&req2.id, None).unwrap();++ let pending = db.get_pending_transition_requests().unwrap();+ assert_eq!(pending.len(), 2);+ assert_eq!(pending[0].id, req1.id);+ assert_eq!(pending[1].id, req3.id);+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_mark_transition_processed_success() {+ 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();++ let fetched = db.get_transition_request(&req.id).unwrap().unwrap();+ assert!(fetched.processed_at.is_some());+ assert!(fetched.error.is_none());+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_mark_transition_processed_with_error() {+ 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, Some("Task not found"))+ .unwrap();++ let fetched = db.get_transition_request(&req.id).unwrap().unwrap();+ assert!(fetched.processed_at.is_some());+ assert_eq!(fetched.error.as_deref(), Some("Task not found"));+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_pending_excludes_processed() {+ let db = Database::open_in_memory_project().unwrap();++ let req1 = TransitionRequest::new("task-1", "move_forward");+ let req2 = TransitionRequest::new("task-2", "move_forward");+ db.create_transition_request(&req1).unwrap();+ db.create_transition_request(&req2).unwrap();++ // Process both+ db.mark_transition_processed(&req1.id, None).unwrap();+ db.mark_transition_processed(&req2.id, Some("error"))+ .unwrap();++ let pending = db.get_pending_transition_requests().unwrap();+ assert!(pending.is_empty());+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_cleanup_old_transition_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();++ // Manually backdate the processed_at to 2 hours ago+ db.cleanup_old_transition_requests().unwrap();++ // The request was just processed (now), so cleanup shouldn't delete it+ let fetched = db.get_transition_request(&req.id).unwrap();+ assert!(fetched.is_some());+}++#[test]+#[cfg(feature = "test-mocks")]+fn test_transition_request_with_task() {+ let db = Database::open_in_memory_project().unwrap();++ // Create a task first+ let task = Task::new("Test task", "claude", "test-project");+ db.create_task(&task).unwrap();++ // Create a transition request for this task+ let req = TransitionRequest::new(&task.id, "move_to_planning");+ db.create_transition_request(&req).unwrap();++ // Verify we can fetch both+ let fetched_task = db.get_task(&task.id).unwrap();+ assert!(fetched_task.is_some());++ let fetched_req = db.get_transition_request(&req.id).unwrap();+ assert!(fetched_req.is_some());+ assert_eq!(fetched_req.unwrap().task_id, task.id);+}