Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 17:50:56 +08:00
commit f0e7f0e603
9 changed files with 3525 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
{
"name": "project-planner-skill",
"description": "Comprehensive project planning and documentation generator for software projects. Creates structured requirements documents, system design documents, and task breakdown plans with implementation tracking.",
"version": "1.0.0",
"author": {
"name": "George A Puiu",
"email": "puiu.adrian@gmail.com"
},
"skills": [
"./"
]
}

3
README.md Normal file
View File

@@ -0,0 +1,3 @@
# project-planner-skill
Comprehensive project planning and documentation generator for software projects. Creates structured requirements documents, system design documents, and task breakdown plans with implementation tracking.

842
SKILL.md Normal file
View File

@@ -0,0 +1,842 @@
---
name: project-planner
description: Comprehensive project planning and documentation generator for software projects. Creates structured requirements documents, system design documents, and task breakdown plans with implementation tracking. Use when starting a new project, defining specifications, creating technical designs, or breaking down complex systems into implementable tasks. Supports user story format, acceptance criteria, component design, API specifications, and hierarchical task decomposition with requirement traceability.
---
# Project Planner Skill
This skill provides templates and guidance for generating comprehensive project planning documents that serve as blueprints for AI-assisted implementation.
## Quick Start
When a user wants to start a new project, generate three core documents:
1. **Requirements Document** - User stories with acceptance criteria
2. **Design Document** - Technical architecture and component specifications
3. **Implementation Plan** - Hierarchical task breakdown with requirement tracing
## Why Explicit Architectural Planning Works
Setting clear roles, responsibilities, and deliverables upfront dramatically improves project outcomes:
### Benefits of Upfront Definition
1. **Component Clarity** - Defining all system components first prevents scope creep and ensures complete coverage
2. **Data Flow Visibility** - Mapping data movement early reveals integration complexities and performance bottlenecks
3. **Integration Planning** - Identifying all touchpoints upfront prevents surprise dependencies during implementation
4. **Clear Boundaries** - Explicitly stating what's in/out of scope focuses effort and prevents feature drift
5. **Measurable Success** - Specific goals and constraints enable objective progress tracking
### The Architect Mindset
When acting as a **Project Architect**, approach planning with:
- **Systems Thinking** - See the whole before diving into parts
- **Interface-First Design** - Define contracts between components before internals
- **Traceability Focus** - Every requirement maps to design elements and tasks
- **Constraint Awareness** - Acknowledge limitations upfront to guide decisions
- **Deliverable Orientation** - Know exactly what artifacts you're producing
## Document Generation Workflow
### 1. Project Architect Role Definition
When starting a project, explicitly establish Claude as the **Project Architect** with clear responsibilities:
**Role:** System Architect and Planning Specialist
**Responsibilities:**
- Define complete system architecture with all components
- Map data flow between system elements
- Identify all integration points and interfaces
- Establish clear project boundaries and constraints
- Create traceable requirements to implementation tasks
### 2. Initial Project Understanding
Before generating documents, gather key information and architectural elements:
```
Required Project Information:
- Project name and purpose
- Target users (single-user local, multi-tenant SaaS, etc.)
- Core functionality (3-5 main features)
- Technical preferences (languages, frameworks, deployment)
- Non-functional requirements (performance, security, scalability)
Required Architectural Elements (define upfront):
- System Components: All major modules/services and their purposes
- Data Flow: How data moves through the entire system
- Integration Points: All external APIs, services, databases
- System Boundaries: What's in scope vs out of scope
- Constraints: Technical, business, and resource limitations
- Success Metrics: Clear, measurable goals for the system
```
### 3. Deliverable Definition (Set Upfront)
Define all deliverables explicitly before starting documentation:
```
Standard Deliverables Package:
1. Requirements Document
- User stories with measurable acceptance criteria
- Complete glossary of terms
- Traceable requirement IDs
2. System Design Document
- Component architecture diagram
- Data flow diagrams for all major processes
- Integration point specifications
- API/Interface contracts
- Performance and scaling targets
3. Implementation Plan
- Hierarchical task breakdown
- Requirement-to-task mapping
- Dependency graph
- Phase-based delivery schedule
Optional Deliverables (specify if needed):
- API Documentation
- Database Schema Design
- Security Threat Model
- Deployment Guide
- Testing Strategy Document
```
### 4. Generate Requirements Document
Use the requirements template to create user-focused specifications:
```python
# Execute this to generate requirements structure
requirements = {
"introduction": "System purpose and scope",
"glossary": "Domain-specific terms",
"requirements": [
{
"id": "REQ-X",
"user_story": "As a [role], I want [feature], so that [benefit]",
"acceptance_criteria": [
"WHEN [condition], THE system SHALL [behavior]",
"WHERE [context], THE system SHALL [behavior]",
"IF [condition], THEN THE system SHALL [behavior]"
]
}
]
}
```
### 5. Generate Design Document
Create technical specifications with explicit architectural elements:
```python
# Execute this to generate comprehensive design structure
design = {
"overview": "High-level system description",
"architecture": {
"diagram": "ASCII or visual representation of all components",
"components": [
{
"id": "COMP-1",
"name": "Component Name",
"type": "Frontend/Backend/Service/Database",
"responsibility": "Single clear purpose",
"boundaries": "What it does and doesn't do"
}
]
},
"data_flow": {
"primary_flows": [
{
"name": "User Registration Flow",
"steps": [
"1. User submits form → Frontend",
"2. Frontend validates → API Gateway",
"3. API Gateway → Auth Service",
"4. Auth Service → User Database",
"5. Response flows back"
],
"data_transformations": "How data changes at each step"
}
]
},
"integration_points": [
{
"name": "External Payment API",
"type": "REST/GraphQL/WebSocket/Database",
"purpose": "Process payments",
"interface": "API contract definition",
"authentication": "Method used",
"error_handling": "Retry/fallback strategy"
}
],
"components_detail": [
{
"name": "Component Name",
"responsibility": "What it does",
"key_classes": ["Class descriptions"],
"interfaces": "API/method signatures",
"dependencies": "What it needs to function",
"performance": "Targets and constraints"
}
],
"data_models": "Entity definitions with relationships",
"system_boundaries": {
"in_scope": ["What the system handles"],
"out_of_scope": ["What it delegates or ignores"],
"assumptions": ["External dependencies assumed available"]
},
"error_handling": "Strategies for failures",
"testing_strategy": "Unit, integration, performance",
"deployment": "Docker, environment, configuration"
}
```
### 6. Generate Implementation Plan
Break down the project into executable tasks with clear scope boundaries:
```python
# Execute this to generate task structure with boundaries
tasks = {
"project_boundaries": {
"must_have": ["Core features for MVP"],
"nice_to_have": ["Enhancement features"],
"out_of_scope": ["Features explicitly excluded"],
"technical_constraints": ["Framework/library limitations"]
},
"phases": [
{
"id": 1,
"name": "Infrastructure Setup",
"deliverables": ["What this phase produces"],
"tasks": [
{
"id": "1.1",
"description": "Task description",
"subtasks": ["Specific actions"],
"requirements_fulfilled": ["REQ-1.1", "REQ-2.3"],
"components_involved": ["COMP-1", "COMP-3"],
"dependencies": [],
"estimated_hours": 4,
"success_criteria": "How to verify completion"
}
]
}
]
}
```
## Requirements Document Template
```markdown
# Requirements Document
## Introduction
[System description in 2-3 sentences. Target user and deployment model.]
## Glossary
- **Term**: Definition specific to this system
- **Component**: Major system module or service
[Add all domain-specific terms]
## Requirements
### Requirement [NUMBER]
**User Story:** As a [user type], I want [capability], so that [benefit]
#### Acceptance Criteria
1. WHEN [trigger/condition], THE [component] SHALL [action/behavior]
2. WHERE [mode/context], THE [component] SHALL [action/behavior]
3. IF [condition], THEN THE [component] SHALL [action/behavior]
4. THE [component] SHALL [capability with measurable target]
[Repeat for each requirement]
```
### Requirements Best Practices
1. **One capability per requirement** - Each requirement should address a single feature
2. **Testable criteria** - Every criterion must be verifiable
3. **Use SHALL for mandatory** - Consistent RFC 2119 keywords
4. **Include performance targets** - "within X milliseconds/seconds"
5. **Specify all states** - Success, failure, edge cases
6. **Number systematically** - REQ-1, REQ-2 for traceability
### Acceptance Criteria Patterns
```
Behavior criteria:
- WHEN [event occurs], THE system SHALL [respond]
- THE system SHALL [provide capability]
- THE system SHALL [enforce rule/limit]
Conditional criteria:
- IF [condition], THEN THE system SHALL [action]
- WHERE [mode is active], THE system SHALL [behavior]
Performance criteria:
- THE system SHALL [complete action] within [time]
- THE system SHALL support [number] concurrent [operations]
- THE system SHALL maintain [metric] above/below [threshold]
Data criteria:
- THE system SHALL persist [data type] with [attributes]
- THE system SHALL validate [input] against [rules]
- THE system SHALL return [data] in [format]
```
## Design Document Template
```markdown
# Design Document
## Overview
[System architecture summary in 3-4 sentences. Key design decisions and priorities.]
## System Architecture
### Component Map
| Component ID | Name | Type | Responsibility | Interfaces With |
|-------------|------|------|----------------|-----------------|
| COMP-1 | Web Frontend | UI | User interface | COMP-2 |
| COMP-2 | API Gateway | Service | Request routing | COMP-3, COMP-4 |
| COMP-3 | Business Logic | Service | Core processing | COMP-5 |
[Complete component inventory]
### High-Level Architecture Diagram
[ASCII diagram showing all components and their relationships]
## Data Flow Specifications
### Primary Data Flows
#### 1. [Flow Name] (e.g., User Authentication)
```
1. [Source] → [Component]: [Data description]
2. [Component] → [Component]: [Transformation applied]
3. [Component] → [Destination]: [Final data format]
```
**Data Transformations:**
- Step 2: [How data changes]
- Step 3: [Validation/Processing applied]
[Repeat for each major data flow]
## Integration Points
### Internal Integration Points
| Source | Target | Protocol | Data Format | Purpose |
|--------|--------|----------|-------------|---------|
| Frontend | API Gateway | HTTPS/REST | JSON | API calls |
| API Gateway | Auth Service | gRPC | Protobuf | Authentication |
[All internal integrations]
### External Integration Points
#### [External System Name]
**Type:** REST API / Database / Message Queue / etc.
**Purpose:** [What this integration provides]
**Endpoint:** [URL/Connection string pattern]
**Authentication:** [Method - OAuth2, API Key, etc.]
**Rate Limits:** [Any constraints]
**Interface Contract:**
```language
// Request format
POST /api/endpoint
{
"field": "type"
}
// Response format
{
"result": "type"
}
```
**Error Handling:**
- Retry strategy: [Exponential backoff, circuit breaker]
- Fallback: [What happens if unavailable]
- Monitoring: [How to detect issues]
[Repeat for each external integration]
## Components and Interfaces
### 1. [Component Name]
**Responsibility:** [Single sentence description]
**Key Classes:**
- `ClassName`: [Purpose and main methods]
- `ServiceName`: [What it manages]
**Interfaces:**
```language
class InterfaceName:
def method_name(params) -> ReturnType
# Core methods only
```
**Data Flow:**
- Receives [input] from [source]
- Processes by [algorithm/logic]
- Outputs [result] to [destination]
**Performance:**
- Target: [metric and value]
- Constraints: [limitations]
[Repeat for each major component]
## Data Models
### [Entity Name]
```language
@dataclass
class EntityName:
field: Type
field: Optional[Type]
# Core fields only
```
## Error Handling
### [Error Category]
**Types:** [List of error scenarios]
**Handling:** [Strategy and recovery]
## Testing Strategy
### Unit Tests
- [Component]: Test [aspects]
- Coverage target: 80%
### Integration Tests
- [Flow]: Test [end-to-end scenario]
### Performance Tests
- [Operation]: Target [metric]
## Deployment
### Docker Configuration
```yaml
# Essential service definitions only
```
### Environment Variables
```
CATEGORY_VAR=description
```
## Performance Targets
- [Operation]: <[time]
- [Throughput]: >[rate]
- [Resource]: <[limit]
## Security Considerations
- [Authentication method if applicable]
- [Data protection approach]
- [Access control model]
```
### Design Best Practices
1. **Component responsibilities** - Single, clear purpose per component
2. **Interface first** - Define contracts before implementation
3. **Data flow clarity** - Show how data moves through system
4. **Error categories** - Group related failures with consistent handling
5. **Performance targets** - Specific, measurable goals
6. **Deployment ready** - Include Docker and configuration
## Implementation Plan Template
```markdown
# Implementation Plan
- [x] 1. [Phase Name]
- [x] 1.1 [Task name]
- [Subtask description]
- [Subtask description]
- _Requirements: [REQ-X.Y, REQ-A.B]_
- [ ] 1.2 [Task name]
- [Subtask description]
- _Requirements: [REQ-X.Y]_
- _Dependencies: Task 1.1_
- [ ] 2. [Phase Name]
- [ ] 2.1 [Task name]
- [Detailed steps or subtasks]
- _Requirements: [REQ-X.Y]_
- _Dependencies: Phase 1_
[Continue for all phases]
```
### Task Planning Best Practices
1. **Hierarchical structure** - Phases > Tasks > Subtasks
2. **Requirement tracing** - Link each task to requirements
3. **Dependency marking** - Identify blockers and prerequisites
4. **Checkbox format** - [x] for complete, [ ] for pending
5. **Atomic tasks** - Each task independently completable
6. **Progressive implementation** - Infrastructure → Core → Features → Polish
### Common Implementation Phases
```markdown
1. **Infrastructure Setup**
- Project structure
- Database schema
- Docker configuration
- Core dependencies
2. **Data Layer**
- Models/entities
- Database operations
- Migrations
3. **Business Logic**
- Core algorithms
- Service classes
- Validation rules
4. **API/Interface Layer**
- REST/GraphQL endpoints
- WebSocket handlers
- Authentication
5. **Frontend/UI**
- Component structure
- State management
- API integration
- Responsive design
6. **Integration**
- External services
- Third-party APIs
- Message queues
7. **Testing**
- Unit tests
- Integration tests
- End-to-end tests
8. **DevOps**
- CI/CD pipeline
- Monitoring
- Logging
- Deployment scripts
9. **Documentation**
- API documentation
- User guides
- Deployment guide
- README
```
## Document Patterns by Project Type
### Web Application (Full-Stack)
Requirements focus:
- User authentication and authorization
- CRUD operations for entities
- Real-time updates
- Responsive UI
- API design
Design focus:
- 3-tier architecture (Frontend, Backend, Database)
- REST/GraphQL API design
- State management strategy
- Component hierarchy
- Database schema
Tasks focus:
1. Database and backend setup
2. API implementation
3. Frontend components
4. Integration and testing
### Microservices System
Requirements focus:
- Service boundaries
- Inter-service communication
- Data consistency
- Service discovery
- Fault tolerance
Design focus:
- Service decomposition
- API contracts between services
- Message queue/event bus
- Distributed tracing
- Container orchestration
Tasks focus:
1. Service scaffolding
2. Shared libraries/contracts
3. Individual service implementation
4. Integration layer
5. Orchestration setup
### Data Pipeline/ETL
Requirements focus:
- Data sources and formats
- Transformation rules
- Data quality checks
- Schedule/triggers
- Error handling and retry
Design focus:
- Pipeline stages
- Data flow diagram
- Schema evolution
- Monitoring and alerting
- Storage strategy
Tasks focus:
1. Data source connectors
2. Transformation logic
3. Validation and quality checks
4. Scheduling setup
5. Monitoring implementation
### CLI Tool/Library
Requirements focus:
- Command structure
- Input/output formats
- Configuration options
- Error messages
- Performance requirements
Design focus:
- Command parser architecture
- Plugin system (if applicable)
- Configuration management
- Output formatters
- Testing strategy
Tasks focus:
1. Core command structure
2. Business logic implementation
3. Input/output handlers
4. Configuration system
5. Documentation and examples
## Generating Documents for Specific Domains
### Trading/Financial Systems
Additional requirements:
- Risk management rules
- Order execution logic
- Market data handling
- Compliance requirements
- Audit trail
Additional design:
- High-frequency data handling
- Position tracking
- Risk calculations
- Order routing
- Failover strategies
### Real-time Systems (Chat, Gaming, IoT)
Additional requirements:
- Latency targets
- Connection handling
- State synchronization
- Offline support
- Push notifications
Additional design:
- WebSocket/SSE architecture
- State management
- Caching strategy
- Message queuing
- Horizontal scaling
### Machine Learning Systems
Additional requirements:
- Model training pipeline
- Feature engineering
- Model versioning
- Prediction API
- Monitoring/drift detection
Additional design:
- Training infrastructure
- Feature store
- Model registry
- Serving architecture
- A/B testing framework
## Quality Checklist
Before finalizing documents, verify:
### Requirements Document
- [ ] Every requirement has a clear user story
- [ ] All acceptance criteria are testable
- [ ] Non-functional requirements specified (performance, security)
- [ ] Glossary covers all domain terms
- [ ] Requirements are numbered for tracing
### Design Document
- [ ] Architecture diagram included
- [ ] All components have clear responsibilities
- [ ] Interfaces defined for integration points
- [ ] Error handling strategy documented
- [ ] Performance targets specified
- [ ] Deployment configuration included
### Implementation Plan
- [ ] Tasks grouped into logical phases
- [ ] Dependencies identified between tasks
- [ ] Requirements traced to tasks
- [ ] Tasks are atomic and completable
- [ ] Checkbox format for progress tracking
## Example Usage Patterns
### Starting a New Project (With Explicit Architecture Focus)
```
User: "I want to build an order flow trading automation system"
Response: "I'll act as your Project Architect to create comprehensive planning documents.
First, let me establish the architectural foundation:
**System Components I need to define:**
- Market data ingestion service
- Order flow analysis engine
- Trading signal generator
- Risk management module
- Order execution service
- Monitoring dashboard
**Data Flows to map:**
- Market data → Analysis → Signals → Execution
- Position tracking → Risk calculation → Trading limits
- All events → Audit trail
**Integration Points to specify:**
- Exchange APIs (which ones?)
- Database system (time-series data needs?)
- Notification services (alerts/reporting?)
**Key Questions:**
1. Is this for personal use (single-user) or a platform (multi-user)?
2. Which specific exchanges/brokers will it connect to?
3. What are your latency requirements (milliseconds matter)?
4. What's your risk tolerance and position sizing approach?
5. Do you need backtesting capabilities?
**Deliverables I'll create:**
1. Requirements document with traceable user stories
2. System design with complete component map and data flows
3. Implementation plan with phased delivery milestones
This architectural blueprint will ensure nothing is overlooked during implementation."
```
### Starting a New Project (Simple Approach)
```
User: "I want to build an order flow trading automation system"
Response: "I'll help you create comprehensive planning documents for your trading system. Let me gather some key information:
1. Is this for personal use (single-user) or a multi-user platform?
2. Which markets/exchanges will it connect to?
3. What are the core trading strategies or patterns?
4. Any specific performance requirements (latency, throughput)?
Based on this, I'll generate:
- Requirements document with user stories
- System design with components and data flow
- Implementation plan with phases and tasks"
```
### Expanding Existing Requirements
```
User: "Add real-time monitoring dashboard to the requirements"
Response: "I'll add dashboard requirements to your document:
### Requirement 15
**User Story:** As a trader, I want a real-time dashboard, so that I can monitor system performance and trading activity
#### Acceptance Criteria
1. THE Dashboard SHALL display active positions with current P&L
2. THE Dashboard SHALL update market data within 1 second
3. THE Dashboard SHALL provide filtering by symbol, timeframe, and date range
4. WHEN a trade executes, THE Dashboard SHALL reflect it within 100ms"
```
## Common Pitfalls to Avoid
### Planning Pitfalls
1. **Skipping architectural planning** - Jumping to requirements without mapping components first
2. **Vague role definition** - Not establishing the architect role leads to unfocused documentation
3. **Hidden integration points** - Discovering external dependencies during implementation
4. **Undefined boundaries** - No clear scope leads to feature creep and timeline slippage
5. **Missing data flow analysis** - Not mapping how data moves reveals issues late
### Requirements Pitfalls
1. **Over-specifying implementation** - Requirements should define "what" not "how"
2. **Vague acceptance criteria** - Avoid "user-friendly" or "fast" without metrics
3. **Missing error cases** - Include failure scenarios in requirements
4. **Untraceable requirements** - Every requirement should map to tasks
### Design Pitfalls
1. **Monolithic components** - Break down large components into focused services
2. **Circular dependencies** - Ensure task dependencies form a DAG
3. **Missing data models** - Define core entities early
4. **Ignoring deployment** - Include Docker/deployment from the start
5. **Unclear component boundaries** - Each component needs explicit responsibilities
## Output Format
Generate documents in Markdown format for easy editing and version control. Use:
- Clear hierarchical headings (##, ###, ####)
- Code blocks with language hints
- Bulleted and numbered lists
- Tables for structured data
- Checkboxes for task tracking
- Bold for emphasis on key terms
- Inline code for technical terms
Save documents as:
- `requirements.md` - Requirements document
- `design.md` - Design document
- `tasks.md` - Implementation plan
These documents serve as the foundation for AI-assisted implementation, providing clear specifications that can be referenced throughout development.

View File

@@ -0,0 +1,83 @@
# Requirements Document Template
## Introduction
[PROJECT NAME] is a [SYSTEM TYPE] designed for [TARGET USERS]. The system [PRIMARY PURPOSE].
## System Context
### Architectural Overview
- **Components:** [List major system components]
- **Data Flow:** [High-level data movement]
- **Integration Points:** [External systems/APIs]
- **Deployment Model:** [Cloud/On-premise/Hybrid]
## Glossary
- **[Term]**: [Definition specific to this system]
- **Component**: Major system module or service
- **Integration Point**: Connection to external system or API
## Functional Requirements
### REQ-1: [Feature Name]
**User Story:** As a [user role], I want [feature], so that [benefit]
**Acceptance Criteria:**
1. WHEN [condition], THE system SHALL [behavior]
2. THE system SHALL [requirement] within [time constraint]
3. IF [error condition], THEN THE system SHALL [error handling]
**Components Involved:** [COMP-1, COMP-2]
**Data Flow:** [How data moves for this requirement]
### REQ-2: [Feature Name]
**User Story:** As a [user role], I want [feature], so that [benefit]
**Acceptance Criteria:**
1. WHEN [condition], THE system SHALL [behavior]
2. WHERE [context], THE system SHALL [behavior]
3. THE system SHALL persist [data] with [attributes]
**Components Involved:** [COMP-3, COMP-4]
**Integration Points:** [External systems used]
## Non-Functional Requirements
### Performance Requirements
- Response time: THE system SHALL respond to user requests within [X] milliseconds
- Throughput: THE system SHALL handle [X] concurrent users
- Data processing: THE system SHALL process [X] records per second
### Security Requirements
- Authentication: THE system SHALL implement [auth method]
- Authorization: THE system SHALL enforce role-based access control
- Data protection: THE system SHALL encrypt sensitive data at rest and in transit
### Reliability Requirements
- Availability: THE system SHALL maintain 99.9% uptime
- Recovery: THE system SHALL recover from failures within [X] minutes
- Data integrity: THE system SHALL ensure ACID compliance for transactions
### Scalability Requirements
- THE system SHALL support horizontal scaling
- THE system SHALL handle [X]% growth in users annually
- THE system SHALL support database sharding for data volumes exceeding [X]
## Constraints and Boundaries
### Technical Constraints
- Technology: [Programming languages, frameworks, databases]
- Infrastructure: [Cloud provider, hardware limitations]
### Business Constraints
- Budget: [Cost limitations]
- Timeline: [Delivery deadlines]
- Compliance: [Regulatory requirements]
### Scope Boundaries
- **In Scope:** [What's included]
- **Out of Scope:** [What's explicitly excluded]
- **Future Considerations:** [Deferred features]

15
plugin.json Normal file
View File

@@ -0,0 +1,15 @@
{
"name": "project-planner-skill",
"description": "Comprehensive project planning and documentation generator for software projects. Creates structured requirements documents, system design documents, and task breakdown plans with implementation tracking.",
"version": "1.0.0",
"author": {
"name": "George A Puiu",
"email": "puiu.adrian@gmail.com"
},
"homepage": "https://github.com/adrianpuiu/claude-skills-marketplace",
"repository": "https://github.com/adrianpuiu/claude-skills-marketplace",
"license": "MIT",
"keywords": ["project-planning", "documentation", "requirements", "design", "implementation"],
"category": "productivity",
"strict": false
}

65
plugin.lock.json Normal file
View File

@@ -0,0 +1,65 @@
{
"$schema": "internal://schemas/plugin.lock.v1.json",
"pluginId": "gh:adrianpuiu/claude-skills-marketplace:project-planner-skill",
"normalized": {
"repo": null,
"ref": "refs/tags/v20251128.0",
"commit": "81b81b946e042f6a789b143d5c09482792d375e6",
"treeHash": "bfc5ab6b0bcaab2ba4730052c02142568ae8c7fc29525ab89ec055870ff1f845",
"generatedAt": "2025-11-28T10:13:01.449491Z",
"toolVersion": "publish_plugins.py@0.2.0"
},
"origin": {
"remote": "git@github.com:zhongweili/42plugin-data.git",
"branch": "master",
"commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390",
"repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data"
},
"manifest": {
"name": "project-planner-skill",
"description": "Comprehensive project planning and documentation generator for software projects. Creates structured requirements documents, system design documents, and task breakdown plans with implementation tracking.",
"version": "1.0.0"
},
"content": {
"files": [
{
"path": "plugin.json",
"sha256": "7b291017ca833dff4b02dc0397b4f5cb072995317c0c79fd3b60ca0a3e5b2bab"
},
{
"path": "README.md",
"sha256": "bdc7011a3d0f58068b96f817b5e25fae61818b9791024219808f2f7d5eb61050"
},
{
"path": "SKILL.md",
"sha256": "f28924ef91365ba9ee0e877be3429c5880d993c4ec0af6df664c1fb74d398c66"
},
{
"path": "references/domain-templates.md",
"sha256": "c2db709e4805a561121739f1ca420ff306155054af0ea6e517aded7a83879a2d"
},
{
"path": "scripts/validate_documents.py",
"sha256": "8e8c6b6e80b9bcf7d11afcf997295b726857521d40220f27fe51567b2c8df620"
},
{
"path": "scripts/generate_project_docs.py",
"sha256": "06ffa88d983ae9cca5f82f8275b1a2d6097fae73a69911b0a5b630fcaa2935b4"
},
{
"path": ".claude-plugin/plugin.json",
"sha256": "0b5e032fcf74465badaa9d3bacfa4d0e1c696d0c4628b86dd908339c26a44662"
},
{
"path": "assets/requirements-template.md",
"sha256": "baae55f4e5e305f269e1d08cbd6d483d1127a17916ddce594423480046d0ab23"
}
],
"dirSha256": "bfc5ab6b0bcaab2ba4730052c02142568ae8c7fc29525ab89ec055870ff1f845"
},
"security": {
"scannedAt": null,
"scannerVersion": null,
"flags": []
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,801 @@
#!/usr/bin/env python3
"""
Project Document Generator
Generates structured requirements, design, and task documents for new projects
"""
import json
import argparse
from datetime import datetime
from typing import Dict, List, Optional
import os
class ProjectDocumentGenerator:
def __init__(self, project_name: str, project_type: str = "web-app"):
self.project_name = project_name
self.project_type = project_type
self.timestamp = datetime.now().strftime("%Y-%m-%d")
def generate_requirements_template(self, features: List[str]) -> str:
"""Generate requirements document template"""
template = f"""# Requirements Document
## Introduction
{self.project_name} is a [DESCRIPTION OF SYSTEM PURPOSE]. The system is designed for [TARGET USERS] and will be deployed as [DEPLOYMENT MODEL].
## Glossary
- **[Term]**: [Definition specific to this system]
- **User**: [Define user types]
- **System**: The {self.project_name} platform
## Requirements
"""
for i, feature in enumerate(features, 1):
template += f"""
### Requirement {i}
**User Story:** As a [USER TYPE], I want {feature}, so that [BENEFIT]
#### Acceptance Criteria
1. WHEN [trigger/condition], THE system SHALL [behavior]
2. WHERE [context applies], THE system SHALL [behavior]
3. THE system SHALL [capability] within [time limit]
4. IF [error condition], THEN THE system SHALL [handle gracefully]
5. THE system SHALL persist [data] with [attributes]
"""
return template
def generate_design_template(self, components: List[str]) -> str:
"""Generate design document template with comprehensive architecture"""
template = f"""# Design Document
## Overview
The {self.project_name} system is built as a [ARCHITECTURE PATTERN] with [KEY COMPONENTS]. The design prioritizes [KEY PRIORITIES].
## System Architecture
### Component Map
| Component ID | Name | Type | Responsibility | Interfaces With |
|-------------|------|------|----------------|-----------------|
| COMP-1 | Frontend | UI | User interface and interaction | COMP-2 |
| COMP-2 | API Gateway | Service | Request routing and authentication | COMP-3, COMP-4 |"""
for i, component in enumerate(components, 3):
template += f"""
| COMP-{i} | {component} | Service | [Responsibility] | [Components] |"""
template += """
### High-Level Architecture Diagram
```
┌─────────────────────────────────────────────────────────────┐
│ Frontend Layer │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ [UI Framework] Application │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
API (REST/GraphQL/WebSocket)
┌─────────────────────────────────────────────────────────────┐
│ Backend Layer │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ [Backend Framework] Application │ │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ Service │ │ Service │ │ Service │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
Database Access
┌─────────────────────────────────────────────────────────────┐
│ Data Layer │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ [Database Type] │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
```
## Data Flow Specifications
### Primary Data Flows
#### 1. User Authentication Flow
```
1. User → Frontend: Login credentials
2. Frontend → API Gateway: Encrypted credentials
3. API Gateway → Auth Service: Validation request
4. Auth Service → User Database: Query user record
5. User Database → Auth Service: User data
6. Auth Service → API Gateway: JWT token
7. API Gateway → Frontend: Auth response with token
```
**Data Transformations:**
- Step 2: Credentials encrypted with HTTPS
- Step 3: Rate limiting applied
- Step 6: JWT token generated with claims
[Add other critical data flows]
## Integration Points
### Internal Integration Points
| Source | Target | Protocol | Data Format | Purpose |
|--------|--------|----------|-------------|---------|
| Frontend | API Gateway | HTTPS/REST | JSON | API calls |
| API Gateway | Services | HTTP/gRPC | JSON/Protobuf | Service calls |
| Services | Database | TCP | SQL | Data persistence |
### External Integration Points
#### [External Service Name]
**Type:** REST API / Database / Message Queue
**Purpose:** [What this integration provides]
**Endpoint:** [URL pattern or connection details]
**Authentication:** [OAuth2, API Key, etc.]
**Rate Limits:** [Any constraints]
**Interface Contract:**
```
POST /api/endpoint
Headers: { "Authorization": "Bearer token" }
Body: { "field": "value" }
Response: { "result": "value" }
```
**Error Handling:**
- Retry strategy: Exponential backoff with jitter
- Circuit breaker: Opens after 5 consecutive failures
- Fallback: [Degraded functionality or cached response]
## System Boundaries
### In Scope
- [Core functionality included]
- [Features to be implemented]
### Out of Scope
- [Features not included]
- [Delegated to external systems]
### Assumptions
- [External services available]
- [Infrastructure provided]
## Components and Interfaces
"""
for component in components:
template += f"""
### {component}
**Responsibility:** [Single sentence description of what this component does]
**Key Classes:**
- `{component}Service`: Main service class for {component.lower()} operations
- `{component}Controller`: Handles API requests for {component.lower()}
- `{component}Repository`: Data access layer for {component.lower()}
**Interfaces:**
```python
class {component}Service:
async def create(self, data: Dict) -> {component}
async def get(self, id: str) -> Optional[{component}]
async def update(self, id: str, data: Dict) -> {component}
async def delete(self, id: str) -> bool
async def list(self, filters: Dict) -> List[{component}]
```
**Data Flow:**
- Receives requests from [API layer/other service]
- Validates input using [validation rules]
- Processes business logic
- Persists to database
- Returns response
**Performance:**
- Target response time: <200ms for queries
- Target response time: <500ms for mutations
- Maximum concurrent operations: 100
"""
template += """
## Data Models
### User
```python
@dataclass
class User:
id: str
email: str
name: str
created_at: datetime
updated_at: datetime
```
[Add other data models]
## Error Handling
### API Errors
**Types:**
- 400 Bad Request - Invalid input
- 401 Unauthorized - Missing/invalid authentication
- 403 Forbidden - Insufficient permissions
- 404 Not Found - Resource doesn't exist
- 500 Internal Server Error - Unexpected error
**Handling:**
- Return consistent error format with code, message, and details
- Log all errors with context
- Implement retry logic for transient failures
### Database Errors
**Types:**
- Connection failures
- Query timeouts
- Constraint violations
**Handling:**
- Retry with exponential backoff
- Graceful degradation where possible
- Transaction rollback on failure
## Testing Strategy
### Unit Tests
- Service layer: Test business logic with mocked dependencies
- Repository layer: Test database operations
- API layer: Test request/response handling
- Coverage target: 80%
### Integration Tests
- End-to-end API tests
- Database integration tests
- External service integration tests
### Performance Tests
- Load testing: 100 concurrent users
- Response time: p95 < 500ms
- Throughput: >100 requests/second
## Deployment
### Docker Configuration
```yaml
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
environment:
- DATABASE_URL=${DATABASE_URL}
depends_on:
- database
database:
image: postgres:15
volumes:
- db_data:/var/lib/postgresql/data
environment:
- POSTGRES_PASSWORD=${DB_PASSWORD}
volumes:
db_data:
```
### Environment Variables
```
DATABASE_URL=postgresql://user:pass@localhost/dbname
API_KEY=your-api-key
JWT_SECRET=your-secret-key
NODE_ENV=production
```
## Performance Targets
- API response time: <200ms (p95)
- Database query time: <50ms (p95)
- Frontend load time: <2s
- Time to interactive: <3s
- Memory usage: <512MB per instance
## Security Considerations
- JWT-based authentication
- Rate limiting on all endpoints
- Input validation and sanitization
- SQL injection prevention via parameterized queries
- XSS prevention via output encoding
- HTTPS only in production
"""
return template
def generate_tasks_template(self, phases: List[Dict]) -> str:
"""Generate implementation plan template with boundaries and deliverables"""
template = f"""# Implementation Plan
Generated: {self.timestamp}
Project: {self.project_name}
Type: {self.project_type}
## Project Boundaries
### Must Have (MVP)
- [Core feature 1]
- [Core feature 2]
- [Core feature 3]
### Nice to Have (Enhancements)
- [Enhancement feature 1]
- [Enhancement feature 2]
### Out of Scope
- [Explicitly excluded feature 1]
- [Deferred to future phase]
### Technical Constraints
- [Framework limitations]
- [Resource constraints]
## Deliverables by Phase
| Phase | Deliverables | Success Criteria |
|-------|-------------|------------------|
| 1. Infrastructure | Working development environment | All developers can run locally |
| 2. Data Layer | Database schema, models | CRUD operations functional |
| 3. Business Logic | Core services implemented | All requirements fulfilled |
| 4. API Layer | REST/GraphQL endpoints | API tests passing |
| 5. Frontend | User interface | End-to-end workflows complete |
| 6. Testing | Test coverage >80% | All tests passing |
| 7. Deployment | Production environment | System accessible and stable |
## Task Breakdown
"""
for phase_num, phase in enumerate(phases, 1):
template += f"- [ ] {phase_num}. {phase['name']}\n\n"
for task_num, task in enumerate(phase.get('tasks', []), 1):
template += f" - [ ] {phase_num}.{task_num} {task['name']}\n"
if 'subtasks' in task:
for subtask in task['subtasks']:
template += f" - {subtask}\n"
if 'requirements' in task:
template += f" - _Requirements: {', '.join(task['requirements'])}_\n"
if 'dependencies' in task and task['dependencies']:
template += f" - _Dependencies: {', '.join(task['dependencies'])}_\n"
template += "\n"
return template
def get_default_phases(self) -> List[Dict]:
"""Get default phases based on project type"""
if self.project_type == "web-app":
return [
{
"name": "Infrastructure Setup",
"tasks": [
{
"name": "Initialize project structure",
"subtasks": [
"Create directory structure",
"Initialize package managers",
"Set up version control"
],
"requirements": ["REQ-12.1"]
},
{
"name": "Set up database",
"subtasks": [
"Create database schema",
"Write migrations",
"Set up connection pooling"
],
"requirements": ["REQ-9.1", "REQ-9.2"]
},
{
"name": "Configure Docker",
"subtasks": [
"Create Dockerfiles",
"Write docker-compose.yml",
"Set up volumes and networks"
],
"requirements": ["REQ-12.2", "REQ-12.3"]
}
]
},
{
"name": "Backend Implementation",
"tasks": [
{
"name": "Create data models",
"subtasks": [
"Define entities",
"Create validation schemas",
"Implement serialization"
],
"requirements": ["REQ-3.1"],
"dependencies": ["1.2"]
},
{
"name": "Implement service layer",
"subtasks": [
"Create business logic services",
"Implement validation rules",
"Add error handling"
],
"requirements": ["REQ-4.1"],
"dependencies": ["2.1"]
},
{
"name": "Build API endpoints",
"subtasks": [
"Create REST/GraphQL routes",
"Add authentication middleware",
"Implement request validation"
],
"requirements": ["REQ-5.1"],
"dependencies": ["2.2"]
}
]
},
{
"name": "Frontend Implementation",
"tasks": [
{
"name": "Set up frontend framework",
"subtasks": [
"Initialize React/Vue/Angular app",
"Configure build tools",
"Set up routing"
],
"requirements": ["REQ-7.1"]
},
{
"name": "Create UI components",
"subtasks": [
"Build reusable components",
"Implement responsive design",
"Add styling/theming"
],
"requirements": ["REQ-7.2"],
"dependencies": ["3.1"]
},
{
"name": "Integrate with backend",
"subtasks": [
"Set up API client",
"Implement state management",
"Add error handling"
],
"requirements": ["REQ-7.3"],
"dependencies": ["2.3", "3.2"]
}
]
},
{
"name": "Testing and Quality Assurance",
"tasks": [
{
"name": "Write unit tests",
"subtasks": [
"Test services",
"Test components",
"Test utilities"
],
"requirements": ["REQ-13.1"],
"dependencies": ["2.2", "3.2"]
},
{
"name": "Create integration tests",
"subtasks": [
"Test API endpoints",
"Test database operations",
"Test external integrations"
],
"requirements": ["REQ-13.2"],
"dependencies": ["4.1"]
},
{
"name": "Perform end-to-end testing",
"subtasks": [
"Test user workflows",
"Test error scenarios",
"Performance testing"
],
"requirements": ["REQ-13.3"],
"dependencies": ["4.2"]
}
]
},
{
"name": "Deployment and Documentation",
"tasks": [
{
"name": "Set up CI/CD pipeline",
"subtasks": [
"Configure build automation",
"Set up test automation",
"Configure deployment"
],
"requirements": ["REQ-14.1"],
"dependencies": ["4.3"]
},
{
"name": "Write documentation",
"subtasks": [
"API documentation",
"User guide",
"Deployment guide"
],
"requirements": ["REQ-15.1"],
"dependencies": ["5.1"]
},
{
"name": "Deploy to production",
"subtasks": [
"Set up production environment",
"Configure monitoring",
"Perform deployment"
],
"requirements": ["REQ-14.2"],
"dependencies": ["5.2"]
}
]
}
]
elif self.project_type == "cli-tool":
return [
{
"name": "Project Setup",
"tasks": [
{
"name": "Initialize project",
"subtasks": [
"Set up package structure",
"Configure build system",
"Add dependencies"
]
},
{
"name": "Design command structure",
"subtasks": [
"Define commands and subcommands",
"Plan argument parsing",
"Design configuration schema"
]
}
]
},
{
"name": "Core Implementation",
"tasks": [
{
"name": "Implement command parser",
"subtasks": [
"Create argument parser",
"Add command handlers",
"Implement help system"
],
"dependencies": ["1.2"]
},
{
"name": "Build core logic",
"subtasks": [
"Implement business logic",
"Add validation",
"Handle errors"
],
"dependencies": ["2.1"]
}
]
},
{
"name": "Testing and Packaging",
"tasks": [
{
"name": "Write tests",
"subtasks": [
"Unit tests",
"Integration tests",
"CLI tests"
],
"dependencies": ["2.2"]
},
{
"name": "Package and distribute",
"subtasks": [
"Create package",
"Write documentation",
"Publish"
],
"dependencies": ["3.1"]
}
]
}
]
elif self.project_type == "api-service":
return [
{
"name": "Service Setup",
"tasks": [
{
"name": "Initialize API project",
"subtasks": [
"Set up framework",
"Configure database",
"Add middleware"
]
},
{
"name": "Design API schema",
"subtasks": [
"Define endpoints",
"Create OpenAPI spec",
"Plan authentication"
]
}
]
},
{
"name": "API Implementation",
"tasks": [
{
"name": "Create endpoints",
"subtasks": [
"Implement routes",
"Add validation",
"Handle errors"
],
"dependencies": ["1.2"]
},
{
"name": "Add authentication",
"subtasks": [
"Implement auth middleware",
"Add JWT/OAuth",
"Set up permissions"
],
"dependencies": ["2.1"]
}
]
}
]
else: # Generic project
return [
{
"name": "Project Setup",
"tasks": [
{
"name": "Initialize project",
"subtasks": ["Create structure", "Set up tools"]
}
]
},
{
"name": "Implementation",
"tasks": [
{
"name": "Build core features",
"subtasks": ["Implement logic", "Add tests"]
}
]
},
{
"name": "Deployment",
"tasks": [
{
"name": "Prepare for production",
"subtasks": ["Test", "Document", "Deploy"]
}
]
}
]
def generate_all_documents(self,
features: List[str] = None,
components: List[str] = None,
output_dir: str = ".") -> Dict[str, str]:
"""Generate all three documents"""
# Use defaults if not provided
if not features:
features = [
"to authenticate and manage my account",
"to create and manage resources",
"to view analytics and reports",
"to configure system settings",
"to receive notifications"
]
if not components:
components = [
"Authentication Service",
"User Management",
"Resource Manager",
"Analytics Engine",
"Notification Service"
]
# Generate documents
docs = {
"requirements.md": self.generate_requirements_template(features),
"design.md": self.generate_design_template(components),
"tasks.md": self.generate_tasks_template(self.get_default_phases())
}
# Save to files
os.makedirs(output_dir, exist_ok=True)
for filename, content in docs.items():
filepath = os.path.join(output_dir, filename)
with open(filepath, 'w') as f:
f.write(content)
print(f"Generated: {filepath}")
return docs
def main():
parser = argparse.ArgumentParser(description="Generate project planning documents")
parser.add_argument("project_name", help="Name of the project")
parser.add_argument("--type", default="web-app",
choices=["web-app", "cli-tool", "api-service", "generic"],
help="Type of project")
parser.add_argument("--features", nargs="+",
help="List of features for requirements")
parser.add_argument("--components", nargs="+",
help="List of components for design")
parser.add_argument("--output", default=".",
help="Output directory for documents")
args = parser.parse_args()
generator = ProjectDocumentGenerator(args.project_name, args.type)
generator.generate_all_documents(
features=args.features,
components=args.components,
output_dir=args.output
)
print(f"\n✅ Successfully generated project documents for '{args.project_name}'")
print(f" Type: {args.type}")
print(f" Location: {args.output}/")
print("\nNext steps:")
print("1. Review and customize the generated documents")
print("2. Fill in the [PLACEHOLDER] sections")
print("3. Add project-specific requirements and design details")
print("4. Use these documents as input for AI-assisted implementation")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,325 @@
#!/usr/bin/env python3
"""
Document Validator
Validates project planning documents for completeness and consistency
"""
import re
import argparse
from typing import List, Dict, Tuple
import os
class DocumentValidator:
def __init__(self):
self.errors = []
self.warnings = []
def validate_requirements(self, content: str) -> Tuple[List[str], List[str]]:
"""Validate requirements document structure and content"""
errors = []
warnings = []
# Check required sections
required_sections = [
"## Introduction",
"## Glossary",
"## Requirements"
]
for section in required_sections:
if section not in content:
errors.append(f"Missing required section: {section}")
# Check for user stories
user_story_pattern = r"\*\*User Story:\*\*.*As a.*I want.*so that"
if not re.search(user_story_pattern, content, re.DOTALL):
warnings.append("No user stories found in requirements")
# Check for acceptance criteria
if "Acceptance Criteria" not in content:
errors.append("No acceptance criteria found")
# Check for SHALL statements
shall_count = content.count("SHALL")
if shall_count < 5:
warnings.append(f"Only {shall_count} SHALL statements found (recommend at least 5)")
# Check for requirement numbering
req_pattern = r"### Requirement \d+|### REQ-\d+"
req_matches = re.findall(req_pattern, content)
if len(req_matches) < 3:
warnings.append(f"Only {len(req_matches)} numbered requirements found")
# Check for placeholders
placeholder_pattern = r"\[.*?\]"
placeholders = re.findall(placeholder_pattern, content)
if len(placeholders) > 10:
warnings.append(f"Found {len(placeholders)} placeholders - remember to fill them in")
return errors, warnings
def validate_design(self, content: str) -> Tuple[List[str], List[str]]:
"""Validate design document structure and content"""
errors = []
warnings = []
# Check required sections
required_sections = [
"## Overview",
"## System Architecture",
"## Data Flow",
"## Integration Points",
"## Components",
"## Data Models",
"## Deployment"
]
for section in required_sections:
if section not in content:
errors.append(f"Missing required section: {section}")
# Check for component map
if "Component Map" not in content and "| Component ID |" not in content:
errors.append("Missing Component Map table")
# Check for data flow specifications
if "Data Flow" not in content:
errors.append("Missing Data Flow specifications")
# Check for integration points
if "Integration Points" not in content:
errors.append("Missing Integration Points section")
# Check for system boundaries
if "System Boundaries" not in content and "In Scope" not in content:
warnings.append("Missing System Boundaries definition")
# Check for architecture diagram
if "```" not in content and "" not in content:
warnings.append("No architecture diagram found")
# Check for interfaces
if "class" not in content and "interface" not in content.lower():
warnings.append("No interface definitions found")
# Check for error handling
if "Error Handling" not in content and "error handling" not in content.lower():
warnings.append("No error handling section found")
# Check for performance targets
if "Performance" not in content and "performance" not in content.lower():
warnings.append("No performance targets specified")
# Check for Docker configuration
if "Docker" not in content and "docker" not in content:
warnings.append("No Docker configuration found")
return errors, warnings
def validate_tasks(self, content: str) -> Tuple[List[str], List[str]]:
"""Validate implementation plan structure and content"""
errors = []
warnings = []
# Check for project boundaries
if "## Project Boundaries" not in content:
errors.append("Missing Project Boundaries section")
if "Must Have" not in content:
warnings.append("Missing 'Must Have' scope definition")
if "Out of Scope" not in content:
warnings.append("Missing 'Out of Scope' definition")
# Check for deliverables
if "## Deliverables" not in content and "Deliverables by Phase" not in content:
warnings.append("Missing Deliverables section")
# Check for success criteria
if "Success Criteria" not in content:
warnings.append("Missing Success Criteria for deliverables")
# Check for task structure
phase_pattern = r"- \[[ x]\] \d+\."
phases = re.findall(phase_pattern, content)
if len(phases) == 0:
errors.append("No phases found in task list")
elif len(phases) < 3:
warnings.append(f"Only {len(phases)} phases found (recommend at least 3)")
# Check for subtasks
task_pattern = r" - \[[ x]\] \d+\.\d+"
tasks = re.findall(task_pattern, content)
if len(tasks) == 0:
errors.append("No tasks found in implementation plan")
elif len(tasks) < 10:
warnings.append(f"Only {len(tasks)} tasks found (recommend at least 10)")
# Check for requirement tracing
req_pattern = r"_Requirements:.*REQ-\d+|_Requirements:.*\d+\.\d+"
req_traces = re.findall(req_pattern, content)
if len(req_traces) == 0:
warnings.append("No requirement tracing found in tasks")
elif len(req_traces) < len(tasks) / 2:
warnings.append(f"Only {len(req_traces)} tasks have requirement tracing")
# Check for component involvement
comp_pattern = r"_Components:.*COMP-\d+"
comp_traces = re.findall(comp_pattern, content)
if len(comp_traces) == 0:
warnings.append("No component mapping found in tasks")
# Check for dependencies
dep_pattern = r"_Dependencies:"
dependencies = re.findall(dep_pattern, content)
if len(dependencies) == 0:
warnings.append("No task dependencies defined")
# Check completion status
completed_pattern = r"- \[x\]"
pending_pattern = r"- \[ \]"
completed = len(re.findall(completed_pattern, content))
pending = len(re.findall(pending_pattern, content))
if completed + pending > 0:
completion_rate = (completed / (completed + pending)) * 100
print(f"Task completion: {completed}/{completed + pending} ({completion_rate:.1f}%)")
return errors, warnings
def validate_consistency(self, req_content: str, design_content: str,
task_content: str) -> Tuple[List[str], List[str]]:
"""Check consistency across documents"""
errors = []
warnings = []
# Extract requirement IDs from requirements doc
req_ids = set()
req_pattern = r"### Requirement (\d+)|### REQ-(\d+)"
for match in re.finditer(req_pattern, req_content):
req_id = match.group(1) or match.group(2)
req_ids.add(f"REQ-{req_id}")
# Check if requirements are referenced in tasks
for req_id in req_ids:
if req_id not in task_content:
warnings.append(f"{req_id} not referenced in any tasks")
# Extract components from design
component_pattern = r"### .*(?:Service|Component|Manager|Engine|Handler)"
components = re.findall(component_pattern, design_content)
# Check if major components have corresponding tasks
for component in components:
component_name = component.replace("### ", "").strip()
if component_name.lower() not in task_content.lower():
warnings.append(f"Component '{component_name}' not mentioned in tasks")
return errors, warnings
def validate_all(self, req_file: str, design_file: str,
task_file: str) -> Dict[str, Tuple[List[str], List[str]]]:
"""Validate all three documents"""
results = {}
# Read files
with open(req_file, 'r') as f:
req_content = f.read()
with open(design_file, 'r') as f:
design_content = f.read()
with open(task_file, 'r') as f:
task_content = f.read()
# Validate individual documents
results['requirements'] = self.validate_requirements(req_content)
results['design'] = self.validate_design(design_content)
results['tasks'] = self.validate_tasks(task_content)
# Validate consistency
results['consistency'] = self.validate_consistency(
req_content, design_content, task_content
)
return results
def print_validation_results(results: Dict[str, Tuple[List[str], List[str]]]):
"""Print validation results in a formatted way"""
total_errors = 0
total_warnings = 0
for doc_name, (errors, warnings) in results.items():
print(f"\n{'='*50}")
print(f"Validation Results: {doc_name.upper()}")
print('='*50)
if errors:
print(f"\n❌ Errors ({len(errors)}):")
for error in errors:
print(f" - {error}")
total_errors += len(errors)
else:
print("\n✅ No errors found")
if warnings:
print(f"\n⚠️ Warnings ({len(warnings)}):")
for warning in warnings:
print(f" - {warning}")
total_warnings += len(warnings)
else:
print("\n✅ No warnings found")
# Summary
print(f"\n{'='*50}")
print("SUMMARY")
print('='*50)
if total_errors == 0 and total_warnings == 0:
print("✅ All documents are valid and complete!")
else:
print(f"Total Errors: {total_errors}")
print(f"Total Warnings: {total_warnings}")
if total_errors > 0:
print("\n⚠️ Please fix errors before using these documents")
else:
print("\n📝 Review warnings to improve document quality")
def main():
parser = argparse.ArgumentParser(description="Validate project planning documents")
parser.add_argument("--requirements", "-r", default="requirements.md",
help="Path to requirements document")
parser.add_argument("--design", "-d", default="design.md",
help="Path to design document")
parser.add_argument("--tasks", "-t", default="tasks.md",
help="Path to tasks/implementation plan")
args = parser.parse_args()
# Check if files exist
for filepath, name in [(args.requirements, "Requirements"),
(args.design, "Design"),
(args.tasks, "Tasks")]:
if not os.path.exists(filepath):
print(f"{name} file not found: {filepath}")
return 1
# Validate documents
validator = DocumentValidator()
results = validator.validate_all(args.requirements, args.design, args.tasks)
# Print results
print_validation_results(results)
# Return exit code based on errors
total_errors = sum(len(errors) for errors, _ in results.values())
return 1 if total_errors > 0 else 0
if __name__ == "__main__":
exit(main())