Content Repurposing Engine - Migration Guide
Step 1: Database Migration
Run the Prisma migration to add the new tables and fields:
cd packages/db
npx prisma migrate dev --name add_content_repurposing
npx prisma generateThis will:
- Add
sourceDeliverableId,sourceActivityId,derivativeType,sourceVersionto Activity table - Create
repurposing_templatetable - Create
repurposing_analyticstable - Add indexes for optimal query performance
Step 2: Update Type Definitions
TypeScript types are automatically generated by Prisma. Rebuild packages:
pnpm run build --filter=@leadmetrics/db
pnpm run build --filter=@leadmetrics/queueStep 3: Start the Worker
The content-repurposer worker needs to be added to your worker startup script.
Edit: apps/api/src/start-workers.ts (or wherever your workers are initialized)
Add the import:
import contentRepurposerWorker from "@leadmetrics/agents/src/workers/content-repurposer.worker";The worker will automatically connect to Redis and start processing jobs from the agent__content-repurposer queue.
Step 4: Seed Default Templates (Optional)
You can optionally seed default repurposing templates into the database:
cd packages/db
npx tsx scripts/seed-repurposing-templates.tsCreate this script at packages/db/scripts/seed-repurposing-templates.ts:
Step 5: Access Template Management Portal
The template management portal is available at:
URL: https://manage.yourdomain.com/templates/repurposing
Features:
- View all global and tenant-specific templates
- Create custom templates with your own prompts
- Edit tenant-specific templates (global templates are read-only)
- Clone global templates to create tenant customizations
- Toggle templates active/inactive
- Configure credit costs per template
- Search and filter templates
Access Control:
- Only accessible to manage app users (admin/DM team)
- Tenant users cannot modify templates
- Global templates can only be created/edited by system admins
Step 6: View Analytics Dashboard
The analytics dashboard is available at:
URL: https://dashboard.yourdomain.com/analytics/repurposing
Metrics Available:
- Total repurposings and derivatives created
- Credits used vs credits saved (ROI calculation)
- Daily activity timeline
- Source type breakdown
- Target type distribution
- Top 10 most-used repurposing paths
- Personalized recommendations
Data Retention:
- Default view: Last 30 days
- Expandable to 7 or 90 days
- Real-time updates as content is repurposed
import { db } from "../src";
const TEMPLATES = [
{
sourceType: "blog_post",
targetType: "social_post",
name: "Blog to Social Post",
description: "Transform blog content into engaging social media posts",
creditCost: 0.5,
promptTemplate: `You are a social media content strategist...` // Copy from worker
},
// Add all other templates from the worker prompts
];
async function seed() {
for (const template of TEMPLATES) {
await db.repurposingTemplate.upsert({
where: {
tenantId_sourceType_targetType: {
tenantId: null, // Global template
sourceType: template.sourceType,
targetType: template.targetType,
},
},
create: { ...template, tenantId: null },
update: { ...template },
});
}
console.log(`✅ Seeded ${TEMPLATES.length} repurposing templates`);
}
seed().finally(() => db.$disconnect());Step 5: Test the Feature
- Navigate to an approved blog post in the dashboard
- Click the “Repurpose Content” button
- Select target formats (e.g., Social Post, Email, Thread)
- Click “Repurpose Content”
- Check the Activities page - you should see new pending activities
- Monitor the worker logs to see the repurposing in progress
- Once complete, you’ll receive a notification
- Review and approve the derivatives
Step 6: Monitor & Optimize
Check Analytics
Query the analytics table to see usage patterns:
SELECT
sourceType,
targetType,
COUNT(*) as total_repurposings,
AVG(derivativeCount) as avg_derivatives_per_batch,
SUM(totalCreditsUsed) as total_credits
FROM repurposing_analytics
GROUP BY sourceType, targetType
ORDER BY total_repurposings DESC;Monitor Worker Health
Check Redis queue metrics:
redis-cli
> LLEN agent__content-repurposer:waiting
> LLEN agent__content-repurposer:active
> LLEN agent__content-repurposer:completed
> LLEN agent__content-repurposer:failedView Logs
Worker logs will show:
- Batch processing started
- Each derivative generation
- Success/failure per derivative
- Credit consumption
- Analytics recording
Troubleshooting
Worker not processing jobs
- Check if worker is running:
ps aux | grep content-repurposer - Check Redis connection: Worker should log ”🚀 Content repurposer worker started”
- Check queue:
redis-cli LLEN agent__content-repurposer:waiting
Derivatives not appearing
- Check Activity table for records with
agentQueue = 'content-repurposer' - Check worker logs for errors
- Verify Claude adapter is working (check credits balance)
Credits not deducted
- Check if
billingpackage credit functions are working - Verify tenant has sufficient credits
- Check
credit_ledgertable for repurposing entries
Templates not applying
- Check if
templateIdis passed in job data - Verify template exists in
repurposing_templatetable - Check template
isActivefield is true
Performance Tuning
Worker Concurrency
Adjust concurrency in content-repurposer.worker.ts:
const worker = new Worker<ContentRepurposerJobData>(queueName, processJob, {
connection: getRedisConnection(),
concurrency: 5, // Increase for more parallel processing
limiter: {
max: 20, // Max jobs per minute
duration: 60_000,
},
});Rate Limiting
If hitting Claude API rate limits, reduce concurrency or add delays:
// Add between derivatives in same batch
await new Promise(resolve => setTimeout(resolve, 1000)); // 1 second delayCredit Costs
Adjust credit costs per repurposing path in RepurposingTemplate table or override in worker.
Next Steps
- Template Management Portal - Build UI in manage app for editing templates
- Analytics Dashboard - Visualize repurposing usage patterns
- Bulk Repurposing - Enable selecting multiple sources
- A/B Testing - Generate multiple variants per derivative
- Smart Suggestions - Auto-suggest optimal repurposing paths
🎉 Content Repurposing Engine is ready to use!