Execute TRD implementation with strategy awareness, direct specialist delegation, and phase-end quality gates
Executes TRD implementation with strategy-aware specialist delegation and phase quality gates.
/plugin marketplace add FortiumPartners/ensemble/plugin install ensemble-development@ensembleensemble/Usage:
/implement-trdfrom project root withdocs/TRD/directory. Hints: "resume", "strategy=characterization", "from TRD-015"
$ARGUMENTS
Examples: (no args), "resume", "strategy=tdd", "from TRD-015", "report status only"
1. Preflight → Load constitution, select TRD, ensure branch, detect strategy
2. Parse → Extract tasks, build phases, load resume state
3. Execute → For each phase: delegate to specialists, update TRD checkboxes
4. Quality Gate → After phase: run tests, debug failures, check coverage
5. Checkpoint → Save state, commit progress
6. Complete → Final report with next steps
Load docs/standards/constitution.md if present. Extract quality gates (coverage targets, security requirements). If absent, use defaults: 80% unit, 70% integration.
Priority: $ARGUMENTS path → $ARGUMENTS name → in-progress TRD in docs/TRD/ → prompt user.
Validate: Must have "Master Task List" section with - [ ] **TRD-XXX**: Description format.
Ensure on feature/<trd-name> branch. Use git town hack or git switch -c as fallback.
Priority: $ARGUMENTS override → TRD explicit → constitution → auto-detect → default (tdd)
| Strategy | Behavior | Best For |
|---|---|---|
tdd | Tests first, RED-GREEN-REFACTOR | Greenfield |
characterization | Document current behavior AS-IS, no refactoring | Legacy/brownfield |
test-after | Implement then test | Prototypes, UI |
bug-fix | Reproduce → failing test → fix → verify | Regressions |
refactor | Tests pass before AND after | Tech debt |
flexible | No enforcement | Mixed work |
Auto-detection rules (first match wins):
characterizationbug-fixrefactortest-aftertddFormat: "- [ ] **TRD-XXX**: Description"
Extract: id, description, dependencies (if "Depends: TRD-YYY"), parallelizable (if "[P]")
Group by ### Phase N or ### Sprint N headings. If none, all tasks = Phase 1.
Sort by dependencies (topological order).
Check .trd-state/<trd-name>/implement.json:
For each phase, delegate tasks to appropriate specialists.
| Keywords | Specialist |
|---|---|
| backend, api, endpoint, database, server | @backend-developer |
| frontend, ui, component, react, vue, angular, web | @frontend-developer |
| mobile, flutter, react-native, ios, android, app | @mobile-developer |
| test, spec, e2e, playwright | @test-runner or @playwright-tester |
| refactor, optimize | @backend-developer or @frontend-developer |
| docs, readme | @documentation-specialist |
| infra, deploy, docker, k8s, aws, cloud | @infrastructure-developer |
Project agents: If .claude/router-rules.json defines project-specific agents with matching triggers, prefer them over global specialists.
Before executing parallel tasks:
Step 1: Infer file touches for each task
| Source | Method |
|---|---|
| Explicit | Task contains Files: path/to/file.ts → use those paths |
| Keyword | "controller" → **/controllers/**, "model" → **/models/**, "service" → **/services/**, "test" → **/*.test.*, "component" → **/components/** |
| Domain | Backend tasks → src/api/, src/services/; Frontend tasks → src/components/, src/pages/ |
| Query | If ambiguous, ask specialist before execution: "What files will you modify for task {task_id}?" |
Step 2: Detect conflicts
Step 3: Execute
max parallel N from $ARGUMENTS)## Task: {task_id} - {task_description}
### Context
- TRD: {trd_file}
- Strategy: {strategy}
- Constitution: {quality_gates_summary or "defaults: 80% unit, 70% integration"}
- Completed: {completed_task_ids from this phase}
### Objective
{acceptance_criteria extracted from TRD task description}
### Files
{file_paths inferred from task description}
### Skills
Use the Skill tool to invoke the {matched_skill_1} skill.
Use the Skill tool to invoke the {matched_skill_2} skill.
{...for each matched skill from router-rules.json}
Report which skill(s) you used.
### Deliverables
1. Implementation complete per objective
2. Files changed (list paths)
3. Tests passing (yes/no/not applicable)
4. Outcome summary
### Strategy Instructions
{Include strategy-specific guidance based on detected strategy}
| Strategy | Instructions |
|----------|-------------|
| `tdd` | Follow Red-Green-Refactor: (1) Write failing test first, (2) Implement minimal passing code, (3) Refactor while keeping tests green |
| `characterization` | Document current behavior AS-IS: Write tests that capture EXISTING behavior. Do NOT refactor or "fix" the code. Tests should pass immediately. |
| `test-after` | Implement first, then add tests. Focus on coverage over test-first methodology. |
| `bug-fix` | (1) Write failing test that reproduces the bug, (2) Implement the fix, (3) Verify the test passes |
| `refactor` | Ensure all tests pass BEFORE changes. Make incremental changes. Run tests after each change. |
| `flexible` | Use your judgment. No strict methodology enforcement. |
Skill discovery order:
.claude/router-rules.json (if exists)${CLAUDE_PLUGIN_ROOT}/router/lib/router-rules.json (if exists)Matching algorithm:
triggers array, check if any trigger is a substring of the task descriptionpatterns array, test regex against task descriptionFallback when no router-rules.json found:
| Task Keywords | Skill |
|---|---|
| JavaScript, TypeScript, Jest, React test | jest |
| Python, pytest, Django, Flask test | pytest |
| Ruby, RSpec, Rails test | rspec |
| Elixir, ExUnit, Phoenix test | exunit |
| C#, .NET, xUnit test | xunit |
| Playwright, E2E, browser test | writing-playwright-tests |
| No match | Omit Skills section from prompt |
For each completed task:
- [ ] → - [x]<type>(TRD-XXX): <description>After all tasks in a phase complete, execute the quality gate. The gate varies by strategy.
| Strategy | Quality Gate Behavior |
|---|---|
tdd | Run tests. MUST pass. Coverage MUST meet threshold. Block on failure. |
characterization | Run tests. Failures are INFORMATIONAL (documenting current behavior). Do not block. |
test-after | Run tests. Warn if coverage below threshold. Do not block. |
bug-fix | Run tests. Verify the specific bug-fix test passes. Block if regression. |
refactor | Run tests. ALL tests must pass (no regressions). Block on any failure. |
flexible | Run tests. Log results. Do not block. |
Delegate to @test-runner:
Run full test suite for files modified in this phase.
Files: {changed_files_this_phase}
Report:
- Pass/fail status
- Coverage percentages (unit, integration)
- Failure details with file:line references
Use the Skill tool to invoke the jest skill.
Use the Skill tool to invoke the pytest skill.
{...based on detected test framework}
Report which skill(s) you used.
If tests fail AND strategy NOT IN [characterization, test-after, flexible]:
Delegate to @deep-debugger:
Tests failing after phase completion.
Strategy: {strategy}
Error output: {test_failure_details}
Files modified: {changed_files_this_phase}
Analyze root cause. Propose fix. Implement if straightforward.
Max retries: 2
Report: fix applied (yes/no), files changed, recommendation
Retry logic:
Compare against constitution targets (default: 80% unit, 70% integration).
| Strategy | Below Threshold Action |
|---|---|
tdd | BLOCK until coverage improved |
refactor | BLOCK (no regressions allowed) |
bug-fix | WARN, continue |
test-after | WARN, continue |
characterization | SKIP (coverage not the goal) |
flexible | LOG, continue |
Delegate to @code-reviewer:
Quick security review of phase changes.
Files: {changed_files_this_phase}
Focus: hardcoded secrets, injection vulnerabilities, input validation.
Report: issues found (list), severity, recommendations
If quality gate passes:
chore(phase N): checkpoint (tests pass; cov X%)If quality gate fails:
.trd-state/<trd-name>/implement.json{
"trd_file": "docs/TRD/feature.md",
"trd_hash": "<sha256>",
"branch": "feature/feature-name",
"strategy": "tdd",
"phase_cursor": 2,
"tasks": {
"TRD-001": { "status": "success", "commit": "abc1234" },
"TRD-002": { "status": "failed", "error": "Test assertion failed" }
},
"coverage": { "unit": 0.82, "integration": 0.71 },
"checkpoints": [
{ "phase": 1, "commit": "def5678", "timestamp": "..." }
]
}
═══════════════════════════════════════════════════════
TRD Implementation Complete
═══════════════════════════════════════════════════════
TRD: feature-name.md
Branch: feature/feature-name
Strategy: {strategy}
Progress: {N} tasks completed, {M} failed
Quality:
Unit Coverage: {X}% (target: 80%)
Integration Coverage: {Y}% (target: 70%)
Security Scan: {Clean/Issues found}
Next Steps:
1. git diff main...feature/feature-name
2. gh pr create
3. After merge: mv docs/TRD/feature.md docs/TRD/completed/
═══════════════════════════════════════════════════════
| Error | Response |
|---|---|
| No TRD found | List available TRDs, suggest /create-trd |
| Task failure | Report error, attempt debug loop, pause if unresolved |
| Coverage below threshold | Strategy-dependent: block, warn, or continue |
| Tests failing | Run @deep-debugger (max 2 retries), then pause for user |
| Resume hash mismatch | Show TRD diff, ask: invalidate affected tasks or continue? |
| File conflict in parallel | Serialize conflicting tasks automatically |