This commit is contained in:
Shayan Rais
2026-03-02 20:02:59 +05:00
parent db43e42605
commit 13874e6fda
33 changed files with 246 additions and 81 deletions
@@ -0,0 +1,634 @@
---
description: Execute phased implementation with validation gates
argument-hint: "<feature-slug> [--phase N] [--validate-only]"
---
## User Input
```text
$ARGUMENTS
```
You **MUST** parse the user input to extract the feature slug (the folder name in `rpi/`).
## Purpose
This command executes phased implementation of features based on planning documentation. It orchestrates specialized agents, enforces validation gates, and ensures constitutional compliance throughout implementation.
**Prerequisites**:
- Feature folder exists at `rpi/{feature-slug}/`
- Planning completed (`rpi/{feature-slug}/plan/PLAN.md` exists)
**Output Location**: `rpi/{feature-slug}/implement/`
**This is Step 4 of the RPI Workflow** (final step - actual implementation).
## Flags
- `--phase N`: Execute specific phase number (1-8), if omitted starts from phase 1
- `--validate-only`: Only validate current phase, don't implement
- `--skip-validation`: Skip validation gate and proceed (use with caution)
## Available Agents
All agents use **Opus model** for maximum quality.
### Implementation Agent
| Agent | Type | When to Use |
|-------|------|-------------|
| `senior-software-engineer` | Custom | All implementation tasks |
### Support Agents
| Agent | Type | Purpose |
|-------|------|---------|
| `Explore` | Built-in | Pre-implementation code exploration |
| `code-reviewer` | Custom | Code review and quality validation |
| `constitutional-validator` | Custom | Validate against project constitution |
| `documentation-analyst-writer` | Built-in | Documentation generation |
### Agent Routing
All implementation tasks are handled by the `senior-software-engineer` agent.
---
## Phase 0: Load Context and Rules
**Prerequisites**: Feature slug parsed from user input
**Process**:
### 0.1 Load Project Constitution
1. Check for a constitution or principles document in the repository
2. If exists, extract:
- Technical constraints (type safety, testing, component isolation)
- Business principles (quality standards, workflow)
- Architectural boundaries
3. Store constraints for enforcement during implementation
### 0.2 Load Domain-Specific Guidelines
Based on files to be modified, load relevant project guidelines:
- Check for component-specific README files
- Check for coding style guides
- Check for testing requirements documentation
### 0.3 Analyze Implementation Scope
1. Read `rpi/{feature-slug}/plan/PLAN.md`
2. Identify all files to be modified
3. Map files to implementation agent
**Outputs**:
- Constitutional context summary
- Domain rules loaded
- File-to-agent mapping
- Phase execution plan
**Validation**:
- [ ] Constitution loaded (if exists)
- [ ] Domain rules loaded for affected files
- [ ] All files mapped to agents
- [ ] Execution plan understood
---
## Phased Implementation Workflow
### Phase Implementation Loop
For each phase in PLAN.md:
```
┌─────────────────────────────────────────────────────────────────┐
│ Phase N: [Phase Name] │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 1. Code Discovery (Explore Agent) │
│ └─→ Understand existing code before changing it │
│ │
│ 2. Implementation (senior-software-engineer) │
│ └─→ Implement phase deliverables │
│ │
│ 3. Self-Validation │
│ └─→ Engineer validates against phase checklist │
│ │
│ 4. Code Review (code-reviewer Agent) │
│ └─→ Security, correctness, maintainability │
│ │
│ 5. User Validation Gate │
│ └─→ STOP and request user approval │
│ ├─→ PASS: Proceed to next phase │
│ ├─→ CONDITIONAL PASS: Note issues, proceed │
│ └─→ FAIL: Fix issues, re-validate │
│ │
│ 6. Documentation Update │
│ └─→ Update phase status in PLAN.md │
│ │
└─────────────────────────────────────────────────────────────────┘
```
---
## Step 1: Code Discovery (Per Phase)
**Agent**: Explore (Built-in, via Task tool)
**Purpose**: Ground implementation in code reality before making changes.
**Process**:
1. Launch Explore agent via Task tool with `subagent_type="Explore"`
2. Request analysis of files affected by current phase
3. Understand existing patterns, integration points, constraints
**Explore Agent Prompt**:
```
Analyze the codebase to prepare for implementing Phase N of [feature-name].
Files to be modified in this phase:
[List files from PLAN.md]
Investigate and document:
1. **Current Implementation**
- How do these files currently work?
- What patterns are used?
- What functions/classes will be affected?
2. **Integration Points**
- What other files import or use these modules?
- What APIs or interfaces will change?
- What tests cover this code?
3. **Dependencies**
- What libraries are used?
- What internal utilities are available?
- What constraints exist from current code?
4. **Patterns to Follow**
- What coding style is used in these files?
- What naming conventions are followed?
- What error handling patterns exist?
5. **Risks and Considerations**
- What could break if we change this?
- What edge cases exist?
- What backward compatibility concerns?
Provide a discovery summary to inform implementation.
```
**Output**: Discovery summary for implementation agent
---
## Step 2: Implementation (Per Phase)
**Agent**: senior-software-engineer
**Process**:
1. Use senior-software-engineer agent
2. Provide discovery context from Step 1
3. Implement all deliverables for the phase
4. Follow constitutional constraints and project rules
**Implementation Agent Prompt Template**:
```
Acting as the [agent-name] agent, implement Phase N deliverables for [feature-name].
## Context
- Constitutional Constraints: [from Phase 0]
- Domain Rules: [from Phase 0]
- Discovery Summary: [from Step 1]
## Phase N Deliverables
[List from PLAN.md]
## Files to Modify
[List files with specific changes from PLAN.md]
## Implementation Requirements
1. Follow existing code patterns identified in discovery
2. Honor constitutional constraints (type safety, testing, etc.)
3. Follow project-specific rules (if applicable)
4. Write tests for new functionality
5. Include appropriate logging
6. Handle errors gracefully
## Quality Checklist
- [ ] Code follows existing patterns
- [ ] Type annotations present where applicable
- [ ] Tests written and passing
- [ ] No breaking changes to existing functionality
- [ ] Logging added for observability
- [ ] Error handling comprehensive
Implement all deliverables and report what was done.
```
---
## Step 3: Self-Validation
**Agent**: senior-software-engineer (same as Step 2)
**Process**:
1. Agent validates implementation against phase checklist
2. Run linting (use project's configured linter)
3. Run tests relevant to changes
4. Verify build succeeds
**Validation Commands** (adjust to your project):
```bash
# Run linter
[your-linter-command]
# Run tests
[your-test-command]
# Build/compile
[your-build-command]
```
**Self-Validation Checklist**:
- [ ] All deliverables implemented
- [ ] Linting passes
- [ ] Tests pass
- [ ] Build succeeds
- [ ] No regressions in existing tests
- [ ] Constitutional constraints honored
- [ ] Domain rules followed
---
## Step 4: Code Review
**Agent**: code-reviewer (Custom, auto-invoked)
**Process**:
1. Invoke code-reviewer agent to review changes
2. Focus on correctness, security, maintainability
3. Address blockers before proceeding
**Code Review Agent Prompt**:
```
Acting as the code-reviewer agent, review the Phase N implementation for [feature-name].
## Files Changed
[List modified files]
## Changes Made
[Summary of implementation]
## Review Focus
- Correctness & tests
- Security & dependency hygiene
- Architectural boundaries
- Clarity over cleverness
## Constitutional Constraints
[From Phase 0]
Provide review using standard output format.
```
**Review Verdicts**:
- **APPROVED**: Proceed to user validation
- **APPROVED WITH SUGGESTIONS**: Note suggestions, proceed
- **NEEDS REVISION**: Fix issues, re-review
---
## Step 5: User Validation Gate
**CRITICAL**: This step REQUIRES user interaction. DO NOT proceed automatically.
**Process**:
1. Present phase deliverables checklist
2. Show what was implemented (files changed, features added)
3. Present validation criteria from PLAN.md
4. Show code review results
5. **STOP and wait for user decision**
**Validation Request Format**:
```
## Phase N Validation Request
### Deliverables Completed
- [x] [Deliverable 1] - [implementation summary]
- [x] [Deliverable 2] - [implementation summary]
- ...
### Files Changed
| File | Change Type | Lines |
|------|-------------|-------|
| [file] | [add/modify] | [±N] |
### Tests
- [x] Unit tests: PASS
- [x] Integration tests: PASS
- [x] Build: SUCCESS
### Code Review
- Verdict: [APPROVED / APPROVED WITH SUGGESTIONS]
- Issues: [None / List]
### Validation Criteria (from PLAN.md)
- [ ] [Criterion 1]
- [ ] [Criterion 2]
- ...
---
**Please validate Phase N:**
- **PASS**: Phase complete, proceed to Phase N+1
- **CONDITIONAL PASS**: Note issues below, proceed with caution
- **FAIL**: Specify issues to fix before proceeding
```
**User Decisions**:
- **PASS**: Proceed to next phase
- **CONDITIONAL PASS**: Document issues, proceed to next phase
- **FAIL**: Fix issues, re-run Steps 2-5
---
## Step 6: Documentation Update
**Process**:
1. Update `rpi/{feature-slug}/plan/PLAN.md` with phase status
2. Update `rpi/{feature-slug}/implement/IMPLEMENT.md` with validation results
3. Append each phase's validation to IMPLEMENT.md
### Phase Status Tracking
Update checkboxes in PLAN.md:
```markdown
- [ ] Phase N: Not Started
- [~] Phase N: In Progress
- [x] Phase N: Validated (PASS)
- [!] Phase N: Conditional Pass (with notes)
- [-] Phase N: Failed Validation (needs rework)
```
### IMPLEMENT.md Template
```markdown
# Implementation Record
**Feature**: [feature-slug]
**Started**: [Date]
**Status**: [IN_PROGRESS / COMPLETED]
---
## Phase 1: [Phase Name]
**Date**: [Date]
**Verdict**: [PASS / CONDITIONAL PASS / FAIL]
### Deliverables
- [x] [Deliverable 1]
- [x] [Deliverable 2]
### Files Changed
[List with line counts]
### Test Results
[Test output summary]
### Code Review
[Review verdict and notes]
### Notes
[Any additional notes]
---
## Phase 2: [Phase Name]
[Same structure as Phase 1...]
---
## Summary
**Phases Completed**: [N] of [N]
**Final Status**: [COMPLETED / IN_PROGRESS]
```
---
## Error Handling
### Implementation Failures
**If implementation fails**:
1. Document the specific failure
2. Analyze root cause
3. Try alternative approach (max 2 attempts)
4. If still failing, STOP and ask user for guidance
5. Do NOT proceed to next phase with broken implementation
**Message**: "Implementation failed: [error]. Attempted [N] approaches. User guidance needed."
### Test Failures
**If tests fail**:
1. Analyze failure cause (code bug vs test bug)
2. Fix the issue
3. Re-run tests
4. If persistent, document and ask user
5. Do NOT mark phase complete with failing tests
**Message**: "Tests failing: [failures]. Fix attempted but unsuccessful. User review needed."
### Build Failures
**If build fails**:
1. Check for type errors
2. Check for missing imports
3. Check for syntax errors
4. Fix and rebuild
5. If persistent, escalate to user
**Message**: "Build failing: [error]. Unable to resolve automatically."
### Agent Failures
**If agent fails or times out**:
1. Retry once with same inputs
2. If still failing, proceed without that agent's contribution
3. Document gap in validation request
**Message**: "Agent [name] failed. Proceeding without contribution."
---
## Completion Report
On successful completion of all phases:
```markdown
## Implementation Complete
### Feature Summary
- **Feature**: [feature-name]
- **Phases Completed**: [N] of [N]
### Phases Executed
| Phase | Status | Notes |
|-------|--------|-------|
| Phase 1 | PASS | [summary] |
| Phase 2 | PASS | [summary] |
| ... | ... | ... |
### Files Modified
| File | Change Type | Lines |
|------|-------------|-------|
| [file] | [type] | [±N] |
### Tests Added
- [test files]
### Code Review Summary
- Blockers Fixed: [N]
- Suggestions Addressed: [N]
### Constitutional Compliance
- [ ] Type safety maintained
- [ ] Tests written
- [ ] Component isolation respected
- [ ] No breaking changes
### Artifacts Created
- `rpi/{feature-slug}/plan/PLAN.md` (updated with phase status)
- `rpi/{feature-slug}/implement/IMPLEMENT.md` (all phase validations)
### Next Steps
1. Create PR with changes
2. Request final human review
3. Deploy to staging
4. Verify in staging environment
5. Deploy to production
### PR Notes
**Title**: [{feature-slug}] [Brief description]
**Summary**:
[What was implemented]
**Changes**:
- [List key changes]
**Testing**:
- [How tested]
**Rollout**:
- [Deployment steps]
**Rollback**:
- [Rollback procedure if issues]
```
---
## Quality Gates
### Per-Phase Quality Gate
Before marking any phase complete:
- [ ] All deliverables implemented
- [ ] Linting passes
- [ ] Tests pass
- [ ] Build succeeds
- [ ] Code review passed
- [ ] User validation received
- [ ] Documentation updated
### Final Quality Gate
Before marking implementation complete:
- [ ] All phases validated
- [ ] No failing tests
- [ ] Build succeeds in full
- [ ] Constitutional compliance verified
- [ ] Domain rules followed
- [ ] PR notes generated
---
## Notes
### When to Use This Command
- After `/rpi:plan` generates PLAN.md
- When phased implementation with validation gates is needed
- For features requiring structured implementation
### When NOT to Use This Command
- Bug fixes (too heavy, just fix directly)
- Very simple changes (<30 minutes work)
- Exploratory prototyping
- Documentation-only changes
### Best Practices
1. **Review PLAN.md first**: Understand what you're implementing
2. **Trust code discovery**: Let Explore agent inform implementation
3. **Follow existing patterns**: Let code discovery inform implementation
4. **Don't skip validation**: Gates exist to catch issues early
5. **Document as you go**: Update status after each phase
6. **Ask when stuck**: Better to ask than to proceed incorrectly
### Part of RPI Workflow
Step 4 of 4 (Describe → Research → Plan → **Implement**)
---
## Command Examples
### Execute all phases
```bash
/rpi:implement "my-feature"
```
### Execute specific phase
```bash
/rpi:implement "my-feature" --phase 3
```
### Validate only (no implementation)
```bash
/rpi:implement "my-feature" --phase 2 --validate-only
```
---
## Post-Completion Action
**IMPORTANT**: After completing implementation (all phases or significant progress), ALWAYS prompt the user to compact the conversation:
> **Context Management**: This implementation workflow consumed significant context. To preserve progress and free up space, please run:
>
> ```
> /compact
> ```
>
> This will summarize the conversation and preserve implementation status while reducing token usage for future work.
**When to prompt for compact**:
- After all phases are complete
- After completing each major phase (if multi-session implementation)
- If context is running low during implementation
@@ -0,0 +1,416 @@
---
description: Create comprehensive planning documentation for a feature
argument-hint: "<feature-slug>"
---
## User Input
```text
$ARGUMENTS
```
You **MUST** parse the user input to extract the feature slug (the folder name in `rpi/`).
## Purpose
This command creates comprehensive planning documentation for a feature request. It generates detailed specifications, technical design, and implementation plans in the feature's RPI folder.
**Prerequisites**:
- Feature folder exists at `rpi/{feature-slug}/`
- Research completed with GO recommendation (`rpi/{feature-slug}/research/RESEARCH.md` exists)
**Output Location**: All files saved to `rpi/{feature-slug}/plan/`
**This is Step 3 of the RPI Workflow** (after Research approves with GO).
## Outline
1. **Load Context**: Read research report and project constitution (if exists)
2. **Understand Requirements**: Parse feature scope and requirements
3. **Analyze Technical Requirements**: Review architecture and dependencies
4. **Design Architecture**: Create high-level architecture and API contracts
5. **Break Down Implementation**: Create phased task breakdown
6. **Generate Documentation**: Create structured documentation files
7. **Validate Output**: Ensure all quality gates pass
8. **Report Completion**: Provide summary and next steps
## Phases
### Phase 0: Load Context
**Prerequisites**: Feature slug provided
**Process**:
1. **Verify research completed**:
- Check `rpi/{feature-slug}/research/RESEARCH.md` exists
- Verify GO recommendation (warn if NO-GO or CONDITIONAL)
2. **Read research findings**:
- Extract product analysis
- Extract technical discovery
- Extract technical feasibility assessment
- Note risks and constraints
3. **Load project constitution** (if exists):
- Look for a constitution or principles document in the repository
- Extract relevant constraints and preferences
**Outputs**:
- Research summary
- Constitutional context (if found)
- Planning constraints
**Validation**:
- [ ] Research report exists
- [ ] GO recommendation confirmed
- [ ] Constitution loaded (if exists)
---
### Phase 1: Understand Feature Requirements
**Prerequisites**: Phase 0 complete
**Process**:
1. **Parse Feature Description** from research report:
- Extract feature name and primary goal
- Identify target component(s)
- Understand user-facing vs. technical feature
- Determine feature complexity level
2. **Identify Affected Components**:
- Primary component (where feature lives)
- Secondary components (integration points)
- Shared utilities needed
- External dependencies
3. **Research Existing Patterns**:
- Search for similar features in codebase
- Review component architecture and patterns
- Identify reusable code and patterns
**Outputs**:
- Feature scope document (internal)
- Affected components list
- Existing patterns catalog
**Validation**:
- [ ] Feature name and goal clearly defined
- [ ] Target component(s) identified
- [ ] Feature complexity assessed
---
### Phase 2: Analyze Technical Requirements
**Prerequisites**: Phase 1 complete
**Process**:
1. **Review Component Architecture**:
- Read component README and documentation
- Review existing code structure
- Identify architectural patterns used
2. **Identify Technical Dependencies**:
- Internal dependencies (other components, shared utilities)
- External dependencies (APIs, services, libraries)
- Database/storage requirements
- Authentication/authorization needs
3. **Assess Integration Points**:
- APIs that need to be created or modified
- Database schema changes required
- Event/message flows
- Frontend-backend integration
4. **Evaluate Technical Risks**:
- Breaking changes to existing features
- Performance implications
- Security concerns
- Data migration needs
**Outputs**:
- Technical requirements document (internal)
- Dependency map
- Integration point diagram
- Risk assessment
**Validation**:
- [ ] Component architecture understood
- [ ] All dependencies identified
- [ ] Integration points mapped
- [ ] Technical risks assessed
---
### Phase 3: Design Feature Architecture
**Prerequisites**: Phases 1-2 complete
**Agent**: senior-software-engineer
**Process**:
1. **Design High-Level Architecture**:
- Component/module structure
- Data flow diagrams
- API interfaces
- Database schema changes
2. **Define Implementation Approach**:
- File structure and organization
- Code organization patterns
- Testing strategy
- Error handling approach
3. **Plan Database/Storage Changes** (if applicable):
- New collections/tables
- Schema modifications
- Migration strategy
- Data validation rules
4. **Design API Contracts** (if applicable):
- Request/response formats
- Authentication requirements
- Error responses
5. **Plan Testing Strategy**:
- Unit test requirements
- Integration test scenarios
- End-to-end test cases
**Outputs**:
- Architecture design document (internal)
- API specifications
- Database schema design
- Testing strategy
**Validation**:
- [ ] High-level architecture designed
- [ ] Implementation approach defined
- [ ] Database changes planned (if needed)
- [ ] API contracts specified (if needed)
- [ ] Testing strategy complete
---
### Phase 4: Break Down Implementation Tasks
**Prerequisites**: Phases 1-3 complete
**Process**:
1. **Identify Implementation Phases**:
- Break feature into 3-5 logical phases
- Each phase should deliver working, testable functionality
- Phases should build on each other progressively
2. **Create Task Breakdown for Each Phase**:
- List specific implementation tasks
- Estimate complexity (Low/Medium/High)
- Identify task dependencies
- Assign to appropriate code areas
3. **Define Success Criteria**:
- Acceptance criteria for each phase
- Testing requirements
- Documentation requirements
4. **Identify Parallelization Opportunities**:
- Tasks that can be done concurrently
- Frontend/backend parallel work
- Independent module development
**Outputs**:
- Phased implementation plan
- Task breakdown with estimates
- Success criteria per phase
- Dependency chart
**Validation**:
- [ ] Feature broken into 3-5 logical phases
- [ ] Each phase has specific tasks
- [ ] All tasks have complexity estimates
- [ ] Dependencies clearly marked
- [ ] Success criteria defined
---
### Phase 5: Generate Documentation
**Prerequisites**: Phases 1-4 complete
**Agent**: documentation-analyst-writer (via Task tool)
**Process**:
1. **Generate pm.md** (Product Requirements):
- Feature description and user stories
- Constitutional alignment (if applicable)
- Business value and success metrics
- User personas and use cases
- Acceptance criteria
- Out of scope items
2. **Generate ux.md** (User Experience Design):
- User interface mockups (text description)
- User flows and interactions
- Accessibility considerations
- Error states and edge cases
3. **Generate eng.md** (Technical Specification):
- Architecture design
- API specifications
- Database schema changes
- Technology stack
- Technical risks and mitigation
4. **Generate PLAN.md** (Implementation Roadmap):
- Phased implementation breakdown
- Task list with estimates per phase
- Dependencies and ordering
- Success criteria per phase
- Testing requirements
- Validation checkpoints
**Output Files** (all saved to `rpi/{feature-slug}/plan/`):
- `pm.md` - Product requirements
- `ux.md` - UX design
- `eng.md` - Technical specification
- `PLAN.md` - Detailed implementation roadmap
**Validation**:
- [ ] All 4 files present (pm, ux, eng, PLAN)
- [ ] pm.md covers business requirements
- [ ] ux.md addresses user experience
- [ ] eng.md provides technical specification
- [ ] PLAN.md has phased implementation
- [ ] No placeholder text remains
- [ ] Markdown formatting is clean
---
## Sub-Agent Delegation
This command orchestrates specialist agents:
| Phase | Agent | Type | Purpose |
|-------|-------|------|---------|
| Phase 3 | senior-software-engineer | Custom | Architecture design |
| Phase 5 | product-manager | Custom | Product requirements (pm.md) |
| Phase 5 | ux-designer | Custom | User experience (ux.md) |
| Phase 5 | senior-software-engineer | Custom | Technical spec (eng.md) |
| Phase 5 | documentation-analyst-writer | Built-in | Documentation synthesis |
### Agent Invocation
**Custom Agents** (product-manager, senior-software-engineer, ux-designer):
- Claude Code automatically detects these from `.claude/agents/`
- Reference them naturally: "Acting as the senior-software-engineer agent..."
- NO Task tool invocation needed
**Built-in Agent** (documentation-analyst-writer):
- Use Task tool with `subagent_type="documentation-analyst-writer"`
---
## Completion Report
Report the following on successful completion:
### Outputs Created
**Documentation Folder**: `rpi/{feature-slug}/plan/`
Files created:
- **pm.md**: Product requirements and user stories ({Y} stories)
- **ux.md**: User experience design ({Z} flows)
- **eng.md**: Technical specification ({A} APIs, {B} schema changes)
- **PLAN.md**: Detailed roadmap ({C} phases, {D} tasks)
### Feature Summary
- **Feature Name**: {feature-name}
- **Target Component**: {component-name}
- **Complexity**: {Simple/Medium/Complex}
- **Implementation Phases**: {N} phases
- **Total Tasks**: {M} tasks
- **Dependencies**: {Y} internal, {Z} external
### Technical Overview
- **Architecture Pattern**: {pattern-name}
- **APIs Added/Modified**: {N} APIs
- **Database Changes**: {Y} collections/tables
- **Testing Requirements**: {Z} test suites
- **Risk Level**: {Low/Medium/High}
### Implementation Phases
1. **Phase 1**: {phase-name} - {task-count} tasks
2. **Phase 2**: {phase-name} - {task-count} tasks
3. **Phase 3**: {phase-name} - {task-count} tasks
[Continue for all phases...]
---
### Next Steps
1. **Review Documentation**:
- Read planning docs in `rpi/{feature-slug}/plan/`
- Review technical spec in `eng.md`
- Understand implementation phases in `PLAN.md`
2. **Validate with Stakeholders**:
- Product review of pm.md
- UX review of ux.md
- Technical review of eng.md
3. **Begin Implementation**:
- Run `/rpi:implement "{feature-slug}"` to execute phased implementation
- Follow PLAN.md phases
- Complete validation gates at each phase
---
## Error Handling
**If research report doesn't exist**:
- Action: Stop and inform user
- Message: "Research report not found. Run `/rpi:research` first."
**If research recommendation is NO-GO**:
- Action: Warn user but allow proceeding
- Message: "Research recommended NO-GO. Proceed anyway? (y/n)"
**If target component doesn't exist**:
- Action: Confirm with user if this is a new component
- Message: "Component not found. Is this a new component?"
**If documentation agent fails**:
- Action: Generate documentation directly
- Warning: "Documentation may not fully adhere to standards"
---
## Notes
- **Prerequisites**: Research completed with GO recommendation
- **Part of RPI Workflow**: Step 3 of 4 (Describe → Research → Plan → Implement)
**Best Practices**:
1. **Review Research First**: Ensure you understand the viability assessment
2. **Leverage Discovery**: Use technical discovery from research phase
3. **Be Specific**: Detailed plans lead to smoother implementation
4. **Validate Early**: Review docs before implementing
---
## Post-Completion Action
**IMPORTANT**: After completing the planning workflow, ALWAYS prompt the user to compact the conversation:
> **Context Management**: This planning workflow consumed significant context. To free up space for implementation, please run:
>
> ```
> /compact
> ```
>
> This will summarize the conversation and preserve the planning decisions while reducing token usage for the implementation phase.
@@ -0,0 +1,381 @@
---
description: Research and analyze feature viability - GO/NO-GO decision gate
argument-hint: "<feature-slug>"
---
## User Input
```text
$ARGUMENTS
```
You **MUST** parse the user input to extract the feature slug (the folder name in `rpi/`).
**Expected Input Format**: `rpi/{feature-slug}/REQUEST.md`
## Purpose
This command performs comprehensive research and analysis of feature requests **before** the planning phase begins. It acts as a critical GO/NO-GO gate to determine whether a feature idea should proceed to detailed planning.
**Key Objectives**:
- Assess product-market fit and user value
- Evaluate technical feasibility and complexity
- Identify risks and potential blockers
- Determine the right approach (build, buy, partner, or decline)
- Make go/no-go recommendation with clear rationale
**Prerequisites**:
- Feature folder exists at `rpi/{feature-slug}/`
- Feature request file exists at `rpi/{feature-slug}/REQUEST.md`
**Output Location**: `rpi/{feature-slug}/research/RESEARCH.md`
**This is Step 2 of the RPI Workflow** (after initial feature description in Step 1).
## Outline
1. **Load Context**: Read feature description from `rpi/{feature-slug}/` and project constitution (if exists)
2. **Parse Feature Request**: Use requirement-parser agent to extract structured requirements
3. **Execute Multi-Phase Research**:
- Phase 1: Parse Feature Request (requirement-parser agent)
- Phase 2: Product Analysis with Constitution Alignment (product-manager agent)
- Phase 2.5: Technical Discovery (Explore agent) - **CRITICAL: Deep code exploration**
- Phase 3: Technical Feasibility (senior-software-engineer agent)
- Phase 4: Strategic Assessment (technical-cto-advisor agent)
- Phase 5: Generate Research Report (documentation-analyst-writer agent)
4. **Synthesize Recommendation**: Combine all analyses into clear go/no-go recommendation
5. **Validate Output**: Check against quality gates
6. **Report Completion**: Provide recommendation, next steps, and report location
## Phases
### Phase 0: Load Context
**Prerequisites**: Feature slug provided, `rpi/{feature-slug}/REQUEST.md` exists
**Process**:
1. **Read feature description**:
- Read `rpi/{feature-slug}/REQUEST.md` (required)
- Extract feature requirements and goals from REQUEST.md
2. **Check for project constitution** (optional):
- Look for a constitution or principles document in the repository
- Common locations: `constitution.md`, `PRINCIPLES.md`, `.project/constitution.md`
- If found, extract core principles, constraints, and objectives
3. **Create research context**:
- Synthesize into concise summary for agents
- Identify key alignment criteria
**Outputs**:
- Feature description summary
- Constitutional principles (if found)
- Alignment criteria for evaluation
**Validation**:
- [ ] Feature folder exists in `rpi/{feature-slug}/`
- [ ] Feature description extracted
- [ ] Constitution checked and loaded (if exists)
---
### Phase 1: Parse Feature Request
**Prerequisites**: Phase 0 complete
**Agent**: requirement-parser (planning domain)
**Process**:
1. **Launch requirement-parser agent** with feature description
2. **Agent extracts**:
- Feature name and type
- Target component(s)
- Goals and objectives
- Functional and non-functional requirements
- Constraints and assumptions
- Complexity estimate
- Clarifying questions (if any)
3. **Review parsing results**:
- If clarifying questions exist, **STOP and ask user** before proceeding
**Outputs**:
- Structured requirements document
- Feature metadata (name, type, component, complexity)
- Clarifying questions (if any)
---
### Phase 2: Product Analysis with Constitution Alignment
**Prerequisites**: Phase 1 complete, requirements clear
**Agent**: product-manager
**Process**:
1. **Launch product-manager agent** with:
- Parsed requirements from Phase 1
- Constitutional context from Phase 0
2. **Agent analyzes**:
- **User Value**: Who benefits? How much impact?
- **Market Fit**: Does this align with market needs?
- **Product Vision**: Does this fit our product strategy?
- **Constitutional Alignment**: Does this align with project principles?
- **Constraints Check**: Does this violate any constitutional constraints?
3. **Agent provides**:
- Product viability score (High/Medium/Low)
- User value assessment
- Strategic alignment evaluation
- Priority recommendation
- Product concerns or red flags
**Outputs**:
- Product viability assessment
- User value analysis
- Strategic alignment score
- Constitutional alignment summary (if applicable)
---
### Phase 2.5: Technical Discovery (Code Exploration)
**Prerequisites**: Phases 1-2 complete, product viability established
**Agent**: Explore (via Task tool with subagent_type="Explore")
**Purpose**: **CRITICAL PHASE** - Deeply analyze existing codebase BEFORE making technical feasibility assessment.
**Process**:
1. **Launch Explore agent** with target component(s)
2. **Agent investigates**:
- **Existing Implementation**: What code already exists for similar functionality?
- **Integration Points**: What systems/modules would this feature touch?
- **Current Architecture**: How is the current system structured?
- **Data Models**: What database schemas or data structures exist?
- **Dependencies**: What libraries, services are already integrated?
- **Existing Patterns**: What coding patterns and conventions are used?
3. **Agent provides**:
- **Current State Summary**: What exists today
- **Integration Analysis**: Where proposed feature would fit
- **Code Conflicts**: What would break or conflict
- **Leverage Opportunities**: What can be reused vs rebuilt
- **Technical Constraints**: Real constraints from existing code
**Outputs**:
- Current implementation summary
- Integration points map
- Code conflicts identified
- Reusable components identified
- Technical constraints from code
**Critical**: This phase ensures Phase 3 is based on **actual code reality**, not assumptions.
---
### Phase 3: Technical Feasibility Assessment
**Prerequisites**: Phases 1-2.5 complete, code explored
**Agent**: senior-software-engineer
**Process**:
1. **Launch senior-software-engineer agent** with:
- Parsed requirements from Phase 1
- Product context from Phase 2
- **Technical discovery results from Phase 2.5**
2. **Agent analyzes** (informed by Phase 2.5 discoveries):
- **Technical Approach**: What are the implementation options?
- **Complexity**: How difficult is this to build?
- **Dependencies**: What systems/services are needed?
- **Technical Debt**: Will this create or reduce tech debt?
- **Risks**: What are the technical risks?
3. **Agent provides**:
- Technical feasibility score (High/Medium/Low)
- Recommended approach (with alternatives)
- Complexity estimate (Simple/Medium/Complex)
- Technical risks and mitigations
**Outputs**:
- Technical feasibility score
- Recommended implementation approach
- Complexity and effort estimate
- Technical risks and mitigations
---
### Phase 4: Strategic Assessment
**Prerequisites**: Phases 1-3 complete
**Agent**: technical-cto-advisor
**Process**:
1. **Launch technical-cto-advisor agent** with all previous phase outputs
2. **Agent synthesizes**:
- **Overall Assessment**: Combine product + technical perspectives
- **Strategic Alignment**: Does this align with engineering principles AND project constitution?
- **Risk vs. Reward**: Is the value worth the effort and risk?
- **Alternative Options**: Build, buy, partner, defer, or decline?
3. **Agent provides**:
- **Go/No-Go Recommendation**: Clear decision with confidence level
- **Rationale**: Detailed reasoning
- **Recommended Approach**: If "go", what's the best path forward?
- **Conditions**: Any prerequisites for proceeding?
- **Risks**: Key risks if we proceed
**Outputs**:
- Go/No-Go recommendation
- Strategic rationale
- Recommended approach
- Risk summary
---
### Phase 5: Generate Research Report
**Prerequisites**: Phases 1-4 complete
**Agent**: documentation-analyst-writer (via Task tool)
**Process**:
1. **Launch documentation-analyst-writer agent** with all phase outputs
2. **Agent generates report** with sections:
- **Executive Summary**: One-paragraph overview with recommendation
- **Feature Overview**: Name, type, component, goals
- **Requirements Summary**: Key functional and non-functional requirements
- **Product Analysis**: User value, market fit, strategic alignment
- **Technical Discovery**: Current state, integration points, constraints from code
- **Technical Analysis**: Feasibility, approach, complexity, risks
- **Strategic Recommendation**: Go/no-go with detailed rationale
- **Next Steps**: What to do based on recommendation
3. **Agent creates markdown file**: `rpi/{feature-slug}/research/RESEARCH.md`
**Outputs**:
- Complete research report saved to `rpi/{feature-slug}/research/RESEARCH.md`
---
## Sub-Agent Delegation
This command orchestrates 6 specialist agents:
| Phase | Agent | Type | Location |
|-------|-------|------|----------|
| Phase 1 | requirement-parser | Custom | .claude/agents/requirement-parser.md |
| Phase 2 | product-manager | Custom | .claude/agents/product-manager.md |
| Phase 2.5 | Explore | Built-in | Task tool with subagent_type="Explore" |
| Phase 3 | senior-software-engineer | Custom | .claude/agents/senior-software-engineer.md |
| Phase 4 | technical-cto-advisor | Custom | .claude/agents/technical-cto-advisor.md |
| Phase 5 | documentation-analyst-writer | Built-in | Task tool with subagent_type="documentation-analyst-writer" |
---
## Completion Report
Report the following on successful completion:
### Research Recommendation
**Decision**: [GO | NO-GO | CONDITIONAL GO | DEFER]
**Confidence**: [High | Medium | Low]
**Rationale** (1-2 sentences):
[Key reasons for recommendation]
---
### Research Summary
**Feature**: {feature-name}
**Type**: {feature-type}
**Component**: {target-component}
**Complexity**: {Simple | Medium | Complex}
**Scores**:
- Product Viability: [High/Medium/Low]
- Technical Feasibility: [High/Medium/Low]
- Overall Assessment: [High/Medium/Low]
**Key Risks**:
1. {risk-1}
2. {risk-2}
3. {risk-3}
---
### Report Location
**Full Research Report**: `rpi/{feature-slug}/research/RESEARCH.md`
---
### Next Steps
Based on the **[GO/NO-GO]** recommendation:
**If GO**:
1. Review the research report: `rpi/{feature-slug}/research/RESEARCH.md`
2. Proceed to planning: `/rpi:plan "{feature-slug}"`
**If CONDITIONAL GO**:
1. Review conditions in report
2. Address conditions before proceeding
3. Re-run research if needed
**If DEFER**:
1. Review timeline recommendation in report
2. Revisit when timing is appropriate
**If NO-GO**:
1. Review rationale in report
2. Consider alternatives mentioned
3. Archive for future reference
---
## Error Handling
**If REQUEST.md doesn't exist**:
- Action: Stop and inform user
- Message: "Feature request file `rpi/{feature-slug}/REQUEST.md` not found. Create the feature folder and REQUEST.md first (Step 1: Describe in Plan Mode)."
**If feature description is too vague**:
- Action: requirement-parser will identify clarifying questions
- Message: "Need more information. Please answer:"
- Next: Wait for answers, then proceed
**If agents fail or timeout**:
- Action: Retry once
- Next: If retry fails, ask user whether to continue with incomplete research
---
## Notes
- **When to Use**: After Step 1 (Describe) creates the feature folder
- **Critical Gate**: This prevents wasted effort on non-viable features
- **Part of RPI Workflow**: Step 2 of 4 (Describe → Research → Plan → Implement)
---
## Post-Completion Action
**IMPORTANT**: After completing the research workflow, ALWAYS prompt the user to compact the conversation:
> **Context Management**: This research workflow consumed significant context. To free up space for the next steps, please run:
>
> ```
> /compact
> ```
>
> This will summarize the conversation and preserve important findings while reducing token usage for subsequent commands.