Skip to content

armgit / agtx

Public Imported from GitHub
0

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

feat: add plugin framework with builtin gsd and spec-kit (#22)

Fynn FlΓΌgge01949981a36b
diff --git a/README.md b/README.md
index bab9cc3..e4dc78a 100644
--- a/README.md
+++ b/README.md
@@ -11,6 +11,7 @@
- **Coding Agent integrations**: Automatic session management for Claude Code, Codex, Gemini and Copilot CLI
- **PR workflow**: Generate descriptions with AI, create PRs directly from the TUI
- **Multi-project dashboard**: Manage tasks across all your projects
+- **Workflow plugins**: Swap between built-in, GSD, spec-kit, or void workflows per project
- **Customizable themes**: Configure colors via config file
## Installation
@@ -63,6 +64,7 @@ agtx -g
| `d` | Show git diff |
| `x` | Delete task |
| `/` | Search tasks |
+| `P` | Select workflow plugin |
| `e` | Toggle project sidebar |
| `q` | Quit |
@@ -118,6 +120,130 @@ init_script = "scripts/init_worktree.sh"
Both options run during the Backlog β†’ Planning transition, after `git worktree add`
and before the agent session starts.
+### Workflow Plugins
+
+Press `P` to select a workflow plugin for the current project. The active plugin is shown in the header bar.
+
+| Plugin | Description |
+|--------|-------------|
+| **agtx** (default) | Built-in workflow with skills and prompts for each phase |
+| **gsd** | Get Shit Done - structured spec-driven development with interactive planning |
+| **spec-kit** | Spec-Driven Development by GitHub - specifications become executable artifacts |
+| **void** | Plain agent session - no prompting or skills, task description prefilled in input |
+
+Each task remembers the plugin it was started with. Switching plugins only affects new tasks β€” existing tasks continue using their original plugin throughout their lifecycle.
+
+#### Agent Compatibility
+
+| | Claude | Codex | Gemini | Copilot | OpenCode |
+|--|:------:|:-----:|:------:|:-------:|:--------:|
+| **agtx** | βœ… | βœ… | βœ… | 🟑 | βœ… |
+| **gsd** | βœ… | βœ… | βœ… | ❌ | βœ… |
+| **spec-kit** | βœ… | βœ… | βœ… | 🟑 | βœ… |
+| **void** | βœ… | βœ… | βœ… | βœ… | βœ… |
+
+βœ… Skills, commands, and prompts fully supported Β· 🟑 Prompt only, no interactive skill support Β· ❌ Not supported
+
+#### Creating a Plugin
+
+Plugins are TOML files that customize the task workflow β€” the commands sent to the agent, the prompts, and the artifact files that signal phase completion.
+
+**Location:** 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 (`P`).
+
+**Minimal example** β€” a plugin that uses custom slash commands:
+
+```toml
+name = "my-plugin"
+description = "My custom workflow"
+
+[commands]
+planning = "/my-plugin:plan"
+running = "/my-plugin:execute"
+review = "/my-plugin:review"
+
+[prompts]
+planning = "Task: {task}"
+running = ""
+review = ""
+```
+
+**Full reference** with all available fields:
+
+```toml
+name = "my-plugin"
+description = "My custom workflow"
+
+# Shell command to run in the worktree after creation, before the agent starts.
+# {agent} is replaced with the agent name (claude, codex, gemini, etc.)
+init_script = "npm install --prefix .my-plugin --{agent}"
+
+# Restrict to specific agents (empty or omitted = all agents supported)
+supported_agents = ["claude", "codex", "gemini", "opencode"]
+
+# Extra directories to copy from project root into each worktree.
+# Agent config dirs (.claude, .gemini, .codex, .github/agents, .config/opencode)
+# are always copied automatically.
+copy_dirs = [".my-plugin"]
+
+# Artifact files that signal phase completion.
+# When detected, the task shows a βœ“ checkmark instead of the spinner.
+# Supports * wildcard for one directory level (e.g. "specs/*/plan.md").
+# Omitted phases fall back to agtx defaults (.agtx/plan.md, .agtx/execute.md, .agtx/review.md).
+[artifacts]
+research = ".my-plugin/research.md"
+planning = ".my-plugin/plan.md"
+running = ".my-plugin/summary.md"
+review = ".my-plugin/review.md"
+
+# Slash commands sent to the agent via tmux for each phase.
+# Written in canonical format (Claude/Gemini style): /namespace:command
+# Automatically transformed per agent:
+# Claude/Gemini: /my-plugin:plan (unchanged)
+# OpenCode: /my-plugin-plan (colon β†’ hyphen)
+# Codex: $my-plugin-plan (slash β†’ dollar, colon β†’ hyphen)
+# Set to "" to skip sending a command for that phase.
+[commands]
+research = "/my-plugin:research {task}"
+planning = "/my-plugin:plan {task}"
+running = "/my-plugin:execute"
+review = "/my-plugin:review"
+
+# Prompt templates sent as task content after the command.
+# {task} = task title + description, {task_id} = unique task ID.
+# Set to "" to skip sending a prompt for that phase.
+[prompts]
+research = "Task: {task}"
+planning = ""
+running = ""
+review = ""
+
+# Text patterns to wait for in the tmux pane before sending the prompt.
+# Useful when a command triggers an interactive prompt that must appear first.
+# Polls every 500ms, times out after 5 minutes.
+[prompt_triggers]
+research = "What do you want to build?"
+```
+
+**How it works at each phase transition:**
+
+1. The **command** is sent to the agent via tmux (e.g., `/my-plugin:plan`)
+2. If a **prompt_trigger** is set, agtx waits for that text to appear in the tmux pane
+3. The **prompt** is sent with `{task}` and `{task_id}` replaced
+4. agtx polls for the **artifact** file β€” when found, the spinner becomes a checkmark
+
+**Custom skills:** If your plugin provides its own skill files, place them in the plugin directory:
+
+```
+.agtx/plugins/my-plugin/
+β”œβ”€β”€ plugin.toml
+└── skills/
+ β”œβ”€β”€ agtx-plan/SKILL.md
+ β”œβ”€β”€ agtx-execute/SKILL.md
+ └── agtx-review/SKILL.md
+```
+
+These override the built-in agtx skills and are deployed to agent-native paths (`.claude/commands/`, `.codex/skills/`, etc.) in each worktree.
+
## How It Works
### Architecture
diff --git a/plugins/gsd/plugin.toml b/plugins/gsd/plugin.toml
new file mode 100644
index 0000000..877de42
--- /dev/null
+++ b/plugins/gsd/plugin.toml
@@ -0,0 +1,25 @@
+name = "gsd"
+description = "Get Shit Done - structured spec-driven development framework"
+init_script = "npx get-shit-done-cc@latest --{agent} --local --non-interactive"
+supported_agents = ["claude", "codex", "gemini", "opencode"]
+
+[artifacts]
+research = ".planning/ROADMAP.md"
+planning = ".planning/1/1-PLAN.md"
+running = ".planning/1/1-SUMMARY.md"
+review = ".planning/1/UAT.md"
+
+[commands]
+research = "/gsd:new-project"
+planning = "/gsd:plan-phase 1"
+running = "/gsd:execute-phase 1"
+review = "/gsd:verify-work 1"
+
+[prompts]
+research = "Task: {task}"
+planning = ""
+running = ""
+review = ""
+
+[prompt_triggers]
+research = "What do you want to build?"
diff --git a/plugins/spec-kit/plugin.toml b/plugins/spec-kit/plugin.toml
new file mode 100644
index 0000000..683ac69
--- /dev/null
+++ b/plugins/spec-kit/plugin.toml
@@ -0,0 +1,24 @@
+name = "spec-kit"
+description = "Spec-Driven Development by GitHub - specifications become executable artifacts"
+# No init_script β€” spec-kit must be installed in the project root first (specify init).
+# The .claude/ directory (containing spec-kit commands) is copied to worktrees automatically.
+copy_dirs = [".specify"]
+
+# Artifact files that signal phase completion.
+# Paths with * match any single directory level (e.g. specs/{branch-name}/plan.md).
+# Omitted phases fall back to agtx defaults (.agtx/execute.md, .agtx/review.md).
+[artifacts]
+research = "specs/*/spec.md"
+planning = "specs/*/plan.md"
+
+[commands]
+research = "/speckit.specify {task}"
+planning = "/speckit.plan {task}"
+running = "/speckit.implement"
+review = "/speckit.analyze"
+
+[prompts]
+research = ""
+planning = ""
+running = ""
+review = ""
diff --git a/plugins/void/plugin.toml b/plugins/void/plugin.toml
new file mode 100644
index 0000000..a178ffc
--- /dev/null
+++ b/plugins/void/plugin.toml
@@ -0,0 +1,14 @@
+name = "void"
+description = "Plain coding agent session without any prompting or skills"
+
+[commands]
+research = ""
+planning = ""
+running = ""
+review = ""
+
+[prompts]
+research = ""
+planning = ""
+running = ""
+review = ""
diff --git a/skills/execute.md b/skills/execute.md
new file mode 100644
index 0000000..a00d420
--- /dev/null
+++ b/skills/execute.md
@@ -0,0 +1,32 @@
+---
+name: agtx-execute
+description: Execute an approved implementation plan. Implement the changes, then write a summary to .agtx/execute.md and stop.
+---
+
+# Execution Phase
+
+You are in the **execution phase** of an agtx-managed task. Your plan has been approved.
+
+## Instructions
+
+1. Read your plan from `.agtx/plan.md`
+2. Implement the changes described in the plan
+3. Run relevant tests to verify your changes
+4. Fix any issues found during testing
+
+## Output
+
+When implementation is complete, write a summary to `.agtx/execute.md` with these sections:
+
+## Changes
+What files were modified/created and what was changed in each.
+
+## Testing
+How you verified the changes β€” tests run, results, manual checks.
+
+## CRITICAL: Stop After Writing
+
+After writing `.agtx/execute.md`:
+- Do NOT start new work beyond the plan
+- Say: "Implementation complete. Summary written to `.agtx/execute.md`."
+- Wait for further instructions
diff --git a/skills/plan.md b/skills/plan.md
new file mode 100644
index 0000000..1846736
--- /dev/null
+++ b/skills/plan.md
@@ -0,0 +1,36 @@
+---
+name: agtx-plan
+description: Plan a task implementation. Analyze the codebase, create a detailed plan, write it to .agtx/plan.md, then stop and wait for user approval before making any changes.
+---
+
+# Planning Phase
+
+You are in the **planning phase** of an agtx-managed task.
+
+## Instructions
+
+1. Read and understand the task description
+2. Explore the codebase to understand relevant files, patterns, and architecture
+3. Identify all files that need to be created or modified
+4. Create a detailed implementation plan
+
+## Output
+
+Write your plan to `.agtx/plan.md` with these sections:
+
+## Analysis
+What you found in the codebase β€” relevant files, patterns, dependencies.
+
+## Plan
+Step-by-step implementation plan β€” files to modify, approach, order of changes.
+
+## Risks
+What could go wrong β€” edge cases, breaking changes, areas needing extra care.
+
+## CRITICAL: Stop After Writing
+
+After writing `.agtx/plan.md`:
+- Do NOT start implementing
+- Do NOT modify any source files
+- Say: "Plan written to `.agtx/plan.md`. Waiting for approval."
+- Wait for explicit instructions to proceed
diff --git a/skills/research.md b/skills/research.md
new file mode 100644
index 0000000..6b69984
--- /dev/null
+++ b/skills/research.md
@@ -0,0 +1,40 @@
+---
+name: agtx-research
+description: Explore the codebase to understand a task before planning. Write findings to .agtx/research/{task-id}.md and stop. This is a read-only exploration β€” do not modify any files.
+---
+
+# Research Phase
+
+You are in the **research phase** of an agtx-managed task. This is a read-only exploration.
+
+## Instructions
+
+1. Read and understand the task description
+2. Explore the codebase to find relevant files, patterns, and architecture
+3. Identify dependencies, related code, and potential complexity
+4. Assess feasibility and estimate scope
+
+## Output
+
+Write your findings to the research artifact path provided in the task prompt. Include:
+
+## Relevant Files
+Key files and their roles β€” what exists, what needs changing.
+
+## Architecture
+How the relevant parts of the codebase fit together.
+
+## Complexity
+Assessment of scope β€” simple change, moderate refactor, or major undertaking.
+
+## Open Questions
+Things that need clarification before planning can begin.
+
+## CRITICAL: Do Not Modify Code
+
+This is a **read-only** exploration:
+- Do NOT modify any source files
+- Do NOT create branches or worktrees
+- Do NOT start planning or implementing
+- Say: "Research complete. Findings written to {artifact_path}."
+- Wait for further instructions
diff --git a/skills/review.md b/skills/review.md
new file mode 100644
index 0000000..af8f910
--- /dev/null
+++ b/skills/review.md
@@ -0,0 +1,35 @@
+---
+name: agtx-review
+description: Self-review completed work. Check for correctness, edge cases, and code quality. Write review to .agtx/review.md and stop.
+---
+
+# Review Phase
+
+You are in the **review phase** of an agtx-managed task.
+
+## Instructions
+
+1. Review all changes made during execution (use git diff)
+2. Check for:
+ - Correctness and edge cases
+ - Error handling
+ - Code style consistency with the existing codebase
+ - Test coverage
+ - Security issues (injection, XSS, etc.)
+3. Fix any issues you find
+
+## Output
+
+Write your review to `.agtx/review.md` with these sections:
+
+## Review
+Findings from your review β€” what looks good, what was fixed, any concerns.
+
+## Status
+Either `READY` (good to merge) or `NEEDS_WORK` (with explanation of remaining issues).
+
+## CRITICAL: Stop After Writing
+
+After writing `.agtx/review.md`:
+- Say: "Review written to `.agtx/review.md`."
+- Wait for further instructions
diff --git a/src/agent/mod.rs b/src/agent/mod.rs
index e1f0cf5..7b0e367 100644
--- a/src/agent/mod.rs
+++ b/src/agent/mod.rs
@@ -33,27 +33,29 @@ impl Agent {
which::which(&self.command).is_ok()
}
- /// Build the shell command to start the agent interactively with a prompt
+ /// Build the shell command to start the agent interactively.
+ /// When prompt is empty, the agent starts with no initial message
+ /// (task content and skill commands are sent later via tmux send_keys).
pub fn build_interactive_command(&self, prompt: &str) -> String {
- // Escape single quotes in prompt for shell
- let escaped_prompt = prompt.replace('\'', "'\"'\"'");
+ if prompt.is_empty() {
+ return match self.name.as_str() {
+ "claude" => "claude --dangerously-skip-permissions".to_string(),
+ "codex" => "codex --approval-mode full-auto".to_string(),
+ "copilot" => "copilot --allow-all-tools".to_string(),
+ "gemini" => "gemini --approval-mode yolo".to_string(),
+ "opencode" => "opencode".to_string(),
+ _ => self.command.clone(),
+ };
+ }
+ let escaped_prompt = prompt.replace('\'', "'\"'\"'");
match self.name.as_str() {
- "claude" => {
- format!("claude --dangerously-skip-permissions '{}'", escaped_prompt)
- }
- "codex" => {
- format!("codex --approval-mode full-auto '{}'", escaped_prompt)
- }
- "copilot" => {
- format!("copilot --allow-all-tools -p '{}'", escaped_prompt)
- }
- "gemini" => {
- format!("gemini -p '{}'", escaped_prompt)
- }
- _ => {
- format!("{} '{}'", self.command, escaped_prompt)
- }
+ "claude" => format!("claude --dangerously-skip-permissions '{}'", escaped_prompt),
+ "codex" => format!("codex --approval-mode full-auto '{}'", escaped_prompt),
+ "copilot" => format!("copilot --allow-all-tools -p '{}'", escaped_prompt),
+ "gemini" => format!("gemini --approval-mode yolo -i '{}'", escaped_prompt),
+ "opencode" => format!("opencode -p '{}'", escaped_prompt),
+ _ => format!("{} '{}'", self.command, escaped_prompt),
}
}
}
@@ -65,9 +67,9 @@ pub fn known_agents() -> Vec<Agent> {
Agent::new("codex", "codex", "OpenAI's Codex CLI", "Codex <[email protected]>"),
Agent::new("copilot", "copilot", "GitHub Copilot CLI", "GitHub Copilot <[email protected]>"),
Agent::new("gemini", "gemini", "Google Gemini CLI", "Gemini <[email protected]>"),
+ Agent::new("opencode", "opencode", "AI-powered coding assistant", "OpenCode <[email protected]>"),
// TODO: investigate CLI usage before enabling
// Agent::new("aider", "aider", "AI pair programming in your terminal", "Aider <[email protected]>"),
- // Agent::new("opencode", "opencode", "AI-powered coding assistant", "OpenCode <[email protected]>"),
// Agent::new("cline", "cline", "AI coding assistant for VS Code", "Cline <[email protected]>"),
]
}
diff --git a/src/agent/operations.rs b/src/agent/operations.rs
index 1dae96f..4e6126b 100644
--- a/src/agent/operations.rs
+++ b/src/agent/operations.rs
@@ -24,7 +24,8 @@ pub trait AgentOperations: Send + Sync {
/// e.g., "Claude <[email protected]>"
fn co_author_string(&self) -> &str;
- /// Build the shell command to start the agent interactively with a prompt
+ /// Build the shell command to start the agent interactively.
+ /// When prompt is empty, the agent starts with no initial message.
fn build_interactive_command(&self, prompt: &str) -> String;
}
diff --git a/src/config/mod.rs b/src/config/mod.rs
index c4afaa0..5332743 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -189,6 +189,9 @@ pub struct ProjectConfig {
/// Shell command to run inside the worktree after creation and file copying
pub init_script: Option<String>,
+
+ /// Workflow plugin name (e.g. "gsd", "spec-kit")
+ pub workflow_plugin: Option<String>,
}
impl GlobalConfig {
@@ -306,6 +309,7 @@ pub struct MergedConfig {
pub theme: ThemeConfig,
pub copy_files: Option<String>,
pub init_script: Option<String>,
+ pub workflow_plugin: Option<String>,
}
impl MergedConfig {
@@ -326,6 +330,124 @@ impl MergedConfig {
theme: global.theme.clone(),
copy_files: project.copy_files.clone(),
init_script: project.init_script.clone(),
+ workflow_plugin: project.workflow_plugin.clone(),
+ }
+ }
+}
+
+/// Workflow plugin configuration loaded from plugin.toml
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WorkflowPlugin {
+ pub name: String,
+ pub description: Option<String>,
+ pub init_script: Option<String>,
+ /// List of supported agent names (e.g. ["claude", "codex", "gemini", "opencode"]).
+ /// If empty or omitted, all agents are assumed supported.
+ #[serde(default)]
+ pub supported_agents: Vec<String>,
+ #[serde(default)]
+ pub artifacts: PluginArtifacts,
+ #[serde(default)]
+ pub commands: PluginCommands,
+ #[serde(default)]
+ pub prompts: PluginPrompts,
+ #[serde(default)]
+ pub prompt_triggers: PluginPromptTriggers,
+ /// Extra directories to copy from project root to worktrees (e.g. [".specify"]).
+ #[serde(default)]
+ pub copy_dirs: Vec<String>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct PluginArtifacts {
+ pub research: Option<String>,
+ pub planning: Option<String>,
+ pub running: Option<String>,
+ pub review: Option<String>,
+}
+
+/// Slash commands to invoke per phase (sent via tmux send_keys as real interactive commands).
+/// e.g. "/gsd:plan-phase 1" or "/speckit.plan"
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct PluginCommands {
+ pub research: Option<String>,
+ pub planning: Option<String>,
+ pub running: Option<String>,
+ pub review: Option<String>,
+}
+
+/// Task content prompts per phase (sent after the command).
+/// Should contain just the task description, not slash commands.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct PluginPrompts {
+ pub research: Option<String>,
+ pub planning: Option<String>,
+ pub running: Option<String>,
+ pub review: Option<String>,
+}
+
+/// Text patterns to wait for before sending the prompt for each phase.
+/// When set, the system polls the tmux pane for this text before sending the prompt.
+/// Useful for interactive commands like /gsd:new-project that ask questions.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct PluginPromptTriggers {
+ pub research: Option<String>,
+ pub planning: Option<String>,
+ pub running: Option<String>,
+ pub review: Option<String>,
+}
+
+impl WorkflowPlugin {
+ /// Check if the given agent is supported by this plugin.
+ /// Returns true if supported_agents is empty (all agents allowed) or contains the agent.
+ pub fn supports_agent(&self, agent_name: &str) -> bool {
+ self.supported_agents.is_empty()
+ || self.supported_agents.iter().any(|a| a == agent_name)
+ }
+
+ /// Load a plugin by name, checking project-local then global directories
+ pub fn load(name: &str, project_path: Option<&Path>) -> Result<Self> {
+ // 1. Check project-local
+ if let Some(pp) = project_path {
+ let local_path = pp.join(".agtx").join("plugins").join(name).join("plugin.toml");
+ if local_path.exists() {
+ let content = std::fs::read_to_string(&local_path)?;
+ return toml::from_str(&content).context("Failed to parse plugin.toml");
+ }
+ }
+ // 2. Check global
+ let home = std::env::var("HOME").context("Could not determine home directory")?;
+ let global_path = PathBuf::from(home)
+ .join(".config")
+ .join("agtx")
+ .join("plugins")
+ .join(name)
+ .join("plugin.toml");
+ if global_path.exists() {
+ let content = std::fs::read_to_string(&global_path)?;
+ return toml::from_str(&content).context("Failed to parse plugin.toml");
+ }
+ anyhow::bail!("Plugin '{}' not found", name)
+ }
+
+ /// Get the plugin directory path (for reading skill files)
+ pub fn plugin_dir(name: &str, project_path: Option<&Path>) -> Option<PathBuf> {
+ // Same lookup order: project-local first, then global
+ if let Some(pp) = project_path {
+ let local = pp.join(".agtx").join("plugins").join(name);
+ if local.join("plugin.toml").exists() {
+ return Some(local);
+ }
+ }
+ let home = std::env::var("HOME").ok()?;
+ let global = PathBuf::from(home)
+ .join(".config")
+ .join("agtx")
+ .join("plugins")
+ .join(name);
+ if global.join("plugin.toml").exists() {
+ return Some(global);
}
+ None
}
}
diff --git a/src/db/models.rs b/src/db/models.rs
index 9c0820b..d471074 100644
--- a/src/db/models.rs
+++ b/src/db/models.rs
@@ -58,6 +58,7 @@ pub struct Task {
pub branch_name: Option<String>,
pub pr_number: Option<i32>,
pub pr_url: Option<String>,
+ pub plugin: Option<String>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
@@ -78,6 +79,7 @@ impl Task {
branch_name: None,
pr_number: None,
pr_url: None,
+ plugin: None,
created_at: now,
updated_at: now,
}
@@ -149,3 +151,14 @@ impl AgentStatus {
}
}
}
+
+/// Phase completion status (runtime-only, not persisted to DB)
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum PhaseStatus {
+ /// Agent is still working, no artifact yet
+ Working,
+ /// Phase artifact detected, ready to advance
+ Ready,
+ /// Tmux window gone (process exited)
+ Exited,
+}
diff --git a/src/db/schema.rs b/src/db/schema.rs
index 9677bba..5295db3 100644
--- a/src/db/schema.rs
+++ b/src/db/schema.rs
@@ -81,6 +81,7 @@ impl Database {
branch_name TEXT,
pr_number INTEGER,
pr_url TEXT,
+ plugin TEXT,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
@@ -94,6 +95,7 @@ impl Database {
let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN branch_name TEXT", []);
let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN pr_number INTEGER", []);
let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN pr_url TEXT", []);
+ let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN plugin TEXT", []);
Ok(())
}
@@ -131,8 +133,8 @@ impl Database {
pub fn create_task(&self, task: &Task) -> Result<()> {
self.conn.execute(
r#"
- INSERT INTO tasks (id, title, description, status, agent, project_id, session_name, worktree_path, branch_name, pr_number, pr_url, created_at, updated_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)
+ INSERT INTO tasks (id, title, description, status, agent, project_id, session_name, worktree_path, branch_name, pr_number, pr_url, plugin, created_at, updated_at)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)
"#,
params![
task.id,
@@ -146,6 +148,7 @@ impl Database {
task.branch_name,
task.pr_number,
task.pr_url,
+ task.plugin,
task.created_at.to_rfc3339(),
task.updated_at.to_rfc3339(),
],
@@ -166,7 +169,8 @@ impl Database {
branch_name = ?8,
pr_number = ?9,
pr_url = ?10,
- updated_at = ?11
+ plugin = ?11,
+ updated_at = ?12
WHERE id = ?1
"#,
params![
@@ -180,6 +184,7 @@ impl Database {
task.branch_name,
task.pr_number,
task.pr_url,
+ task.plugin,
task.updated_at.to_rfc3339(),
],
)?;
@@ -206,6 +211,7 @@ impl Database {
branch_name: row.get("branch_name").ok().flatten(),
pr_number: row.get("pr_number").ok().flatten(),
pr_url: row.get("pr_url").ok().flatten(),
+ plugin: row.get("plugin").ok().flatten(),
created_at: chrono::DateTime::parse_from_rfc3339(&row.get::<_, String>("created_at")?)
.map(|dt| dt.with_timezone(&chrono::Utc))
.unwrap_or_else(|_| chrono::Utc::now()),
diff --git a/src/git/operations.rs b/src/git/operations.rs
index 171c0e6..8a94ccc 100644
--- a/src/git/operations.rs
+++ b/src/git/operations.rs
@@ -59,6 +59,7 @@ pub trait GitOperations: Send + Sync {
worktree_path: &Path,
copy_files: Option<String>,
init_script: Option<String>,
+ copy_dirs: Vec<String>,
) -> Vec<String>;
}
@@ -209,7 +210,8 @@ impl GitOperations for RealGitOps {
worktree_path: &Path,
copy_files: Option<String>,
init_script: Option<String>,
+ copy_dirs: Vec<String>,
) -> Vec<String> {
- super::initialize_worktree(project_path, worktree_path, copy_files.as_deref(), init_script.as_deref())
+ super::initialize_worktree(project_path, worktree_path, copy_files.as_deref(), init_script.as_deref(), &copy_dirs)
}
}
diff --git a/src/git/worktree.rs b/src/git/worktree.rs
index 9e064d7..3d07b88 100644
--- a/src/git/worktree.rs
+++ b/src/git/worktree.rs
@@ -56,7 +56,17 @@ pub fn create_worktree(project_path: &Path, task_slug: &str) -> Result<PathBuf>
Ok(worktree_path)
}
-/// Initialize a worktree by copying files and running an init script.
+/// Agent config directories that are always copied from project root to worktrees.
+/// These contain commands, skills, and configuration that agents need.
+pub const AGENT_CONFIG_DIRS: &[&str] = &[
+ ".claude",
+ ".gemini",
+ ".codex",
+ ".github/agents",
+ ".config/opencode",
+];
+
+/// Initialize a worktree by copying agent config dirs, user-specified files, and running an init script.
///
/// Returns a Vec of warning messages for any issues encountered.
/// Does not fail fatally β€” errors are collected and returned for the caller to display.
@@ -65,9 +75,33 @@ pub fn initialize_worktree(
worktree_path: &Path,
copy_files: Option<&str>,
init_script: Option<&str>,
+ copy_dirs: &[String],
) -> Vec<String> {
let mut warnings = Vec::new();
+ // Always copy agent config directories
+ for dir_name in AGENT_CONFIG_DIRS {
+ let src = project_path.join(dir_name);
+ if src.is_dir() {
+ let dst = worktree_path.join(dir_name);
+ if let Err(e) = copy_dir_recursive(&src, &dst) {
+ warnings.push(format!("Failed to copy '{}' to worktree: {}", dir_name, e));
+ }
+ }
+ }
+
+ // Copy plugin-specific extra directories
+ for dir_name in copy_dirs {
+ let src = project_path.join(dir_name);
+ if src.is_dir() {
+ let dst = worktree_path.join(dir_name);
+ if let Err(e) = copy_dir_recursive(&src, &dst) {
+ warnings.push(format!("Failed to copy '{}' to worktree: {}", dir_name, e));
+ }
+ }
+ }
+
+ // Copy user-specified files/directories
if let Some(files_str) = copy_files {
for entry in files_str.split(',') {
let file_name = entry.trim();
@@ -77,18 +111,6 @@ pub fn initialize_worktree(
let src = project_path.join(file_name);
let dst = worktree_path.join(file_name);
- if let Some(parent) = dst.parent() {
- if !parent.exists() {
- if let Err(e) = std::fs::create_dir_all(parent) {
- warnings.push(format!(
- "Failed to create directory for '{}': {}",
- file_name, e
- ));
- continue;
- }
- }
- }
-
if !src.exists() {
warnings.push(format!(
"copy_files: '{}' not found in project root, skipping",
@@ -98,15 +120,24 @@ pub fn initialize_worktree(
}
if src.is_dir() {
- warnings.push(format!(
- "copy_files: '{}' is a directory, only individual files are supported",
- file_name
- ));
- continue;
- }
-
- if let Err(e) = std::fs::copy(&src, &dst) {
- warnings.push(format!("Failed to copy '{}' to worktree: {}", file_name, e));
+ if let Err(e) = copy_dir_recursive(&src, &dst) {
+ warnings.push(format!("Failed to copy directory '{}' to worktree: {}", file_name, e));
+ }
+ } else {
+ if let Some(parent) = dst.parent() {
+ if !parent.exists() {
+ if let Err(e) = std::fs::create_dir_all(parent) {
+ warnings.push(format!(
+ "Failed to create directory for '{}': {}",
+ file_name, e
+ ));
+ continue;
+ }
+ }
+ }
+ if let Err(e) = std::fs::copy(&src, &dst) {
+ warnings.push(format!("Failed to copy '{}' to worktree: {}", file_name, e));
+ }
}
}
}
@@ -135,6 +166,22 @@ pub fn initialize_worktree(
warnings
}
+/// Recursively copy a directory and its contents.
+fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
+ std::fs::create_dir_all(dst)?;
+ for entry in std::fs::read_dir(src)? {
+ let entry = entry?;
+ let src_path = entry.path();
+ let dst_path = dst.join(entry.file_name());
+ if src_path.is_dir() {
+ copy_dir_recursive(&src_path, &dst_path)?;
+ } else {
+ std::fs::copy(&src_path, &dst_path)?;
+ }
+ }
+ Ok(())
+}
+
/// Detect the main branch name (main or master)
fn detect_main_branch(project_path: &Path) -> Result<String> {
// Check if 'main' exists
diff --git a/src/lib.rs b/src/lib.rs
index 7c880b7..d0c57bb 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 skills;
pub mod tmux;
pub mod tui;
diff --git a/src/skills.rs b/src/skills.rs
new file mode 100644
index 0000000..f40cfce
--- /dev/null
+++ b/src/skills.rs
@@ -0,0 +1,214 @@
+/// Default skill content for agtx phases.
+/// Skills follow the Agent Skills spec (SKILL.md with YAML frontmatter + markdown).
+/// Content is loaded from .md files at compile time via include_str!().
+
+pub const RESEARCH_SKILL: &str = include_str!("../skills/research.md");
+pub const PLAN_SKILL: &str = include_str!("../skills/plan.md");
+pub const EXECUTE_SKILL: &str = include_str!("../skills/execute.md");
+pub const REVIEW_SKILL: &str = include_str!("../skills/review.md");
+
+/// Default built-in skills: (directory_name, SKILL.md content)
+/// Used for worktree phases (Research, Planning, Running, Review)
+pub const DEFAULT_SKILLS: &[(&str, &str)] = &[
+ ("agtx-research", RESEARCH_SKILL),
+ ("agtx-plan", PLAN_SKILL),
+ ("agtx-execute", EXECUTE_SKILL),
+ ("agtx-review", REVIEW_SKILL),
+];
+
+/// Default task prompts per phase transition.
+/// These are sent as the task content message AFTER the skill command.
+/// For agents with native skill invocation, the skill is invoked separately via send_keys.
+pub const DEFAULT_PROMPT_RESEARCH: &str =
+ "Task: {task}\n\nWrite your findings to .agtx/research/{task_id}.md";
+pub const DEFAULT_PROMPT_PLANNING: &str =
+ "Task: {task}";
+pub const DEFAULT_PROMPT_PLANNING_WITH_RESEARCH: &str =
+ "Task: {task}\n\nResearch findings are available in .agtx/research.md β€” use them as context.";
+pub const DEFAULT_PROMPT_RUNNING: &str =
+ "Plan approved. Implement the changes described in .agtx/plan.md";
+pub const DEFAULT_PROMPT_REVIEW: &str =
+ "Implementation complete. Review the changes.";
+
+/// Agent-native command/skill directory paths.
+/// Returns (base_dir_relative_to_worktree, namespace_subdir) or None if agent has no native discovery.
+/// Returns (base_dir_relative_to_worktree, namespace_subdir) or None if agent has no native discovery.
+/// For Codex, namespace is empty because skills go directly under `.codex/skills/{skill-name}/SKILL.md`.
+pub fn agent_native_skill_dir(agent_name: &str) -> Option<(&'static str, &'static str)> {
+ match agent_name {
+ "claude" => Some((".claude/commands", "agtx")),
+ "gemini" => Some((".gemini/commands", "agtx")),
+ "opencode" => Some((".config/opencode/command", "")),
+ "codex" => Some((".codex/skills", "")),
+ "copilot" => Some((".github/agents", "agtx")),
+ _ => None,
+ }
+}
+
+/// Transform SKILL.md frontmatter `name: agtx-plan` to command name `agtx:plan`.
+/// Replaces the first hyphen with `:`.
+pub fn skill_name_to_command(skill_name: &str) -> String {
+ if let Some(pos) = skill_name.find('-') {
+ format!("{}:{}", &skill_name[..pos], &skill_name[pos + 1..])
+ } else {
+ skill_name.to_string()
+ }
+}
+
+/// Map internal skill directory name to agent-native command file name.
+/// Format depends on the agent:
+/// - Claude/Gemini: "agtx-plan" β†’ "plan.md" / "plan.toml" (namespace subdir handles prefix)
+/// - OpenCode: "agtx-plan" β†’ "agtx-plan.md" (flat directory, full name)
+/// - Codex: uses SKILL.md in skill directories (handled separately)
+pub fn skill_dir_to_filename(skill_dir_name: &str, agent_name: &str) -> String {
+ match agent_name {
+ "gemini" => {
+ let short = skill_dir_name.strip_prefix("agtx-").unwrap_or(skill_dir_name);
+ format!("{}.toml", short)
+ }
+ "opencode" => {
+ // Flat structure: command/agtx-plan.md (invoked as /agtx-plan)
+ format!("{}.md", skill_dir_name)
+ }
+ _ => {
+ let short = skill_dir_name.strip_prefix("agtx-").unwrap_or(skill_dir_name);
+ format!("{}.md", short)
+ }
+ }
+}
+
+/// Generate the send_keys command to invoke a skill interactively.
+/// Returns None for agents without interactive skill invocation.
+///
+/// Each agent has a different syntax:
+/// - Claude: `/agtx:plan` (slash command from .claude/commands/)
+/// - Gemini: `/agtx:plan` (slash command from .gemini/commands/)
+/// - OpenCode: `/agtx-plan` (slash command, hyphen separator)
+/// - Codex: `$agtx-plan` (dollar-sign mention from .codex/skills/)
+pub fn skill_invocation_command(agent_name: &str, skill_dir_name: &str) -> Option<String> {
+ match agent_name {
+ "claude" | "gemini" => {
+ let cmd = skill_name_to_command(skill_dir_name);
+ Some(format!("/{}", cmd))
+ }
+ "opencode" => {
+ Some(format!("/{}", skill_dir_name))
+ }
+ "codex" => {
+ Some(format!("${}", skill_dir_name))
+ }
+ _ => None,
+ }
+}
+
+/// Transform a canonical plugin command (Claude/Gemini format) for a specific agent.
+///
+/// Plugin commands in plugin.toml are stored in canonical form: `/namespace:command args`
+/// This transforms them for each agent's expected syntax:
+/// - Claude/Gemini: unchanged (`/gsd:plan-phase 1`)
+/// - OpenCode: colon β†’ hyphen (`/gsd-plan-phase 1`)
+/// - Codex: slash β†’ dollar + colon β†’ hyphen (`$gsd-plan-phase 1`)
+/// - Unsupported agents: None (will fall back to file-path reference)
+pub fn transform_plugin_command(canonical_cmd: &str, agent_name: &str) -> Option<String> {
+ match agent_name {
+ "claude" | "gemini" => Some(canonical_cmd.to_string()),
+ "opencode" => {
+ // /gsd:plan-phase 1 β†’ /gsd-plan-phase 1
+ Some(canonical_cmd.replacen(':', "-", 1))
+ }
+ "codex" => {
+ // /gsd:plan-phase 1 β†’ $gsd-plan-phase 1
+ let transformed = canonical_cmd.replacen(':', "-", 1);
+ if let Some(rest) = transformed.strip_prefix('/') {
+ Some(format!("${}", rest))
+ } else {
+ Some(transformed)
+ }
+ }
+ _ => None,
+ }
+}
+
+/// Generate skill reference text for prompts (fallback for agents without interactive invocation).
+/// For agents with skill invocation: empty string (skill is invoked via send_keys).
+/// For agents without: "Follow the instructions in .agtx/skills/agtx-plan/SKILL.md"
+pub fn skill_reference(agent_name: &str, skill_dir_name: &str) -> String {
+ if skill_invocation_command(agent_name, skill_dir_name).is_some() {
+ String::new()
+ } else {
+ format!(
+ "Follow the instructions in .agtx/skills/{}/SKILL.md",
+ skill_dir_name
+ )
+ }
+}
+
+/// Map a phase name to the corresponding skill directory name.
+pub fn phase_to_skill_dir(phase: &str) -> &'static str {
+ match phase {
+ "research" => "agtx-research",
+ "planning" | "planning_with_research" => "agtx-plan",
+ "running" => "agtx-execute",
+ "review" => "agtx-review",
+ _ => "",
+ }
+}
+
+/// Strip YAML frontmatter from a skill file, returning just the body content.
+pub fn strip_frontmatter(content: &str) -> &str {
+ if content.starts_with("---") {
+ if let Some(end) = content[3..].find("---") {
+ let after = &content[3 + end + 3..];
+ return after.trim_start_matches('\n');
+ }
+ }
+ content
+}
+
+/// Convert skill content to Gemini TOML command format.
+/// Gemini commands are .toml files with `description` and `prompt` fields.
+pub fn skill_to_gemini_toml(description: &str, skill_content: &str) -> String {
+ let body = strip_frontmatter(skill_content);
+ // Escape backslashes and triple-quotes for TOML multi-line strings
+ let escaped = body.replace('\\', "\\\\").replace("\"\"\"", "\\\"\\\"\\\"");
+ format!(
+ "description = \"{}\"\n\nprompt = \"\"\"\n{}\n\"\"\"\n",
+ description.replace('"', "\\\""),
+ escaped
+ )
+}
+
+/// Bundled plugin configurations: (name, description, plugin.toml content)
+/// These are embedded at compile time so the TUI can install them without external files.
+pub const BUNDLED_PLUGINS: &[(&str, &str, &str)] = &[
+ (
+ "gsd",
+ "Get Shit Done - structured spec-driven development",
+ include_str!("../plugins/gsd/plugin.toml"),
+ ),
+ (
+ "spec-kit",
+ "Spec-Driven Development by GitHub",
+ include_str!("../plugins/spec-kit/plugin.toml"),
+ ),
+ (
+ "void",
+ "Plain agent session - no prompting or skills",
+ include_str!("../plugins/void/plugin.toml"),
+ ),
+];
+
+/// Extract the description from YAML frontmatter.
+pub fn extract_description(content: &str) -> Option<String> {
+ if content.starts_with("---") {
+ if let Some(end) = content[3..].find("---") {
+ let frontmatter = &content[3..3 + end];
+ for line in frontmatter.lines() {
+ if let Some(desc) = line.strip_prefix("description:") {
+ return Some(desc.trim().to_string());
+ }
+ }
+ }
+ }
+ None
+}
diff --git a/src/tmux/operations.rs b/src/tmux/operations.rs
index 4e14683..875528e 100644
--- a/src/tmux/operations.rs
+++ b/src/tmux/operations.rs
@@ -65,7 +65,9 @@ impl TmuxOperations for RealTmuxOps {
.args(["-c", working_dir]);
if let Some(ref shell_cmd) = command {
- cmd.args(["sh", "-c", shell_cmd]);
+ // Wrap command so it drops to a shell after the agent exits
+ let wrapped = format!("{}; exec $SHELL", shell_cmd);
+ cmd.args(["sh", "-c", &wrapped]);
}
let output = cmd.output()?;
diff --git a/src/tui/app.rs b/src/tui/app.rs
index ca14193..eb97b93 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -5,15 +5,17 @@ use crossterm::{
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{prelude::*, widgets::*};
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use std::io::{self, Stdout};
use std::path::{Path, PathBuf};
use std::sync::{mpsc, Arc};
+use std::time::Instant;
use crate::agent::{self, AgentOperations};
-use crate::config::{GlobalConfig, MergedConfig, ProjectConfig, ThemeConfig};
-use crate::db::{Database, Task, TaskStatus};
+use crate::config::{GlobalConfig, MergedConfig, ProjectConfig, ThemeConfig, WorkflowPlugin};
+use crate::db::{Database, PhaseStatus, Task, TaskStatus};
use crate::git::{self, GitOperations, GitProviderOperations, PullRequestState, RealGitHubOps, RealGitOps};
+use crate::skills;
use crate::tmux::{self, RealTmuxOps, TmuxOperations};
use crate::AppMode;
@@ -36,7 +38,7 @@ fn build_footer_text(input_mode: InputMode, sidebar_focused: bool, selected_colu
" [j/k] navigate [Enter] open [l] board [e] hide sidebar [q] quit ".to_string()
} else {
match selected_column {
- 0 => " [o] new [/] search [Enter] open [x] del [d] diff [m] plan [M] run [e] sidebar [q] quit".to_string(),
+ 0 => " [o] new [/] search [Enter] open [x] del [d] diff [R] research [m] plan [M] run [e] sidebar [q] quit".to_string(),
1 => " [o] new [/] search [Enter] open [x] del [d] diff [m] run [e] sidebar [q] quit".to_string(),
2 | 3 => " [o] new [/] search [Enter] open [x] del [d] diff [m] move [r] move left [e] sidebar [q] quit".to_string(),
_ => " [o] new [/] search [Enter] open [x] del [e] sidebar [q] quit".to_string(),
@@ -114,6 +116,14 @@ struct AppState {
delete_confirm_popup: Option<DeleteConfirmPopup>,
// Confirmation popup for asking if user wants to create PR when moving to Review
review_confirm_popup: Option<ReviewConfirmPopup>,
+ // Phase detection
+ phase_status_cache: HashMap<String, (PhaseStatus, Instant)>,
+ spinner_frame: usize,
+ cached_plugin: Option<Option<WorkflowPlugin>>,
+ // Transient warning message shown in footer (auto-clears after a few seconds)
+ warning_message: Option<(String, Instant)>,
+ // Plugin selection popup
+ plugin_select_popup: Option<PluginSelectPopup>,
}
/// State for confirming move to Done
@@ -205,6 +215,21 @@ struct ReviewConfirmPopup {
task_title: String,
}
+/// State for plugin selection popup
+#[derive(Debug, Clone)]
+struct PluginSelectPopup {
+ selected: usize,
+ options: Vec<PluginOption>,
+}
+
+#[derive(Debug, Clone)]
+struct PluginOption {
+ name: String, // "" for none, "gsd", "spec-kit", etc.
+ label: String, // Display name
+ description: String, // One-line description
+ active: bool, // Currently active for this project
+}
+
pub struct App {
terminal: Terminal,
state: AppState,
@@ -307,9 +332,20 @@ impl App {
done_confirm_popup: None,
delete_confirm_popup: None,
review_confirm_popup: None,
+ phase_status_cache: HashMap::new(),
+ spinner_frame: 0,
+ cached_plugin: None,
+ warning_message: None,
+ plugin_select_popup: None,
},
};
+ // Load and cache workflow plugin
+ app.state.cached_plugin = Some(load_plugin_if_configured(
+ &app.state.config,
+ app.state.project_path.as_deref(),
+ ));
+
// Load tasks if in project mode
app.refresh_tasks()?;
// Load projects from global database
@@ -373,6 +409,13 @@ impl App {
// Periodically refresh session status
self.refresh_sessions()?;
+
+ // Clear expired warning messages
+ if let Some((_, created)) = &self.state.warning_message {
+ if created.elapsed() >= std::time::Duration::from_secs(5) {
+ self.state.warning_message = None;
+ }
+ }
}
Ok(())
@@ -432,8 +475,19 @@ impl App {
.split(content_area);
// Header
- let header = Paragraph::new(format!(" {} ", state.project_name))
- .style(Style::default().fg(Color::Cyan).bold())
+ let 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![
+ 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
+ let mut spans = vec![left, Span::raw(" ".repeat(padding))];
+ spans.extend(right_spans);
+ let header = Paragraph::new(Line::from(spans))
.block(Block::default().borders(Borders::ALL));
frame.render_widget(header, chunks[0]);
@@ -517,7 +571,7 @@ impl App {
break;
}
- Self::draw_task_card(frame, task, card_area, is_selected, &state.config.theme);
+ Self::draw_task_card(frame, task, card_area, is_selected, &state.config.theme, state.phase_status_cache.get(&task.id), state.spinner_frame);
}
// Draw scrollbar if needed
@@ -554,11 +608,21 @@ impl App {
}
}
- // Footer with help
- let footer_text = build_footer_text(state.input_mode, state.sidebar_focused, state.board.selected_column);
+ // Footer with help (or transient warning)
+ let (footer_text, footer_style) = if let Some((ref msg, created)) = state.warning_message {
+ if created.elapsed() < std::time::Duration::from_secs(5) {
+ (msg.clone(), Style::default().fg(Color::Yellow))
+ } else {
+ (build_footer_text(state.input_mode, state.sidebar_focused, state.board.selected_column),
+ Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)))
+ }
+ } else {
+ (build_footer_text(state.input_mode, state.sidebar_focused, state.board.selected_column),
+ Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)))
+ };
let footer = Paragraph::new(footer_text.as_str())
- .style(Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)))
+ .style(footer_style)
.block(Block::default().borders(Borders::ALL));
frame.render_widget(footer, chunks[2]);
@@ -988,6 +1052,51 @@ impl App {
frame.render_widget(content, inner);
}
+ // Plugin selection popup
+ if let Some(ref popup) = state.plugin_select_popup {
+ let popup_area = centered_rect(50, 40, area);
+ frame.render_widget(Clear, popup_area);
+
+ let main_block = Block::default()
+ .title(" Select Workflow Plugin ")
+ .borders(Borders::ALL)
+ .border_style(Style::default().fg(hex_to_color(&state.config.theme.color_popup_border)));
+ frame.render_widget(main_block, popup_area);
+
+ let inner = popup_area.inner(ratatui::layout::Margin { horizontal: 2, vertical: 1 });
+ let mut lines: Vec<Line> = Vec::new();
+
+ for (i, opt) in popup.options.iter().enumerate() {
+ let is_selected = i == popup.selected;
+ let marker = if is_selected { "> " } else { " " };
+ let check = if opt.active { " βœ“" } else { "" };
+
+ let name_style = if is_selected {
+ Style::default().fg(hex_to_color(&state.config.theme.color_selected)).add_modifier(Modifier::BOLD)
+ } else {
+ Style::default().fg(hex_to_color(&state.config.theme.color_text))
+ };
+
+ lines.push(Line::from(vec![
+ Span::styled(marker, name_style),
+ Span::styled(&opt.label, name_style),
+ Span::styled(check, Style::default().fg(Color::Green)),
+ ]));
+
+ let desc_style = Style::default().fg(hex_to_color(&state.config.theme.color_description));
+ lines.push(Line::from(Span::styled(format!(" {}", opt.description), desc_style)));
+ lines.push(Line::from(""));
+ }
+
+ lines.push(Line::from(Span::styled(
+ " [Enter] select [Esc] cancel",
+ Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)),
+ )));
+
+ let content = Paragraph::new(lines);
+ frame.render_widget(content, inner);
+ }
+
// Git diff popup
if let Some(ref popup) = state.diff_popup {
let popup_area = centered_rect(80, 80, area);
@@ -1068,7 +1177,7 @@ impl App {
shell_popup::render_shell_popup(popup, frame, popup_area, styled_lines, &colors);
}
- fn draw_task_card(frame: &mut Frame, task: &Task, area: Rect, is_selected: bool, theme: &ThemeConfig) {
+ fn draw_task_card(frame: &mut Frame, task: &Task, area: Rect, is_selected: bool, theme: &ThemeConfig, phase_status: Option<&(PhaseStatus, Instant)>, spinner_frame: usize) {
let border_style = if is_selected {
Style::default().fg(hex_to_color(&theme.color_selected))
} else {
@@ -1103,15 +1212,41 @@ impl App {
let inner = card_block.inner(area);
frame.render_widget(card_block, area);
- // Title line
- let title_line = Paragraph::new(title).style(title_style);
- let title_area = Rect {
- x: inner.x,
- y: inner.y,
- width: inner.width,
- height: 1,
- };
- frame.render_widget(title_line, title_area);
+ // Title line with optional phase indicator
+ let show_indicator = matches!(task.status,
+ TaskStatus::Planning | TaskStatus::Running | TaskStatus::Review)
+ || (task.status == TaskStatus::Backlog && task.session_name.is_some());
+
+ if show_indicator {
+ const SPINNER_FRAMES: &[&str] = &["\u{280b}", "\u{2819}", "\u{2839}", "\u{2838}", "\u{283c}", "\u{2834}", "\u{2826}", "\u{2827}", "\u{2807}", "\u{280f}"];
+ let indicator = match phase_status {
+ Some((PhaseStatus::Ready, _)) => Span::styled("\u{2713} ", Style::default().fg(Color::Green)),
+ Some((PhaseStatus::Working, _)) => {
+ let spinner = SPINNER_FRAMES[spinner_frame % SPINNER_FRAMES.len()];
+ Span::styled(format!("{} ", spinner), Style::default().fg(Color::Yellow))
+ }
+ Some((PhaseStatus::Exited, _)) => Span::styled("\u{2717} ", Style::default().fg(Color::Red)),
+ None => Span::raw(""),
+ };
+ let title_spans = Line::from(vec![indicator, Span::styled(title, title_style)]);
+ let title_line = Paragraph::new(title_spans);
+ let title_area = Rect {
+ x: inner.x,
+ y: inner.y,
+ width: inner.width,
+ height: 1,
+ };
+ frame.render_widget(title_line, title_area);
+ } else {
+ let title_line = Paragraph::new(title).style(title_style);
+ let title_area = Rect {
+ x: inner.x,
+ y: inner.y,
+ width: inner.width,
+ height: 1,
+ };
+ frame.render_widget(title_line, title_area);
+ }
// Preview area (below title) - always show description
if inner.height > 1 {
@@ -1293,6 +1428,11 @@ impl App {
return self.handle_pr_confirm_key(key);
}
+ // Handle plugin selection popup if open
+ if self.state.plugin_select_popup.is_some() {
+ return self.handle_plugin_select_key(key);
+ }
+
// Handle task search popup if open
if self.state.task_search.is_some() {
return self.handle_task_search_key(key);
@@ -1375,6 +1515,94 @@ impl App {
Ok(())
}
+ fn open_plugin_select_popup(&mut self) {
+ let current = self.state.config.workflow_plugin.as_deref().unwrap_or("");
+ let mut options = vec![PluginOption {
+ name: String::new(),
+ label: "agtx".to_string(),
+ description: "Built-in workflow with skills and prompts".to_string(),
+ active: current.is_empty(),
+ }];
+ for (name, desc, _content) in skills::BUNDLED_PLUGINS {
+ options.push(PluginOption {
+ name: name.to_string(),
+ label: name.to_string(),
+ description: desc.to_string(),
+ active: current == *name,
+ });
+ }
+ let selected = options.iter().position(|o| o.active).unwrap_or(0);
+ self.state.plugin_select_popup = Some(PluginSelectPopup { selected, options });
+ }
+
+ fn handle_plugin_select_key(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {
+ if let Some(ref mut popup) = self.state.plugin_select_popup {
+ match key.code {
+ KeyCode::Char('j') | KeyCode::Down => {
+ if popup.selected < popup.options.len().saturating_sub(1) {
+ popup.selected += 1;
+ }
+ }
+ KeyCode::Char('k') | KeyCode::Up => {
+ if popup.selected > 0 {
+ popup.selected -= 1;
+ }
+ }
+ KeyCode::Enter => {
+ let name = popup.options[popup.selected].name.clone();
+ self.state.plugin_select_popup = None;
+ self.install_plugin(&name)?;
+ }
+ KeyCode::Esc => {
+ self.state.plugin_select_popup = None;
+ }
+ _ => {}
+ }
+ }
+ Ok(())
+ }
+
+ fn install_plugin(&mut self, plugin_name: &str) -> Result<()> {
+ let Some(project_path) = self.state.project_path.clone() else {
+ return Ok(());
+ };
+
+ // Load current project config
+ let mut project_config = ProjectConfig::load(&project_path).unwrap_or_default();
+
+ if plugin_name.is_empty() {
+ // Clear plugin
+ project_config.workflow_plugin = None;
+ } else {
+ // Find bundled plugin content and write it
+ if let Some((_name, _desc, content)) = skills::BUNDLED_PLUGINS
+ .iter()
+ .find(|(n, _, _)| *n == plugin_name)
+ {
+ let plugin_dir = project_path
+ .join(".agtx")
+ .join("plugins")
+ .join(plugin_name);
+ let _ = std::fs::create_dir_all(&plugin_dir);
+ let _ = std::fs::write(plugin_dir.join("plugin.toml"), content);
+ }
+ project_config.workflow_plugin = Some(plugin_name.to_string());
+ }
+
+ // Save project config
+ project_config.save(&project_path)?;
+
+ // Refresh merged config and cached plugin
+ let global_config = GlobalConfig::load().unwrap_or_default();
+ self.state.config = MergedConfig::merge(&global_config, &project_config);
+ self.state.cached_plugin = Some(load_plugin_if_configured(
+ &self.state.config,
+ Some(&project_path),
+ ));
+
+ Ok(())
+ }
+
fn force_move_to_done(&mut self, task_id: &str) -> Result<()> {
if let (Some(db), Some(project_path)) = (&self.state.db, self.state.project_path.clone()) {
if let Some(mut task) = db.get_task(task_id)? {
@@ -1886,9 +2114,11 @@ impl App {
self.state.editing_task_id = None;
}
KeyCode::Enter => {
- // If in Backlog, edit the task; otherwise open shell popup
if let Some(task) = self.state.board.selected_task() {
- if task.status == TaskStatus::Backlog {
+ if task.status == TaskStatus::Backlog && task.session_name.is_some() {
+ // Backlog task with active research session β€” open tmux popup
+ self.open_selected_task()?;
+ } else if task.status == TaskStatus::Backlog {
// Edit task
self.state.editing_task_id = Some(task.id.clone());
self.state.input_buffer = task.title.clone();
@@ -1905,6 +2135,14 @@ impl App {
KeyCode::Char('d') => self.show_task_diff()?,
KeyCode::Char('m') => self.move_task_right()?,
KeyCode::Char('M') => self.move_backlog_to_running()?,
+ KeyCode::Char('R') => {
+ if let Some(task) = self.state.board.selected_task() {
+ if task.status == TaskStatus::Backlog && task.session_name.is_none() {
+ let task_id = task.id.clone();
+ self.start_research(&task_id)?;
+ }
+ }
+ }
KeyCode::Char('r') => {
if let Some(task) = self.state.board.selected_task() {
let task_id = task.id.clone();
@@ -1925,6 +2163,10 @@ impl App {
selected: 0,
});
}
+ KeyCode::Char('P') => {
+ // Open plugin selection popup
+ self.open_plugin_select_popup();
+ }
_ => {}
}
Ok(())
@@ -2239,7 +2481,12 @@ impl App {
fn show_task_diff(&mut self) -> Result<()> {
if let Some(task) = self.state.board.selected_task() {
let diff_content = if let Some(worktree_path) = &task.worktree_path {
- collect_task_diff(worktree_path, self.state.git_ops.as_ref())
+ let mut exclude_prefixes: Vec<&str> = crate::git::AGENT_CONFIG_DIRS.to_vec();
+ let plugin = self.load_task_plugin(task);
+ let plugin_dirs: Vec<String> = plugin.map_or_else(Vec::new, |p| p.copy_dirs.clone());
+ let plugin_dir_refs: Vec<&str> = plugin_dirs.iter().map(|s| s.as_str()).collect();
+ exclude_prefixes.extend(plugin_dir_refs);
+ collect_task_diff(worktree_path, self.state.git_ops.as_ref(), &exclude_prefixes)
} else {
"(task has no worktree yet)".to_string()
};
@@ -2275,76 +2522,142 @@ impl App {
if let Some(new_status) = next_status {
// Create worktree and tmux window when moving from Backlog to Planning
if current_status == TaskStatus::Backlog && new_status == TaskStatus::Planning {
- // Build the prompt from task title and description
- // Instruct agent to plan first and wait for approval
- let task_content = if let Some(desc) = &task.description {
- format!("{}\n\n{}", task.title, desc)
- } else {
- task.title.clone()
- };
- let prompt = format!(
- "Task: {}\n\nPlease analyze this task and create a detailed implementation plan. \
- List the files you'll need to modify and the changes you'll make. \
- Wait for my approval before making any changes.",
- task_content
- );
+ // Stamp plugin on task if not already set (may be set from research)
+ if task.plugin.is_none() {
+ task.plugin = self.state.config.workflow_plugin.clone();
+ }
+ let plugin = self.load_task_plugin(&task);
- let target = setup_task_worktree(
- &mut task,
- &project_path,
- &self.state.project_name,
- &prompt,
- self.state.config.copy_files.clone(),
- self.state.config.init_script.clone(),
- self.state.tmux_ops.as_ref(),
- self.state.git_ops.as_ref(),
- self.state.agent_registry.get(&self.state.config.default_agent).as_ref(),
- )?;
-
- // Wait for agent to show the bypass warning prompt, then accept it and rename session
- // Poll until we see "Yes, I accept" option or timeout after 5 seconds
- let target_clone = target.clone();
- let task_id_clone = task.id.clone();
- let tmux_ops = Arc::clone(&self.state.tmux_ops);
- std::thread::spawn(move || {
- let mut accepted = false;
- for _ in 0..50 {
- std::thread::sleep(std::time::Duration::from_millis(100));
-
- // Check pane content for the bypass prompt
- if let Ok(content) = tmux_ops.capture_pane(&target_clone) {
- // Look for the bypass warning prompt options
- if content.contains("Yes, I accept") || content.contains("I accept the risk") {
- // Found the prompt, send "2" and Enter
- let _ = tmux_ops.send_keys_literal(&target_clone, "2");
- std::thread::sleep(std::time::Duration::from_millis(50));
- let _ = tmux_ops.send_keys_literal(&target_clone, "Enter");
- accepted = true;
- break;
+ let has_live_session = task.session_name.as_ref().map_or(false, |s| {
+ self.state.tmux_ops.window_exists(s).unwrap_or(false)
+ });
+
+ if has_live_session {
+ // Reuse existing session from research β€” just send planning command
+ let target = task.session_name.clone().unwrap();
+ let task_content = if let Some(desc) = &task.description {
+ format!("{}\n\n{}", task.title, desc)
+ } else {
+ task.title.clone()
+ };
+ let skill_cmd = resolve_skill_command(&plugin, "planning", &self.state.config.default_agent, &task_content);
+ let prompt = resolve_prompt(&plugin, "planning", &task_content, &task.id, &self.state.config.default_agent);
+
+ let tmux_ops = Arc::clone(&self.state.tmux_ops);
+ let task_content_clone = task_content.clone();
+ std::thread::spawn(move || {
+ if let Some(ref cmd) = skill_cmd {
+ let _ = tmux_ops.send_keys(&target, cmd);
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ }
+ if !prompt.is_empty() {
+ let _ = tmux_ops.send_keys(&target, &prompt);
+ } else if skill_cmd.is_none() {
+ // No command and no prompt (e.g. void plugin): prefill task in input
+ let oneline = task_content_clone.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).collect::<Vec<_>>().join(" ");
+ if !oneline.is_empty() {
+ let _ = tmux_ops.send_keys_literal(&target, &oneline);
}
}
- }
-
- // After accepting, wait for agent to be ready and rename the session
- if accepted {
- std::thread::sleep(std::time::Duration::from_millis(1000));
- // Send /rename command to name the session with task ID for later resume
- let rename_cmd = format!("/rename {}", task_id_clone);
- let _ = tmux_ops.send_keys(&target_clone, &rename_cmd);
- }
- });
+ });
+ } else {
+ // No research session β€” create worktree + tmux window from scratch
+ let task_content = if let Some(desc) = &task.description {
+ format!("{}\n\n{}", task.title, desc)
+ } else {
+ task.title.clone()
+ };
+ let prompt = resolve_prompt(&plugin, "planning", &task_content, &task.id, &self.state.config.default_agent);
+
+ let target = setup_task_worktree(
+ &mut task,
+ &project_path,
+ &self.state.project_name,
+ &prompt,
+ self.state.config.copy_files.clone(),
+ self.state.config.init_script.clone(),
+ &plugin,
+ &self.state.config.default_agent,
+ self.state.tmux_ops.as_ref(),
+ self.state.git_ops.as_ref(),
+ self.state.agent_registry.get(&self.state.config.default_agent).as_ref(),
+ )?;
+
+ // Wait for agent to be ready, then send skill command and task content
+ let target_clone = target.clone();
+ let tmux_ops = Arc::clone(&self.state.tmux_ops);
+ let skill_cmd = resolve_skill_command(&plugin, "planning", &self.state.config.default_agent, &task_content);
+ let prompt_clone = prompt.clone();
+ let prompt_trigger = resolve_prompt_trigger(&plugin, "planning");
+ let task_content_clone = task_content.clone();
+ std::thread::spawn(move || {
+ if let Some(target) = wait_for_agent_ready(&tmux_ops, &target_clone) {
+ if let Some(ref cmd) = skill_cmd {
+ let _ = tmux_ops.send_keys(&target, cmd);
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ }
+ if !prompt_clone.is_empty() {
+ if let Some(ref trigger) = prompt_trigger {
+ if wait_for_prompt_trigger(&tmux_ops, &target, trigger) {
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ let _ = tmux_ops.send_keys(&target, &prompt_clone);
+ }
+ } else {
+ let _ = tmux_ops.send_keys(&target, &prompt_clone);
+ }
+ } else if skill_cmd.is_none() {
+ // No command and no prompt (e.g. void plugin): prefill task in input
+ let oneline = task_content_clone.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).collect::<Vec<_>>().join(" ");
+ if !oneline.is_empty() {
+ let _ = tmux_ops.send_keys_literal(&target, &oneline);
+ }
+ }
+ }
+ });
+ }
}
- // When moving from Planning to Running, tell agent to start implementing
+ // When moving from Planning to Running, send skill command to agent
if current_status == TaskStatus::Planning && new_status == TaskStatus::Running {
if let Some(session_name) = &task.session_name {
- // Send message to start implementation (send_keys adds Enter at the end)
- let _ = self.state.tmux_ops.send_keys(session_name, "Looks good, please proceed with the implementation.");
+ let plugin = self.load_task_plugin(&task);
+ let task_content = if let Some(desc) = &task.description {
+ format!("{}\n\n{}", task.title, desc)
+ } else {
+ task.title.clone()
+ };
+ let skill_cmd = resolve_skill_command(&plugin, "running", &self.state.config.default_agent, &task_content);
+ if let Some(cmd) = skill_cmd {
+ let _ = self.state.tmux_ops.send_keys(session_name, &cmd);
+ } else {
+ let msg = resolve_prompt(&plugin, "running", &task_content, &task.id, &self.state.config.default_agent);
+ if !msg.is_empty() {
+ let _ = self.state.tmux_ops.send_keys(session_name, &msg);
+ }
+ }
}
}
- // When moving from Running to Review: Ask if user wants to create PR
+ // When moving from Running to Review: send skill command, then ask about PR
if current_status == TaskStatus::Running && new_status == TaskStatus::Review {
+ // Send review skill command to agent
+ if let Some(session_name) = &task.session_name {
+ let plugin = self.load_task_plugin(&task);
+ let task_content = if let Some(desc) = &task.description {
+ format!("{}\n\n{}", task.title, desc)
+ } else {
+ task.title.clone()
+ };
+ let skill_cmd = resolve_skill_command(&plugin, "review", &self.state.config.default_agent, &task_content);
+ if let Some(cmd) = skill_cmd {
+ let _ = self.state.tmux_ops.send_keys(session_name, &cmd);
+ } else {
+ let msg = resolve_prompt(&plugin, "review", &task_content, &task.id, &self.state.config.default_agent);
+ if !msg.is_empty() {
+ let _ = self.state.tmux_ops.send_keys(session_name, &msg);
+ }
+ }
+ }
// Check if PR already exists (task was resumed from Review)
if task.pr_number.is_some() {
// PR already exists - just commit and push the new changes
@@ -2435,6 +2748,85 @@ impl App {
Ok(())
}
+ /// Start a research session for a Backlog task (creates worktree, reused in planning)
+ fn start_research(&mut self, task_id: &str) -> Result<()> {
+ let mut task = {
+ let Some(db) = &self.state.db else { return Ok(()) };
+ let Some(task) = db.get_task(task_id)? else { return Ok(()) };
+ task
+ };
+ let Some(project_path) = self.state.project_path.clone() else { return Ok(()) };
+ // Stamp plugin on task for research
+ task.plugin = self.state.config.workflow_plugin.clone();
+ let plugin = self.load_task_plugin(&task);
+ let agent_name = self.state.config.default_agent.clone();
+
+ let task_content = if let Some(desc) = &task.description {
+ format!("{}\n\n{}", task.title, desc)
+ } else {
+ task.title.clone()
+ };
+
+ let prompt = resolve_prompt(&plugin, "research", &task_content, &task.id, &agent_name);
+
+ // Create worktree + tmux window (same as planning, so it can be reused)
+ let target = setup_task_worktree(
+ &mut task,
+ &project_path,
+ &self.state.project_name,
+ &prompt,
+ self.state.config.copy_files.clone(),
+ self.state.config.init_script.clone(),
+ &plugin,
+ &agent_name,
+ self.state.tmux_ops.as_ref(),
+ self.state.git_ops.as_ref(),
+ self.state.agent_registry.get(&agent_name).as_ref(),
+ )?;
+
+ // Send research skill command + task prompt (with optional trigger polling)
+ let target_clone = target.clone();
+ let tmux_ops = Arc::clone(&self.state.tmux_ops);
+ let skill_cmd = resolve_skill_command(&plugin, "research", &agent_name, &task_content);
+ let prompt_clone = prompt.clone();
+ let prompt_trigger = resolve_prompt_trigger(&plugin, "research");
+ let task_content_clone = task_content.clone();
+ std::thread::spawn(move || {
+ if let Some(target) = wait_for_agent_ready(&tmux_ops, &target_clone) {
+ if let Some(ref cmd) = skill_cmd {
+ let _ = tmux_ops.send_keys(&target, cmd);
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ }
+ if !prompt_clone.is_empty() {
+ if let Some(ref trigger) = prompt_trigger {
+ // Wait for the trigger text before sending the prompt
+ if wait_for_prompt_trigger(&tmux_ops, &target, trigger) {
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ let _ = tmux_ops.send_keys(&target, &prompt_clone);
+ }
+ } else {
+ let _ = tmux_ops.send_keys(&target, &prompt_clone);
+ }
+ } else if skill_cmd.is_none() {
+ // No command and no prompt (e.g. void plugin): prefill task in input
+ let oneline = task_content_clone.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).collect::<Vec<_>>().join(" ");
+ if !oneline.is_empty() {
+ let _ = tmux_ops.send_keys_literal(&target, &oneline);
+ }
+ }
+ }
+ });
+
+ // Store session name β€” task stays in Backlog
+ task.updated_at = chrono::Utc::now();
+ if let Some(db) = &self.state.db {
+ db.update_task(&task)?;
+ }
+ self.refresh_tasks()?;
+
+ Ok(())
+ }
+
/// Move task directly from Backlog to Running (skip Planning)
fn move_backlog_to_running(&mut self) -> Result<()> {
let (mut task, project_path) = match (
@@ -2460,6 +2852,9 @@ impl App {
task_content
);
+ // Stamp plugin on task
+ task.plugin = self.state.config.workflow_plugin.clone();
+ let plugin = self.load_task_plugin(&task);
let target = setup_task_worktree(
&mut task,
&project_path,
@@ -2467,36 +2862,36 @@ impl App {
&prompt,
self.state.config.copy_files.clone(),
self.state.config.init_script.clone(),
+ &plugin,
+ &self.state.config.default_agent,
self.state.tmux_ops.as_ref(),
self.state.git_ops.as_ref(),
self.state.agent_registry.get(&self.state.config.default_agent).as_ref(),
)?;
- // Wait for agent to show the bypass warning prompt, then accept it and rename session
+ // Wait for agent to be ready, then send execute skill command and task content
let target_clone = target.clone();
- let task_id_clone = task.id.clone();
let tmux_ops = Arc::clone(&self.state.tmux_ops);
+ let skill_cmd = resolve_skill_command(&plugin, "running", &self.state.config.default_agent, &task_content);
+ let prompt_clone = prompt.clone();
+ let prompt_trigger = resolve_prompt_trigger(&plugin, "running");
std::thread::spawn(move || {
- let mut accepted = false;
- for _ in 0..50 {
- std::thread::sleep(std::time::Duration::from_millis(100));
-
- if let Ok(content) = tmux_ops.capture_pane(&target_clone) {
- if content.contains("Yes, I accept") || content.contains("I accept the risk") {
- let _ = tmux_ops.send_keys_literal(&target_clone, "2");
- std::thread::sleep(std::time::Duration::from_millis(50));
- let _ = tmux_ops.send_keys_literal(&target_clone, "Enter");
- accepted = true;
- break;
+ if let Some(target) = wait_for_agent_ready(&tmux_ops, &target_clone) {
+ if let Some(ref cmd) = skill_cmd {
+ let _ = tmux_ops.send_keys(&target, cmd);
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ }
+ if !prompt_clone.is_empty() {
+ if let Some(ref trigger) = prompt_trigger {
+ if wait_for_prompt_trigger(&tmux_ops, &target, trigger) {
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ let _ = tmux_ops.send_keys(&target, &prompt_clone);
+ }
+ } else {
+ let _ = tmux_ops.send_keys(&target, &prompt_clone);
}
}
}
-
- if accepted {
- std::thread::sleep(std::time::Duration::from_millis(1000));
- let rename_cmd = format!("/rename {}", task_id_clone);
- let _ = tmux_ops.send_keys(&target_clone, &rename_cmd);
- }
});
task.status = TaskStatus::Running;
@@ -2573,6 +2968,21 @@ impl App {
Ok(())
}
+ /// Load the plugin that a specific task was created with.
+ /// Returns None for tasks created with agtx defaults (task.plugin is None).
+ fn load_task_plugin(&self, task: &Task) -> Option<WorkflowPlugin> {
+ let plugin = match &task.plugin {
+ Some(name) => WorkflowPlugin::load(name, self.state.project_path.as_deref()).ok(),
+ None => None,
+ };
+ if let Some(ref p) = plugin {
+ if !p.supports_agent(&self.state.config.default_agent) {
+ return None;
+ }
+ }
+ plugin
+ }
+
fn refresh_tasks(&mut self) -> Result<()> {
if let Some(db) = &self.state.db {
self.state.board.tasks = db.get_all_tasks()?;
@@ -2609,7 +3019,60 @@ impl App {
}
fn refresh_sessions(&mut self) -> Result<()> {
- // TODO: Periodically check tmux sessions and update task status
+ let now = Instant::now();
+ const CACHE_TTL: std::time::Duration = std::time::Duration::from_secs(2);
+
+ let project_path = self.state.project_path.clone();
+
+ let tasks_to_check: Vec<_> = self.state.board.tasks.iter()
+ .filter(|t| {
+ matches!(t.status, TaskStatus::Planning | TaskStatus::Running | TaskStatus::Review)
+ || (t.status == TaskStatus::Backlog && t.session_name.is_some())
+ })
+ .filter(|t| t.worktree_path.is_some() || t.session_name.is_some())
+ .map(|t| (t.id.clone(), t.status, t.worktree_path.clone(), t.plugin.clone()))
+ .collect();
+
+ // Cache loaded plugins by name to avoid reloading from disk for each task
+ let mut plugin_cache: HashMap<Option<String>, Option<WorkflowPlugin>> = HashMap::new();
+
+ for (task_id, status, worktree_path, task_plugin) in tasks_to_check {
+ if let Some((_, timestamp)) = self.state.phase_status_cache.get(&task_id) {
+ if now.duration_since(*timestamp) < CACHE_TTL {
+ continue;
+ }
+ }
+
+ let phase_status = if status == TaskStatus::Backlog {
+ // Research artifact: check worktree first, then project root
+ let found = worktree_path.as_ref().map_or(false, |wt| {
+ Path::new(wt).join(".agtx").join("research")
+ .join(format!("{}.md", task_id)).exists()
+ }) || project_path.as_ref().map_or(false, |pp| {
+ pp.join(".agtx").join("research")
+ .join(format!("{}.md", task_id)).exists()
+ });
+ if found { PhaseStatus::Ready } else { PhaseStatus::Working }
+ } else if let Some(ref wt) = worktree_path {
+ let plugin = plugin_cache.entry(task_plugin.clone()).or_insert_with(|| {
+ match &task_plugin {
+ Some(name) => WorkflowPlugin::load(name, self.state.project_path.as_deref()).ok(),
+ None => None,
+ }
+ });
+ if phase_artifact_exists(wt, status, plugin) {
+ PhaseStatus::Ready
+ } else {
+ PhaseStatus::Working
+ }
+ } else {
+ PhaseStatus::Working
+ };
+
+ self.state.phase_status_cache.insert(task_id, (phase_status, now));
+ }
+
+ self.state.spinner_frame = self.state.spinner_frame.wrapping_add(1);
Ok(())
}
@@ -2692,6 +3155,27 @@ fn cleanup_task_for_done(
tmux_ops: &dyn TmuxOperations,
git_ops: &dyn GitOperations,
) {
+ // Archive artifacts before removing worktree
+ if let Some(worktree) = &task.worktree_path {
+ let artifacts_dir = Path::new(worktree).join(".agtx");
+ if artifacts_dir.exists() {
+ let slug = task.branch_name.as_deref()
+ .and_then(|b| b.strip_prefix("task/"))
+ .unwrap_or(&task.id);
+ let archive_dir = project_path.join(".agtx").join("archive").join(slug);
+ if let Ok(()) = std::fs::create_dir_all(&archive_dir) {
+ if let Ok(entries) = std::fs::read_dir(&artifacts_dir) {
+ for entry in entries.flatten() {
+ let path = entry.path();
+ if path.is_file() && path.extension().map_or(false, |ext| ext == "md") {
+ let _ = std::fs::copy(&path, archive_dir.join(entry.file_name()));
+ }
+ }
+ }
+ }
+ }
+ }
+
if let Some(session_name) = &task.session_name {
let _ = tmux_ops.kill_window(session_name);
}
@@ -2709,6 +3193,10 @@ fn cleanup_task_for_done(
/// Creates worktree, initializes it (copy files + init script), creates tmux window with agent.
/// Updates task fields (session_name, worktree_path, branch_name) in place.
/// Returns the tmux target string on success.
+///
+/// `prompt` is used only for agents without native skill invocation (fallback).
+/// For agents with skill support, the agent starts with no prompt and the skill command
+/// is sent later via send_keys (see the acceptance thread in move_task_right).
fn setup_task_worktree(
task: &mut Task,
project_path: &Path,
@@ -2716,6 +3204,8 @@ fn setup_task_worktree(
prompt: &str,
copy_files: Option<String>,
init_script: Option<String>,
+ plugin: &Option<WorkflowPlugin>,
+ agent_name: &str,
tmux_ops: &dyn TmuxOperations,
git_ops: &dyn GitOperations,
agent_ops: &dyn AgentOperations,
@@ -2736,18 +3226,65 @@ fn setup_task_worktree(
// Initialize worktree: copy files and run init script
let worktree_path = Path::new(&worktree_path_str);
+ let copy_dirs = plugin.as_ref().map_or_else(Vec::new, |p| p.copy_dirs.clone());
let init_warnings = git_ops.initialize_worktree(
project_path,
worktree_path,
copy_files,
init_script,
+ copy_dirs,
);
for warning in &init_warnings {
eprintln!("Worktree init: {}", warning);
}
- // Build the interactive command using injected agent ops
- let agent_cmd = agent_ops.build_interactive_command(prompt);
+ // Write skills to worktree .agtx/skills/ and agent-native discovery paths
+ write_skills_to_worktree(&worktree_path_str, project_path, plugin, agent_name);
+
+ // Copy research artifact into worktree if it exists
+ let research_path = project_path.join(".agtx").join("research")
+ .join(format!("{}.md", task.id));
+ if research_path.exists() {
+ let dst_dir = Path::new(&worktree_path_str).join(".agtx");
+ let _ = std::fs::create_dir_all(&dst_dir);
+ let _ = std::fs::copy(&research_path, dst_dir.join("research.md"));
+ }
+
+ // Run plugin init_script (in addition to project init_script)
+ // Supports {agent} placeholder for agent-specific initialization
+ if let Some(ref p) = plugin {
+ if let Some(ref script) = p.init_script {
+ let script = script.replace("{agent}", agent_name);
+ let output = std::process::Command::new("sh")
+ .arg("-c").arg(&script)
+ .current_dir(&worktree_path_str)
+ .output();
+ match output {
+ Ok(o) if !o.status.success() => {
+ let stderr = String::from_utf8_lossy(&o.stderr);
+ anyhow::bail!(
+ "Plugin init_script failed (exit {}): {}\n{}",
+ o.status.code().unwrap_or(-1),
+ script,
+ stderr.trim()
+ );
+ }
+ Err(e) => {
+ anyhow::bail!("Plugin init_script failed to run: {}\n{}", script, e);
+ }
+ _ => {}
+ }
+ }
+ }
+
+ // Build the interactive command. For agents with skill/command support,
+ // start with no prompt β€” the skill command and task content are sent via send_keys.
+ let has_skill_support = resolve_skill_command(plugin, "planning", agent_name, "").is_some();
+ let agent_cmd = if has_skill_support {
+ agent_ops.build_interactive_command("")
+ } else {
+ agent_ops.build_interactive_command(prompt)
+ };
// Ensure project tmux session exists
ensure_project_tmux_session(project_name, project_path, tmux_ops);
@@ -2790,7 +3327,7 @@ fn delete_task_resources(
/// Collect git diff content from a worktree
/// Returns formatted diff sections (unstaged, staged, untracked)
-fn collect_task_diff(worktree_path: &str, git_ops: &dyn GitOperations) -> String {
+fn collect_task_diff(worktree_path: &str, git_ops: &dyn GitOperations, exclude_prefixes: &[&str]) -> String {
let worktree = Path::new(worktree_path);
let mut sections = Vec::new();
@@ -2811,7 +3348,12 @@ fn collect_task_diff(worktree_path: &str, git_ops: &dyn GitOperations) -> String
if !untracked.trim().is_empty() {
let mut untracked_section = String::from("=== Untracked Files ===\n");
for file in untracked.lines() {
- if file.trim().is_empty() {
+ let file = file.trim();
+ if file.is_empty() {
+ continue;
+ }
+ // Skip files in copied directories (agent configs, plugin dirs)
+ if exclude_prefixes.iter().any(|prefix| file.starts_with(&format!("{}/", prefix.trim_end_matches('/')))) {
continue;
}
// Show diff for untracked file (as if adding new file)
@@ -3327,6 +3869,336 @@ fn fuzzy_score(haystack: &str, needle: &str) -> i32 {
}
}
+/// Resolve the task prompt for a given phase transition, using plugin override or default.
+/// This returns the task content message only β€” skill invocation is handled separately via send_keys.
+/// For agents without native skill invocation, a file-path fallback is appended.
+fn resolve_prompt(plugin: &Option<WorkflowPlugin>, phase: &str, task_content: &str, task_id: &str, agent_name: &str) -> String {
+ let template = match phase {
+ "research" => plugin.as_ref()
+ .and_then(|p| p.prompts.research.as_deref())
+ .unwrap_or(skills::DEFAULT_PROMPT_RESEARCH),
+ "planning" => plugin.as_ref()
+ .and_then(|p| p.prompts.planning.as_deref())
+ .unwrap_or(skills::DEFAULT_PROMPT_PLANNING),
+ "planning_with_research" => plugin.as_ref()
+ .and_then(|p| p.prompts.planning.as_deref())
+ .unwrap_or(skills::DEFAULT_PROMPT_PLANNING_WITH_RESEARCH),
+ "running" => plugin.as_ref()
+ .and_then(|p| p.prompts.running.as_deref())
+ .unwrap_or(skills::DEFAULT_PROMPT_RUNNING),
+ "review" => plugin.as_ref()
+ .and_then(|p| p.prompts.review.as_deref())
+ .unwrap_or(skills::DEFAULT_PROMPT_REVIEW),
+ _ => return task_content.to_string(),
+ };
+
+ // Explicit empty prompt means "send nothing" (e.g., void plugin)
+ if template.is_empty() {
+ return String::new();
+ }
+
+ // For agents without interactive skill invocation, append a file-path reference
+ let skill_dir_name = skills::phase_to_skill_dir(phase);
+ let skill_ref = skills::skill_reference(agent_name, skill_dir_name);
+
+ let result = template
+ .replace("{task}", task_content)
+ .replace("{task_id}", task_id);
+
+ if skill_ref.is_empty() {
+ result
+ } else {
+ format!("{}\n\n{}", result, skill_ref)
+ }
+}
+
+/// Resolve the skill command to send via send_keys for a given phase.
+/// Checks plugin commands first, then falls back to agent-native skill invocation.
+/// Returns None if neither plugin nor agent has a command for this phase.
+fn resolve_skill_command(plugin: &Option<WorkflowPlugin>, phase: &str, agent_name: &str, task_content: &str) -> Option<String> {
+ // Plugin commands take priority (e.g., "/gsd:plan-phase 1")
+ // Commands are stored in canonical form (Claude/Gemini syntax) and transformed per agent
+ // Commands may contain {task} placeholder for inline task content
+ if let Some(ref p) = plugin {
+ let cmd = match phase {
+ "research" => p.commands.research.as_deref(),
+ "planning" | "planning_with_research" => p.commands.planning.as_deref(),
+ "running" => p.commands.running.as_deref(),
+ "review" => p.commands.review.as_deref(),
+ _ => None,
+ };
+ if let Some(c) = cmd {
+ if c.is_empty() {
+ // Explicit empty command means "no command" (e.g., void plugin)
+ return None;
+ }
+ // Collapse task content to single line for commands (newlines β†’ spaces)
+ let task_oneline = task_content.lines().map(|l| l.trim()).filter(|l| !l.is_empty()).collect::<Vec<_>>().join(" ");
+ let expanded = c.replace("{task}", &task_oneline);
+ return skills::transform_plugin_command(&expanded, agent_name);
+ }
+ }
+
+ // Fall back to agent-native agtx skill invocation (e.g., "/agtx:plan" for Claude)
+ let skill_dir = skills::phase_to_skill_dir(phase);
+ skills::skill_invocation_command(agent_name, skill_dir)
+}
+
+/// Resolve the prompt trigger text for a given phase.
+/// When set, the system polls the tmux pane for this text before sending the prompt.
+fn resolve_prompt_trigger(plugin: &Option<WorkflowPlugin>, phase: &str) -> Option<String> {
+ plugin.as_ref().and_then(|p| {
+ match phase {
+ "research" => p.prompt_triggers.research.clone(),
+ "planning" | "planning_with_research" => p.prompt_triggers.planning.clone(),
+ "running" => p.prompt_triggers.running.clone(),
+ "review" => p.prompt_triggers.review.clone(),
+ _ => None,
+ }
+ }).filter(|s| !s.is_empty())
+}
+
+/// Wait for a specific text to appear in a tmux pane, then return.
+/// Returns true if the trigger was found, false if timed out.
+fn wait_for_prompt_trigger(tmux_ops: &Arc<dyn TmuxOperations>, target: &str, trigger: &str) -> bool {
+ let mut last_content = String::new();
+ let mut stable_ticks = 0u32; // how many consecutive polls the content hasn't changed
+
+ for _ in 0..600 { // ~5 minutes (600 * 500ms) β€” long timeout to handle interactive steps
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ if let Ok(content) = tmux_ops.capture_pane(target) {
+ if content == last_content {
+ stable_ticks += 1;
+ } else {
+ stable_ticks = 0;
+ last_content = content.clone();
+ }
+ // Trigger when the text is present AND pane has been stable for ~2s.
+ // While the agent is reading files / generating output, content keeps
+ // changing. Once it asks the question and waits for input, it settles.
+ if stable_ticks >= 4 && content.contains(trigger) {
+ return true;
+ }
+ }
+ }
+ false
+}
+
+/// Check if the phase artifact exists for a task in its worktree
+fn phase_artifact_exists(worktree_path: &str, status: TaskStatus, plugin: &Option<WorkflowPlugin>) -> bool {
+ let rel_path = if let Some(ref p) = plugin {
+ match status {
+ TaskStatus::Planning => p.artifacts.planning.as_deref(),
+ TaskStatus::Running => p.artifacts.running.as_deref(),
+ TaskStatus::Review => p.artifacts.review.as_deref(),
+ _ => None,
+ }
+ } else {
+ None
+ };
+
+ let rel_path = rel_path.unwrap_or(match status {
+ TaskStatus::Planning => ".agtx/plan.md",
+ TaskStatus::Running => ".agtx/execute.md",
+ TaskStatus::Review => ".agtx/review.md",
+ _ => return false,
+ });
+
+ let full_path = Path::new(worktree_path).join(rel_path);
+
+ // Support simple wildcard: "specs/*/plan.md" matches any single directory level
+ if rel_path.contains('*') {
+ return glob_path_exists(&full_path.to_string_lossy());
+ }
+
+ full_path.exists()
+}
+
+/// Simple glob matching for paths with a single `*` wildcard (one directory level).
+/// e.g. "/path/to/specs/*/plan.md" matches "/path/to/specs/my-feature/plan.md"
+fn glob_path_exists(pattern: &str) -> bool {
+ let Some(star_pos) = pattern.find('*') else {
+ return Path::new(pattern).exists();
+ };
+
+ // Split at the wildcard: parent_dir / * / remainder
+ let parent = &pattern[..star_pos];
+ let remainder = &pattern[star_pos + 1..];
+ let parent = parent.trim_end_matches('/');
+
+ let Ok(entries) = std::fs::read_dir(parent) else {
+ return false;
+ };
+
+ for entry in entries.flatten() {
+ if !entry.path().is_dir() {
+ continue;
+ }
+ let candidate = format!("{}{}", entry.path().display(), remainder);
+ if remainder.contains('*') {
+ if glob_path_exists(&candidate) {
+ return true;
+ }
+ } else if Path::new(&candidate).exists() {
+ return true;
+ }
+ }
+ false
+}
+
+/// Wait for an agent in a tmux pane to be ready for input.
+/// Handles both the bypass warning prompt (sends acceptance) and agents that skip it.
+/// Returns the target string if the agent became ready, None on timeout.
+fn wait_for_agent_ready(tmux_ops: &Arc<dyn TmuxOperations>, target: &str) -> Option<String> {
+ for _ in 0..50 {
+ std::thread::sleep(std::time::Duration::from_millis(100));
+
+ if let Ok(content) = tmux_ops.capture_pane(target) {
+ // Check for bypass warning prompt (needs acceptance)
+ if content.contains("Yes, I accept") || content.contains("I accept the risk") {
+ let _ = tmux_ops.send_keys_literal(target, "2");
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ let _ = tmux_ops.send_keys_literal(target, "Enter");
+ std::thread::sleep(std::time::Duration::from_millis(1000));
+ return Some(target.to_string());
+ }
+ // Agent started without acceptance prompt (e.g. --dangerously-skip-permissions)
+ if content.contains(">") || content.contains("❯") || content.contains("$") {
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ return Some(target.to_string());
+ }
+ }
+ }
+ None
+}
+
+/// Load workflow plugin if configured
+fn load_plugin_if_configured(config: &MergedConfig, project_path: Option<&Path>) -> Option<WorkflowPlugin> {
+ config.workflow_plugin.as_ref()
+ .and_then(|name| WorkflowPlugin::load(name, project_path).ok())
+}
+
+/// Write skill files to a worktree's .agtx/skills/ directory and agent-native discovery paths.
+/// `agent_name` determines which native path to use (e.g. `.claude/commands/agtx/` for Claude).
+fn write_skills_to_worktree(worktree_path: &str, project_path: &Path, plugin: &Option<WorkflowPlugin>, agent_name: &str) {
+ let agtx_dir = Path::new(worktree_path).join(".agtx");
+ let _ = std::fs::create_dir_all(&agtx_dir);
+
+ // Write canonical .agtx/skills/ directory
+ let skills_dir = agtx_dir.join("skills");
+ if let Some(ref p) = plugin {
+ // Copy skills from plugin directory, falling back to built-in defaults
+ if let Some(plugin_dir) = WorkflowPlugin::plugin_dir(&p.name, Some(project_path)) {
+ for (skill_name, default_content) in skills::DEFAULT_SKILLS {
+ let src = plugin_dir.join(skill_name).join("SKILL.md");
+ let dst_dir = skills_dir.join(skill_name);
+ let _ = std::fs::create_dir_all(&dst_dir);
+ if src.exists() {
+ let _ = std::fs::copy(&src, dst_dir.join("SKILL.md"));
+ } else {
+ let _ = std::fs::write(dst_dir.join("SKILL.md"), default_content);
+ }
+ }
+ } else {
+ // Plugin dir not found, write defaults
+ for (skill_name, skill_content) in skills::DEFAULT_SKILLS {
+ let skill_dir = skills_dir.join(skill_name);
+ let _ = std::fs::create_dir_all(&skill_dir);
+ let _ = std::fs::write(skill_dir.join("SKILL.md"), skill_content);
+ }
+ }
+ } else {
+ // Write built-in default skills
+ for (skill_name, skill_content) in skills::DEFAULT_SKILLS {
+ let skill_dir = skills_dir.join(skill_name);
+ let _ = std::fs::create_dir_all(&skill_dir);
+ let _ = std::fs::write(skill_dir.join("SKILL.md"), skill_content);
+ }
+ }
+
+ // Write to agent-native discovery path (e.g. .claude/commands/agtx/)
+ if let Some((base_dir, namespace)) = skills::agent_native_skill_dir(agent_name) {
+ let native_dir = if namespace.is_empty() {
+ Path::new(worktree_path).join(base_dir)
+ } else {
+ Path::new(worktree_path).join(base_dir).join(namespace)
+ };
+ let _ = std::fs::create_dir_all(&native_dir);
+
+ for (skill_dir_name, default_content) in skills::DEFAULT_SKILLS {
+ let content = resolve_skill_content(plugin, skill_dir_name, project_path, default_content);
+
+ match agent_name {
+ "gemini" => {
+ // Gemini uses .toml command files with description + prompt fields
+ let description = skills::extract_description(&content)
+ .unwrap_or_else(|| format!("agtx {} phase skill", skill_dir_name));
+ let toml_content = skills::skill_to_gemini_toml(&description, &content);
+ let filename = skills::skill_dir_to_filename(skill_dir_name, agent_name);
+ let _ = std::fs::write(native_dir.join(&filename), toml_content);
+ }
+ "codex" => {
+ // Codex uses SKILL.md in skill-name/ subdirectories
+ let skill_subdir = native_dir.join(skill_dir_name);
+ let _ = std::fs::create_dir_all(&skill_subdir);
+ let _ = std::fs::write(skill_subdir.join("SKILL.md"), &content);
+ }
+ "opencode" => {
+ // OpenCode uses flat .md files: command/agtx-plan.md (invoked as /agtx-plan)
+ let content = transform_skill_for_opencode(&content);
+ let filename = skills::skill_dir_to_filename(skill_dir_name, agent_name);
+ let _ = std::fs::write(native_dir.join(&filename), content);
+ }
+ _ => {
+ // Claude and others: .md files with transformed frontmatter
+ let content = transform_skill_frontmatter(&content);
+ let filename = skills::skill_dir_to_filename(skill_dir_name, agent_name);
+ let _ = std::fs::write(native_dir.join(&filename), content);
+ }
+ }
+ }
+ }
+}
+
+/// Transform YAML frontmatter `name: agtx-plan` β†’ `name: agtx:plan` for agent commands
+fn transform_skill_frontmatter(content: &str) -> String {
+ if let Some(start) = content.find("name: agtx-") {
+ let after_name = &content[start + 6..]; // after "name: "
+ if let Some(newline) = after_name.find('\n') {
+ let old_name = after_name[..newline].trim();
+ let new_name = skills::skill_name_to_command(old_name);
+ return content.replacen(
+ &format!("name: {}", old_name),
+ &format!("name: {}", new_name),
+ 1,
+ );
+ }
+ }
+ content.to_string()
+}
+
+/// Transform skill content for OpenCode: strip frontmatter, keep as .md
+/// OpenCode uses flat command files and hyphen-separated names (no colon namespace)
+fn transform_skill_for_opencode(content: &str) -> String {
+ // OpenCode doesn't use YAML frontmatter in commands β€” just the markdown body
+ skills::strip_frontmatter(content).to_string()
+}
+
+/// Resolve skill content: check plugin override, then fall back to default
+fn resolve_skill_content(plugin: &Option<WorkflowPlugin>, skill_name: &str, project_path: &Path, default: &str) -> String {
+ if let Some(ref p) = plugin {
+ if let Some(plugin_dir) = WorkflowPlugin::plugin_dir(&p.name, Some(project_path)) {
+ let src = plugin_dir.join(skill_name).join("SKILL.md");
+ if src.exists() {
+ if let Ok(content) = std::fs::read_to_string(&src) {
+ return content;
+ }
+ }
+ }
+ }
+ default.to_string()
+}
+
#[cfg(test)]
#[path = "app_tests.rs"]
mod tests;
diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rs
index 045a1e6..af4fc65 100644
--- a/src/tui/app_tests.rs
+++ b/src/tui/app_tests.rs
@@ -204,6 +204,7 @@ fn test_create_pr_with_content_success() {
branch_name: Some("feature/test".to_string()),
pr_number: None,
pr_url: None,
+ plugin: None,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
@@ -290,6 +291,7 @@ fn test_create_pr_with_content_no_changes() {
branch_name: Some("feature/test".to_string()),
pr_number: None,
pr_url: None,
+ plugin: None,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
@@ -346,6 +348,7 @@ fn test_create_pr_with_content_push_failure() {
branch_name: Some("feature/test".to_string()),
pr_number: None,
pr_url: None,
+ plugin: None,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
@@ -399,6 +402,7 @@ fn test_push_changes_to_existing_pr_success() {
branch_name: Some("feature/existing".to_string()),
pr_number: Some(99),
pr_url: Some("https://github.com/org/repo/pull/99".to_string()),
+ plugin: None,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
@@ -449,6 +453,7 @@ fn test_push_changes_to_existing_pr_no_changes() {
branch_name: Some("feature/no-changes".to_string()),
pr_number: Some(50),
pr_url: Some("https://github.com/org/repo/pull/50".to_string()),
+ plugin: None,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
@@ -482,6 +487,7 @@ fn test_push_changes_to_existing_pr_no_url() {
branch_name: Some("feature/branch".to_string()),
pr_number: None,
pr_url: None, // No PR URL
+ plugin: None,
created_at: chrono::Utc::now(),
updated_at: chrono::Utc::now(),
};
@@ -1006,7 +1012,7 @@ fn test_collect_task_diff_all_changes() {
.expect_diff_untracked_file()
.returning(|_, _| "+++ new_file.rs\n+content".to_string());
- let result = collect_task_diff("/tmp/worktree", &mock_git);
+ let result = collect_task_diff("/tmp/worktree", &mock_git, &[]);
assert!(result.contains("Unstaged Changes"));
assert!(result.contains("Staged Changes"));
@@ -1023,7 +1029,7 @@ fn test_collect_task_diff_no_changes() {
mock_git.expect_diff_cached().returning(|_| String::new());
mock_git.expect_list_untracked_files().returning(|_| String::new());
- let result = collect_task_diff("/tmp/worktree", &mock_git);
+ let result = collect_task_diff("/tmp/worktree", &mock_git, &[]);
assert!(result.contains("(no changes)"));
assert!(result.contains("/tmp/worktree"));
@@ -1042,7 +1048,7 @@ fn test_collect_task_diff_only_unstaged() {
mock_git.expect_diff_cached().returning(|_| String::new());
mock_git.expect_list_untracked_files().returning(|_| String::new());
- let result = collect_task_diff("/tmp/worktree", &mock_git);
+ let result = collect_task_diff("/tmp/worktree", &mock_git, &[]);
assert!(result.contains("Unstaged Changes"));
assert!(!result.contains("Staged Changes"));
@@ -1333,7 +1339,7 @@ fn test_setup_task_worktree_success() {
// Expect worktree initialization
mock_git
.expect_initialize_worktree()
- .returning(|_, _, _, _| vec![]);
+ .returning(|_, _, _, _, _| vec![]);
// Expect agent command building
mock_agent
@@ -1359,6 +1365,8 @@ fn test_setup_task_worktree_success() {
"implement this",
None,
None,
+ &None,
+ "claude",
&mock_tmux,
&mock_git,
&mock_agent,
@@ -1388,7 +1396,7 @@ fn test_setup_task_worktree_sets_task_fields() {
.returning(|_, slug| Ok(format!("/project/.agtx/worktrees/{}", slug)));
mock_git
.expect_initialize_worktree()
- .returning(|_, _, _, _| vec![]);
+ .returning(|_, _, _, _, _| vec![]);
mock_agent
.expect_build_interactive_command()
.returning(|prompt| format!("claude '{}'", prompt));
@@ -1404,6 +1412,8 @@ fn test_setup_task_worktree_sets_task_fields() {
"fix the bug",
Some("CLAUDE.md".to_string()),
Some("./init.sh".to_string()),
+ &None,
+ "claude",
&mock_tmux,
&mock_git,
&mock_agent,
@@ -1436,7 +1446,7 @@ fn test_setup_task_worktree_worktree_creation_fails() {
// Should still initialize and create window with fallback path
mock_git
.expect_initialize_worktree()
- .returning(|_, _, _, _| vec![]);
+ .returning(|_, _, _, _, _| vec![]);
mock_agent
.expect_build_interactive_command()
.returning(|prompt| format!("claude '{}'", prompt));
@@ -1452,6 +1462,8 @@ fn test_setup_task_worktree_worktree_creation_fails() {
"do something",
None,
None,
+ &None,
+ "claude",
&mock_tmux,
&mock_git,
&mock_agent,
@@ -1478,7 +1490,7 @@ fn test_setup_task_worktree_tmux_window_fails() {
.returning(|_, slug| Ok(format!("/project/.agtx/worktrees/{}", slug)));
mock_git
.expect_initialize_worktree()
- .returning(|_, _, _, _| vec![]);
+ .returning(|_, _, _, _, _| vec![]);
mock_agent
.expect_build_interactive_command()
.returning(|prompt| format!("claude '{}'", prompt));
@@ -1498,6 +1510,8 @@ fn test_setup_task_worktree_tmux_window_fails() {
"do something",
None,
None,
+ &None,
+ "claude",
&mock_tmux,
&mock_git,
&mock_agent,
@@ -1523,7 +1537,7 @@ fn test_setup_task_worktree_creates_session_when_missing() {
.returning(|_, slug| Ok(format!("/project/.agtx/worktrees/{}", slug)));
mock_git
.expect_initialize_worktree()
- .returning(|_, _, _, _| vec![]);
+ .returning(|_, _, _, _, _| vec![]);
mock_agent
.expect_build_interactive_command()
.returning(|prompt| format!("claude '{}'", prompt));
@@ -1548,6 +1562,8 @@ fn test_setup_task_worktree_creates_session_when_missing() {
"do work",
None,
None,
+ &None,
+ "claude",
&mock_tmux,
&mock_git,
&mock_agent,
@@ -1573,11 +1589,11 @@ fn test_setup_task_worktree_passes_init_config() {
// Verify copy_files and init_script are passed through
mock_git
.expect_initialize_worktree()
- .withf(|_, _, copy_files, init_script| {
+ .withf(|_, _, copy_files, init_script, _copy_dirs| {
copy_files.as_deref() == Some("CLAUDE.md,.env")
&& init_script.as_deref() == Some("./setup.sh")
})
- .returning(|_, _, _, _| vec!["warning: .env not found".to_string()]);
+ .returning(|_, _, _, _, _| vec!["warning: .env not found".to_string()]);
mock_agent
.expect_build_interactive_command()
@@ -1594,6 +1610,8 @@ fn test_setup_task_worktree_passes_init_config() {
"implement feature",
Some("CLAUDE.md,.env".to_string()),
Some("./setup.sh".to_string()),
+ &None,
+ "claude",
&mock_tmux,
&mock_git,
&mock_agent,
@@ -1601,3 +1619,640 @@ fn test_setup_task_worktree_passes_init_config() {
assert!(result.is_ok());
}
+
+// ── Agent-Native Skill Discovery Tests ──────────────────────────────────────
+
+#[test]
+fn test_skill_name_to_command() {
+ assert_eq!(skills::skill_name_to_command("agtx-plan"), "agtx:plan");
+ assert_eq!(skills::skill_name_to_command("agtx-execute"), "agtx:execute");
+ assert_eq!(skills::skill_name_to_command("agtx-review"), "agtx:review");
+ assert_eq!(skills::skill_name_to_command("agtx-research"), "agtx:research");
+ assert_eq!(skills::skill_name_to_command("simple"), "simple");
+}
+
+#[test]
+fn test_skill_dir_to_filename() {
+ // Claude/default: .md files with prefix stripped
+ assert_eq!(skills::skill_dir_to_filename("agtx-plan", "claude"), "plan.md");
+ assert_eq!(skills::skill_dir_to_filename("agtx-execute", "claude"), "execute.md");
+ assert_eq!(skills::skill_dir_to_filename("agtx-review", "claude"), "review.md");
+ assert_eq!(skills::skill_dir_to_filename("custom", "claude"), "custom.md");
+ // Gemini: .toml files with prefix stripped
+ assert_eq!(skills::skill_dir_to_filename("agtx-plan", "gemini"), "plan.toml");
+ assert_eq!(skills::skill_dir_to_filename("agtx-execute", "gemini"), "execute.toml");
+ // OpenCode: .md files with full name (flat directory, no namespace)
+ assert_eq!(skills::skill_dir_to_filename("agtx-plan", "opencode"), "agtx-plan.md");
+ assert_eq!(skills::skill_dir_to_filename("agtx-execute", "opencode"), "agtx-execute.md");
+ // Copilot: .md files with prefix stripped (same as Claude default)
+ assert_eq!(skills::skill_dir_to_filename("agtx-plan", "copilot"), "plan.md");
+ assert_eq!(skills::skill_dir_to_filename("agtx-execute", "copilot"), "execute.md");
+}
+
+#[test]
+fn test_agent_native_skill_dir() {
+ assert_eq!(skills::agent_native_skill_dir("claude"), Some((".claude/commands", "agtx")));
+ assert_eq!(skills::agent_native_skill_dir("gemini"), Some((".gemini/commands", "agtx")));
+ assert_eq!(skills::agent_native_skill_dir("opencode"), Some((".config/opencode/command", "")));
+ assert_eq!(skills::agent_native_skill_dir("codex"), Some((".codex/skills", "")));
+ assert_eq!(skills::agent_native_skill_dir("copilot"), Some((".github/agents", "agtx")));
+ assert_eq!(skills::agent_native_skill_dir("unknown"), None);
+}
+
+#[test]
+fn test_skill_reference_native_agent() {
+ // Agents with skill invocation get empty reference (skill sent via send_keys)
+ assert_eq!(skills::skill_reference("claude", "agtx-plan"), "");
+ assert_eq!(skills::skill_reference("gemini", "agtx-execute"), "");
+ assert_eq!(skills::skill_reference("opencode", "agtx-plan"), "");
+ assert_eq!(skills::skill_reference("codex", "agtx-review"), "");
+}
+
+#[test]
+fn test_skill_reference_fallback_agent() {
+ // Agents without skill invocation get file-path reference
+ let ref_copilot = skills::skill_reference("copilot", "agtx-plan");
+ assert_eq!(ref_copilot, "Follow the instructions in .agtx/skills/agtx-plan/SKILL.md");
+
+ let ref_unknown = skills::skill_reference("unknown", "agtx-execute");
+ assert!(ref_unknown.contains(".agtx/skills/agtx-execute/SKILL.md"));
+}
+
+#[test]
+fn test_skill_invocation_command() {
+ assert_eq!(skills::skill_invocation_command("claude", "agtx-plan"), Some("/agtx:plan".to_string()));
+ assert_eq!(skills::skill_invocation_command("gemini", "agtx-execute"), Some("/agtx:execute".to_string()));
+ assert_eq!(skills::skill_invocation_command("opencode", "agtx-plan"), Some("/agtx-plan".to_string()));
+ assert_eq!(skills::skill_invocation_command("codex", "agtx-plan"), Some("$agtx-plan".to_string()));
+ assert_eq!(skills::skill_invocation_command("copilot", "agtx-plan"), None);
+ assert_eq!(skills::skill_invocation_command("unknown", "agtx-plan"), None);
+}
+
+#[test]
+fn test_transform_plugin_command() {
+ // Claude/Gemini: canonical form unchanged
+ assert_eq!(skills::transform_plugin_command("/gsd:plan-phase 1", "claude"), Some("/gsd:plan-phase 1".to_string()));
+ assert_eq!(skills::transform_plugin_command("/gsd:plan-phase 1", "gemini"), Some("/gsd:plan-phase 1".to_string()));
+ // OpenCode: colon β†’ hyphen
+ assert_eq!(skills::transform_plugin_command("/gsd:plan-phase 1", "opencode"), Some("/gsd-plan-phase 1".to_string()));
+ assert_eq!(skills::transform_plugin_command("/gsd:discuss-phase 1", "opencode"), Some("/gsd-discuss-phase 1".to_string()));
+ // Codex: slash β†’ dollar, colon β†’ hyphen
+ assert_eq!(skills::transform_plugin_command("/gsd:plan-phase 1", "codex"), Some("$gsd-plan-phase 1".to_string()));
+ assert_eq!(skills::transform_plugin_command("/gsd:execute-phase 1", "codex"), Some("$gsd-execute-phase 1".to_string()));
+ // Spec-kit style (dot separator, no colon): transform only affects colon
+ assert_eq!(skills::transform_plugin_command("/speckit.plan", "opencode"), Some("/speckit.plan".to_string()));
+ assert_eq!(skills::transform_plugin_command("/speckit.plan", "codex"), Some("$speckit.plan".to_string()));
+ // Unsupported agents
+ assert_eq!(skills::transform_plugin_command("/gsd:plan-phase 1", "copilot"), None);
+ assert_eq!(skills::transform_plugin_command("/gsd:plan-phase 1", "unknown"), None);
+}
+
+#[test]
+fn test_phase_to_skill_dir() {
+ assert_eq!(skills::phase_to_skill_dir("research"), "agtx-research");
+ assert_eq!(skills::phase_to_skill_dir("planning"), "agtx-plan");
+ assert_eq!(skills::phase_to_skill_dir("planning_with_research"), "agtx-plan");
+ assert_eq!(skills::phase_to_skill_dir("running"), "agtx-execute");
+ assert_eq!(skills::phase_to_skill_dir("review"), "agtx-review");
+ assert_eq!(skills::phase_to_skill_dir("other"), "");
+}
+
+#[test]
+fn test_strip_frontmatter() {
+ let with_fm = "---\nname: agtx-plan\ndescription: test\n---\n# Content\nBody";
+ assert_eq!(skills::strip_frontmatter(with_fm), "# Content\nBody");
+
+ let without_fm = "# Content\nBody";
+ assert_eq!(skills::strip_frontmatter(without_fm), "# Content\nBody");
+}
+
+#[test]
+fn test_skill_to_gemini_toml() {
+ let toml = skills::skill_to_gemini_toml("Plan a task", "---\nname: agtx-plan\n---\n# Planning\nDo stuff");
+ assert!(toml.contains("description = \"Plan a task\""));
+ assert!(toml.contains("prompt = \"\"\""));
+ assert!(toml.contains("# Planning"));
+ assert!(toml.contains("Do stuff"));
+ // Should not contain frontmatter
+ assert!(!toml.contains("name: agtx-plan"));
+}
+
+#[test]
+fn test_extract_description() {
+ let content = "---\nname: agtx-plan\ndescription: Plan a task implementation.\n---\n# Content";
+ assert_eq!(skills::extract_description(content), Some("Plan a task implementation.".to_string()));
+
+ let no_desc = "---\nname: agtx-plan\n---\n# Content";
+ assert_eq!(skills::extract_description(no_desc), None);
+
+ let no_frontmatter = "# Content";
+ assert_eq!(skills::extract_description(no_frontmatter), None);
+}
+
+#[test]
+fn test_transform_skill_frontmatter() {
+ let input = "---\nname: agtx-plan\ndescription: test\n---\n# Content";
+ let output = transform_skill_frontmatter(input);
+ assert!(output.contains("name: agtx:plan"));
+ assert!(output.contains("# Content"));
+ assert!(output.contains("description: test"));
+}
+
+#[test]
+fn test_transform_skill_frontmatter_no_agtx() {
+ let input = "---\nname: other-skill\n---\n# Content";
+ let output = transform_skill_frontmatter(input);
+ // Should not transform non-agtx names
+ assert_eq!(output, input);
+}
+
+#[test]
+fn test_resolve_prompt_claude_no_skill_ref() {
+ // Claude has skill invocation support β€” prompt should NOT contain skill reference
+ let prompt = resolve_prompt(&None, "planning", "my task", "task-123", "claude");
+ assert!(prompt.contains("my task"));
+ assert!(!prompt.contains("/agtx:plan"));
+ assert!(!prompt.contains("SKILL.md"));
+}
+
+#[test]
+fn test_resolve_prompt_copilot_has_file_path() {
+ // Copilot has no skill invocation β€” prompt should contain file-path reference
+ let prompt = resolve_prompt(&None, "planning", "my task", "task-123", "copilot");
+ assert!(prompt.contains("my task"));
+ assert!(prompt.contains(".agtx/skills/agtx-plan/SKILL.md"));
+}
+
+#[test]
+fn test_resolve_prompt_research_has_task_id() {
+ let prompt = resolve_prompt(&None, "research", "my task", "abc-123", "claude");
+ assert!(prompt.contains("abc-123"));
+ // Claude should NOT have skill ref in prompt (sent via send_keys)
+ assert!(!prompt.contains("/agtx:research"));
+}
+
+#[test]
+fn test_resolve_prompt_running_phase() {
+ let prompt = resolve_prompt(&None, "running", "my task", "task-123", "claude");
+ assert!(prompt.contains("Plan approved"));
+ assert!(!prompt.contains("SKILL.md"));
+}
+
+#[test]
+fn test_resolve_prompt_review_phase() {
+ let prompt = resolve_prompt(&None, "review", "my task", "task-123", "copilot");
+ assert!(prompt.contains("Implementation complete"));
+ assert!(prompt.contains(".agtx/skills/agtx-review/SKILL.md"));
+}
+
+#[test]
+fn test_resolve_skill_command_no_plugin() {
+ // No plugin: falls back to agent-native skill invocation
+ assert_eq!(resolve_skill_command(&None, "planning", "claude", ""), Some("/agtx:plan".to_string()));
+ assert_eq!(resolve_skill_command(&None, "running", "codex", ""), Some("$agtx-execute".to_string()));
+ assert_eq!(resolve_skill_command(&None, "review", "gemini", ""), Some("/agtx:review".to_string()));
+ assert_eq!(resolve_skill_command(&None, "planning", "opencode", ""), Some("/agtx-plan".to_string()));
+ assert_eq!(resolve_skill_command(&None, "planning", "copilot", ""), None);
+}
+
+#[test]
+fn test_resolve_skill_command_with_plugin() {
+ use crate::config::{WorkflowPlugin, PluginArtifacts, PluginCommands, PluginPrompts, PluginPromptTriggers};
+ let plugin = Some(WorkflowPlugin {
+ name: "gsd".to_string(),
+ description: None,
+ init_script: None,
+ supported_agents: vec![],
+ artifacts: PluginArtifacts::default(),
+ commands: PluginCommands {
+ research: Some("/gsd:discuss-phase 1".to_string()),
+ planning: Some("/gsd:plan-phase 1".to_string()),
+ running: Some("/gsd:execute-phase 1".to_string()),
+ review: Some("/gsd:verify-work 1".to_string()),
+ },
+ prompts: PluginPrompts::default(),
+ prompt_triggers: PluginPromptTriggers::default(),
+ copy_dirs: vec![],
+ });
+ // Claude/Gemini: canonical form unchanged
+ assert_eq!(resolve_skill_command(&plugin, "planning", "claude", ""), Some("/gsd:plan-phase 1".to_string()));
+ assert_eq!(resolve_skill_command(&plugin, "running", "claude", ""), Some("/gsd:execute-phase 1".to_string()));
+ assert_eq!(resolve_skill_command(&plugin, "review", "gemini", ""), Some("/gsd:verify-work 1".to_string()));
+ assert_eq!(resolve_skill_command(&plugin, "research", "claude", ""), Some("/gsd:discuss-phase 1".to_string()));
+ // OpenCode: colon β†’ hyphen
+ assert_eq!(resolve_skill_command(&plugin, "planning", "opencode", ""), Some("/gsd-plan-phase 1".to_string()));
+ assert_eq!(resolve_skill_command(&plugin, "research", "opencode", ""), Some("/gsd-discuss-phase 1".to_string()));
+ // Codex: slash β†’ dollar, colon β†’ hyphen
+ assert_eq!(resolve_skill_command(&plugin, "planning", "codex", ""), Some("$gsd-plan-phase 1".to_string()));
+ assert_eq!(resolve_skill_command(&plugin, "running", "codex", ""), Some("$gsd-execute-phase 1".to_string()));
+ // Unsupported agents: None (will use file-path fallback in prompt)
+ assert_eq!(resolve_skill_command(&plugin, "planning", "copilot", ""), None);
+}
+
+#[test]
+fn test_plugin_supports_agent() {
+ use crate::config::WorkflowPlugin;
+
+ // Empty supported_agents = all agents supported
+ let plugin = WorkflowPlugin {
+ name: "test".to_string(),
+ description: None,
+ init_script: None,
+ supported_agents: vec![],
+ artifacts: Default::default(),
+ commands: Default::default(),
+ prompts: Default::default(),
+ prompt_triggers: Default::default(),
+ copy_dirs: vec![],
+ };
+ assert!(plugin.supports_agent("claude"));
+ assert!(plugin.supports_agent("copilot"));
+ assert!(plugin.supports_agent("anything"));
+
+ // Explicit list = only those agents supported
+ let plugin = WorkflowPlugin {
+ name: "gsd".to_string(),
+ description: None,
+ init_script: None,
+ supported_agents: vec!["claude".into(), "codex".into(), "gemini".into(), "opencode".into()],
+ artifacts: Default::default(),
+ commands: Default::default(),
+ prompts: Default::default(),
+ prompt_triggers: Default::default(),
+ copy_dirs: vec![],
+ };
+ assert!(plugin.supports_agent("claude"));
+ assert!(plugin.supports_agent("codex"));
+ assert!(plugin.supports_agent("gemini"));
+ assert!(plugin.supports_agent("opencode"));
+ assert!(!plugin.supports_agent("copilot"));
+ assert!(!plugin.supports_agent("aider"));
+}
+
+#[test]
+fn test_glob_path_exists() {
+ // Create temp dir with nested structure: specs/my-feature/plan.md
+ let tmp = std::env::temp_dir().join("agtx_test_glob");
+ let _ = std::fs::remove_dir_all(&tmp);
+ let feature_dir = tmp.join("specs").join("my-feature");
+ std::fs::create_dir_all(&feature_dir).unwrap();
+ std::fs::write(feature_dir.join("plan.md"), "# Plan").unwrap();
+ std::fs::write(feature_dir.join("spec.md"), "# Spec").unwrap();
+
+ // Glob should match
+ let pattern = format!("{}/specs/*/plan.md", tmp.display());
+ assert!(glob_path_exists(&pattern));
+
+ let pattern = format!("{}/specs/*/spec.md", tmp.display());
+ assert!(glob_path_exists(&pattern));
+
+ // Non-existent file
+ let pattern = format!("{}/specs/*/tasks.md", tmp.display());
+ assert!(!glob_path_exists(&pattern));
+
+ // Non-existent dir
+ let pattern = format!("{}/nonexistent/*/plan.md", tmp.display());
+ assert!(!glob_path_exists(&pattern));
+
+ // Exact path (no wildcard)
+ let exact = format!("{}/specs/my-feature/plan.md", tmp.display());
+ assert!(glob_path_exists(&exact));
+
+ let _ = std::fs::remove_dir_all(&tmp);
+}
+
+#[test]
+fn test_phase_artifact_exists_with_glob() {
+ use crate::config::{WorkflowPlugin, PluginArtifacts, PluginCommands, PluginPrompts};
+
+ let tmp = std::env::temp_dir().join("agtx_test_artifact_glob");
+ let _ = std::fs::remove_dir_all(&tmp);
+ let feature_dir = tmp.join("specs").join("add-login");
+ std::fs::create_dir_all(&feature_dir).unwrap();
+ std::fs::write(feature_dir.join("plan.md"), "# Plan").unwrap();
+
+ let plugin = Some(WorkflowPlugin {
+ name: "spec-kit".to_string(),
+ description: None,
+ init_script: None,
+ supported_agents: vec![],
+ artifacts: PluginArtifacts {
+ research: Some("specs/*/spec.md".to_string()),
+ planning: Some("specs/*/plan.md".to_string()),
+ running: None,
+ review: None,
+ },
+ commands: PluginCommands::default(),
+ prompts: PluginPrompts::default(),
+ prompt_triggers: Default::default(),
+ copy_dirs: vec![],
+ });
+
+ let worktree = tmp.to_string_lossy().to_string();
+
+ // Planning artifact exists (glob matches)
+ assert!(phase_artifact_exists(&worktree, TaskStatus::Planning, &plugin));
+
+ // Research artifact doesn't exist yet (no spec.md)
+ assert!(!phase_artifact_exists(&worktree, TaskStatus::Backlog, &plugin));
+
+ // Running/Review fall back to agtx defaults (don't exist)
+ assert!(!phase_artifact_exists(&worktree, TaskStatus::Running, &plugin));
+ assert!(!phase_artifact_exists(&worktree, TaskStatus::Review, &plugin));
+
+ let _ = std::fs::remove_dir_all(&tmp);
+}
+
+#[test]
+fn test_bundled_plugins_are_valid_toml() {
+ use crate::config::WorkflowPlugin;
+ // Each bundled plugin.toml must parse as a valid WorkflowPlugin
+ for (name, _desc, content) in skills::BUNDLED_PLUGINS {
+ let plugin: WorkflowPlugin = toml::from_str(content)
+ .unwrap_or_else(|e| panic!("Bundled plugin '{}' has invalid TOML: {}", name, e));
+ assert_eq!(plugin.name, *name);
+ }
+}
+
+#[test]
+fn test_bundled_plugins_list() {
+ // We ship gsd, spec-kit, and void
+ let names: Vec<&str> = skills::BUNDLED_PLUGINS.iter().map(|(n, _, _)| *n).collect();
+ assert!(names.contains(&"gsd"));
+ assert!(names.contains(&"spec-kit"));
+ assert!(names.contains(&"void"));
+ assert_eq!(names.len(), 3);
+}
+
+#[test]
+fn test_plugin_select_popup_construction_no_active() {
+ // When no plugin is active, (none) should be selected
+ let current = "";
+ let mut options = vec![PluginOption {
+ name: String::new(),
+ label: "(none)".to_string(),
+ description: "Use agtx built-in defaults".to_string(),
+ active: current.is_empty(),
+ }];
+ for (name, desc, _) in skills::BUNDLED_PLUGINS {
+ options.push(PluginOption {
+ name: name.to_string(),
+ label: name.to_string(),
+ description: desc.to_string(),
+ active: current == *name,
+ });
+ }
+ let selected = options.iter().position(|o| o.active).unwrap_or(0);
+ assert_eq!(selected, 0);
+ assert!(options[0].active);
+ assert!(!options[1].active);
+ assert!(!options[2].active);
+}
+
+#[test]
+fn test_plugin_select_popup_construction_gsd_active() {
+ let current = "gsd";
+ let mut options = vec![PluginOption {
+ name: String::new(),
+ label: "(none)".to_string(),
+ description: "Use agtx built-in defaults".to_string(),
+ active: current.is_empty(),
+ }];
+ for (name, desc, _) in skills::BUNDLED_PLUGINS {
+ options.push(PluginOption {
+ name: name.to_string(),
+ label: name.to_string(),
+ description: desc.to_string(),
+ active: current == *name,
+ });
+ }
+ let selected = options.iter().position(|o| o.active).unwrap_or(0);
+ // gsd is the second option (index 1)
+ assert_eq!(selected, 1);
+ assert!(!options[0].active);
+ assert!(options[1].active);
+ assert_eq!(options[1].name, "gsd");
+}
+
+#[test]
+fn test_install_plugin_writes_files() {
+ use crate::config::ProjectConfig;
+
+ let tmp = std::env::temp_dir().join("agtx_test_install_plugin");
+ let _ = std::fs::remove_dir_all(&tmp);
+ std::fs::create_dir_all(&tmp).unwrap();
+
+ // Simulate install_plugin logic for "gsd"
+ let plugin_name = "gsd";
+ if let Some((_name, _desc, content)) = skills::BUNDLED_PLUGINS
+ .iter()
+ .find(|(n, _, _)| *n == plugin_name)
+ {
+ let plugin_dir = tmp.join(".agtx").join("plugins").join(plugin_name);
+ std::fs::create_dir_all(&plugin_dir).unwrap();
+ std::fs::write(plugin_dir.join("plugin.toml"), content).unwrap();
+ }
+
+ let mut project_config = ProjectConfig::default();
+ project_config.workflow_plugin = Some(plugin_name.to_string());
+ project_config.save(&tmp).unwrap();
+
+ // Verify plugin.toml was written
+ let plugin_toml = tmp.join(".agtx").join("plugins").join("gsd").join("plugin.toml");
+ assert!(plugin_toml.exists());
+ let content = std::fs::read_to_string(&plugin_toml).unwrap();
+ assert!(content.contains("name = \"gsd\""));
+
+ // Verify project config was updated
+ let loaded = ProjectConfig::load(&tmp).unwrap();
+ assert_eq!(loaded.workflow_plugin, Some("gsd".to_string()));
+
+ let _ = std::fs::remove_dir_all(&tmp);
+}
+
+#[test]
+fn test_install_plugin_none_clears_config() {
+ use crate::config::ProjectConfig;
+
+ let tmp = std::env::temp_dir().join("agtx_test_install_plugin_none");
+ let _ = std::fs::remove_dir_all(&tmp);
+ std::fs::create_dir_all(&tmp).unwrap();
+
+ // Start with gsd configured
+ let mut project_config = ProjectConfig::default();
+ project_config.workflow_plugin = Some("gsd".to_string());
+ project_config.save(&tmp).unwrap();
+
+ // Simulate clearing plugin (selecting "(none)")
+ let mut project_config = ProjectConfig::load(&tmp).unwrap();
+ project_config.workflow_plugin = None;
+ project_config.save(&tmp).unwrap();
+
+ // Verify plugin was cleared
+ let loaded = ProjectConfig::load(&tmp).unwrap();
+ assert_eq!(loaded.workflow_plugin, None);
+
+ let _ = std::fs::remove_dir_all(&tmp);
+}
+
+// =============================================================================
+// Tests for research session and session reuse
+// =============================================================================
+
+#[test]
+fn test_footer_text_backlog_includes_research() {
+ let text = build_footer_text(InputMode::Normal, false, 0);
+ assert!(text.contains("[R] research"));
+}
+
+#[test]
+fn test_backlog_task_with_research_session_detected() {
+ // A Backlog task with session_name containing "research-" should be treated as having research
+ let session_name = Some("my-project:task-abc12345-my-task".to_string());
+ // has_live_session logic: session_name is Some, window_exists would need to return true
+ assert!(session_name.is_some());
+}
+
+#[test]
+fn test_resolve_skill_command_research_phase() {
+ use crate::config::WorkflowPlugin;
+ // GSD plugin maps research to /gsd:new-project
+ let plugin_toml = r#"
+ name = "gsd"
+ init_script = "echo test"
+ [commands]
+ research = "/gsd:new-project"
+ planning = "/gsd:plan-phase 1"
+ running = "/gsd:execute-phase 1"
+ review = "/gsd:verify-work 1"
+ [prompts]
+ [artifacts]
+ "#;
+ let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();
+ let cmd = resolve_skill_command(&Some(plugin), "research", "claude", "");
+ assert_eq!(cmd, Some("/gsd:new-project".to_string()));
+}
+
+#[test]
+fn test_resolve_skill_command_planning_with_plugin() {
+ use crate::config::WorkflowPlugin;
+ let plugin_toml = r#"
+ name = "gsd"
+ init_script = "echo test"
+ [commands]
+ research = "/gsd:new-project"
+ planning = "/gsd:plan-phase 1"
+ running = "/gsd:execute-phase 1"
+ review = "/gsd:verify-work 1"
+ [prompts]
+ [artifacts]
+ "#;
+ let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();
+ let cmd = resolve_skill_command(&Some(plugin), "planning", "claude", "");
+ assert_eq!(cmd, Some("/gsd:plan-phase 1".to_string()));
+}
+
+#[test]
+fn test_resolve_prompt_empty_for_gsd_planning() {
+ use crate::config::WorkflowPlugin;
+ // GSD planning has empty prompt β€” plan-phase reads from .planning/ files
+ let plugin_toml = r#"
+ name = "gsd"
+ init_script = "echo test"
+ [commands]
+ [prompts]
+ planning = ""
+ running = ""
+ review = ""
+ [artifacts]
+ "#;
+ let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();
+ let prompt = resolve_prompt(&Some(plugin), "planning", "my task content", "task-123", "claude");
+ assert!(prompt.is_empty());
+}
+
+#[test]
+fn test_resolve_prompt_research_with_task() {
+ use crate::config::WorkflowPlugin;
+ let plugin_toml = r#"
+ name = "gsd"
+ init_script = "echo test"
+ [commands]
+ [prompts]
+ research = "Task: {task}"
+ [artifacts]
+ "#;
+ let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();
+ let prompt = resolve_prompt(&Some(plugin), "research", "add tests", "task-123", "claude");
+ assert_eq!(prompt, "Task: add tests");
+}
+
+#[test]
+fn test_gsd_plugin_toml_has_research_command() {
+ use crate::config::WorkflowPlugin;
+ // Verify the bundled GSD plugin has the expected research command
+ let (_name, _desc, content) = skills::BUNDLED_PLUGINS
+ .iter()
+ .find(|(n, _, _)| *n == "gsd")
+ .expect("gsd plugin should be bundled");
+ let plugin: WorkflowPlugin = toml::from_str(content).unwrap();
+ assert_eq!(plugin.commands.research, Some("/gsd:new-project".to_string()));
+ assert_eq!(plugin.commands.planning, Some("/gsd:plan-phase 1".to_string()));
+}
+
+#[test]
+fn test_resolve_prompt_trigger_with_gsd() {
+ use crate::config::{WorkflowPlugin, PluginPromptTriggers};
+ let plugin = Some(WorkflowPlugin {
+ name: "gsd".to_string(),
+ description: None,
+ init_script: None,
+ supported_agents: vec![],
+ artifacts: Default::default(),
+ commands: Default::default(),
+ prompts: Default::default(),
+ prompt_triggers: PluginPromptTriggers {
+ research: Some("What do you want to build?".to_string()),
+ planning: None,
+ running: None,
+ review: None,
+ },
+ copy_dirs: vec![],
+ });
+ assert_eq!(
+ resolve_prompt_trigger(&plugin, "research"),
+ Some("What do you want to build?".to_string())
+ );
+ assert_eq!(resolve_prompt_trigger(&plugin, "planning"), None);
+ assert_eq!(resolve_prompt_trigger(&plugin, "running"), None);
+ assert_eq!(resolve_prompt_trigger(&plugin, "review"), None);
+}
+
+#[test]
+fn test_resolve_prompt_trigger_no_plugin() {
+ assert_eq!(resolve_prompt_trigger(&None, "research"), None);
+ assert_eq!(resolve_prompt_trigger(&None, "planning"), None);
+}
+
+#[test]
+fn test_resolve_prompt_trigger_empty_string_filtered() {
+ use crate::config::{WorkflowPlugin, PluginPromptTriggers};
+ let plugin = Some(WorkflowPlugin {
+ name: "test".to_string(),
+ description: None,
+ init_script: None,
+ supported_agents: vec![],
+ artifacts: Default::default(),
+ commands: Default::default(),
+ prompts: Default::default(),
+ prompt_triggers: PluginPromptTriggers {
+ research: Some("".to_string()),
+ planning: None,
+ running: None,
+ review: None,
+ },
+ copy_dirs: vec![],
+ });
+ // Empty strings should be filtered out
+ assert_eq!(resolve_prompt_trigger(&plugin, "research"), None);
+}
diff --git a/tests/config_tests.rs b/tests/config_tests.rs
index 6603ef7..e6db565 100644
--- a/tests/config_tests.rs
+++ b/tests/config_tests.rs
@@ -107,6 +107,7 @@ fn test_merged_config_project_overrides() {
github_url: Some("https://github.com/user/repo".to_string()),
copy_files: Some(".env, .env.local".to_string()),
init_script: Some("npm install".to_string()),
+ workflow_plugin: None,
};
let merged = MergedConfig::merge(&global, &project);
diff --git a/tests/git_tests.rs b/tests/git_tests.rs
index d71a880..6a41843 100644
--- a/tests/git_tests.rs
+++ b/tests/git_tests.rs
@@ -312,7 +312,7 @@ fn test_initialize_worktree_no_config() {
let temp_dir = setup_git_repo();
let worktree_path = git::create_worktree(temp_dir.path(), "init-none").unwrap();
- let warnings = git::initialize_worktree(temp_dir.path(), &worktree_path, None, None);
+ let warnings = git::initialize_worktree(temp_dir.path(), &worktree_path, None, None, &[]);
assert!(warnings.is_empty());
}
@@ -329,6 +329,7 @@ fn test_initialize_worktree_copy_files() {
&worktree_path,
Some(".env, .env.local"),
None,
+ &[],
);
assert!(warnings.is_empty());
assert_eq!(
@@ -351,6 +352,7 @@ fn test_initialize_worktree_copy_missing_file() {
&worktree_path,
Some(".nonexistent"),
None,
+ &[],
);
assert_eq!(warnings.len(), 1);
assert!(warnings[0].contains(".nonexistent"));
@@ -366,6 +368,7 @@ fn test_initialize_worktree_init_script_success() {
&worktree_path,
None,
Some("touch initialized.marker"),
+ &[],
);
assert!(warnings.is_empty());
assert!(worktree_path.join("initialized.marker").exists());
@@ -381,6 +384,7 @@ fn test_initialize_worktree_init_script_failure() {
&worktree_path,
None,
Some("exit 1"),
+ &[],
);
assert_eq!(warnings.len(), 1);
assert!(warnings[0].contains("init_script"));
@@ -398,6 +402,7 @@ fn test_initialize_worktree_copy_then_script() {
&worktree_path,
Some(".env"),
Some("cat .env > verified.txt"),
+ &[],
);
assert!(warnings.is_empty());
assert_eq!(
@@ -420,6 +425,7 @@ fn test_initialize_worktree_copy_nested_path() {
&worktree_path,
Some("web/.env.local"),
None,
+ &[],
);
assert!(warnings.is_empty());
assert_eq!(
@@ -438,12 +444,13 @@ fn test_initialize_worktree_empty_copy_files() {
&worktree_path,
Some(", , "),
None,
+ &[],
);
assert!(warnings.is_empty());
}
#[test]
-fn test_initialize_worktree_copy_directory_rejected() {
+fn test_initialize_worktree_copy_directory_supported() {
let temp_dir = setup_git_repo();
let config_dir = temp_dir.path().join("config");
std::fs::create_dir_all(&config_dir).unwrap();
@@ -456,7 +463,11 @@ fn test_initialize_worktree_copy_directory_rejected() {
&worktree_path,
Some("config"),
None,
+ &[],
);
- assert_eq!(warnings.len(), 1);
- assert!(warnings[0].contains("directory"));
+ assert_eq!(warnings.len(), 0);
+ // Directory and its contents should be copied
+ assert!(worktree_path.join("config").join("app.toml").exists());
+ let content = std::fs::read_to_string(worktree_path.join("config").join("app.toml")).unwrap();
+ assert_eq!(content, "key = 1");
}