self-replicating/docs/workflow-specifications.md

566 lines
10 KiB
Markdown

# Workflow Specifications
Detailed specifications for all 8 autonomous workflows in the Self-Replicating Business System.
## Workflow Execution Model
All workflows extend `WorkflowBase` which provides:
- ✅ Automatic retry logic (3 attempts with exponential backoff)
- ✅ Error handling and logging
- ✅ Database state tracking
- ✅ Alert integration
- ✅ Execution metrics
---
## 1. Market Validation Workflow
**Type**: `MARKET_VALIDATION`
**Phase**: Validation (Sequential)
**Critical**: Yes (pauses business on failure)
### Purpose
Determine if a business idea is viable before investing resources.
### Inputs
- Business ID
- Business idea (text)
- Business name
### Process
1. **Competitor Search**
- Google Custom Search API (if configured)
- Fallback: Web scraping
- Returns: Top 5 competitors with URLs, descriptions
2. **Demand Analysis**
- Google Trends API
- Search volume estimation
- Trend direction (rising/stable/declining)
- Seasonality detection
3. **Claude AI Analysis**
- Combines competitor data + demand data
- Generates viability score (0-100)
- Identifies top 3 risks
- Identifies top 3 opportunities
- Makes go/no-go recommendation
4. **Decision**
- Score ≥ 60 && Viable = Proceed to MVP
- Score < 60 || Not Viable = Shutdown business
### Outputs
```json
{
"viable": true,
"score": 75,
"analysis": "Strong market opportunity...",
"risks": ["High competition", "Seasonal demand", "..."],
"opportunities": ["Underserved niche", "Growing market", "..."],
"competitors": [...],
"demandData": {...}
}
```
### Success Criteria
- Competitor search finds 2+ competitors
- Demand data shows search volume > 100/month
- Claude analysis completes within 30 seconds
---
## 2. MVP Development Workflow
**Type**: `MVP_DEVELOPMENT`
**Phase**: Development (Sequential)
**Critical**: Yes (pauses business on failure)
### Purpose
Generate and deploy a functional MVP product.
### Inputs
- Business ID
- Business idea
- Business name
### Process
1. **Code Generation**
- Claude generates Next.js 14+ code
- Includes: Landing page, API routes, Tailwind styling
- Returns: Map of filename → code content
2. **Local Storage**
- Saves code to `/data/businesses/{id}/mvp/`
- Creates directory structure
- Writes all files
- Generates README
3. **Git Initialization** (if Vercel enabled)
- `git init`
- `git add .`
- `git commit -m "Initial commit"`
4. **Deployment** (if Vercel token configured)
- Creates vercel.json
- Runs `vercel --prod`
- Extracts deployment URL
5. **Database Update**
- Stores MVP URL
- Updates status to `LAUNCHING`
### Outputs
```json
{
"mvpUrl": "https://business-abc123.vercel.app",
"filesGenerated": 8,
"projectDir": "/data/businesses/abc123/mvp"
}
```
### Success Criteria
- Generates minimum 5 files
- Deployment succeeds (or saves locally)
- MVP URL is accessible
---
## 3. Landing Page SEO Workflow
**Type**: `LANDING_PAGE_SEO`
**Phase**: Marketing (Parallel)
**Critical**: No
### Purpose
Optimize landing page for search engines and organic traffic.
### Inputs
- Business ID
- Business idea
- Target audience
### Process
1. **Keyword Research**
- Extract seed keywords from idea
- Use Claude SEO Expert skill
- Generate keyword list (10-20 keywords)
2. **SEO Strategy**
- Claude generates comprehensive SEO plan
- On-page optimization tips
- Technical SEO checklist
- Link building strategy
3. **Content Optimization** (if MVP exists)
- Analyze current content
- Generate optimized copy
- Meta title (60 chars)
- Meta description (155 chars)
- H1, H2 tags
4. **Content Calendar**
- Generate 10-20 blog post ideas
- Keyword-focused topics
- Publishing schedule
5. **Database Update**
- Set `seoOptimized = true`
### Outputs
```json
{
"keywordResearch": "...",
"seoStrategy": "...",
"contentIdeas": [...]
}
```
### Success Criteria
- Keyword list generated
- SEO strategy document created
- Content calendar populated
---
## 4. Paid Ads Workflow
**Type**: `PAID_ADS`
**Phase**: Marketing (Parallel)
**Critical**: No
### Purpose
Launch paid advertising campaigns on Facebook and Google.
### Inputs
- Business ID
- Business idea
- Budget
- Target audience
### Process
1. **Facebook Ads**
- Claude Ads Expert generates strategy
- Creates campaign via Facebook Ads API
- Objective: CONVERSIONS
- Budget: From business.budget or $500 default
- Saves campaign to database
2. **Google Ads**
- Claude Ads Expert generates strategy
- Creates Search campaign via Google Ads API
- Keywords: Extracted from idea
- Budget: From business.budget or $500 default
- Saves campaign to database
3. **Database Update**
- Set `adsActive = true`
- Set status = `RUNNING_ADS`
### Outputs
```json
{
"facebook": {
"success": true,
"campaignId": "fb_123456",
"strategy": "..."
},
"google": {
"success": true,
"campaignId": "google_789012",
"strategy": "..."
}
}
```
### Success Criteria
- At least 1 campaign created (FB or Google)
- Campaign is active
- Budget allocated correctly
---
## 5. Content Marketing Workflow
**Type**: `CONTENT_MARKETING`
**Phase**: Marketing (Parallel)
**Critical**: No
### Purpose
Create and publish SEO-optimized content.
### Inputs
- Business ID
- Business idea
- Keywords
### Process
1. **Content Generation**
- Claude generates SEO-optimized content
- Meta title, description
- Headlines (H1, H2, H3)
- 500+ word landing page copy
2. **Publishing** (future)
- Publish to CMS
- Schedule blog posts
- Social media sharing
### Outputs
```json
{
"contentGenerated": true,
"contentLength": 1200
}
```
### Success Criteria
- Content generated (500+ words)
- SEO-optimized format
---
## 6. Email Automation Workflow
**Type**: `EMAIL_AUTOMATION`
**Phase**: Marketing (Parallel)
**Critical**: No
### Purpose
Set up email sequences for lead nurturing.
### Inputs
- Business ID
- Business name
### Process
1. **Template Creation**
- Welcome email
- Onboarding sequence (3-5 emails)
- Drip campaign
2. **Sendgrid Setup** (if configured)
- Create templates via API
- Set up automation rules
3. **Database Update**
- Set `emailAutomation = true`
### Outputs
```json
{
"configured": true,
"templates": 2
}
```
### Success Criteria
- Templates created
- Automation configured
---
## 7. Analytics Setup Workflow
**Type**: `ANALYTICS_SETUP`
**Phase**: Marketing (Parallel)
**Critical**: No
### Purpose
Install tracking and analytics for data-driven optimization.
### Inputs
- Business ID
- MVP URL
### Process
1. **Google Analytics**
- Create GA4 property
- Install tracking code
- Set up conversion goals
2. **Meta Pixel**
- Create Facebook Pixel
- Install pixel code
- Configure custom events
3. **Conversion Tracking**
- Track: page views, signups, purchases
- Configure event tracking
### Outputs
```json
{
"googleAnalytics": {
"configured": true,
"trackingId": "G-XXXXXXXXXX"
},
"metaPixel": {
"configured": true,
"pixelId": "1234567890"
}
}
```
### Success Criteria
- GA4 tracking installed
- Pixel tracking installed
- Events configured
---
## 8. Optimization Loop Workflow
**Type**: `OPTIMIZATION_LOOP`
**Phase**: Continuous (Forever)
**Critical**: No
### Purpose
Continuously optimize campaigns and budgets for maximum ROI.
### Schedule
Runs every 24 hours (configurable via `OPTIMIZATION_INTERVAL_MINUTES`)
### Inputs
- Business ID
### Process
1. **Metrics Collection**
- Fetch from Google Analytics
- Fetch from Facebook Ads API
- Fetch from Google Ads API
- Aggregate data
2. **Campaign Analysis**
- Calculate ROAS for each campaign
- Calculate CTR, conversion rate
- Classify performance: good/acceptable/poor
3. **Budget Optimization**
- High performers (ROAS > 3): +20% budget
- Poor performers (ROAS < 1): -30% budget
- Record budget changes
4. **Pause Underperformers**
- ROAS < 0.5: Pause campaign
- Losing 50%+ on ad spend
5. **A/B Testing** (future)
- Create ad variants
- Test different copy/targeting
6. **Metrics Recording**
- Save daily snapshot to database
- Update business revenue
### Outputs
```json
{
"metrics": {
"revenue": 5000,
"adSpend": 1500,
"roas": 3.33
},
"budgetChanges": [
{
"campaignId": "...",
"action": "increase_budget",
"change": "+20%"
}
],
"pausedCampaigns": ["..."],
"adTests": {
"testsRunning": 2
}
}
```
### Success Criteria
- Metrics collected successfully
- At least 1 optimization performed
- No campaigns with ROAS < 0.5 left active
---
## Workflow Dependencies
```
Market Validation
└─> MVP Development
└─> [PARALLEL]
├─> Landing Page SEO
├─> Paid Ads
├─> Content Marketing
├─> Email Automation
└─> Analytics Setup
└─> Optimization Loop (forever)
```
## Error Handling
### Retry Policy
- Max retries: 3
- Backoff: Exponential (2s, 4s, 8s)
- Timeout: 2 minutes per attempt
### Failure Actions
**Critical Workflows** (1, 2):
- Pause business
- Send critical alert
- Stop lifecycle execution
**Non-Critical Workflows** (3-8):
- Log error
- Send warning alert
- Continue lifecycle
### Recovery
Workflows can be manually re-run:
```bash
# Retry failed workflow
pnpm retry-workflow --business-id abc123 --type MARKET_VALIDATION
```
---
## Monitoring Workflows
### Database Tracking
Each workflow run creates a `WorkflowRun` record:
```sql
SELECT
workflowType,
status,
attempts,
error,
completedAt - startedAt as duration
FROM "WorkflowRun"
WHERE businessId = 'abc123'
ORDER BY createdAt DESC;
```
### Logs
```bash
# View workflow logs
docker logs srb-orchestrator | grep "MARKET_VALIDATION"
# Real-time monitoring
docker logs -f srb-orchestrator
```
### Metrics
- Execution time (should be < 5 minutes)
- Success rate (should be > 95%)
- Retry rate (should be < 10%)
---
## Extending Workflows
To add a new workflow:
1. Create file: `src/workflows/09-new-workflow.ts`
2. Extend `WorkflowBase`
3. Implement `execute()` method
4. Add to `WorkflowExecutor` map
5. Add to Prisma `WorkflowType` enum
6. Update orchestrator lifecycle
Example:
```typescript
export class NewWorkflow extends WorkflowBase {
protected type: WorkflowType = 'NEW_WORKFLOW';
protected async execute(context: WorkflowContext): Promise<WorkflowResult> {
const business = await this.getBusiness(context.businessId);
// Your logic here
return {
success: true,
data: { ... }
};
}
}
```
---
**Last Updated**: 2026-02-04