ππΌββοΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.
Rust adeai-agentsclaudeclaude-codecodexcursorgeminigrokopencodespec-driven-developmentvibe-codingvim
feat: add cyclic phases, copy-back, and discuss fallback to plugin system (#28)
Fynn FlΓΌgge371fcebe2685
diff --git a/CLAUDE.md b/CLAUDE.mdindex 25f334d..b31fef0 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -54,6 +54,7 @@ skills/ # Built-in skill files (embedded at compile time)βββ research.md # Research phase instructionsplugins/ # Bundled plugin configs (embedded at compile time)+βββ agtx/plugin.toml # Default workflow with skills and promptsβββ gsd/plugin.toml # Get Shit Done workflowβββ spec-kit/plugin.toml # GitHub spec-kit workflowβββ void/plugin.toml # Plain agent session, no prompting@@ -87,12 +88,15 @@ Backlog β Planning β Running β Review β Done### Workflow PluginsPlugins customize the task lifecycle per phase. A plugin is a TOML file (`plugin.toml`) that defines:-- **commands**: Slash commands sent to the agent at each phase (auto-translated per agent)-- **prompts**: Task content templates with `{task}` and `{task_id}` placeholders-- **artifacts**: File paths that signal phase completion (supports `*` wildcards)+- **commands**: Slash commands sent to the agent at each phase (auto-translated per agent). Supports `preresearch` (one-time setup) and `research` (default research command).+- **prompts**: Task content templates with `{task}`, `{task_id}`, and `{phase}` placeholders+- **artifacts**: File paths that signal phase completion (supports `*` wildcards and `{phase}` placeholder)- **prompt_triggers**: Text patterns to wait for in tmux before sending prompts- **init_script**: Shell command run in worktree before agent starts (`{agent}` placeholder)- **copy_dirs**: Extra directories to copy from project root into worktrees+- **copy_files**: Individual files to copy from project root into worktrees (merged with project-level `copy_files`)+- **copy_back**: Files/dirs to copy from worktree back to project root when a phase completes+- **cyclic**: When true, enables Review β Planning transition with incrementing phase counter- **supported_agents**: Agent whitelist (empty = all supported)Plugin resolution: project-local `.agtx/plugins/{name}/` β global `~/.config/agtx/plugins/{name}/` β bundled.@@ -113,7 +117,7 @@ Commands are written once in canonical format (`/ns:command`) and auto-translate- Claude/Gemini: `/ns:command` (unchanged)- OpenCode: `/ns-command` (colon β hyphen)- Codex: `$ns-command` (slash β dollar, colon β hyphen)-- Copilot: no interactive skill invocation (falls back to file-path reference in prompt)+- Copilot: no interactive skill invocation (prompt only, no commands sent)### Session Persistence- Tmux window stays open when moving Running β Review@@ -242,7 +246,7 @@ color_popup_header = "#69fae7" # Popup headers (light cyan)### Phase Status Polling- `refresh_sessions()` runs every 100ms, checks artifact files with 2-second cache TTL-- Three states: Working (spinner), Ready (checkmark), Exited (no window)+- Four states: Working (spinner), Idle (pause icon, 15s no output), Ready (checkmark), Exited (no window)- Phase artifact paths come from the task's plugin or agtx defaults- Plugin instances cached per task in `HashMap<Option<String>, Option<WorkflowPlugin>>` to avoid repeated disk reads@@ -250,7 +254,8 @@ color_popup_header = "#69fae7" # Popup headers (light cyan)- Agents spawned via `build_interactive_command()` in `src/agent/mod.rs`- Each agent has its own flags: Claude (`--dangerously-skip-permissions`), Codex (`--approval-mode full-auto`), Gemini (`--approval-mode yolo`), Copilot (`--allow-all-tools`)- Skills deployed to agent-native paths via `write_skills_to_worktree()` in app.rs-- Commands and prompts resolved per-task via `resolve_skill_command()` and `resolve_prompt()`+- Commands resolved per-task via `resolve_skill_command()` (plugin command + agent transform)+- Prompts resolved per-task via `resolve_prompt()` (pure template substitution, agent-agnostic)## Building & Testing@@ -289,8 +294,7 @@ Dependencies require:1. Add to `known_agents()` in `src/agent/mod.rs`2. Add `build_interactive_command()` match arm in `src/agent/mod.rs`3. Add agent-native skill dir in `agent_native_skill_dir()` in `src/skills.rs`-4. Add skill invocation format in `skill_invocation_command()` in `src/skills.rs`-5. Add plugin command transform in `transform_plugin_command()` in `src/skills.rs`+4. Add plugin command transform in `transform_plugin_command()` in `src/skills.rs`### Adding a keyboard shortcut1. Find the appropriate `handle_*_key` function in `src/tui/app.rs`diff --git a/README.md b/README.mdindex c76dfa4..e4a6a88 100644--- a/README.md+++ b/README.md@@ -14,7 +14,7 @@ Let different coding agents collaborate on the same task. Plug in any existing s## Features-- **Kanban workflow**: Backlog/Research β Planning β Running β Review β Done+- **Kanban workflow**: Backlog/Research β Planning β Running β Review β Done (with optional cyclic phases for multi-milestone plugins)- **Git worktree and tmux isolation**: Each task gets its own worktree and tmux window, keeping work separated- **Coding agent integrations**: Automatic session management for Claude Code, Codex, Gemini, OpenCode and Copilot- **Multi-agent per task**: Configure different agents per workflow phase β e.g. Gemini for planning, Claude for implementation, Codex for review β with automatic agent switching in the same tmux window@@ -70,7 +70,8 @@ agtx -g| `R` | Enter research mode || `β©` | Open task (view agent session) || `m` | Move task forward in workflow |-| `r` | Resume task (Review β Running) |+| `r` | Resume task (Review β Running) / Move back (Running β Planning) |+| `p` | Next phase (Review β Planning, cyclic plugins only) || `d` | Show git diff || `x` | Delete task || `/` | Search tasks |@@ -194,8 +195,6 @@ review = "/my-plugin:review"[prompts]planning = "Task: {task}"-running = ""-review = ""```**Full reference** with all available fields:@@ -216,15 +215,29 @@ supported_agents = ["claude", "codex", "gemini", "opencode"]# are always copied automatically.copy_dirs = [".my-plugin"]+# Individual files to copy from project root into each worktree.+# Merged with project-level copy_files from .agtx/config.toml.+copy_files = ["PROJECT.md", "REQUIREMENTS.md"]++# When true, enables Review β Planning transition via the `p` key.+# Each cycle increments the phase counter ({phase} placeholder).+# Use this for multi-milestone workflows (e.g. plan β execute β review β next milestone).+cyclic = false++# When true, the research phase must be completed before planning or running.+# Prevents skipping research for plugins that depend on it.+research_required = false+# 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).+# Use {phase} for cycle-aware paths (replaced with the current cycle number).+# Omitted phases show no completion indicator.[artifacts]research = ".my-plugin/research.md"-planning = ".my-plugin/plan.md"-running = ".my-plugin/summary.md"-review = ".my-plugin/review.md"+planning = ".my-plugin/{phase}/plan.md"+running = ".my-plugin/{phase}/summary.md"+review = ".my-plugin/{phase}/review.md"# Slash commands sent to the agent via tmux for each phase.# Written in canonical format (Claude/Gemini style): /namespace:command@@ -232,35 +245,49 @@ review = ".my-plugin/review.md"# Claude/Gemini: /my-plugin:plan (unchanged)# OpenCode: /my-plugin-plan (colon -> hyphen)# Codex: $my-plugin-plan (slash -> dollar, colon -> hyphen)+# Omitted phases fall back to agent-native agtx skill invocation+# (e.g. /agtx:plan for Claude, $agtx-plan for Codex).# Set to "" to skip sending a command for that phase.+# Use {phase} for cycle-aware commands (replaced with the current cycle number).+# Use {task} to inline the task description.[commands]-research = "/my-plugin:research {task}"-planning = "/my-plugin:plan {task}"-running = "/my-plugin:execute"-review = "/my-plugin:review"+preresearch = "/my-plugin:research {task}" # Used only when no research artifacts exist yet+research = "/my-plugin:discuss {phase}"+planning = "/my-plugin:plan {phase}"+running = "/my-plugin:execute {phase}"+review = "/my-plugin:review {phase}"# 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.+# {task} = task title + description, {task_id} = unique task ID, {phase} = cycle number.+# Omitted phases send no prompt (the skill/command handles instructions).[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?"++# Files/dirs to copy from worktree back to project root after a phase completes.+# Triggered automatically when the phase artifact is detected (spinner β checkmark).+# Useful for sharing research artifacts (specs, plans) across worktrees.+[copy_back]+research = ["PROJECT.md", "REQUIREMENTS.md", ".my-plugin"]```**What happens 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 prompt trigger 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 to indicate task phase completion+3. The **prompt** is sent with `{task}`, `{task_id}`, and `{phase}` replaced+4. agtx polls for the **artifact** file β when found, the spinner becomes a checkmark+5. If **copy_back** is configured, artifacts are copied from worktree to project root on completion+6. If the agent appears idle (no output for 15s), the spinner becomes a pause icon++**Preresearch fallback:** When pressing `R` on a task, if `preresearch` is configured and no research artifacts from `copy_back` exist in the project root yet, the `preresearch` command is used instead of `research`. This lets plugins run a one-time project setup (e.g. `/gsd:new-project`) before switching to the regular research command for subsequent tasks.++**Cyclic workflows:** When `cyclic = true`, pressing `p` in Review moves the task back to Planning with an incremented phase counter. This enables multi-milestone workflows where each cycle (plan β execute β review) produces artifacts in a separate `{phase}` directory.**Custom skills:** If your plugin provides its own skill files, place them in the plugin directory:diff --git a/plugins/agtx/plugin.toml b/plugins/agtx/plugin.tomlindex 9969afe..e871d1e 100644--- a/plugins/agtx/plugin.toml+++ b/plugins/agtx/plugin.toml@@ -8,7 +8,10 @@ running = ".agtx/execute.md"review = ".agtx/review.md"[commands]-# Unset β uses agent-native skill invocation (/agtx:plan, $agtx-plan, etc.)+research = "/agtx:research"+planning = "/agtx:plan"+running = "/agtx:execute"+review = "/agtx:review"[prompts]research = "Task: {task}"diff --git a/plugins/gsd/plugin.toml b/plugins/gsd/plugin.tomlindex 65181f3..f7b769b 100644--- a/plugins/gsd/plugin.toml+++ b/plugins/gsd/plugin.toml@@ -3,22 +3,28 @@ 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"]research_required = true+cyclic = true+copy_files = ["PROJECT.md", "REQUIREMENTS.md", "ROADMAP.md", "STATE.md"]copy_dirs = [".planning"][artifacts]-research = ".planning/ROADMAP.md"-planning = ".planning/1/1-PLAN.md"-running = ".planning/1/1-SUMMARY.md"-review = ".planning/1/UAT.md"+research = ".planning/1/1-CONTEXT.md"+planning = ".planning/{phase}/*-PLAN.md"+running = ".planning/{phase}/*-SUMMARY.md"+review = ".planning/{phase}/UAT.md"[commands]-research = "/gsd:new-project"-planning = "/gsd:plan-phase 1"-running = "/gsd:execute-phase 1"-review = "/gsd:verify-work 1"+preresearch = "/gsd:new-project"+research = "/gsd:discuss-phase {phase}"+planning = "/gsd:plan-phase {phase}"+running = "/gsd:execute-phase {phase}"+review = "/gsd:verify-work {phase}"[prompts]research = "Task: {task}"[prompt_triggers]research = "What do you want to build?"++[copy_back]+research = ["PROJECT.md", "REQUIREMENTS.md", "ROADMAP.md", "STATE.md", ".planning"]diff --git a/plugins/void/plugin.toml b/plugins/void/plugin.tomlindex a178ffc..9de3702 100644--- a/plugins/void/plugin.toml+++ b/plugins/void/plugin.toml@@ -1,14 +1,3 @@name = "void"description = "Plain coding agent session without any prompting or skills"--[commands]-research = ""-planning = ""-running = ""-review = ""--[prompts]-research = ""-planning = ""-running = ""-review = ""+cyclic = truediff --git a/src/config/mod.rs b/src/config/mod.rsindex 887f5b3..335654c 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -404,6 +404,17 @@ pub struct WorkflowPlugin {/// Extra directories to copy from project root to worktrees (e.g. [".specify"]).#[serde(default)]pub copy_dirs: Vec<String>,+ /// Individual files to copy from project root to worktrees (e.g. ["PROJECT.md"]).+ /// Merged with project-level copy_files during worktree setup.+ #[serde(default)]+ pub copy_files: Vec<String>,+ /// When true, enables Review β Planning transition for multi-phase workflows.+ #[serde(default)]+ pub cyclic: bool,+ /// Files/dirs to copy from worktree back to project root after a phase completes.+ /// Keyed by phase name (e.g. { research = ["PROJECT.md", ".planning"] }).+ #[serde(default)]+ pub copy_back: std::collections::HashMap<String, Vec<String>>,}#[derive(Debug, Clone, Default, Serialize, Deserialize)]@@ -418,6 +429,10 @@ pub struct PluginArtifacts {/// e.g. "/gsd:plan-phase 1" or "/speckit.plan"#[derive(Debug, Clone, Default, Serialize, Deserialize)]pub struct PluginCommands {+ /// Command to run before research artifacts exist (e.g. "/gsd:new-project").+ /// Used only when no research artifacts are found in the project root.+ /// Falls back to `research` if not set.+ pub preresearch: Option<String>,pub research: Option<String>,pub planning: Option<String>,pub running: Option<String>,diff --git a/src/db/models.rs b/src/db/models.rsindex 98239cb..2580a59 100644--- a/src/db/models.rs+++ b/src/db/models.rs@@ -69,6 +69,7 @@ pub struct Task {pub pr_number: Option<i32>,pub pr_url: Option<String>,pub plugin: Option<String>,+ pub cycle: i32,pub created_at: DateTime<Utc>,pub updated_at: DateTime<Utc>,}@@ -90,6 +91,7 @@ impl Task {pr_number: None,pr_url: None,plugin: None,+ cycle: 1,created_at: now,updated_at: now,}@@ -167,6 +169,8 @@ impl AgentStatus {pub enum PhaseStatus {/// Agent is still working, no artifact yetWorking,+ /// Agent output hasn't changed for 15s β may need user input+ Idle,/// Phase artifact detected, ready to advanceReady,/// Tmux window gone (process exited)diff --git a/src/db/schema.rs b/src/db/schema.rsindex 5295db3..cb757df 100644--- a/src/db/schema.rs+++ b/src/db/schema.rs@@ -96,6 +96,7 @@ impl Database {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", []);+ let _ = self.conn.execute("ALTER TABLE tasks ADD COLUMN cycle INTEGER NOT NULL DEFAULT 1", []);Ok(())}@@ -133,8 +134,8 @@ impl Database {pub fn create_task(&self, task: &Task) -> Result<()> {self.conn.execute(r#"- INSERT INTO tasks (id, title, description, status, agent, project_id, session_name, worktree_path, branch_name, pr_number, pr_url, plugin, created_at, updated_at)- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)+ INSERT INTO tasks (id, title, description, status, agent, project_id, session_name, worktree_path, branch_name, pr_number, pr_url, plugin, cycle, created_at, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15)"#,params![task.id,@@ -149,6 +150,7 @@ impl Database {task.pr_number,task.pr_url,task.plugin,+ task.cycle,task.created_at.to_rfc3339(),task.updated_at.to_rfc3339(),],@@ -170,7 +172,8 @@ impl Database {pr_number = ?9,pr_url = ?10,plugin = ?11,- updated_at = ?12+ cycle = ?12,+ updated_at = ?13WHERE id = ?1"#,params![@@ -185,6 +188,7 @@ impl Database {task.pr_number,task.pr_url,task.plugin,+ task.cycle,task.updated_at.to_rfc3339(),],)?;@@ -212,6 +216,7 @@ impl Database {pr_number: row.get("pr_number").ok().flatten(),pr_url: row.get("pr_url").ok().flatten(),plugin: row.get("plugin").ok().flatten(),+ cycle: row.get("cycle").unwrap_or(1),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/worktree.rs b/src/git/worktree.rsindex 3d07b88..761bf38 100644--- a/src/git/worktree.rs+++ b/src/git/worktree.rs@@ -167,7 +167,7 @@ pub fn initialize_worktree(}/// Recursively copy a directory and its contents.-fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {+pub 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?;diff --git a/src/skills.rs b/src/skills.rsindex b55f98c..8402a3e 100644--- a/src/skills.rs+++ b/src/skills.rs@@ -73,28 +73,6 @@ pub fn skill_dir_to_filename(skill_dir_name: &str, agent_name: &str) -> String {/// 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`@@ -123,31 +101,6 @@ pub fn transform_plugin_command(canonical_cmd: &str, agent_name: &str) -> Option}}-/// 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("---") {diff --git a/src/tui/app.rs b/src/tui/app.rsindex a2733a5..2ff42e2 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -31,7 +31,7 @@ fn hex_to_color(hex: &str) -> Color {}/// Build footer help text based on current UI state-fn build_footer_text(input_mode: InputMode, sidebar_focused: bool, selected_column: usize) -> String {+fn build_footer_text(input_mode: InputMode, sidebar_focused: bool, selected_column: usize, has_cyclic_plugin: bool) -> String {match input_mode {InputMode::Normal => {if sidebar_focused {@@ -40,7 +40,9 @@ fn build_footer_text(input_mode: InputMode, sidebar_focused: bool, selected_columatch selected_column {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(),+ 2 => " [o] new [/] search [Enter] open [x] del [d] diff [m] move [r] move left [e] sidebar [q] quit".to_string(),+ 3 if has_cyclic_plugin => " [o] new [/] search [Enter] open [x] del [d] diff [m] done [r] resume [p] next phase [e] sidebar [q] quit".to_string(),+ 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(),}}@@ -127,6 +129,8 @@ struct AppState {// Phase detectionphase_status_cache: HashMap<String, (PhaseStatus, Instant)>,spinner_frame: usize,+ // Idle detection: (content_hash, last_change_time) per task+ pane_content_hashes: HashMap<String, (u64, Instant)>,cached_plugin: Option<Option<WorkflowPlugin>>,// Transient warning message shown in footer (auto-clears after a few seconds)warning_message: Option<(String, Instant)>,@@ -384,6 +388,7 @@ impl App {review_confirm_popup: None,phase_status_cache: HashMap::new(),spinner_frame: 0,+ pane_content_hashes: HashMap::new(),cached_plugin: None,warning_message: None,plugin_select_popup: None,@@ -686,15 +691,19 @@ impl App {}// Footer with help (or transient warning)+ let has_cyclic_plugin = state.board.selected_task()+ .and_then(|t| t.plugin.as_ref())+ .and_then(|name| WorkflowPlugin::load(name, state.project_path.as_deref()).ok())+ .map_or(false, |p| p.cyclic);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),+ (build_footer_text(state.input_mode, state.sidebar_focused, state.board.selected_column, has_cyclic_plugin),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),+ (build_footer_text(state.input_mode, state.sidebar_focused, state.board.selected_column, has_cyclic_plugin),Style::default().fg(hex_to_color(&state.config.theme.color_dimmed)))};@@ -1399,6 +1408,7 @@ impl App {let spinner = SPINNER_FRAMES[spinner_frame % SPINNER_FRAMES.len()];Span::styled(format!("{} ", spinner), Style::default().fg(Color::Yellow))}+ Some((PhaseStatus::Idle, _)) => Span::styled("\u{23f8} ", Style::default().fg(hex_to_color(&theme.color_dimmed))),Some((PhaseStatus::Exited, _)) => Span::styled("\u{2717} ", Style::default().fg(Color::Red)),None => Span::raw(""),};@@ -2386,6 +2396,18 @@ impl App {}}}+ KeyCode::Char('p') => {+ // Cyclic: Review β Planning (next phase) β only when plugin is cyclic+ if let Some(task) = self.state.board.selected_task() {+ if task.status == TaskStatus::Review {+ let plugin = self.load_task_plugin(&task);+ if plugin.as_ref().map_or(false, |p| p.cyclic) {+ let task_id = task.id.clone();+ self.move_review_to_planning(&task_id)?;+ }+ }+ }+ }KeyCode::Char('/') => {// Open task searchself.state.task_search = Some(TaskSearchState {@@ -2884,7 +2906,7 @@ impl App {{let plugin = self.load_task_plugin(&task);if let Some(ref wt_path) = task.worktree_path {- if !phase_artifact_exists(wt_path, current_status, &plugin) {+ if !phase_artifact_exists(wt_path, current_status, &plugin, task.cycle) {// Check if agent is still running in the tmux panelet agent_running = task.session_name.as_ref().map_or(false, |target| {self.state.tmux_ops.window_exists(target).unwrap_or(false)@@ -2943,8 +2965,8 @@ impl App {research_artifact_exists(wt, &task.id, &plugin)});let planning_phase = if has_research { "planning_with_research" } else { "planning" };- let skill_cmd = resolve_skill_command(&plugin, planning_phase, &planning_agent, &task_content);- let prompt = resolve_prompt(&plugin, planning_phase, &task_content, &task.id, &planning_agent);+ let skill_cmd = resolve_skill_command(&plugin, planning_phase, &planning_agent, &task_content, task.cycle);+ let prompt = resolve_prompt(&plugin, planning_phase, &task_content, &task.id, task.cycle);let prompt_trigger = resolve_prompt_trigger(&plugin, planning_phase);let tmux_ops = Arc::clone(&self.state.tmux_ops);@@ -2971,8 +2993,8 @@ impl App {} else {task.title.clone()};- let prompt = resolve_prompt(&plugin, "planning", &task_content, &task.id, &planning_agent);- let skill_cmd = resolve_skill_command(&plugin, "planning", &planning_agent, &task_content);+ let prompt = resolve_prompt(&plugin, "planning", &task_content, &task.id, task.cycle);+ let skill_cmd = resolve_skill_command(&plugin, "planning", &planning_agent, &task_content, task.cycle);let prompt_trigger = resolve_prompt_trigger(&plugin, "planning");let all_agents = collect_phase_agents(&self.state.config);let project_name = self.state.project_name.clone();@@ -3057,11 +3079,11 @@ impl App {task.title.clone()};let has_plan = task.worktree_path.as_ref().map_or(false, |wt| {- phase_artifact_exists(wt, TaskStatus::Planning, &plugin)+ phase_artifact_exists(wt, TaskStatus::Planning, &plugin, task.cycle)});let run_phase = if has_plan { "running" } else { "running_direct" };- let skill_cmd = resolve_skill_command(&plugin, "running", &running_agent, &task_content);- let prompt = resolve_prompt(&plugin, run_phase, &task_content, &task.id, &running_agent);+ let skill_cmd = resolve_skill_command(&plugin, "running", &running_agent, &task_content, task.cycle);+ let prompt = resolve_prompt(&plugin, run_phase, &task_content, &task.id, task.cycle);let prompt_trigger = resolve_prompt_trigger(&plugin, "running");let session_clone = session_name.clone();let tmux_ops = Arc::clone(&self.state.tmux_ops);@@ -3093,8 +3115,8 @@ impl App {} else {task.title.clone()};- let skill_cmd = resolve_skill_command(&plugin, "review", &review_agent, &task_content);- let prompt = resolve_prompt(&plugin, "review", &task_content, &task.id, &review_agent);+ let skill_cmd = resolve_skill_command(&plugin, "review", &review_agent, &task_content, task.cycle);+ let prompt = resolve_prompt(&plugin, "review", &task_content, &task.id, task.cycle);let prompt_trigger = resolve_prompt_trigger(&plugin, "review");let session_clone = session_name.clone();let tmux_ops = Arc::clone(&self.state.tmux_ops);@@ -3249,9 +3271,19 @@ impl App {task.title.clone()};- let prompt = resolve_prompt(&plugin, "research", &task_content, &task.id, &agent_name);- let skill_cmd = resolve_skill_command(&plugin, "research", &agent_name, &task_content);- let prompt_trigger = resolve_prompt_trigger(&plugin, "research");+ // Check if research artifacts already exist in project root (preresearch fallback)+ // If artifacts exist, use "research" command. If not and preresearch is configured, use "preresearch".+ let use_preresearch = plugin.as_ref().map_or(false, |p| {+ p.commands.preresearch.is_some()+ && !p.copy_back.get("research").map_or(false, |entries| {+ entries.iter().any(|e| project_path.join(e).exists())+ })+ });+ let research_phase = if use_preresearch { "preresearch" } else { "research" };++ let prompt = resolve_prompt(&plugin, research_phase, &task_content, &task.id, task.cycle);+ let skill_cmd = resolve_skill_command(&plugin, research_phase, &agent_name, &task_content, task.cycle);+ let prompt_trigger = resolve_prompt_trigger(&plugin, research_phase);let all_agents = collect_phase_agents(&self.state.config);let project_name = self.state.project_name.clone();let copy_files = self.state.config.copy_files.clone();@@ -3369,8 +3401,8 @@ impl App {let plugin = self.load_task_plugin(&task);let running_agent = self.state.config.agent_for_phase("running").to_string();let all_agents = collect_phase_agents(&self.state.config);- let prompt = resolve_prompt(&plugin, "running_direct", &task_content, &task.id, &running_agent);- let skill_cmd = resolve_skill_command(&plugin, "running", &running_agent, &task_content);+ let prompt = resolve_prompt(&plugin, "running_direct", &task_content, &task.id, task.cycle);+ let skill_cmd = resolve_skill_command(&plugin, "running", &running_agent, &task_content, task.cycle);let prompt_trigger = resolve_prompt_trigger(&plugin, "running");let project_name = self.state.project_name.clone();let copy_files = self.state.config.copy_files.clone();@@ -3476,6 +3508,54 @@ impl App {Ok(())}+ fn move_review_to_planning(&mut self, task_id: &str) -> Result<()> {+ if let (Some(db), Some(_project_path)) = (&self.state.db, &self.state.project_path) {+ if let Some(mut task) = db.get_task(task_id)? {+ if task.status != TaskStatus::Review {+ return Ok(());+ }++ // Increment cycle counter for the next phase+ task.cycle += 1;++ // Switch agent if planning phase uses a different agent than review+ let (planning_agent, agent_switch) = needs_agent_switch(&self.state.config, &task, "planning");+ let plugin = self.load_task_plugin(&task);++ // Resolve skill command and prompt for the new planning phase+ let task_content = task.description.as_deref().unwrap_or(&task.title).to_string();+ let skill_cmd = resolve_skill_command(&plugin, "planning", &planning_agent, &task_content, task.cycle);+ let prompt = resolve_prompt(&plugin, "planning", &task_content, &task.id, task.cycle);+ let prompt_trigger = resolve_prompt_trigger(&plugin, "planning");++ if let Some(session_name) = &task.session_name {+ let session_clone = session_name.clone();+ let tmux_ops = Arc::clone(&self.state.tmux_ops);+ let agent_registry = Arc::clone(&self.state.agent_registry);+ let planning_agent_clone = planning_agent.clone();+ let current_agent_clone = task.agent.clone();+ let task_content_clone = task_content.clone();+ std::thread::spawn(move || {+ if agent_switch {+ let agent_ops = agent_registry.get(&planning_agent_clone);+ let new_cmd = agent_ops.build_interactive_command("");+ switch_agent_in_tmux(tmux_ops.as_ref(), &session_clone, ¤t_agent_clone, &new_cmd);+ let _ = wait_for_agent_ready(&tmux_ops, &session_clone);+ }+ send_skill_and_prompt(&tmux_ops, &session_clone, &skill_cmd, &prompt, &prompt_trigger, &task_content_clone, &planning_agent_clone);+ });+ }++ task.agent = planning_agent;+ task.status = TaskStatus::Planning;+ task.updated_at = chrono::Utc::now();+ db.update_task(&task)?;+ self.refresh_tasks()?;+ }+ }+ Ok(())+ }+fn move_running_to_planning(&mut self, task_id: &str) -> Result<()> {if let (Some(db), Some(_project_path)) = (&self.state.db, &self.state.project_path) {if let Some(mut task) = db.get_task(task_id)? {@@ -3602,13 +3682,13 @@ impl App {|| (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()))+ .map(|t| (t.id.clone(), t.status, t.worktree_path.clone(), t.plugin.clone(), t.session_name.clone(), t.cycle)).collect();// Cache loaded plugins by name to avoid reloading from disk for each tasklet mut plugin_cache: HashMap<Option<String>, Option<WorkflowPlugin>> = HashMap::new();- for (task_id, status, worktree_path, task_plugin) in tasks_to_check {+ for (task_id, status, worktree_path, task_plugin, session_name, cycle) in tasks_to_check {if let Some((_, timestamp)) = self.state.phase_status_cache.get(&task_id) {if now.duration_since(*timestamp) < CACHE_TTL {continue;@@ -3634,7 +3714,7 @@ impl App {None => skills::load_bundled_plugin("agtx"),}});- if phase_artifact_exists(wt, status, plugin) {+ if phase_artifact_exists(wt, status, plugin, cycle) {PhaseStatus::Ready} else {PhaseStatus::Working@@ -3643,6 +3723,50 @@ impl App {PhaseStatus::Working};+ // Idle detection: if Working, check if pane content has been stable for 15s+ let mut phase_status = phase_status;+ if phase_status == PhaseStatus::Working {+ if let Some(ref session_name) = session_name {+ if let Ok(content) = self.state.tmux_ops.capture_pane(session_name) {+ use std::hash::{Hash, Hasher};+ let mut hasher = std::collections::hash_map::DefaultHasher::new();+ content.hash(&mut hasher);+ let hash = hasher.finish();++ let entry = self.state.pane_content_hashes+ .entry(task_id.clone())+ .or_insert((hash, now));+ if entry.0 != hash {+ *entry = (hash, now);+ } else if now.duration_since(entry.1) >= std::time::Duration::from_secs(15) {+ phase_status = PhaseStatus::Idle;+ }+ }+ }+ } else if phase_status == PhaseStatus::Ready {+ self.state.pane_content_hashes.remove(&task_id);++ // Copy-back: on Working β Ready transition, copy artifacts from worktree to project root+ let was_ready = self.state.phase_status_cache.get(&task_id)+ .map_or(false, |(prev, _)| *prev == PhaseStatus::Ready);+ if !was_ready {+ if let (Some(ref wt), Some(ref pp)) = (&worktree_path, &project_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 => skills::load_bundled_plugin("agtx"),+ }+ });+ let phase_name = status.as_str();+ if let Some(ref p) = plugin {+ if let Some(entries) = p.copy_back.get(phase_name) {+ copy_back_to_project(Path::new(wt), Path::new(pp), entries);+ }+ }+ }+ }+ }+self.state.phase_status_cache.insert(task_id, (phase_status, now));}@@ -3707,6 +3831,31 @@ fn ensure_project_tmux_session(project_name: &str, project_path: &Path, tmux_ops}}+/// Copy files/dirs from worktree back to project root.+/// Used by plugins with `[copy_back]` to sync artifacts after phase completion.+fn copy_back_to_project(worktree: &Path, project_root: &Path, entries: &[String]) {+ for entry in entries {+ let src = worktree.join(entry);+ let dst = project_root.join(entry);+ if !src.exists() {+ continue;+ }+ if src.is_dir() {+ if let Err(e) = crate::git::copy_dir_recursive(&src, &dst) {+ eprintln!("copy_back: failed to copy dir '{}': {}", entry, e);+ }+ } else {+ // Ensure parent directory exists for nested file paths+ if let Some(parent) = dst.parent() {+ let _ = std::fs::create_dir_all(parent);+ }+ if let Err(e) = std::fs::copy(&src, &dst) {+ eprintln!("copy_back: failed to copy file '{}': {}", entry, e);+ }+ }+ }+}+/// Generate a URL-safe slug from task ID and titlefn generate_task_slug(task_id: &str, title: &str) -> String {let title_slug: String = title@@ -3840,12 +3989,27 @@ fn setup_task_worktree(};// Initialize worktree: copy files and run init script+ // Merge plugin-level copy_files with project-level copy_fileslet worktree_path = Path::new(&worktree_path_str);let copy_dirs = plugin.as_ref().map_or_else(Vec::new, |p| p.copy_dirs.clone());+ let merged_copy_files = {+ let mut parts: Vec<String> = Vec::new();+ if let Some(ref cf) = copy_files {+ if !cf.trim().is_empty() {+ parts.push(cf.clone());+ }+ }+ if let Some(ref p) = plugin {+ if !p.copy_files.is_empty() {+ parts.push(p.copy_files.join(","));+ }+ }+ if parts.is_empty() { None } else { Some(parts.join(",")) }+ };let init_warnings = git_ops.initialize_worktree(project_path,worktree_path,- copy_files,+ merged_copy_files,init_script,copy_dirs,);@@ -3887,7 +4051,7 @@ fn setup_task_worktree(// 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 has_skill_support = resolve_skill_command(plugin, "planning", agent_name, "", task.cycle).is_some();let agent_cmd = if has_skill_support {agent_ops.build_interactive_command("")} else {@@ -4477,12 +4641,11 @@ 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 {+/// Resolve the task prompt for a given phase transition, using plugin prompt template.+/// Substitutes {task}, {task_id}, and {phase} placeholders. Returns empty if no template is configured.+fn resolve_prompt(plugin: &Option<WorkflowPlugin>, phase: &str, task_content: &str, task_id: &str, cycle: i32) -> String {let template = match phase {- "research" => plugin.as_ref()+ "preresearch" | "research" => plugin.as_ref().and_then(|p| p.prompts.research.as_deref()).unwrap_or(""),"planning" => plugin.as_ref()@@ -4504,61 +4667,48 @@ fn resolve_prompt(plugin: &Option<WorkflowPlugin>, phase: &str, task_content: &s_ => return task_content.to_string(),};- // 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);-if template.is_empty() {- // No prompt text β return just the skill reference (if any)- return skill_ref;+ return String::new();}- let result = template+ template.replace("{task}", task_content)- .replace("{task_id}", task_id);-- if skill_ref.is_empty() {- result- } else {- format!("{}\n\n{}", result, skill_ref)- }+ .replace("{task_id}", task_id)+ .replace("{phase}", &cycle.to_string())}/// 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")+/// Returns the plugin command transformed for the target agent, or None if no command is configured.+fn resolve_skill_command(plugin: &Option<WorkflowPlugin>, phase: &str, agent_name: &str, task_content: &str, cycle: i32) -> Option<String> {+ let p = plugin.as_ref()?;+// 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;- }- // When research was already done, strip {task} β agent already has context- let expanded = if phase == "planning_with_research" {- c.replace("{task}", "").trim().to_string()- } else {- // 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(" ");- c.replace("{task}", &task_oneline)- };- return skills::transform_plugin_command(&expanded, agent_name);- }+ // Commands may contain {task} and {phase} placeholders+ let cmd = match phase {+ "preresearch" => p.commands.preresearch.as_deref()+ .or(p.commands.research.as_deref()),+ "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 cmd.is_empty() {+ // Explicit empty command means "no command" (e.g., void plugin)+ return None;}- // 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)+ // When research was already done, strip {task} β agent already has context+ let expanded = if phase == "planning_with_research" {+ cmd.replace("{task}", "").trim().to_string()+ } else {+ // 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(" ");+ cmd.replace("{task}", &task_oneline)+ };+ let expanded = expanded.replace("{phase}", &cycle.to_string());+ skills::transform_plugin_command(&expanded, agent_name)}/// Resolve the prompt trigger text for a given phase.@@ -4667,7 +4817,7 @@ fn send_skill_and_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(),+ "preresearch" | "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(),@@ -4719,17 +4869,18 @@ fn wait_for_prompt_trigger(tmux_ops: &Arc<dyn TmuxOperations>, target: &str, tri}/// 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 = plugin.as_ref().and_then(|p| match status {+fn phase_artifact_exists(worktree_path: &str, status: TaskStatus, plugin: &Option<WorkflowPlugin>, cycle: i32) -> bool {+ let rel_template = plugin.as_ref().and_then(|p| match status {TaskStatus::Planning => p.artifacts.planning.as_deref(),TaskStatus::Running => p.artifacts.running.as_deref(),TaskStatus::Review => p.artifacts.review.as_deref(),_ => None,});- let Some(rel_path) = rel_path else { return false; };+ let Some(rel_template) = rel_template else { return false; };+ let rel_path = rel_template.replace("{phase}", &cycle.to_string());- let full_path = Path::new(worktree_path).join(rel_path);+ let full_path = Path::new(worktree_path).join(&rel_path);// Support simple wildcard: "specs/*/plan.md" matches any single directory levelif rel_path.contains('*') {diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rsindex 32acddb..08e34ea 100644--- a/src/tui/app_tests.rs+++ b/src/tui/app_tests.rs@@ -205,6 +205,7 @@ fn test_create_pr_with_content_success() {pr_number: None,pr_url: None,plugin: None,+ cycle: 1,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -292,6 +293,7 @@ fn test_create_pr_with_content_no_changes() {pr_number: None,pr_url: None,plugin: None,+ cycle: 1,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -349,6 +351,7 @@ fn test_create_pr_with_content_push_failure() {pr_number: None,pr_url: None,plugin: None,+ cycle: 1,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -403,6 +406,7 @@ fn test_push_changes_to_existing_pr_success() {pr_number: Some(99),pr_url: Some("https://github.com/org/repo/pull/99".to_string()),plugin: None,+ cycle: 1,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -454,6 +458,7 @@ fn test_push_changes_to_existing_pr_no_changes() {pr_number: Some(50),pr_url: Some("https://github.com/org/repo/pull/50".to_string()),plugin: None,+ cycle: 1,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -488,6 +493,7 @@ fn test_push_changes_to_existing_pr_no_url() {pr_number: None,pr_url: None, // No PR URLplugin: None,+ cycle: 1,created_at: chrono::Utc::now(),updated_at: chrono::Utc::now(),};@@ -1259,7 +1265,7 @@ fn test_word_boundary_roundtrip() {#[test]fn test_footer_text_sidebar_focused() {- let text = build_footer_text(InputMode::Normal, true, 0);+ let text = build_footer_text(InputMode::Normal, true, 0, false);assert!(text.contains("[j/k] navigate"));assert!(text.contains("[e] hide sidebar"));assert!(!text.contains("[o] new"));@@ -1267,7 +1273,7 @@ fn test_footer_text_sidebar_focused() {#[test]fn test_footer_text_backlog_column() {- let text = build_footer_text(InputMode::Normal, false, 0);+ let text = build_footer_text(InputMode::Normal, false, 0, false);assert!(text.contains("[M] run"));assert!(text.contains("[m] plan"));assert!(!text.contains("[r] move left"));@@ -1275,7 +1281,7 @@ fn test_footer_text_backlog_column() {#[test]fn test_footer_text_planning_column() {- let text = build_footer_text(InputMode::Normal, false, 1);+ let text = build_footer_text(InputMode::Normal, false, 1, false);assert!(text.contains("[m] run"));assert!(!text.contains("[M] run"));assert!(!text.contains("[r] move left"));@@ -1283,21 +1289,29 @@ fn test_footer_text_planning_column() {#[test]fn test_footer_text_running_column() {- let text = build_footer_text(InputMode::Normal, false, 2);+ let text = build_footer_text(InputMode::Normal, false, 2, false);assert!(text.contains("[r] move left"));assert!(text.contains("[m] move"));}#[test]fn test_footer_text_review_column() {- let text = build_footer_text(InputMode::Normal, false, 3);+ let text = build_footer_text(InputMode::Normal, false, 3, false);assert!(text.contains("[r] move left"));assert!(text.contains("[m] move"));}+#[test]+fn test_footer_text_review_column_cyclic() {+ let text = build_footer_text(InputMode::Normal, false, 3, true);+ assert!(text.contains("[p] next phase"));+ assert!(text.contains("[r] resume"));+ assert!(text.contains("[m] done"));+}+#[test]fn test_footer_text_done_column() {- let text = build_footer_text(InputMode::Normal, false, 4);+ let text = build_footer_text(InputMode::Normal, false, 4, false);assert!(!text.contains("[m] move"));assert!(!text.contains("[r]"));assert!(!text.contains("[d] diff"));@@ -1305,14 +1319,14 @@ fn test_footer_text_done_column() {#[test]fn test_footer_text_input_title() {- let text = build_footer_text(InputMode::InputTitle, false, 0);+ let text = build_footer_text(InputMode::InputTitle, false, 0, false);assert!(text.contains("Enter task title"));assert!(text.contains("[Esc] cancel"));}#[test]fn test_footer_text_input_description() {- let text = build_footer_text(InputMode::InputDescription, false, 0);+ let text = build_footer_text(InputMode::InputDescription, false, 0, false);assert!(text.contains("[#] file search"));assert!(text.contains("[\\+Enter] newline"));}@@ -1665,35 +1679,6 @@ fn test_agent_native_skill_dir() {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@@ -1713,16 +1698,6 @@ fn test_transform_plugin_command() {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";@@ -1773,28 +1748,17 @@ fn test_transform_skill_frontmatter_no_agtx() {}#[test]-fn test_resolve_prompt_claude_no_skill_ref() {- // Claude has skill invocation support β prompt should NOT contain skill reference+fn test_resolve_prompt_with_template() {let plugin = skills::load_bundled_plugin("agtx");- let prompt = resolve_prompt(&plugin, "planning", "my task", "task-123", "claude");+ let prompt = resolve_prompt(&plugin, "planning", "my task", "task-123", 1);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 plugin = skills::load_bundled_plugin("agtx");- let prompt = resolve_prompt(&plugin, "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() {let plugin = skills::load_bundled_plugin("agtx");- let prompt = resolve_prompt(&plugin, "research", "my task", "abc-123", "claude");+ let prompt = resolve_prompt(&plugin, "research", "my task", "abc-123", 1);assert!(prompt.contains("my task"));// Claude should NOT have skill ref in prompt (sent via send_keys)assert!(!prompt.contains("/agtx:research"));@@ -1803,7 +1767,7 @@ fn test_resolve_prompt_research_has_task() {#[test]fn test_resolve_prompt_running_phase() {let plugin = skills::load_bundled_plugin("agtx");- let prompt = resolve_prompt(&plugin, "running", "my task", "task-123", "claude");+ let prompt = resolve_prompt(&plugin, "running", "my task", "task-123", 1);// No running prompt β execute skill handles instructionsassert!(prompt.is_empty());}@@ -1811,16 +1775,15 @@ fn test_resolve_prompt_running_phase() {#[test]fn test_resolve_prompt_review_phase() {let plugin = skills::load_bundled_plugin("agtx");- let prompt = resolve_prompt(&plugin, "review", "my task", "task-123", "copilot");- // No review prompt β review skill handles instructions.- // Copilot gets skill file reference since it has no interactive invocation.- assert!(prompt.contains(".agtx/skills/agtx-review/SKILL.md"));+ let prompt = resolve_prompt(&plugin, "review", "my task", "task-123", 1);+ // No review prompt template defined β returns empty+ assert!(prompt.is_empty());}#[test]fn test_resolve_prompt_planning_with_research() {let plugin = skills::load_bundled_plugin("agtx");- let prompt = resolve_prompt(&plugin, "planning_with_research", "my task", "task-123", "claude");+ let prompt = resolve_prompt(&plugin, "planning_with_research", "my task", "task-123", 1);// Empty β agent already has task from research session, skill handles research file discoveryassert!(prompt.is_empty());}@@ -1828,7 +1791,7 @@ fn test_resolve_prompt_planning_with_research() {#[test]fn test_resolve_prompt_no_plugin_returns_empty() {// Without a plugin, all prompts return empty- let prompt = resolve_prompt(&None, "planning", "my task", "task-123", "claude");+ let prompt = resolve_prompt(&None, "planning", "my task", "task-123", 1);assert!(prompt.is_empty());}@@ -1842,22 +1805,22 @@ fn test_agtx_plugin_artifacts() {}#[test]-fn test_agtx_plugin_has_no_commands() {+fn test_agtx_plugin_has_commands() {let plugin = skills::load_bundled_plugin("agtx").expect("agtx plugin should load");- assert!(plugin.commands.research.is_none());- assert!(plugin.commands.planning.is_none());- assert!(plugin.commands.running.is_none());- assert!(plugin.commands.review.is_none());+ assert_eq!(plugin.commands.research.as_deref(), Some("/agtx:research"));+ assert_eq!(plugin.commands.planning.as_deref(), Some("/agtx:plan"));+ assert_eq!(plugin.commands.running.as_deref(), Some("/agtx:execute"));+ assert_eq!(plugin.commands.review.as_deref(), Some("/agtx:review"));}#[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);+ // No plugin: no commands, returns None for all agents/phases+ assert_eq!(resolve_skill_command(&None, "planning", "claude", "", 1), None);+ assert_eq!(resolve_skill_command(&None, "running", "codex", "", 1), None);+ assert_eq!(resolve_skill_command(&None, "review", "gemini", "", 1), None);+ assert_eq!(resolve_skill_command(&None, "planning", "opencode", "", 1), None);+ assert_eq!(resolve_skill_command(&None, "planning", "copilot", "", 1), None);}#[test]@@ -1871,6 +1834,7 @@ fn test_resolve_skill_command_with_plugin() {artifacts: PluginArtifacts::default(),commands: PluginCommands {research: Some("/gsd:discuss-phase 1".to_string()),+ preresearch: None,planning: Some("/gsd:plan-phase 1".to_string()),running: Some("/gsd:execute-phase 1".to_string()),review: Some("/gsd:verify-work 1".to_string()),@@ -1879,20 +1843,23 @@ fn test_resolve_skill_command_with_plugin() {prompt_triggers: PluginPromptTriggers::default(),research_required: false,copy_dirs: vec![],+ copy_files: vec![],+ cyclic: false,+ copy_back: std::collections::HashMap::new(),});// 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()));+ assert_eq!(resolve_skill_command(&plugin, "planning", "claude", "", 1), Some("/gsd:plan-phase 1".to_string()));+ assert_eq!(resolve_skill_command(&plugin, "running", "claude", "", 1), Some("/gsd:execute-phase 1".to_string()));+ assert_eq!(resolve_skill_command(&plugin, "review", "gemini", "", 1), Some("/gsd:verify-work 1".to_string()));+ assert_eq!(resolve_skill_command(&plugin, "research", "claude", "", 1), 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()));+ assert_eq!(resolve_skill_command(&plugin, "planning", "opencode", "", 1), Some("/gsd-plan-phase 1".to_string()));+ assert_eq!(resolve_skill_command(&plugin, "research", "opencode", "", 1), 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()));+ assert_eq!(resolve_skill_command(&plugin, "planning", "codex", "", 1), Some("$gsd-plan-phase 1".to_string()));+ assert_eq!(resolve_skill_command(&plugin, "running", "codex", "", 1), 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);+ assert_eq!(resolve_skill_command(&plugin, "planning", "copilot", "", 1), None);}#[test]@@ -1911,6 +1878,9 @@ fn test_plugin_supports_agent() {prompt_triggers: Default::default(),research_required: false,copy_dirs: vec![],+ copy_files: vec![],+ cyclic: false,+ copy_back: std::collections::HashMap::new(),};assert!(plugin.supports_agent("claude"));assert!(plugin.supports_agent("copilot"));@@ -1928,6 +1898,9 @@ fn test_plugin_supports_agent() {prompt_triggers: Default::default(),research_required: false,copy_dirs: vec![],+ copy_files: vec![],+ cyclic: false,+ copy_back: std::collections::HashMap::new(),};assert!(plugin.supports_agent("claude"));assert!(plugin.supports_agent("codex"));@@ -1995,19 +1968,22 @@ fn test_phase_artifact_exists_with_glob() {prompt_triggers: Default::default(),research_required: false,copy_dirs: vec![],+ copy_files: vec![],+ cyclic: false,+ copy_back: std::collections::HashMap::new(),});let worktree = tmp.to_string_lossy().to_string();// Planning artifact exists (glob matches)- assert!(phase_artifact_exists(&worktree, TaskStatus::Planning, &plugin));+ assert!(phase_artifact_exists(&worktree, TaskStatus::Planning, &plugin, 1));// Research artifact doesn't exist yet (no spec.md)- assert!(!phase_artifact_exists(&worktree, TaskStatus::Backlog, &plugin));+ assert!(!phase_artifact_exists(&worktree, TaskStatus::Backlog, &plugin, 1));// 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));+ assert!(!phase_artifact_exists(&worktree, TaskStatus::Running, &plugin, 1));+ assert!(!phase_artifact_exists(&worktree, TaskStatus::Review, &plugin, 1));let _ = std::fs::remove_dir_all(&tmp);}@@ -2152,7 +2128,7 @@ fn test_install_plugin_none_clears_config() {#[test]fn test_footer_text_backlog_includes_research() {- let text = build_footer_text(InputMode::Normal, false, 0);+ let text = build_footer_text(InputMode::Normal, false, 0, false);assert!(text.contains("[R] research"));}@@ -2180,7 +2156,7 @@ fn test_resolve_skill_command_research_phase() {[artifacts]"#;let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();- let cmd = resolve_skill_command(&Some(plugin), "research", "claude", "");+ let cmd = resolve_skill_command(&Some(plugin), "research", "claude", "", 1);assert_eq!(cmd, Some("/gsd:new-project".to_string()));}@@ -2199,7 +2175,7 @@ fn test_resolve_skill_command_planning_with_plugin() {[artifacts]"#;let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();- let cmd = resolve_skill_command(&Some(plugin), "planning", "claude", "");+ let cmd = resolve_skill_command(&Some(plugin), "planning", "claude", "", 1);assert_eq!(cmd, Some("/gsd:plan-phase 1".to_string()));}@@ -2218,7 +2194,7 @@ fn test_resolve_prompt_empty_for_gsd_planning() {[artifacts]"#;let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();- let prompt = resolve_prompt(&Some(plugin), "planning", "my task content", "task-123", "claude");+ let prompt = resolve_prompt(&Some(plugin), "planning", "my task content", "task-123", 1);assert!(prompt.is_empty());}@@ -2234,7 +2210,7 @@ fn test_resolve_prompt_research_with_task() {[artifacts]"#;let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();- let prompt = resolve_prompt(&Some(plugin), "research", "add tests", "task-123", "claude");+ let prompt = resolve_prompt(&Some(plugin), "research", "add tests", "task-123", 1);assert_eq!(prompt, "Task: add tests");}@@ -2247,8 +2223,10 @@ fn test_gsd_plugin_toml_has_research_command() {.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()));+ assert_eq!(plugin.commands.preresearch, Some("/gsd:new-project".to_string()));+ assert_eq!(plugin.commands.research, Some("/gsd:discuss-phase {phase}".to_string()));+ assert_eq!(plugin.commands.planning, Some("/gsd:plan-phase {phase}".to_string()));+ assert!(plugin.cyclic);}#[test]@@ -2270,6 +2248,9 @@ fn test_resolve_prompt_trigger_with_gsd() {},research_required: false,copy_dirs: vec![],+ copy_files: vec![],+ cyclic: false,+ copy_back: std::collections::HashMap::new(),});assert_eq!(resolve_prompt_trigger(&plugin, "research"),@@ -2305,6 +2286,9 @@ fn test_resolve_prompt_trigger_empty_string_filtered() {},research_required: false,copy_dirs: vec![],+ copy_files: vec![],+ cyclic: false,+ copy_back: std::collections::HashMap::new(),});// Empty strings should be filtered outassert_eq!(resolve_prompt_trigger(&plugin, "research"), None);@@ -2662,3 +2646,147 @@ fn test_switch_agent_codex_sends_ctrl_c() {switch_agent_in_tmux(&mock, "sess:win", "codex", "claude");assert!(ctrl_c_sent.load(Ordering::SeqCst), "Ctrl+C should be sent for codex");}++// =============================================================================+// Tests for cyclic phase support and {phase} substitution+// =============================================================================++#[test]+fn test_resolve_skill_command_phase_substitution() {+ use crate::config::{WorkflowPlugin, PluginCommands};+ let plugin_toml = r#"+ name = "gsd"+ init_script = "echo test"+ [commands]+ preresearch = "/gsd:new-project"+ research = "/gsd:discuss-phase {phase}"+ planning = "/gsd:plan-phase {phase}"+ running = "/gsd:execute-phase {phase}"+ review = "/gsd:verify-work {phase}"+ [prompts]+ [artifacts]+ "#;+ let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();+ let p = Some(plugin);++ // Cycle 1: {phase} β "1"+ assert_eq!(resolve_skill_command(&p, "planning", "claude", "", 1), Some("/gsd:plan-phase 1".to_string()));+ assert_eq!(resolve_skill_command(&p, "running", "claude", "", 1), Some("/gsd:execute-phase 1".to_string()));+ assert_eq!(resolve_skill_command(&p, "review", "claude", "", 1), Some("/gsd:verify-work 1".to_string()));++ // Cycle 2: {phase} β "2"+ assert_eq!(resolve_skill_command(&p, "planning", "claude", "", 2), Some("/gsd:plan-phase 2".to_string()));+ assert_eq!(resolve_skill_command(&p, "running", "claude", "", 2), Some("/gsd:execute-phase 2".to_string()));+ assert_eq!(resolve_skill_command(&p, "review", "claude", "", 2), Some("/gsd:verify-work 2".to_string()));++ // preresearch also gets {phase} substitution (falls back to research command)+ assert_eq!(resolve_skill_command(&p, "preresearch", "claude", "", 1), Some("/gsd:new-project".to_string()));+}++#[test]+fn test_phase_artifact_exists_with_phase_substitution() {+ use crate::config::{WorkflowPlugin, PluginArtifacts};++ let tmp = std::env::temp_dir().join("agtx_test_phase_artifact");+ let _ = std::fs::remove_dir_all(&tmp);++ // Create .planning/2/UAT.md to simulate phase 2 review artifact+ let phase_dir = tmp.join(".planning").join("2");+ std::fs::create_dir_all(&phase_dir).unwrap();+ std::fs::write(phase_dir.join("UAT.md"), "# UAT").unwrap();++ let plugin_toml = r#"+ name = "gsd"+ init_script = "echo test"+ [commands]+ [prompts]+ [artifacts]+ review = ".planning/{phase}/UAT.md"+ "#;+ let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();+ let p = Some(plugin);+ let wt = tmp.to_string_lossy().to_string();++ // Phase 1: artifact doesn't exist+ assert!(!phase_artifact_exists(&wt, TaskStatus::Review, &p, 1));++ // Phase 2: artifact exists+ assert!(phase_artifact_exists(&wt, TaskStatus::Review, &p, 2));++ let _ = std::fs::remove_dir_all(&tmp);+}++#[test]+fn test_footer_text_review_non_cyclic_no_next_phase() {+ let text = build_footer_text(InputMode::Normal, false, 3, false);+ assert!(!text.contains("[p] next phase"));+ assert!(text.contains("[m] move"));+}++#[test]+fn test_resolve_skill_command_preresearch_fallback() {+ // When preresearch is not set, falls back to research command+ let plugin_toml = r#"+ name = "test"+ init_script = "echo test"+ [commands]+ research = "/test:discuss"+ [prompts]+ [artifacts]+ "#;+ use crate::config::WorkflowPlugin;+ let plugin: WorkflowPlugin = toml::from_str(plugin_toml).unwrap();+ let p = Some(plugin);+ assert_eq!(resolve_skill_command(&p, "preresearch", "claude", "", 1), Some("/test:discuss".to_string()));+}++#[test]+fn test_copy_back_to_project() {+ let tmp = std::env::temp_dir().join("agtx_test_copy_back");+ let _ = std::fs::remove_dir_all(&tmp);++ let worktree = tmp.join("worktree");+ let project = tmp.join("project");+ std::fs::create_dir_all(&worktree).unwrap();+ std::fs::create_dir_all(&project).unwrap();++ // Create files in worktree+ std::fs::write(worktree.join("PROJECT.md"), "# Project").unwrap();+ std::fs::write(worktree.join("ROADMAP.md"), "# Roadmap").unwrap();+ let planning_dir = worktree.join(".planning");+ std::fs::create_dir_all(&planning_dir).unwrap();+ std::fs::write(planning_dir.join("context.md"), "# Context").unwrap();++ // Copy back+ let entries = vec![+ "PROJECT.md".to_string(),+ "ROADMAP.md".to_string(),+ ".planning".to_string(),+ "NONEXISTENT.md".to_string(), // Should be silently skipped+ ];+ copy_back_to_project(&worktree, &project, &entries);++ // Verify files were copied+ assert!(project.join("PROJECT.md").exists());+ assert!(project.join("ROADMAP.md").exists());+ assert!(project.join(".planning").join("context.md").exists());+ assert!(!project.join("NONEXISTENT.md").exists());++ let _ = std::fs::remove_dir_all(&tmp);+}++#[test]+fn test_gsd_plugin_has_cyclic_and_copy_back() {+ use crate::config::WorkflowPlugin;+ 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!(plugin.cyclic);+ assert!(!plugin.copy_files.is_empty());+ assert!(plugin.copy_back.contains_key("research"));+ let research_entries = &plugin.copy_back["research"];+ assert!(research_entries.contains(&"PROJECT.md".to_string()));+ assert!(research_entries.contains(&".planning".to_string()));+}