<!-- AUTO-GENERATED by scripts/gen-adapters.js - DO NOT EDIT -->
---
description: Master workflow orchestrator with autonomous task-to-production automation
agent: general
---

> **OpenCode Note**: Invoke agents using `@agent-name` syntax.
> Available agents: task-discoverer, exploration-agent, planning-agent,
> implementation-agent, deslop-agent, delivery-validator, sync-docs-agent, consult-agent
> Example: `@exploration-agent analyze the codebase`


## Phase 1: Policy Selection (Built-in Options)

Ask the user these questions using AskUserQuestion:

**Question 1 - Source**: "Where should I look for tasks?"
- GitHub Issues - Use `gh issue list` to find issues
- GitLab Issues - Use `glab issue list` to find issues
- Local tasks.md - Read from PLAN.md, tasks.md, or TODO.md in the repo
- Custom - User specifies their own source
- Other - User describes source, you figure it out

**Question 2 - Priority**: "What type of tasks to prioritize?"
- All - Consider all tasks, pick by score
- Bugs - Focus on bug fixes
- Security - Security issues first
- Features - New feature development

**Question 3 - Stop Point**: "How far should I take this task?"
- Merged - Until PR is merged to main
- PR Created - Stop after creating PR
- Implemented - Stop after local implementation
- Deployed - Deploy to staging
- Production - Full production deployment

After user answers, proceed to Phase 2 with the selected policy.


# /next-task - Master Workflow Orchestrator

Discover what to work on next and execute the complete implementation workflow.

---

<no-shortcuts-policy>
## No Shortcuts Policy

This workflow exists because each step serves a purpose. Taking shortcuts defeats the purpose of automation.

| Step | Purpose | What Happens If Skipped |
|------|---------|------------------------|
| Worktree creation | Parallel task isolation | Conflicts, lost work |
| Review loop (3 iterations) | Catches bugs humans miss | Bugs ship to production |
| 3-minute CI wait | Auto-reviewers need time | Miss critical feedback |
| Address all PR comments | Quality gate | Merge blocked, trust lost |

### Enforcement Rules

1. Every step is mandatory - not suggestions, not guidelines, requirements
2. Use the specified agents - do not substitute with manual commands
3. Output verification blocks - prove each step completed
4. If you think a step is unnecessary, review the "What Happens If Skipped" column above

### Forbidden Shortcuts

- `git checkout -b` or `git branch` instead of `worktree-manager` agent
- Single CI check instead of monitoring loop
- Rationalizing skips ("it's faster", "not needed this time")
</no-shortcuts-policy>

---

## Workflow Overview

**Phases 1-6 (User Interaction):**
1. Policy Selection
2. Task Discovery
3. Worktree Setup
4. Exploration
5. Planning
6. User Approval

**Phases 7-12 (Autonomous):**
7. Implementation
8. Pre-Review Gates
9. Review Loop
10. Delivery Validation
11. Docs Update
12. /ship

**Human interaction points (ONLY THESE):**
1. Policy selection via checkboxes
2. Task selection from ranked list
3. Plan approval (EnterPlanMode/ExitPlanMode)

<workflow-gates>
## Workflow Gates

Each phase must complete before the next starts:

| Gate | Requirement |
|------|-------------|
| Implementation | Agent completes all plan steps |
| Pre-Review | deslop-agent + test-coverage-checker (parallel) |
| Review Loop | Must approve (no open issues or override) |
| Delivery | Tests pass, build passes |
| Docs | Documentation updated |
| Ship | Explicit /ship invocation (not hook-only) |

**Forbidden actions for agents:**
- No agent may create PRs or push to remote (only /ship)
- No agent may skip Phase 9, delivery-validator, or docs update
</workflow-gates>

## Arguments

Parse from $ARGUMENTS:
- `--status`: Show current workflow state and exit
- `--resume [task/branch/worktree]`: Continue from last checkpoint
- `--abort`: Cancel workflow and cleanup
- `--implement`: Skip to implementation after task selection
- `[filter]`: Task filter (bug, feature, security, test)

### Resume Syntax

```
/next-task --resume                     # Resume active worktree (if only one)
/next-task --resume 123                 # Resume by task ID
/next-task --resume feature/my-task-123 # Resume by branch name
/next-task --resume ../worktrees/my-task-123  # Resume by worktree path
```

## Default Behavior (No Arguments)

1. Goes to Phase 1: Policy Selection
2. Policy selector checks for existing tasks in `{stateDir}/tasks.json`
3. If existing tasks found, **ASKS USER** what to do
4. Then continues with normal policy configuration

The workflow never auto-resumes. It always asks first.

<opencode-constraint>
## OpenCode Label Limit

All AskUserQuestion option labels must be ≤30 characters. Put details in `description`, not `label`.
</opencode-constraint>

## State Management

Uses `lib/state/workflow-state.js` for all state operations:

| File | Location | Purpose |
|------|----------|---------|
| `tasks.json` | Main repo `{stateDir}/` | Active task registry |
| `flow.json` | Worktree `{stateDir}/` | Workflow progress |

Key functions:
- `workflowState.startPhase(phase)` - Begin a phase
- `workflowState.completePhase(result)` - Complete and advance
- `workflowState.updateFlow(updates)` - Partial state updates
- `workflowState.hasActiveTask()` - Check for existing work
- `workflowState.canResume()` - Check if resumable

## Pre-flight: Handle Arguments

*(JavaScript reference - not executable in OpenCode)*

<phase-1>
## Phase 1: Policy Selection

No agent needed. Use AskUserQuestion tool with ALL 3 questions from `lib/sources/policy-questions.js`.

**MANDATORY - Ask ALL 3 Questions:**

| # | Header | Question | Options |
|---|--------|----------|---------|
| 1 | Source | Where should I look for tasks? | GitHub Issues, GitLab Issues, Local tasks.md, Custom, Other (+ cached if exists) |
| 2 | Priority | What type of tasks to prioritize? | All, Bugs, Security, Features |
| 3 | Stop Point | How far should I take this task? | Merged, PR Created, Implemented, Deployed, Production |

**Forbidden Actions:**
- Skipping any of the 3 questions
- Inventing your own questions instead of using the exact ones above
- Proceeding to Phase 2 without all 3 answers

- Use AskUserQuestion tool for user input

</phase-1>

<phase-2>
## Phase 2: Task Discovery

**Agent**: `task-discoverer` (sonnet)

- Phase: task-discovery

</phase-2>

<phase-3>
## Phase 3: Worktree Setup

**Blocking gate** - Cannot proceed to Phase 4 without completing this.

Spawn: `worktree-manager` (haiku)

- Phase: worktree-setup


### Forbidden Actions for Phase 3
- `git checkout -b <branch>` (use worktree-manager agent)
- `git branch <branch>` (use worktree-manager agent)
- Proceeding to Phase 4 without worktree verification output
- Skipping worktree "because branching is faster"
</phase-3>

<phase-4>
## Phase 4: Exploration

**Agent**: `exploration-agent` (opus)

- Phase: exploration

</phase-4>

<phase-5>
## Phase 5: Planning

**Agent**: `planning-agent` (opus)

- Phase: planning

</phase-5>

<phase-6>
## Phase 6: User Approval (Plan Mode)

**Last human interaction point.** Present plan via EnterPlanMode/ExitPlanMode.

```javascript
EnterPlanMode();
// User reviews and approves via ExitPlanMode
workflowState.completePhase({ planApproved: true, plan });
```
</phase-6>

<phase-7>
## Phase 7: Implementation

**Agent**: `implementation-agent` (opus)

- Phase: implementation

</phase-7>

<phase-8>
## Phase 8: Pre-Review Gates

**Agents** (parallel): `deslop-agent` + `test-coverage-checker` (sonnet)

- Invoke `@deslop-agent` agent
- Invoke `@test-coverage-checker` agent
- Phase: pre-review-gates

</phase-8>

<phase-9>
## Phase 9: Review Loop

**Blocking gate** - Must run iterations before delivery validation.

**CRITICAL**: You MUST spawn multiple parallel reviewer agents. Do NOT use a single generic reviewer.

### Step 1: Get Changed Files

```bash
git diff --name-only main...HEAD
```

### Step 2: Detect Signals for Conditional Specialists

Based on changed files, detect which additional specialists are needed:

| Signal | Pattern | Specialist |
|--------|---------|------------|
| hasDb | `/(db\|migrations?\|schema\|prisma\|sql)/i` | database specialist |
| hasApi | `/(api\|routes?\|controllers?\|handlers?)/i` | api designer |
| hasFrontend | `/\.(tsx\|jsx\|vue\|svelte)$/` | frontend specialist |
| hasBackend | `/(server\|backend\|services?\|domain)/i` | backend specialist |
| hasDevops | `/(\.github\/workflows\|Dockerfile\|k8s\|terraform)/i` | devops reviewer |
| needsArchitecture | 20+ changed files | architecture reviewer |

### Step 3: Spawn ALL Reviewer Agents in Parallel

**MANDATORY**: Spawn these 4 core reviewers (ALWAYS) + any conditional specialists detected above.

*(JavaScript reference - not executable in OpenCode)*

### Step 4: Aggregate Findings

Combine all reviewer findings, deduplicate by file+line+description, group by severity.

### Step 5: Fix Issues (severity order: critical -> high -> medium -> low)

For each finding, use Edit tool to apply the suggested fix. Commit after each batch.

### Step 6: Iterate Until Clean (max 5 iterations)

Repeat steps 3-5 until:
- `openCount === 0` (all issues resolved) -> approved
- 3+ iterations with only medium/low issues -> orchestrator may override
- 5 iterations reached -> blocked

### Review Iteration Rules
- MUST run at least 1 full iteration with ALL 4 core reviewers
- Do NOT use a single generic reviewer - spawn all specialists in parallel
- Orchestrator may override after 3+ iterations if only medium/low issues remain
- Do not skip directly to delivery validation
- Do not claim "review passed" without spawning the reviewer agents

### Verification Output (MANDATORY)

After review loop completes, output:
```
[VERIFIED] Review Loop Complete
- Iterations: N
- Core reviewers spawned: code-quality, security, performance, test-coverage
- Conditional specialists: [list any that were added]
- Findings resolved: X critical, Y high, Z medium
- Status: approved | blocked
```
</phase-9>

<phase-10>
## Phase 10: Delivery Validation

**Agent**: `delivery-validator` (sonnet)

- Invoke `@delivery-validator` agent
- Phase: delivery-validation

</phase-10>

<phase-11>
## Phase 11: Docs Update

**Agent**: `sync-docs-agent` (sonnet)

Uses the unified sync-docs agent from the sync-docs plugin with `before-pr` scope.

- Invoke `@sync-docs-agent` agent
- Phase: docs-update

</phase-11>

<phase-12>
## Phase 12: Handoff to /ship

After docs update (sync-docs-agent) completes, invoke /ship explicitly:

*(JavaScript reference - not executable in OpenCode)*

**/ship responsibilities:**
- Create PR, push branch
- Monitor CI and review comments
- Merge when approved
- Cleanup worktree and tasks.json
</phase-12>

## Error Handling

```javascript
try {
  // ... workflow phases ...
} catch (error) {
  workflowState.failPhase(error.message);
  console.log(`Workflow failed. Use --resume to retry or --abort to cancel.`);
}
```

## Success Criteria

- Policy selection via checkboxes
- Two-file state management (tasks.json + flow.json)
- Resume by task ID, branch, or worktree path
- Worktree isolation for parallel workflows
- Opus for complex tasks (explore, plan, implement)
- Sonnet for validation tasks (review, delivery)
- Haiku for simple tasks (worktree)
- Fully autonomous after plan approval
- Explicit /ship handoff for PR workflow

Begin workflow now.
