Integration of PRPs with agentic engine:

Eploring the posibility of integrating PRPs with agentic engine via an expansion pack.

PRPs-agentic-engine is work created by Wirasm

see: https://github.com/Wirasm/PRPs-agentic-engine

This implementation tries to combine the structured planning and team coordination of BMad-Method with the optimized single-agent execution of PRPs-agentic-eng, creating a powerful hybrid development framework that gives developers the best of both approaches! 🚀
This commit is contained in:
David Manning 2025-08-05 10:25:45 +10:00
parent 5dc4043577
commit d7c18ad64b
14 changed files with 2625 additions and 0 deletions

View File

@ -0,0 +1,447 @@
# BMad-PRP Integration Expansion Pack
## Overview
The BMad-PRP Integration Expansion Pack combines the structured planning and team coordination of BMad-Method with the optimized single-agent execution of PRPs-agentic-eng. This integration provides the best of both approaches: systematic planning with one-pass implementation success.
## Features
### 🔄 **Hybrid Workflow**
- **BMad Planning**: Use PM, Architect, and SM agents for comprehensive planning
- **PRP Execution**: Convert stories to PRP format for optimized implementation
- **Seamless Integration**: Maintain traceability between frameworks
- **Quality Gates**: Comprehensive validation at each phase
### 🤖 **Specialized Agents**
- **PRP Converter**: Transforms BMad stories to PRP format
- **PRP Executor**: Manages PRP execution using PRPs-agentic-eng
- **PRP Validator**: Validates results and maps back to BMad format
- **Hybrid Orchestrator**: Coordinates the complete workflow
### 📋 **Workflow Phases**
1. **Planning Phase (BMad)**: Create PRD, architecture, and detailed stories
2. **PRP Generation**: Convert stories to PRP format with comprehensive context
3. **Execution Phase (PRP)**: Execute PRPs for one-pass implementation
4. **Validation & Integration**: Validate results and integrate back to BMad
## Installation
### Prerequisites
- BMad-Method v4.0+ installed
- Python 3.8+ (for PRP runner)
- PRPs-agentic-eng repository (for PRP runner)
### Install the Expansion Pack
```bash
# Install BMad with PRP integration
npx bmad-method install --expansion-packs bmad-prp-integration
# Or install separately
npx bmad-method install-expansion bmad-prp-integration
```
### Setup PRP Runner
```bash
# Clone PRPs-agentic-eng repository
git clone https://github.com/Wirasm/PRPs-agentic-eng.git
cd PRPs-agentic-eng
# Install Python dependencies
pip install -r requirements.txt
# Copy PRP runner to your project
cp PRPs/scripts/prp_runner.py /path/to/your/project/tools/
```
## Usage
### Basic Workflow
1. **Start with BMad Planning**:
```bash
@pm Create a PRD for user authentication system
@architect Design the system architecture
@sm Create detailed stories for authentication features
```
2. **Convert Stories to PRPs**:
```bash
@prp-converter Convert story 1.1 to PRP format
```
3. **Execute PRPs**:
```bash
@prp-executor Execute PRP for user authentication
```
4. **Validate Results**:
```bash
@prp-validator Validate execution results
@qa Review implementation quality
```
### Advanced Workflow
#### Hybrid Orchestration
```bash
@hybrid-orchestrator Run complete hybrid workflow
```
#### Parallel Execution
```bash
@hybrid-orchestrator Run parallel workflow mode
```
#### Adaptive Execution
```bash
@hybrid-orchestrator Run adaptive workflow mode
```
### Command Reference
#### PRP Converter Commands
- `@prp-converter convert-story <story-id>` - Convert story to PRP
- `@prp-converter validate-prp <prp-file>` - Validate PRP format
- `@prp-converter enhance-context <prp-file>` - Enhance PRP context
#### PRP Executor Commands
- `@prp-executor execute <prp-file>` - Execute PRP
- `@prp-executor execute-interactive <prp-file>` - Interactive execution
- `@prp-executor execute-headless <prp-file>` - Headless execution
- `@prp-executor validate-environment` - Validate execution environment
#### PRP Validator Commands
- `@prp-validator validate-results <execution-results>` - Validate results
- `@prp-validator map-to-story <results>` - Map results to BMad format
- `@prp-validator quality-assessment <results>` - Quality assessment
#### Hybrid Orchestrator Commands
- `@hybrid-orchestrator run-workflow <mode>` - Run complete workflow
- `@hybrid-orchestrator status` - Check workflow status
- `@hybrid-orchestrator pause` - Pause workflow
- `@hybrid-orchestrator resume` - Resume workflow
## Configuration
### Core Configuration
Add to your `core-config.yaml`:
```yaml
prp:
enabled: true
runner-path: ./tools/prp_runner.py
templates-path: ./PRPs/templates
output-dir: ./PRPs
validation:
auto-validate: true
quality-gates: true
context-completeness: true
execution:
default-mode: interactive
timeout: 300000
verbose: false
```
### Environment Setup
```bash
# Set up PRP environment
export PRP_RUNNER_PATH=./tools/prp_runner.py
export PRP_OUTPUT_DIR=./PRPs
export PRP_TEMPLATES_DIR=./PRPs/templates
```
## Workflow Modes
### Sequential Mode
- Execute phases in sequence
- Validation gates between phases
- Suitable for complex projects
### Parallel Mode
- Execute compatible phases in parallel
- Dependency management
- Faster execution for simple projects
### Adaptive Mode
- Dynamic workflow adjustment
- Context-aware decision making
- Intelligent error recovery
## Quality Gates
### Planning Quality Gate
- [ ] PRD complete and validated
- [ ] Architecture designed and documented
- [ ] Stories created with acceptance criteria
- [ ] All requirements captured
### PRP Quality Gate
- [ ] PRP format valid
- [ ] Context complete and comprehensive
- [ ] Validation loops executable
- [ ] Traceability maintained
### Execution Quality Gate
- [ ] Execution successful
- [ ] Code quality acceptable
- [ ] Tests passing
- [ ] Requirements met
### Validation Quality Gate
- [ ] Acceptance criteria met
- [ ] Integration tests passing
- [ ] Quality standards met
- [ ] Documentation complete
## Error Handling
### Common Issues
#### PRP Runner Not Found
```bash
# Check if PRP runner is installed
ls tools/prp_runner.py
# Install PRP runner
cp /path/to/PRPs-agentic-eng/PRPs/scripts/prp_runner.py tools/
```
#### Python Environment Issues
```bash
# Check Python version
python --version
# Install dependencies
pip install -r requirements.txt
```
#### Context Completeness Issues
```bash
# Enhance PRP context
@prp-converter enhance-context <prp-file>
# Add missing documentation
@prp-converter add-documentation <prp-file> <doc-path>
```
### Recovery Procedures
#### Execution Failures
1. Check execution environment
2. Validate PRP format and context
3. Debug execution issues
4. Fall back to BMad development workflow if needed
#### Validation Failures
1. Address quality issues
2. Fix failing tests
3. Resolve integration problems
4. Re-run validation phase
## Testing
### Run Tests
```bash
# Run unit tests
npm test -- expansion-packs/bmad-prp-integration/tests/unit/
# Run integration tests
npm test -- expansion-packs/bmad-prp-integration/tests/integration/
# Run end-to-end tests
npm test -- expansion-packs/bmad-prp-integration/tests/e2e/
```
### Test Coverage
```bash
# Generate coverage report
npm run test:coverage -- expansion-packs/bmad-prp-integration/
```
## Examples
### Simple Feature Implementation
1. **Create Story**:
```markdown
Story 1.1: User Login
As a user, I want to login with email and password, so that I can access the application.
Acceptance Criteria:
- User can enter email and password
- System validates credentials
- User receives JWT token on success
- Error message shown for invalid credentials
```
2. **Convert to PRP**:
```bash
@prp-converter convert-story 1.1
```
3. **Execute PRP**:
```bash
@prp-executor execute PRPs/1.1.user-login.md
```
4. **Validate Results**:
```bash
@prp-validator validate-results
```
### Complex System Implementation
1. **Planning Phase**:
```bash
@pm Create PRD for e-commerce platform
@architect Design microservices architecture
@sm Create stories for all features
```
2. **PRP Generation**:
```bash
@prp-converter convert-all-stories
```
3. **Parallel Execution**:
```bash
@hybrid-orchestrator run-workflow parallel
```
4. **Integration Validation**:
```bash
@prp-validator validate-integration
@qa review-complete-system
```
## Best Practices
### PRP Creation
1. **Start with BMad Story**: Use BMad story as foundation
2. **Enhance Context**: Add comprehensive context and examples
3. **Validate Completeness**: Ensure context completeness check passes
4. **Test Validation Loops**: Verify validation loops are executable
5. **Maintain Traceability**: Keep links to original BMad story
### PRP Execution
1. **Environment Setup**: Ensure proper execution environment
2. **Context Validation**: Verify all context is available
3. **Progressive Validation**: Run validation loops progressively
4. **Error Handling**: Handle errors and provide recovery options
5. **Result Collection**: Collect and validate execution results
### Result Integration
1. **Quality Validation**: Validate results against BMad standards
2. **Context Mapping**: Map results back to BMad story format
3. **Documentation Update**: Update story with execution results
4. **Workflow Continuation**: Prepare for next BMad workflow phase
## Troubleshooting
### Debug Mode
```bash
# Enable debug logging
export PRP_DEBUG=true
export BMAD_DEBUG=true
# Run with verbose output
@prp-executor execute --verbose <prp-file>
```
### Log Files
- PRP execution logs: `logs/prp-execution.log`
- BMad workflow logs: `logs/bmad-workflow.log`
- Integration logs: `logs/integration.log`
### Common Solutions
#### Context Issues
- Add missing documentation to PRP
- Enhance code examples and patterns
- Include known gotchas and constraints
#### Execution Issues
- Check Python environment and dependencies
- Validate PRP runner installation
- Verify file permissions and paths
#### Integration Issues
- Check BMad configuration
- Validate story format compatibility
- Ensure traceability is maintained
## Contributing
### Development Setup
```bash
# Clone the repository
git clone https://github.com/bmadcode/bmad-method.git
cd bmad-method
# Install dependencies
npm install
# Set up development environment
npm run setup:dev
```
### Running Tests
```bash
# Run all tests
npm test
# Run specific test suite
npm test -- expansion-packs/bmad-prp-integration/
# Run with coverage
npm run test:coverage
```
### Code Style
```bash
# Format code
npm run format
# Lint code
npm run lint
# Fix linting issues
npm run lint:fix
```
## Support
### Documentation
- [BMad-Method User Guide](../bmad-core/user-guide.md)
- [PRPs-agentic-eng Documentation](https://github.com/Wirasm/PRPs-agentic-eng)
- [Integration Examples](./examples/)
### Community
- [Discord Community](https://discord.gg/gk8jAdXWmj)
- [GitHub Issues](https://github.com/bmadcode/bmad-method/issues)
- [GitHub Discussions](https://github.com/bmadcode/bmad-method/discussions)
### Getting Help
1. Check the documentation and examples
2. Search existing issues and discussions
3. Ask questions in the Discord community
4. Create a new issue with detailed information
## License
This expansion pack is licensed under the MIT License. See the [LICENSE](../../LICENSE) file for details.
## Acknowledgments
- **BMad-Method Team**: For the core framework and support
- **PRPs-agentic-eng Team**: For the PRP methodology and runner
- **Community Contributors**: For feedback and improvements
---
**Happy coding with BMad-PRP Integration! 🚀**

View File

@ -0,0 +1,139 @@
# Hybrid Orchestrator Agent
## Role
Hybrid Orchestrator Agent
## Persona
A master coordinator agent that orchestrates the complete hybrid workflow combining BMad-Method's structured planning with PRPs-agentic-eng's optimized execution. This agent manages the entire process from story creation through PRP execution to final validation, ensuring seamless integration between the two frameworks.
## Dependencies
```yaml
dependencies:
templates:
- hybrid-workflow-tmpl.yaml
- orchestration-result-tmpl.yaml
tasks:
- hybrid-workflow.md
- orchestrate-execution.md
- coordinate-validation.md
data:
- integration-guidelines.md
- workflow-standards.md
- orchestration-patterns.md
```
## Startup Instructions
Load the integration guidelines and workflow standards. Prepare to orchestrate the complete hybrid workflow, coordinating between BMad planning agents and PRP execution agents while maintaining workflow integrity and ensuring successful project delivery.
## Capabilities
### Workflow Orchestration
- Coordinate the complete hybrid development workflow
- Manage transitions between BMad and PRP phases
- Ensure workflow integrity and consistency
- Handle workflow exceptions and recovery
### Agent Coordination
- Coordinate between BMad agents (PM, Architect, SM, Dev, QA)
- Manage PRP agents (Converter, Executor, Validator)
- Facilitate communication and data flow between agents
- Maintain context and state across agent interactions
### Process Management
- Manage workflow phases and transitions
- Track progress and completion status
- Handle dependencies and sequencing
- Ensure quality gates and validation checkpoints
### Integration Management
- Maintain consistency between frameworks
- Handle data transformation and mapping
- Manage configuration and environment setup
- Ensure seamless user experience
## Key Responsibilities
1. **Workflow Orchestration**: Coordinate the complete hybrid workflow
2. **Agent Management**: Manage and coordinate all participating agents
3. **Process Control**: Control workflow phases and transitions
4. **Integration Coordination**: Ensure seamless framework integration
5. **Quality Assurance**: Maintain workflow quality and consistency
## Working Style
- Strategic and systematic approach
- Strong coordination and communication skills
- Proactive problem-solving and issue resolution
- Quality-focused and results-oriented
- Integration-aware and context-sensitive
## Success Criteria
- Complete workflow executes successfully
- All agents coordinate effectively
- Integration points work seamlessly
- Quality gates and validations pass
- User experience is smooth and intuitive
## Workflow Phases
### Phase 1: Planning (BMad)
- PM creates PRD and requirements
- Architect designs system architecture
- SM creates detailed stories
- Quality validation of planning artifacts
### Phase 2: PRP Generation
- PRP Converter transforms stories to PRP format
- Context mapping and validation
- PRP format verification and optimization
### Phase 3: Execution (PRP)
- PRP Executor runs implementation
- Real-time progress monitoring
- Error handling and recovery
- Result collection and validation
### Phase 4: Validation & Integration
- PRP Validator assesses results
- Quality assurance and compliance checking
- Result mapping back to BMad format
- Story completion and documentation
## Orchestration Patterns
### Sequential Orchestration
- Linear workflow execution
- Phase-by-phase progression
- Clear handoffs between phases
- Comprehensive validation at each step
### Parallel Orchestration
- Concurrent execution where possible
- Dependency management
- Resource coordination
- Synchronization points
### Adaptive Orchestration
- Dynamic workflow adjustment
- Context-aware decision making
- Flexible phase transitions
- Intelligent error recovery
## Integration Points
### BMad Integration
- Story creation and management
- Architecture and planning artifacts
- Quality validation and checklists
- Workflow state management
### PRP Integration
- PRP generation and execution
- Context mapping and preservation
- Result validation and processing
- Framework compatibility
### User Integration
- Seamless user experience
- Clear progress reporting
- Intuitive workflow control
- Comprehensive documentation

View File

@ -0,0 +1,69 @@
# PRP Converter Agent
## Role
PRP Converter Agent
## Persona
A specialized agent responsible for converting BMad-Method stories into PRPs-agentic-eng format. This agent ensures that all story requirements, context, and technical details are accurately preserved while adapting to the PRP methodology's structure and validation requirements.
## Dependencies
```yaml
dependencies:
templates:
- story-to-prp-tmpl.yaml
- prp-to-story-tmpl.yaml
tasks:
- convert-story-to-prp.md
- validate-prp-format.md
data:
- prp-methodology.md
- integration-guidelines.md
- validation-standards.md
```
## Startup Instructions
Load the PRP methodology documentation and integration guidelines to understand the conversion requirements and validation standards. Be ready to convert BMad stories to PRP format while maintaining all technical context and requirements.
## Capabilities
### Story Analysis
- Parse BMad story format and extract all components
- Identify story requirements, acceptance criteria, and technical context
- Map story elements to PRP structure
### PRP Generation
- Convert story content to PRP format following PRPs-agentic-eng methodology
- Preserve all technical context and implementation details
- Ensure context completeness for one-pass implementation success
### Validation
- Validate generated PRPs against PRP methodology standards
- Check for context completeness and information density
- Ensure validation loops are properly defined
### Context Mapping
- Map BMad architecture context to PRP context format
- Maintain consistency between frameworks
- Handle version compatibility and format differences
## Key Responsibilities
1. **Story Parsing**: Extract all relevant information from BMad stories
2. **Format Conversion**: Transform story content to PRP format
3. **Context Preservation**: Ensure all technical context is maintained
4. **Validation**: Verify PRP completeness and correctness
5. **Documentation**: Generate clear, actionable PRPs
## Working Style
- Methodical and thorough in analysis
- Focus on context preservation and completeness
- Validation-driven approach
- Clear communication of conversion decisions
- Error handling and edge case management
## Success Criteria
- All story requirements accurately converted to PRP format
- Technical context preserved and enhanced
- Validation loops properly defined
- PRP passes context completeness check
- Conversion maintains traceability to original story

View File

@ -0,0 +1,92 @@
# PRP Executor Agent
## Role
PRP Executor Agent
## Persona
A specialized agent responsible for executing PRPs using the PRPs-agentic-eng framework. This agent manages the execution environment, handles the PRP runner integration, and ensures successful implementation of features through optimized single-agent execution.
## Dependencies
```yaml
dependencies:
templates:
- prp-execution-tmpl.yaml
- execution-result-tmpl.yaml
tasks:
- execute-prp.md
- validate-execution.md
- handle-execution-errors.md
data:
- prp-methodology.md
- integration-guidelines.md
- execution-standards.md
```
## Startup Instructions
Load the PRP execution methodology and integration guidelines. Prepare to execute PRPs using the PRPs-agentic-eng runner while maintaining execution context and handling any errors or issues that arise during implementation.
## Capabilities
### PRP Execution
- Execute PRPs using PRPs-agentic-eng runner
- Manage execution environment and context
- Handle different execution modes (interactive, headless, streaming)
### Environment Management
- Set up proper execution environment
- Configure PRP runner with correct parameters
- Manage file paths and project structure
### Result Collection
- Collect execution results and artifacts
- Parse and validate execution output
- Handle success and error scenarios
### Error Handling
- Detect and handle execution errors
- Provide meaningful error messages
- Implement retry and recovery mechanisms
### Integration Management
- Coordinate with BMad workflow
- Maintain execution state and context
- Handle communication between frameworks
## Key Responsibilities
1. **PRP Execution**: Run PRPs using PRPs-agentic-eng framework
2. **Environment Setup**: Configure execution environment properly
3. **Result Processing**: Collect and validate execution results
4. **Error Management**: Handle errors and provide recovery options
5. **Integration**: Coordinate with BMad workflow and other agents
## Working Style
- Execution-focused and results-oriented
- Robust error handling and recovery
- Clear communication of execution status
- Methodical approach to problem-solving
- Integration-aware and context-sensitive
## Success Criteria
- PRPs execute successfully with minimal errors
- Execution results are properly collected and validated
- Integration with BMad workflow is seamless
- Error handling is robust and informative
- Performance meets or exceeds expectations
## Execution Modes
### Interactive Mode
- Real-time execution with user interaction
- Immediate feedback and course correction
- Suitable for development and debugging
### Headless Mode
- Automated execution without user interaction
- Suitable for CI/CD and batch processing
- Structured output for programmatic handling
### Streaming Mode
- Real-time progress monitoring
- Continuous feedback and status updates
- Suitable for long-running executions

View File

@ -0,0 +1,103 @@
# PRP Validator Agent
## Role
PRP Validator Agent
## Persona
A specialized agent responsible for validating PRP execution results and mapping them back to BMad-Method story format. This agent ensures quality assurance, validates implementation against requirements, and maintains consistency between the two frameworks.
## Dependencies
```yaml
dependencies:
templates:
- validation-result-tmpl.yaml
- prp-to-story-tmpl.yaml
tasks:
- validate-prp-result.md
- map-result-to-story.md
- quality-assurance.md
data:
- validation-standards.md
- integration-guidelines.md
- quality-metrics.md
```
## Startup Instructions
Load the validation standards and integration guidelines. Prepare to validate PRP execution results, ensure quality compliance, and map results back to BMad story format while maintaining traceability and consistency.
## Capabilities
### Result Validation
- Validate PRP execution results against requirements
- Check code quality and compliance with standards
- Verify test coverage and functionality
- Assess performance and security considerations
### Quality Assurance
- Run automated quality checks
- Validate against coding standards
- Check for security vulnerabilities
- Assess maintainability and readability
### Result Mapping
- Map PRP execution results back to BMad story format
- Maintain traceability between frameworks
- Update story status and completion notes
- Preserve implementation context and decisions
### Integration Validation
- Ensure consistency between frameworks
- Validate workflow integration points
- Check for data integrity and completeness
- Verify cross-framework compatibility
## Key Responsibilities
1. **Result Validation**: Validate PRP execution results comprehensively
2. **Quality Assurance**: Ensure code quality and compliance
3. **Result Mapping**: Map results back to BMad story format
4. **Integration Validation**: Maintain consistency between frameworks
5. **Documentation**: Update story documentation with results
## Working Style
- Quality-focused and detail-oriented
- Systematic validation approach
- Clear reporting and documentation
- Integration-aware and context-sensitive
- Proactive issue identification and resolution
## Success Criteria
- All validation checks pass successfully
- Code quality meets or exceeds standards
- Results are accurately mapped to BMad format
- Integration consistency is maintained
- Documentation is complete and accurate
## Validation Categories
### Functional Validation
- Requirements compliance
- Feature functionality
- User acceptance criteria
- Integration testing
### Quality Validation
- Code quality standards
- Performance benchmarks
- Security compliance
- Maintainability assessment
### Integration Validation
- Framework consistency
- Data integrity
- Workflow compatibility
- Cross-framework traceability
## Validation Workflow
1. **Result Analysis**: Analyze PRP execution results
2. **Quality Assessment**: Run quality checks and validations
3. **Compliance Verification**: Verify against standards and requirements
4. **Result Mapping**: Map validated results to BMad format
5. **Documentation Update**: Update story documentation
6. **Integration Check**: Verify cross-framework consistency

View File

@ -0,0 +1,27 @@
name: bmad-prp-integration
version: 1.0.0
short-title: BMad-PRP Integration Pack
description: >-
Integration expansion pack that combines BMad-Method's structured planning
and team coordination with PRPs-agentic-eng's optimized single-agent execution.
Enables hybrid workflows for enhanced development productivity.
author: Brian (BMad) & Community
slashPrefix: bmadprp
dependencies:
core:
- pm
- architect
- sm
- dev
- qa
templates:
- story-tmpl.yaml
- prd-tmpl.yaml
- architecture-tmpl.yaml
tasks:
- create-next-story.md
- shard-doc.md
- validate-next-story.md
data:
- bmad-kb.md
- technical-preferences.md

View File

@ -0,0 +1,199 @@
# PRP Methodology for BMad Integration
## Overview
This document outlines the PRP (Product Requirement Prompt) methodology as implemented in PRPs-agentic-eng and how it integrates with BMad-Method's structured planning approach.
## PRP Core Principles
### 1. Context is King
- **Comprehensive Context**: Every PRP must contain ALL necessary documentation, examples, and caveats
- **Information Density**: Use keywords and patterns from the codebase
- **Context Completeness**: "If someone knew nothing about this codebase, would they have everything needed to implement this successfully?"
### 2. Validation Loops
- **Executable Validation**: Provide executable tests/lints the AI can run and fix
- **Progressive Success**: Start simple, validate, then enhance
- **Quality Gates**: Multiple validation levels (syntax → tests → integration)
### 3. One-Pass Implementation
- **Complete Context**: All implementation details included in PRP
- **Clear Requirements**: Specific, measurable success criteria
- **Actionable Tasks**: Detailed implementation blueprint with dependencies
## PRP Structure
### Goal Section
```
**Feature Goal**: [Specific, measurable end state]
**Deliverable**: [Concrete artifact - API endpoint, service class, etc.]
**Success Definition**: [How you'll know this is complete and working]
```
### Why Section
- Business value and user impact
- Integration with existing features
- Problems this solves and for whom
### What Section
- User-visible behavior and technical requirements
- Success criteria with specific measurable outcomes
### All Needed Context Section
```
### Context Completeness Check
_Before writing this PRP, validate: "If someone knew nothing about this codebase, would they have everything needed to implement this successfully?"_
### Documentation & References
- url: [Complete URL with section anchor]
why: [Specific methods/concepts needed for implementation]
critical: [Key insights that prevent common implementation errors]
- file: [exact/path/to/pattern/file.py]
why: [Specific pattern to follow - class structure, error handling, etc.]
pattern: [Brief description of what pattern to extract]
gotcha: [Known constraints or limitations to avoid]
### Known Gotchas
# CRITICAL: [Library name] requires [specific setup]
# Example: FastAPI requires async functions for endpoints
```
### Implementation Blueprint Section
```
### Data models and structure
Create the core data models, we ensure type safety and consistency.
### Implementation Tasks (ordered by dependencies)
Task 1: CREATE src/models/{domain}_models.py
Task 2: IMPLEMENT src/services/{domain}_service.py
Task 3: ADD src/api/{domain}_endpoints.py
```
### Validation Loop Section
```
### Level 1: Syntax & Style
ruff check src/ --fix
mypy src/
### Level 2: Unit Tests
uv run pytest tests/test_{domain}.py -v
### Level 3: Integration Test
curl -X POST http://localhost:8000/{domain}/create \
-H "Content-Type: application/json" \
-d '{"field": "value"}'
```
## Integration with BMad-Method
### Story to PRP Conversion
#### Mapping BMad Story Components
- **Story Statement** → **Goal Section**
- **Acceptance Criteria** → **Success Criteria**
- **Dev Notes** → **All Needed Context**
- **Tasks/Subtasks** → **Implementation Blueprint**
- **Testing Requirements** → **Validation Loop**
#### Context Preservation
- **Architecture Documents**: Map BMad architecture context to PRP format
- **Technical Constraints**: Preserve all technical constraints and gotchas
- **Implementation Patterns**: Maintain existing code patterns and conventions
- **Testing Standards**: Convert BMad testing requirements to PRP validation
### PRP to Story Conversion
#### Mapping PRP Results to BMad
- **Implementation Results** → **Dev Agent Record**
- **Validation Results** → **QA Review**
- **Generated Artifacts** → **Story Completion Notes**
- **Performance Metrics** → **Story Validation Results**
#### Quality Assurance
- **Code Quality**: Validate against BMad coding standards
- **Test Coverage**: Ensure test coverage meets BMad requirements
- **Integration Testing**: Verify integration with existing BMad workflow
- **Documentation**: Update BMad story documentation with results
## Best Practices
### PRP Creation
1. **Start with BMad Story**: Use BMad story as foundation
2. **Enhance Context**: Add comprehensive context and examples
3. **Validate Completeness**: Ensure context completeness check passes
4. **Test Validation Loops**: Verify validation loops are executable
5. **Maintain Traceability**: Keep links to original BMad story
### PRP Execution
1. **Environment Setup**: Ensure proper execution environment
2. **Context Validation**: Verify all context is available
3. **Progressive Validation**: Run validation loops progressively
4. **Error Handling**: Handle errors and provide recovery options
5. **Result Collection**: Collect and validate execution results
### Result Integration
1. **Quality Validation**: Validate results against BMad standards
2. **Context Mapping**: Map results back to BMad story format
3. **Documentation Update**: Update story with execution results
4. **Workflow Continuation**: Prepare for next BMad workflow phase
## Validation Standards
### Context Completeness
- [ ] All necessary documentation included
- [ ] Code examples and patterns provided
- [ ] Technical constraints documented
- [ ] Validation loops executable
- [ ] Information density sufficient
### Implementation Quality
- [ ] Code follows project patterns
- [ ] Tests cover all requirements
- [ ] Performance meets standards
- [ ] Security requirements met
- [ ] Documentation complete
### Integration Consistency
- [ ] BMad story requirements preserved
- [ ] Architecture context maintained
- [ ] Testing standards followed
- [ ] Quality gates passed
- [ ] Traceability maintained
## Error Handling
### Context Issues
- **Missing Documentation**: Request additional documentation
- **Incomplete Context**: Enhance context with examples
- **Outdated Information**: Update context with current information
### Execution Issues
- **Environment Problems**: Fix execution environment
- **Dependency Issues**: Resolve missing dependencies
- **Validation Failures**: Address validation issues
### Integration Issues
- **Format Mismatches**: Handle format conversion issues
- **Context Loss**: Preserve context during conversion
- **Quality Issues**: Address quality and compliance issues
## Success Metrics
### Conversion Quality
- **Context Preservation**: 95%+ context preserved during conversion
- **Format Compliance**: 100% PRP format compliance
- **Validation Completeness**: All validation loops executable
- **Traceability**: Full traceability between frameworks
### Execution Success
- **Success Rate**: 90%+ successful PRP executions
- **Quality Compliance**: 95%+ quality standards met
- **Performance**: <10% overhead on execution time
- **Error Recovery**: 80%+ error recovery success rate
### Integration Effectiveness
- **Workflow Continuity**: Seamless workflow integration
- **Quality Maintenance**: Maintained quality standards
- **User Experience**: Improved development experience
- **Productivity**: Increased development productivity

View File

@ -0,0 +1,188 @@
# Convert Story to PRP Task
## Purpose
To convert a BMad-Method story into PRPs-agentic-eng format while preserving all requirements, context, and technical details. This task ensures that the PRP contains everything needed for one-pass implementation success through comprehensive context engineering.
## SEQUENTIAL Task Execution (Do not proceed until current Task is complete)
### 0. Load Configuration and Validate Input
- Load `{root}/core-config.yaml` from the project root
- Validate that the story file exists and is in correct BMad format
- Check that PRP output directory exists (`PRPs/`)
- Verify that all required templates and data files are available
### 1. Parse BMad Story Content
#### 1.1 Extract Story Components
- **Story Information**: Extract story ID, title, status, and basic metadata
- **Story Statement**: Parse the "As a... I want... so that..." format
- **Acceptance Criteria**: Extract numbered acceptance criteria list
- **Tasks/Subtasks**: Parse the task breakdown and dependencies
- **Dev Notes**: Extract technical context, architecture references, and implementation details
- **Testing Requirements**: Extract testing standards and validation requirements
#### 1.2 Validate Story Completeness
- Ensure all required story components are present
- Verify that technical context is sufficient for implementation
- Check that acceptance criteria are clear and measurable
- Validate that tasks are properly structured and sequenced
### 2. Map BMad Context to PRP Context
#### 2.1 Architecture Context Mapping
- **If `architectureVersion: >= v4` and `architectureSharded: true`**:
- Read relevant architecture documents based on story type
- Map architecture sections to PRP context format
- **Else**: Use monolithic architecture file for context extraction
#### 2.2 Context Completeness Assessment
- **Documentation & References**: Map architecture documents to PRP format
- Include relevant URLs, file paths, and documentation references
- Add code examples and implementation patterns
- Include known gotchas and technical constraints
- **Current Codebase Context**: Extract relevant project structure
- File paths and naming conventions
- Existing patterns and conventions
- Technical stack and dependencies
- **Technical Constraints**: Identify and document
- Version requirements and compatibility
- Performance considerations
- Security requirements
- Integration constraints
### 3. Generate PRP Structure
#### 3.1 Goal Section
- **Feature Goal**: Extract specific, measurable end state from story
- **Deliverable**: Define concrete artifact (API endpoint, service class, etc.)
- **Success Definition**: How to know the feature is complete and working
#### 3.2 Why Section
- Extract business value and user impact from story
- Identify integration with existing features
- Document problems this solves and for whom
#### 3.3 What Section
- Convert story description to user-visible behavior
- Transform acceptance criteria to success criteria
- Maintain all technical requirements and constraints
#### 3.4 All Needed Context Section
- **Context Completeness Check**: Validate that PRP contains everything needed
- **Documentation & References**: Include all relevant documentation and examples
- **Current Codebase Context**: Provide project structure and patterns
- **Known Gotchas**: Document technical constraints and limitations
#### 3.5 Implementation Blueprint Section
- **Data Models**: Extract data model requirements from story
- **Implementation Tasks**: Convert BMad tasks to PRP format
- Maintain task dependencies and sequencing
- Include technical implementation details
#### 3.6 Validation Loop Section
- **Level 1: Syntax & Style**: Code quality and style checks
- **Level 2: Unit Tests**: Unit test requirements and coverage
- **Level 3: Integration Test**: Integration testing requirements
### 4. Validate Generated PRP
#### 4.1 Context Completeness Validation
- **Critical Check**: "If someone knew nothing about this codebase, would they have everything needed to implement this successfully?"
- Verify all necessary documentation is included
- Ensure code examples and patterns are provided
- Check that technical constraints are documented
#### 4.2 Information Density Validation
- Verify PRP uses keywords and patterns from the codebase
- Ensure context is information-dense and actionable
- Check that validation loops are executable
#### 4.3 Progressive Success Validation
- Verify implementation tasks are properly sequenced
- Ensure validation gates are progressive (syntax → tests → integration)
- Check that success criteria are clear and measurable
### 5. Generate PRP File
#### 5.1 File Creation
- Create PRP file: `PRPs/{story_id}.{story_title_short}.md`
- Use PRP template structure and formatting
- Include all mapped content and context
#### 5.2 Metadata and Traceability
- Add metadata linking back to original BMad story
- Include conversion timestamp and version information
- Maintain traceability between frameworks
### 6. Final Validation and Documentation
#### 6.1 PRP Quality Check
- Verify PRP follows PRPs-agentic-eng methodology
- Check that all sections are complete and accurate
- Validate that context is comprehensive and actionable
#### 6.2 Documentation Update
- Update story with PRP conversion status
- Document any conversion decisions or adaptations
- Maintain audit trail of conversion process
## Success Criteria
- [ ] BMad story successfully converted to PRP format
- [ ] All story requirements preserved and enhanced
- [ ] Technical context comprehensively mapped
- [ ] PRP passes context completeness check
- [ ] Validation loops are executable and comprehensive
- [ ] Traceability maintained between frameworks
- [ ] PRP file created and properly formatted
## Error Handling
### Story Parsing Errors
- **Missing Components**: Alert user and request missing information
- **Invalid Format**: Provide guidance on correct BMad story format
- **Incomplete Context**: Request additional technical context
### Context Mapping Errors
- **Missing Architecture**: Alert user to missing architecture documents
- **Incomplete Context**: Request additional context or documentation
- **Version Conflicts**: Handle version compatibility issues
### PRP Generation Errors
- **Template Errors**: Validate template structure and content
- **Format Issues**: Ensure PRP follows correct format
- **Validation Failures**: Address validation issues before completion
## Output
The task produces a complete PRP file in `PRPs/{story_id}.{story_title_short}.md` that contains:
1. **Goal**: Clear feature goal and success definition
2. **Why**: Business value and user impact
3. **What**: User-visible behavior and technical requirements
4. **All Needed Context**: Comprehensive context for implementation
5. **Implementation Blueprint**: Detailed implementation plan
6. **Validation Loop**: Executable validation and testing
The PRP is ready for execution using the PRPs-agentic-eng framework while maintaining full traceability to the original BMad story.

View File

@ -0,0 +1,189 @@
# Execute PRP Task
## Purpose
To execute a PRP using the PRPs-agentic-eng framework, managing the execution environment, handling the PRP runner integration, and ensuring successful implementation of features through optimized single-agent execution.
## SEQUENTIAL Task Execution (Do not proceed until current Task is complete)
### 0. Load Configuration and Validate Input
- Load `{root}/core-config.yaml` from the project root
- Validate that the PRP file exists and is in correct format
- Check that PRP runner is available and properly configured
- Verify execution environment and dependencies
### 1. Prepare Execution Environment
#### 1.1 PRP Runner Setup
- **Locate PRP Runner**: Find PRP runner executable (`prp_runner.py`)
- **Validate Runner**: Check runner version and compatibility
- **Configure Environment**: Set up Python environment and dependencies
- **Verify Permissions**: Ensure runner has necessary file access
#### 1.2 Project Context Setup
- **Working Directory**: Set up proper working directory for execution
- **File Paths**: Configure relative and absolute paths
- **Environment Variables**: Set required environment variables
- **Dependencies**: Verify project dependencies are available
#### 1.3 PRP Validation
- **Format Validation**: Verify PRP follows correct format
- **Context Completeness**: Check that PRP contains all necessary context
- **Validation Loops**: Verify validation loops are executable
- **Dependencies**: Check for any missing dependencies or context
### 2. Configure Execution Parameters
#### 2.1 Execution Mode Selection
- **Interactive Mode**: Real-time execution with user interaction
- Suitable for development and debugging
- Immediate feedback and course correction
- User can intervene during execution
- **Headless Mode**: Automated execution without user interaction
- Suitable for CI/CD and batch processing
- Structured output for programmatic handling
- No user intervention required
- **Streaming Mode**: Real-time progress monitoring
- Continuous feedback and status updates
- Suitable for long-running executions
- Progress tracking and monitoring
#### 2.2 Output Configuration
- **Output Format**: Configure output format (text, json, stream-json)
- **Logging Level**: Set appropriate logging verbosity
- **Error Handling**: Configure error handling and recovery
- **Progress Reporting**: Set up progress tracking and reporting
### 3. Execute PRP
#### 3.1 PRP Runner Execution
- **Command Construction**: Build PRP runner command with parameters
- **Execution Launch**: Launch PRP runner with configured parameters
- **Process Management**: Monitor execution process and status
- **Output Capture**: Capture and process execution output
#### 3.2 Real-time Monitoring
- **Progress Tracking**: Monitor execution progress in real-time
- **Status Updates**: Provide regular status updates to user
- **Error Detection**: Detect and handle execution errors
- **Resource Monitoring**: Monitor resource usage and performance
#### 3.3 Interactive Support
- **User Interaction**: Handle user input and interaction (if interactive mode)
- **Decision Points**: Present decision points to user when needed
- **Error Recovery**: Provide error recovery options to user
- **Progress Reporting**: Keep user informed of execution progress
### 4. Handle Execution Results
#### 4.1 Result Collection
- **Output Processing**: Process and parse execution output
- **Artifact Collection**: Collect generated artifacts and files
- **Log Collection**: Gather execution logs and debugging information
- **Status Information**: Collect execution status and completion information
#### 4.2 Success Validation
- **Completion Check**: Verify execution completed successfully
- **Output Validation**: Validate generated output and artifacts
- **Quality Check**: Assess quality of generated code and implementation
- **Requirement Verification**: Verify all requirements were met
#### 4.3 Error Handling
- **Error Analysis**: Analyze any execution errors or failures
- **Error Classification**: Classify errors by type and severity
- **Recovery Options**: Provide recovery options and suggestions
- **Error Reporting**: Report errors with context and debugging information
### 5. Process Execution Output
#### 5.1 Output Parsing
- **Structured Output**: Parse structured output (JSON, etc.)
- **Text Output**: Process text output and logs
- **Artifact Analysis**: Analyze generated artifacts and files
- **Metadata Extraction**: Extract execution metadata and statistics
#### 5.2 Result Validation
- **Code Quality**: Assess quality of generated code
- **Test Results**: Validate test execution results
- **Performance Metrics**: Analyze performance and resource usage
- **Security Assessment**: Check for security issues or vulnerabilities
#### 5.3 Documentation Generation
- **Execution Summary**: Generate execution summary report
- **Artifact Documentation**: Document generated artifacts and files
- **Performance Report**: Create performance and resource usage report
- **Issue Report**: Document any issues or concerns
### 6. Integration with BMad Workflow
#### 6.1 Result Mapping
- **BMad Format**: Map execution results to BMad story format
- **Status Update**: Update story status based on execution results
- **Completion Notes**: Document execution results and completion notes
- **Traceability**: Maintain traceability between PRP and story
#### 6.2 Workflow Continuation
- **Next Steps**: Determine next steps in BMad workflow
- **Validation**: Prepare for validation phase
- **Documentation**: Update story documentation with results
- **Handoff**: Prepare for handoff to next phase
## Success Criteria
- [ ] PRP executed successfully using PRPs-agentic-eng framework
- [ ] All execution parameters properly configured
- [ ] Execution environment set up correctly
- [ ] Real-time monitoring and progress tracking active
- [ ] Execution results collected and processed
- [ ] Output validated against requirements
- [ ] Results mapped to BMad story format
- [ ] Integration with BMad workflow maintained
## Error Handling
### Environment Setup Errors
- **Missing Dependencies**: Install or configure missing dependencies
- **Permission Issues**: Resolve file and directory permissions
- **Configuration Errors**: Fix configuration and setup issues
### Execution Errors
- **Runner Errors**: Handle PRP runner errors and failures
- **Process Errors**: Manage execution process errors
- **Resource Errors**: Handle resource and performance issues
### Result Processing Errors
- **Output Parsing Errors**: Handle output parsing and processing errors
- **Validation Errors**: Address validation and quality issues
- **Integration Errors**: Resolve integration and mapping issues
## Output
The task produces execution results including:
1. **Execution Status**: Success/failure status and completion information
2. **Generated Artifacts**: Code files, tests, and other generated artifacts
3. **Execution Logs**: Detailed logs and debugging information
4. **Performance Metrics**: Resource usage and performance statistics
5. **Quality Assessment**: Code quality and validation results
6. **Integration Data**: Data mapped to BMad story format
The results are ready for validation and integration with the BMad workflow.

View File

@ -0,0 +1,150 @@
template:
id: prp-to-story-template-v1
name: PRP Result to Story Conversion Template
version: 1.0
output:
format: markdown
filename: docs/stories/{{story_id}}.{{story_title_short}}.story.md
title: "Story {{story_id}}: {{story_title}}"
workflow:
mode: interactive
elicitation: advanced-elicitation
agent_config:
editable_sections:
- Status
- Dev Agent Record
- Implementation Results
- Validation Results
- Change Log
sections:
- id: status
title: Status
type: choice
choices: [Done, Review, InProgress, Approved, Draft]
instruction: |
Update story status based on PRP execution results:
- Done: PRP executed successfully, all validations passed
- Review: PRP executed but requires review
- InProgress: PRP execution in progress
- Approved: Ready for PRP execution
- Draft: Story being prepared
owner: prp-validator
editors: [prp-validator, sm]
- id: dev-record
title: Dev Agent Record
type: structured-text
instruction: |
Document the PRP execution results and implementation details:
### Implementation Summary
- Brief summary of what was implemented
- Key technical decisions made
- Any deviations from original plan
### Code Changes
- Files created or modified
- Key implementation patterns used
- Technical architecture decisions
### Challenges & Solutions
- Any challenges encountered during implementation
- Solutions implemented
- Lessons learned for future stories
template: |
### Implementation Summary
{{implementation_summary}}
### Code Changes
{{code_changes}}
### Challenges & Solutions
{{challenges_solutions}}
elicit: true
owner: prp-validator
editors: [prp-validator, dev]
- id: implementation-results
title: Implementation Results
type: structured-text
instruction: |
Document the specific implementation results from PRP execution:
### Completed Tasks
- List all completed tasks from PRP implementation
- Include task completion status and details
### Acceptance Criteria Status
- Map each acceptance criterion to implementation status
- Include validation results for each criterion
### Technical Artifacts
- Generated code files and locations
- Test files and coverage information
- Documentation created or updated
template: |
### Completed Tasks
{{completed_tasks}}
### Acceptance Criteria Status
{{acceptance_criteria_status}}
### Technical Artifacts
{{technical_artifacts}}
elicit: true
owner: prp-validator
editors: [prp-validator]
- id: validation-results
title: Validation Results
type: structured-text
instruction: |
Document validation results from PRP execution:
### Quality Validation
- Code quality check results
- Linting and formatting validation
- Security scan results
### Test Results
- Unit test execution results
- Test coverage information
- Integration test results
### Performance Validation
- Performance benchmark results
- Memory usage analysis
- Response time measurements
template: |
### Quality Validation
{{quality_validation}}
### Test Results
{{test_results}}
### Performance Validation
{{performance_validation}}
elicit: true
owner: prp-validator
editors: [prp-validator, qa]
- id: change-log
title: Change Log
type: table
columns: [Date, Version, Description, Author]
instruction: |
Track changes made during PRP execution and story completion:
- Implementation changes and decisions
- Validation results and updates
- Status changes and approvals
template: |
| Date | Version | Description | Author |
|------|---------|-------------|--------|
| {{current_date}} | {{version}} | PRP execution completed | PRP Validator |
| {{current_date}} | {{version}} | Validation results documented | PRP Validator |
| {{current_date}} | {{version}} | Story status updated to Done | PRP Validator |
owner: prp-validator
editors: [prp-validator, sm, qa]

View File

@ -0,0 +1,157 @@
template:
id: story-to-prp-template-v1
name: Story to PRP Conversion Template
version: 1.0
output:
format: markdown
filename: PRPs/{{story_id}}.{{story_title_short}}.md
title: "PRP: {{story_title}}"
workflow:
mode: interactive
elicitation: advanced-elicitation
agent_config:
editable_sections:
- Goal
- Why
- What
- All Needed Context
- Implementation Blueprint
- Validation Loop
sections:
- id: goal
title: Goal
type: template-text
template: |
**Feature Goal**: {{story_goal}}
**Deliverable**: {{deliverable}}
**Success Definition**: {{success_definition}}
instruction: |
Convert the BMad story goal into PRP goal format. Extract the specific, measurable end state
and concrete deliverables from the story requirements.
elicit: true
owner: prp-converter
editors: [prp-converter]
- id: why
title: Why
type: bullet-list
instruction: |
Extract the business value, user impact, and justification from the story. Include:
- Business value and user impact
- Integration with existing features
- Problems this solves and for whom
template: |
- [Business value and user impact from story]
- [Integration with existing features]
- [Problems this solves and for whom]
elicit: true
owner: prp-converter
editors: [prp-converter]
- id: what
title: What
type: template-text
template: |
{{story_description}}
### Success Criteria
{{acceptance_criteria}}
instruction: |
Convert the story description and acceptance criteria into PRP "What" section.
Maintain all user-visible behavior and technical requirements.
elicit: true
owner: prp-converter
editors: [prp-converter]
- id: context
title: All Needed Context
type: structured-text
instruction: |
Map BMad architecture context to PRP context format. Include:
### Context Completeness Check
_Before writing this PRP, validate: "If someone knew nothing about this codebase, would they have everything needed to implement this successfully?"_
### Documentation & References
- Map architecture documents to PRP context format
- Include relevant code examples and patterns
- Add known gotchas and technical constraints
### Current Codebase Context
- Extract relevant file paths and structures
- Include existing patterns and conventions
- Map technical stack and dependencies
template: |
### Context Completeness Check
_Before writing this PRP, validate: "If someone knew nothing about this codebase, would they have everything needed to implement this successfully?"_
### Documentation & References
{{architecture_context}}
### Current Codebase Context
{{codebase_context}}
### Known Gotchas
{{technical_constraints}}
elicit: true
owner: prp-converter
editors: [prp-converter]
- id: implementation
title: Implementation Blueprint
type: structured-text
instruction: |
Convert BMad tasks and subtasks into PRP implementation blueprint. Include:
### Data models and structure
- Extract data model requirements from story
- Include schema and validation requirements
### Implementation Tasks (ordered by dependencies)
- Convert BMad tasks to PRP implementation tasks
- Maintain task dependencies and sequencing
- Include technical implementation details
template: |
### Data models and structure
{{data_models}}
### Implementation Tasks (ordered by dependencies)
{{implementation_tasks}}
elicit: true
owner: prp-converter
editors: [prp-converter]
- id: validation
title: Validation Loop
type: structured-text
instruction: |
Convert BMad testing requirements into PRP validation loop. Include:
### Level 1: Syntax & Style
- Code quality and style checks
- Linting and formatting validation
### Level 2: Unit Tests
- Unit test requirements and coverage
- Test framework and patterns
### Level 3: Integration Test
- Integration testing requirements
- End-to-end validation
template: |
### Level 1: Syntax & Style
{{syntax_validation}}
### Level 2: Unit Tests
{{unit_test_validation}}
### Level 3: Integration Test
{{integration_validation}}
elicit: true
owner: prp-converter
editors: [prp-converter]

View File

@ -0,0 +1,221 @@
const { describe, it, expect, beforeEach } = require('@jest/globals');
const path = require('path');
const fs = require('fs').promises;
// Mock the PRP runner adapter
jest.mock('../../tools/prp-runner-adapter');
describe('Story to PRP Converter', () => {
let converter;
let mockStory;
let mockArchitecture;
beforeEach(() => {
// Reset mocks
jest.clearAllMocks();
// Mock story content
mockStory = {
id: '1.1',
title: 'User Authentication',
status: 'Draft',
story: 'As a user, I want to authenticate with email and password, so that I can access protected resources',
acceptanceCriteria: [
'User can login with valid email and password',
'User receives JWT token upon successful login',
'Invalid credentials return appropriate error message'
],
tasks: [
'Create authentication service',
'Implement login endpoint',
'Add JWT token generation',
'Write unit tests'
],
devNotes: {
technicalContext: 'Use JWT tokens for authentication',
architecture: 'Follow REST API patterns',
testing: 'Use pytest for unit tests'
}
};
// Mock architecture content
mockArchitecture = {
techStack: 'Python, FastAPI, SQLAlchemy',
patterns: 'REST API, JWT authentication',
testing: 'pytest, coverage > 80%'
};
});
describe('Story Parsing', () => {
it('should parse BMad story format correctly', async () => {
// Test story parsing functionality
const parsedStory = await converter.parseStory(mockStory);
expect(parsedStory).toBeDefined();
expect(parsedStory.goal).toBeDefined();
expect(parsedStory.acceptanceCriteria).toHaveLength(3);
expect(parsedStory.tasks).toHaveLength(4);
});
it('should extract story components accurately', async () => {
const components = await converter.extractComponents(mockStory);
expect(components.storyStatement).toContain('As a user');
expect(components.acceptanceCriteria).toContain('User can login');
expect(components.tasks).toContain('Create authentication service');
});
it('should validate story completeness', async () => {
const validation = await converter.validateStory(mockStory);
expect(validation.isComplete).toBe(true);
expect(validation.missingComponents).toHaveLength(0);
});
});
describe('Context Mapping', () => {
it('should map BMad architecture to PRP context', async () => {
const context = await converter.mapContext(mockStory, mockArchitecture);
expect(context.documentation).toBeDefined();
expect(context.codebaseContext).toBeDefined();
expect(context.technicalConstraints).toBeDefined();
});
it('should preserve technical context during mapping', async () => {
const context = await converter.mapContext(mockStory, mockArchitecture);
expect(context.technicalConstraints).toContain('JWT');
expect(context.codebaseContext).toContain('FastAPI');
});
it('should handle missing architecture gracefully', async () => {
const context = await converter.mapContext(mockStory, null);
expect(context.documentation).toBeDefined();
expect(context.warnings).toContain('No architecture context available');
});
});
describe('PRP Generation', () => {
it('should generate valid PRP format', async () => {
const prp = await converter.generatePRP(mockStory, mockArchitecture);
expect(prp).toContain('## Goal');
expect(prp).toContain('## Why');
expect(prp).toContain('## What');
expect(prp).toContain('## All Needed Context');
expect(prp).toContain('## Implementation Blueprint');
expect(prp).toContain('## Validation Loop');
});
it('should include all story requirements in PRP', async () => {
const prp = await converter.generatePRP(mockStory, mockArchitecture);
expect(prp).toContain('User can login with valid email and password');
expect(prp).toContain('Create authentication service');
expect(prp).toContain('JWT tokens');
});
it('should create executable validation loops', async () => {
const prp = await converter.generatePRP(mockStory, mockArchitecture);
expect(prp).toContain('### Level 1: Syntax & Style');
expect(prp).toContain('### Level 2: Unit Tests');
expect(prp).toContain('### Level 3: Integration Test');
});
});
describe('Validation', () => {
it('should validate PRP context completeness', async () => {
const prp = await converter.generatePRP(mockStory, mockArchitecture);
const validation = await converter.validatePRP(prp);
expect(validation.contextComplete).toBe(true);
expect(validation.validationLoopsExecutable).toBe(true);
});
it('should detect missing context', async () => {
const incompleteStory = { ...mockStory, devNotes: {} };
const prp = await converter.generatePRP(incompleteStory, mockArchitecture);
const validation = await converter.validatePRP(prp);
expect(validation.contextComplete).toBe(false);
expect(validation.missingContext).toBeDefined();
});
it('should validate information density', async () => {
const prp = await converter.generatePRP(mockStory, mockArchitecture);
const validation = await converter.validatePRP(prp);
expect(validation.informationDensity).toBeGreaterThan(0.7);
});
});
describe('File Operations', () => {
it('should create PRP file with correct naming', async () => {
const prp = await converter.generatePRP(mockStory, mockArchitecture);
const filePath = await converter.savePRP(prp, mockStory);
expect(filePath).toContain('PRPs/1.1.user-authentication.md');
});
it('should maintain traceability to original story', async () => {
const prp = await converter.generatePRP(mockStory, mockArchitecture);
await converter.savePRP(prp, mockStory);
const savedPRP = await fs.readFile('PRPs/1.1.user-authentication.md', 'utf8');
expect(savedPRP).toContain('Original Story: 1.1');
expect(savedPRP).toContain('Conversion Date:');
});
});
describe('Error Handling', () => {
it('should handle invalid story format', async () => {
const invalidStory = { id: '1.1' }; // Missing required fields
await expect(converter.generatePRP(invalidStory, mockArchitecture))
.rejects.toThrow('Invalid story format');
});
it('should handle missing dependencies', async () => {
// Mock missing dependencies
jest.spyOn(fs, 'access').mockRejectedValue(new Error('File not found'));
await expect(converter.validateEnvironment())
.rejects.toThrow('Missing required dependencies');
});
it('should provide helpful error messages', async () => {
try {
await converter.generatePRP(null, mockArchitecture);
} catch (error) {
expect(error.message).toContain('Story is required');
}
});
});
describe('Integration', () => {
it('should integrate with BMad workflow', async () => {
const result = await converter.convertStoryToPRP(mockStory, mockArchitecture);
expect(result.success).toBe(true);
expect(result.prpPath).toBeDefined();
expect(result.traceability).toBeDefined();
});
it('should maintain BMad story format compatibility', async () => {
const result = await converter.convertStoryToPRP(mockStory, mockArchitecture);
expect(result.bmadCompatible).toBe(true);
expect(result.storyId).toBe('1.1');
});
it('should support workflow continuation', async () => {
const result = await converter.convertStoryToPRP(mockStory, mockArchitecture);
expect(result.nextSteps).toBeDefined();
expect(result.workflowState).toBe('ready_for_execution');
});
});
});

View File

@ -0,0 +1,404 @@
#!/usr/bin/env node
/**
* PRP Runner Adapter for BMad-Method Integration
*
* This tool provides integration between BMad-Method and PRPs-agentic-eng
* by managing PRP execution, result collection, and integration with BMad workflow.
*/
const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs').promises;
const yaml = require('js-yaml');
class PRPRunnerAdapter {
constructor(config = {}) {
this.config = {
runnerPath: config.runnerPath || 'tools/prp_runner.py',
outputDir: config.outputDir || 'PRPs',
workingDir: config.workingDir || process.cwd(),
...config
};
}
/**
* Execute a PRP using the PRPs-agentic-eng runner
* @param {string} prpPath - Path to the PRP file
* @param {Object} options - Execution options
* @returns {Promise<Object>} Execution results
*/
async executePRP(prpPath, options = {}) {
const {
mode = 'interactive',
outputFormat = 'text',
verbose = false,
timeout = 300000 // 5 minutes default
} = options;
try {
// Validate PRP file exists
await this.validatePRPFile(prpPath);
// Build runner command
const command = this.buildRunnerCommand(prpPath, {
mode,
outputFormat,
verbose
});
// Execute PRP
const result = await this.runPRPCommand(command, { timeout });
// Process results
return await this.processResults(result, prpPath);
} catch (error) {
throw new Error(`PRP execution failed: ${error.message}`);
}
}
/**
* Validate PRP file exists and is properly formatted
* @param {string} prpPath - Path to PRP file
*/
async validatePRPFile(prpPath) {
try {
const stats = await fs.stat(prpPath);
if (!stats.isFile()) {
throw new Error(`PRP path is not a file: ${prpPath}`);
}
// Basic format validation
const content = await fs.readFile(prpPath, 'utf8');
if (!content.includes('## Goal') || !content.includes('## What')) {
throw new Error(`PRP file does not appear to be in correct format: ${prpPath}`);
}
} catch (error) {
if (error.code === 'ENOENT') {
throw new Error(`PRP file not found: ${prpPath}`);
}
throw error;
}
}
/**
* Build PRP runner command with parameters
* @param {string} prpPath - Path to PRP file
* @param {Object} options - Command options
* @returns {Array} Command array for spawn
*/
buildRunnerCommand(prpPath, options) {
const { mode, outputFormat, verbose } = options;
const args = [
this.config.runnerPath,
'--prp-path', prpPath
];
// Add mode-specific arguments
if (mode === 'interactive') {
args.push('--interactive');
} else if (mode === 'headless') {
args.push('--output-format', outputFormat);
} else if (mode === 'streaming') {
args.push('--output-format', 'stream-json');
}
// Add verbose flag if requested
if (verbose) {
args.push('--verbose');
}
return ['python', args];
}
/**
* Execute PRP runner command
* @param {Array} command - Command array
* @param {Object} options - Execution options
* @returns {Promise<Object>} Execution result
*/
runPRPCommand(command, options = {}) {
return new Promise((resolve, reject) => {
const [executable, args] = command;
const { timeout } = options;
const child = spawn(executable, args, {
cwd: this.config.workingDir,
stdio: ['pipe', 'pipe', 'pipe'],
env: { ...process.env }
});
let stdout = '';
let stderr = '';
let exitCode = null;
// Set timeout
const timeoutId = timeout ? setTimeout(() => {
child.kill('SIGTERM');
reject(new Error(`PRP execution timed out after ${timeout}ms`));
}, timeout) : null;
// Handle stdout
child.stdout.on('data', (data) => {
stdout += data.toString();
});
// Handle stderr
child.stderr.on('data', (data) => {
stderr += data.toString();
});
// Handle process completion
child.on('close', (code) => {
exitCode = code;
if (timeoutId) {
clearTimeout(timeoutId);
}
if (code === 0) {
resolve({
success: true,
stdout,
stderr,
exitCode
});
} else {
reject(new Error(`PRP execution failed with exit code ${code}: ${stderr}`));
}
});
// Handle process errors
child.on('error', (error) => {
if (timeoutId) {
clearTimeout(timeoutId);
}
reject(new Error(`PRP execution error: ${error.message}`));
});
});
}
/**
* Process PRP execution results
* @param {Object} result - Raw execution result
* @param {string} prpPath - Original PRP file path
* @returns {Object} Processed results
*/
async processResults(result, prpPath) {
const { stdout, stderr, exitCode } = result;
// Parse output based on format
let parsedOutput;
try {
if (stdout.includes('{') && stdout.includes('}')) {
// Try to parse as JSON
const jsonMatch = stdout.match(/\{[\s\S]*\}/);
if (jsonMatch) {
parsedOutput = JSON.parse(jsonMatch[0]);
}
}
} catch (error) {
// Fall back to text parsing
parsedOutput = this.parseTextOutput(stdout);
}
// Collect generated artifacts
const artifacts = await this.collectArtifacts(prpPath);
return {
success: true,
exitCode,
output: parsedOutput || stdout,
stderr,
artifacts,
metadata: {
prpPath,
executionTime: new Date().toISOString(),
runnerVersion: await this.getRunnerVersion()
}
};
}
/**
* Parse text output from PRP execution
* @param {string} output - Raw output text
* @returns {Object} Parsed output
*/
parseTextOutput(output) {
const lines = output.split('\n');
const result = {
files: [],
tests: [],
errors: [],
warnings: []
};
for (const line of lines) {
if (line.includes('Created:') || line.includes('Modified:')) {
const fileMatch = line.match(/(?:Created|Modified):\s*(.+)/);
if (fileMatch) {
result.files.push(fileMatch[1].trim());
}
} else if (line.includes('test') && line.includes('passed')) {
result.tests.push(line.trim());
} else if (line.includes('ERROR:') || line.includes('FAILED:')) {
result.errors.push(line.trim());
} else if (line.includes('WARNING:') || line.includes('Warning:')) {
result.warnings.push(line.trim());
}
}
return result;
}
/**
* Collect artifacts generated during PRP execution
* @param {string} prpPath - Original PRP file path
* @returns {Array} List of generated artifacts
*/
async collectArtifacts(prpPath) {
const artifacts = [];
const prpDir = path.dirname(prpPath);
const workingDir = this.config.workingDir;
try {
// Look for common artifact patterns
const patterns = [
'src/**/*.py',
'src/**/*.js',
'src/**/*.ts',
'tests/**/*.py',
'tests/**/*.js',
'tests/**/*.ts',
'*.md',
'*.json',
'*.yaml',
'*.yml'
];
for (const pattern of patterns) {
try {
const files = await this.findFiles(path.join(workingDir, pattern));
artifacts.push(...files);
} catch (error) {
// Pattern not found, continue
}
}
// Remove duplicates and filter by modification time
const uniqueArtifacts = [...new Set(artifacts)];
const recentArtifacts = await this.filterRecentFiles(uniqueArtifacts, prpPath);
return recentArtifacts;
} catch (error) {
console.warn(`Warning: Could not collect artifacts: ${error.message}`);
return [];
}
}
/**
* Find files matching a pattern
* @param {string} pattern - File pattern
* @returns {Array} Matching files
*/
async findFiles(pattern) {
const { glob } = require('glob');
return await glob(pattern, { cwd: this.config.workingDir });
}
/**
* Filter files modified after PRP file
* @param {Array} files - List of files
* @param {string} prpPath - PRP file path
* @returns {Array} Recently modified files
*/
async filterRecentFiles(files, prpPath) {
try {
const prpStats = await fs.stat(prpPath);
const recentFiles = [];
for (const file of files) {
try {
const fileStats = await fs.stat(path.join(this.config.workingDir, file));
if (fileStats.mtime > prpStats.mtime) {
recentFiles.push(file);
}
} catch (error) {
// File not accessible, skip
}
}
return recentFiles;
} catch (error) {
console.warn(`Warning: Could not filter recent files: ${error.message}`);
return files;
}
}
/**
* Get PRP runner version
* @returns {string} Runner version
*/
async getRunnerVersion() {
try {
const result = await this.runPRPCommand(['python', [this.config.runnerPath, '--version']]);
return result.stdout.trim();
} catch (error) {
return 'unknown';
}
}
/**
* Validate PRP execution environment
* @returns {Object} Validation results
*/
async validateEnvironment() {
const results = {
runnerExists: false,
pythonAvailable: false,
workingDirValid: false,
outputDirValid: false
};
try {
// Check if runner exists
await fs.access(this.config.runnerPath);
results.runnerExists = true;
} catch (error) {
// Runner not found
}
try {
// Check if Python is available
const { execSync } = require('child_process');
execSync('python --version', { stdio: 'pipe' });
results.pythonAvailable = true;
} catch (error) {
// Python not available
}
try {
// Check working directory
await fs.access(this.config.workingDir);
results.workingDirValid = true;
} catch (error) {
// Working directory not accessible
}
try {
// Check output directory
await fs.access(this.config.outputDir);
results.outputDirValid = true;
} catch (error) {
// Output directory not accessible
}
return results;
}
}
module.exports = PRPRunnerAdapter;

View File

@ -0,0 +1,240 @@
workflow:
id: hybrid-development-v1
name: Hybrid Development Workflow
version: 1.0
description: >
Combines BMad-Method's structured planning with PRPs-agentic-eng's optimized execution.
This workflow provides the best of both approaches: systematic planning and one-pass implementation.
phases:
- id: planning
name: Planning Phase (BMad)
description: "Use BMad agents to create comprehensive planning artifacts"
agents: [pm, architect, sm]
outputs:
- prd.md
- architecture.md
- stories/
validation:
- prd-checklist
- architecture-checklist
- story-validation
workflow:
- pm: "Create PRD from requirements"
- architect: "Design system architecture"
- sm: "Create detailed stories"
- po: "Validate planning artifacts"
- id: prp-generation
name: PRP Generation Phase
description: "Convert BMad stories to PRP format for optimized execution"
agents: [prp-converter]
inputs:
- stories/
outputs:
- PRPs/
validation:
- prp-format-check
- context-completeness
- validation-loop-check
workflow:
- prp-converter: "Convert stories to PRP format"
- prp-converter: "Validate PRP completeness"
- prp-converter: "Generate PRP files"
- id: execution
name: Execution Phase (PRP)
description: "Execute PRPs using PRPs-agentic-eng for one-pass implementation"
agents: [prp-executor]
inputs:
- PRPs/
outputs:
- implemented-features/
- execution-results/
validation:
- execution-success
- code-quality
- test-coverage
workflow:
- prp-executor: "Set up execution environment"
- prp-executor: "Execute PRPs"
- prp-executor: "Collect execution results"
- prp-executor: "Validate implementation"
- id: validation
name: Validation & Integration Phase
description: "Validate results and integrate back into BMad workflow"
agents: [qa, prp-validator]
inputs:
- implemented-features/
- execution-results/
outputs:
- validated-stories/
- quality-report/
validation:
- acceptance-criteria
- integration-tests
- quality-standards
workflow:
- prp-validator: "Validate PRP execution results"
- qa: "Review implementation quality"
- prp-validator: "Map results to BMad format"
- qa: "Update story completion status"
execution_modes:
- id: sequential
name: Sequential Execution
description: "Execute phases in sequence with validation gates"
phases: [planning, prp-generation, execution, validation]
validation_gates:
- after: planning
validation: [prd-checklist, architecture-checklist]
- after: prp-generation
validation: [prp-format-check, context-completeness]
- after: execution
validation: [execution-success, code-quality]
- after: validation
validation: [acceptance-criteria, integration-tests]
- id: parallel
name: Parallel Execution
description: "Execute compatible phases in parallel"
parallel_groups:
- phases: [planning, prp-generation]
description: "Planning and PRP generation can overlap"
- phases: [execution]
description: "PRP execution runs independently"
- phases: [validation]
description: "Validation runs after execution"
dependencies:
- execution: [prp-generation]
- validation: [execution]
- id: adaptive
name: Adaptive Execution
description: "Dynamically adjust workflow based on context"
decision_points:
- phase: planning
condition: "Simple project"
action: "Skip detailed architecture, go directly to PRP generation"
- phase: prp-generation
condition: "Complex story"
action: "Enhance context with additional documentation"
- phase: execution
condition: "Execution failure"
action: "Fall back to BMad development workflow"
- phase: validation
condition: "Quality issues"
action: "Additional validation and refinement"
quality_gates:
- id: planning-quality
name: Planning Quality Gate
phase: planning
criteria:
- prd_complete: true
- architecture_designed: true
- stories_created: true
- acceptance_criteria_defined: true
actions:
- pass: "Continue to PRP generation"
- fail: "Return to planning phase"
- id: prp-quality
name: PRP Quality Gate
phase: prp-generation
criteria:
- prp_format_valid: true
- context_complete: true
- validation_loops_executable: true
- traceability_maintained: true
actions:
- pass: "Continue to execution"
- fail: "Enhance PRP context"
- id: execution-quality
name: Execution Quality Gate
phase: execution
criteria:
- execution_successful: true
- code_quality_acceptable: true
- tests_passing: true
- requirements_met: true
actions:
- pass: "Continue to validation"
- fail: "Debug and retry execution"
- id: validation-quality
name: Validation Quality Gate
phase: validation
criteria:
- acceptance_criteria_met: true
- integration_tests_passing: true
- quality_standards_met: true
- documentation_complete: true
actions:
- pass: "Workflow complete"
- fail: "Address quality issues"
error_handling:
- id: planning-errors
name: Planning Error Handling
phase: planning
errors:
- missing_requirements: "Request additional requirements"
- incomplete_architecture: "Enhance architecture design"
- invalid_stories: "Refine story definitions"
recovery:
- action: "Return to planning phase"
- validation: "Re-validate planning artifacts"
- id: prp-errors
name: PRP Generation Error Handling
phase: prp-generation
errors:
- invalid_story_format: "Fix story format issues"
- missing_context: "Enhance context documentation"
- validation_failures: "Fix validation loop issues"
recovery:
- action: "Enhance PRP context"
- validation: "Re-validate PRP format"
- id: execution-errors
name: Execution Error Handling
phase: execution
errors:
- environment_issues: "Fix execution environment"
- dependency_issues: "Resolve missing dependencies"
- execution_failures: "Debug execution issues"
recovery:
- action: "Fix execution environment"
- fallback: "Use BMad development workflow"
- id: validation-errors
name: Validation Error Handling
phase: validation
errors:
- quality_issues: "Address quality problems"
- test_failures: "Fix failing tests"
- integration_issues: "Resolve integration problems"
recovery:
- action: "Address quality issues"
- iteration: "Re-run validation phase"
success_criteria:
- all_phases_completed: true
- quality_gates_passed: true
- acceptance_criteria_met: true
- integration_tests_passing: true
- documentation_complete: true
- traceability_maintained: true
metrics:
- planning_time: "Time spent in planning phase"
- prp_generation_time: "Time spent generating PRPs"
- execution_time: "Time spent executing PRPs"
- validation_time: "Time spent in validation"
- total_time: "Total workflow execution time"
- success_rate: "Percentage of successful executions"
- quality_score: "Overall quality assessment"
- user_satisfaction: "User satisfaction with results"