#!/usr/bin/env python3
"""
Genesis Platform Mastery Research Swarm
=======================================
Fires 50 parallel Gemini research agents via tmux to investigate:
- Revenue potential of platform KB ingestion → AI agent apps
- Top target platforms
- App launch implementation plans
- Website names per vertical
- Marketing copy
- AI SDK landscape

Each agent writes its output to /mnt/e/genesis-system/research_swarm/
"""

import os
import subprocess
import time
import json
from pathlib import Path

OUTPUT_DIR = Path("/mnt/e/genesis-system/research_swarm")
OUTPUT_DIR.mkdir(exist_ok=True)

TMUX_SESSION = "platform-mastery-swarm"

# ──────────────────────────────────────────────────────────────
# Research Mission Definitions (50 agents)
# ──────────────────────────────────────────────────────────────

MISSIONS = [
    # ═══ WAVE 1: MARKET SIZING & REVENUE (agents 1-8) ═══
    {
        "id": "M01_tam_sizing",
        "prompt": """You are a market research analyst. Calculate the Total Addressable Market (TAM) for "Platform Mastery AI Agents" — AI assistants that have ingested an entire platform's documentation, API reference, and knowledge base, and can guide customers, answer any query, build integrations, and take actions on their behalf.

Consider:
- Number of SaaS platforms with 500+ page documentation
- Average spend on customer support, onboarding, training per platform
- Developer tool market size ($50B+)
- AI agent market projections (2026-2030)
- Platform-specific AI assistant demand

Output a detailed TAM/SAM/SOM analysis with dollar figures and growth rates. Be specific with numbers and cite reasoning."""
    },
    {
        "id": "M02_revenue_models",
        "prompt": """Design 5 distinct revenue models for an AI agent that has ingested an entire platform's knowledge base and can act as a platform expert. The agent can answer questions, write code, configure settings, debug issues, and guide users through complex workflows.

For each model:
1. Pricing structure (tiers, usage-based, enterprise)
2. Target customer segment
3. Unit economics (CAC, LTV, margin)
4. Scalability analysis
5. Competitive moat strength

Models to analyze: (a) B2B SaaS subscription, (b) Marketplace/app-store model, (c) Platform partnership/white-label, (d) Usage-based API, (e) Freemium + premium.

Include specific price points in AUD. Calculate break-even and path to $100K MRR."""
    },
    {
        "id": "M03_competitive_landscape",
        "prompt": """Comprehensive competitive analysis for "Platform Mastery AI Agents" — AI assistants with complete platform knowledge. Research and analyze:

1. **Direct competitors**: Companies building platform-specific AI agents (e.g., Mendable, Inkeep, Glean, Kapa.ai, AskAI, DocsBot)
2. **Platform-native solutions**: Built-in AI assistants (Salesforce Einstein, HubSpot AI, Shopify Sidekick, AWS Q)
3. **Horizontal AI tools**: ChatGPT plugins, Claude MCP, Gemini extensions
4. **Developer tool companies**: Cursor, Replit, GitHub Copilot (for code-specific platforms)

For each competitor: pricing, features, limitations, market share, funding.
Identify the GAP that Genesis can exploit. What do they all miss?"""
    },
    {
        "id": "M04_platform_pain_points",
        "prompt": """Research the top pain points that platform users experience that an AI agent with complete platform knowledge could solve:

1. **Onboarding friction**: Average time to first value for complex platforms (Salesforce: 3-6 months, AWS: weeks)
2. **Support costs**: Average cost per support ticket ($15-$40), resolution time, tier escalation rates
3. **Documentation maze**: Users can't find answers in 10,000+ page docs
4. **Integration complexity**: Average time to build integrations between platforms
5. **Training costs**: Enterprise platform training market ($2-5K per person)
6. **Developer experience**: Time wasted searching Stack Overflow, forums, docs

Quantify each pain point with dollar amounts and time costs. This is the VALUE PROPOSITION for platform mastery agents."""
    },
    {
        "id": "M05_pricing_strategy",
        "prompt": """Design the optimal pricing strategy for "PlatformAI" — a product that creates AI agents with complete platform knowledge for any SaaS platform.

Tiers (in AUD):
- Starter: What features, what price, what limits?
- Professional: What additional features justify 2x price?
- Enterprise: What premium features, custom pricing?
- Platform Partner: Revenue share model with the platform itself?

Consider:
- Cost to ingest a platform's KB (Gemini embedding costs, storage, compute)
- Cost to serve queries (inference, RAG retrieval)
- Willingness to pay by segment (freelancer, SMB, enterprise, platform vendor)
- Competitive pricing benchmarks (Kapa.ai charges $X, Mendable charges $Y)

Output a complete pricing page spec with feature comparison table."""
    },
    {
        "id": "M06_unit_economics",
        "prompt": """Calculate detailed unit economics for a Platform Mastery AI Agent business:

COSTS per platform agent:
- KB ingestion: sitemap crawl + HTML extraction + chunking + embedding (Gemini text-embedding-004, 3072d)
- Vector storage: Qdrant/Cloudflare Vectorize
- Inference: serving queries via Claude/Gemini/local models
- Infrastructure: Cloudflare Workers ($10/mo), Elestio PG ($46/mo)
- Maintenance: re-crawling for freshness (weekly? monthly?)

REVENUE per agent:
- Subscription pricing at $97/$297/$997/mo tiers
- Expected queries per day per customer
- Upsell rate to higher tiers

Calculate:
- Gross margin per agent
- Break-even number of customers
- Path to $50K MRR, $100K MRR, $1M ARR
- Infrastructure cost at 100, 1000, 10000 agents"""
    },
    {
        "id": "M07_go_to_market",
        "prompt": """Design a complete go-to-market strategy for launching Platform Mastery AI Agents.

Phase 1 (Month 1-2): MVP Launch
- Which 3 platforms to launch with first and WHY?
- How to acquire first 10 customers
- Content marketing strategy
- Community building (Reddit, HN, Product Hunt)

Phase 2 (Month 3-6): Scale
- Paid acquisition channels
- Platform marketplace listings (Salesforce AppExchange, Shopify App Store, etc.)
- Partnership with platform vendors
- Agency/consultant channel

Phase 3 (Month 6-12): Moat
- Network effects strategy
- Platform coverage expansion (new platforms per month)
- Enterprise sales motion
- White-label/API offering

Include specific tactics, budgets, and expected results for each phase."""
    },
    {
        "id": "M08_partnership_strategy",
        "prompt": """Design a partnership strategy for Platform Mastery AI Agents — getting the PLATFORM VENDORS themselves to partner with or acquire the agent.

For each of the top 10 platforms (Salesforce, HubSpot, Shopify, Stripe, AWS, Twilio, Telnyx, Zendesk, Intercom, Atlassian):
1. What's their current AI/support strategy?
2. Where does a Genesis platform agent add value they can't build themselves?
3. What's the partnership pitch? (reduce support costs, improve onboarding, increase API adoption)
4. Revenue model: co-sell, white-label, rev-share, acquisition?
5. Contact strategy: who to reach, through what channel

This is the $10M+ play — platform vendors paying Genesis to power their AI assistants."""
    },

    # ═══ WAVE 2: TOP TARGET PLATFORMS (agents 9-28) ═══
    {
        "id": "M09_target_salesforce",
        "prompt": """Deep analysis of Salesforce as a target for Platform Mastery AI Agent:
- Documentation size (pages, API endpoints, objects)
- Customer pain points with Salesforce (complexity, admin overhead, Apex learning curve)
- Existing AI solutions (Einstein AI, Agentforce) - gaps and limitations
- Developer ecosystem size
- Pricing opportunity (what would Salesforce admins/devs pay?)
- Technical feasibility (sitemap structure, API docs format)
- Competitive agents already serving Salesforce
- Website name suggestion for a Salesforce-mastery AI agent
- One-paragraph marketing pitch"""
    },
    {
        "id": "M10_target_hubspot",
        "prompt": """Deep analysis of HubSpot as a target for Platform Mastery AI Agent:
- Documentation size (pages, API endpoints, CRM objects)
- Customer pain points (workflow complexity, integration challenges, migration from Salesforce)
- Existing AI solutions (ChatSpot, Breeze AI) - gaps
- Developer/agency ecosystem size
- Pricing opportunity
- Technical feasibility
- Website name suggestion
- One-paragraph marketing pitch
- Specific use cases the agent would handle (portal setup, workflow debugging, API integration help)"""
    },
    {
        "id": "M11_target_shopify",
        "prompt": """Deep analysis of Shopify as a target for Platform Mastery AI Agent:
- Documentation size (Liquid docs, API reference, Plus features, Hydrogen/Remix)
- Customer pain points (theme customization, app conflicts, checkout optimization)
- Existing AI (Sidekick/Magic) - what it can't do
- Developer/agency ecosystem (200K+ Shopify partners)
- Pricing opportunity for merchants AND agencies
- Website name suggestion
- Marketing pitch
- Key use cases: Liquid code help, app recommendation, store optimization, migration assistance"""
    },
    {
        "id": "M12_target_stripe",
        "prompt": """Deep analysis of Stripe as a target for Platform Mastery AI Agent:
- Documentation size (API reference, guides, Stripe CLI docs)
- Customer pain points (webhook debugging, subscription logic, PCI compliance)
- Existing AI solutions - gaps
- Developer ecosystem size
- Pricing opportunity
- Technical feasibility (docs.stripe.com structure)
- Website name suggestion
- Marketing pitch
- Key use cases: payment flow debugging, subscription setup, Connect onboarding, Stripe Tax config"""
    },
    {
        "id": "M13_target_aws",
        "prompt": """Deep analysis of AWS as a target for Platform Mastery AI Agent:
- Documentation size (200+ services, tens of thousands of pages)
- Customer pain points (service selection, IAM complexity, cost optimization, architecture decisions)
- Existing AI (Amazon Q, CodeWhisperer) - limitations
- Developer ecosystem (millions)
- Pricing opportunity (enterprises spend $1M+ on AWS training)
- Technical feasibility (massive doc corpus)
- Website name suggestion
- Marketing pitch
- Key use cases: architecture review, cost optimization, IAM policy generation, service recommendation"""
    },
    {
        "id": "M14_target_ghl",
        "prompt": """Deep analysis of GoHighLevel (GHL) as a target for Platform Mastery AI Agent:
- Documentation size (help docs, API reference, marketplace)
- Customer pain points (steep learning curve, workflow complexity, white-label setup)
- Current AI limitations in GHL
- Agency ecosystem size (60K+ agencies)
- Pricing opportunity (agencies pay $97-$497/mo for GHL, would pay extra for AI guide)
- Website name suggestion
- Marketing pitch
- Genesis already has 269-tool GHL MCP built — massive head start
- Key use cases: workflow building, pipeline setup, automation debugging, snapshot creation"""
    },
    {
        "id": "M15_target_twilio",
        "prompt": """Deep analysis of Twilio as a target for Platform Mastery AI Agent:
- Documentation size (Voice, SMS, Flex, Verify, SendGrid, Segment)
- Customer pain points (complex API, telephony regulations, migration from legacy)
- Existing AI solutions
- Developer ecosystem size
- Pricing opportunity
- Technical feasibility
- Website name suggestion
- Marketing pitch
- Key use cases: voice app building, SMS workflow setup, Flex contact center config, regulatory compliance"""
    },
    {
        "id": "M16_target_zendesk",
        "prompt": """Deep analysis of Zendesk as a target for Platform Mastery AI Agent:
- Documentation size (Support, Sell, Talk, Guide, Explore)
- Customer pain points (admin complexity, app integration, reporting)
- Existing AI (Zendesk AI agents) - gaps
- Ecosystem size
- Pricing opportunity
- Website name suggestion and marketing pitch
- Key use cases: ticket routing optimization, macro creation, integration setup, analytics"""
    },
    {
        "id": "M17_target_intercom",
        "prompt": """Deep analysis of Intercom as a target for Platform Mastery AI Agent:
- Documentation size
- Customer pain points (Fin AI limitations, workflow builder complexity, pricing)
- Existing AI - gaps
- Website name suggestion and marketing pitch
- Key use cases"""
    },
    {
        "id": "M18_target_atlassian",
        "prompt": """Deep analysis of Atlassian (Jira, Confluence, Bitbucket) as a target for Platform Mastery AI Agent:
- Documentation size (massive — Jira alone has thousands of pages)
- Customer pain points (JQL complexity, workflow customization, Confluence organization, migration to Cloud)
- Existing AI (Atlassian Intelligence, Rovo) - gaps
- Enterprise ecosystem
- Pricing opportunity
- Website name and marketing pitch
- Key use cases: JQL query building, workflow automation, Confluence template creation, migration planning"""
    },
    {
        "id": "M19_target_notion",
        "prompt": """Deep analysis of Notion as a target for Platform Mastery AI Agent:
- Documentation size (API, formulas, database features)
- Customer pain points (formula complexity, database relations, API integration)
- Existing AI - gaps
- Community size (millions of users)
- Pricing opportunity
- Website name and marketing pitch"""
    },
    {
        "id": "M20_target_airtable",
        "prompt": """Deep analysis of Airtable as a target for Platform Mastery AI Agent:
- Documentation size
- Customer pain points (formula limitations, automation complexity, Interface Designer)
- Pricing opportunity
- Website name and marketing pitch"""
    },
    {
        "id": "M21_target_vercel_nextjs",
        "prompt": """Deep analysis of Vercel/Next.js as a target for Platform Mastery AI Agent:
- Documentation size (Next.js docs, Vercel platform, AI SDK, v0.dev)
- Customer pain points (App Router migration, deployment issues, edge runtime)
- Developer ecosystem size (massive)
- Pricing opportunity
- Website name and marketing pitch
- Key advantage: developers would pay for an agent that KNOWS all of Next.js"""
    },
    {
        "id": "M22_target_supabase",
        "prompt": """Deep analysis of Supabase as a target for Platform Mastery AI Agent:
- Documentation size (Auth, Database, Storage, Edge Functions, Realtime, Vector)
- Customer pain points (RLS policies, migration from Firebase, edge function debugging)
- Developer community size
- Pricing opportunity
- Website name and marketing pitch"""
    },
    {
        "id": "M23_target_firebase",
        "prompt": """Deep analysis of Firebase/Google Cloud as a target for Platform Mastery AI Agent:
- Documentation size (massive Google Cloud + Firebase ecosystem)
- Customer pain points (pricing confusion, service selection, Firestore vs Realtime DB)
- Website name and marketing pitch"""
    },
    {
        "id": "M24_target_cloudflare",
        "prompt": """Deep analysis of Cloudflare (Workers, Pages, D1, R2, AI, Zero Trust) as a target for Platform Mastery AI Agent:
- Documentation size
- Customer pain points (Workers runtime differences, D1 limitations, migration from AWS)
- Developer ecosystem growth
- Website name and marketing pitch"""
    },
    {
        "id": "M25_target_telnyx",
        "prompt": """Deep analysis of Telnyx as a target for Platform Mastery AI Agent:
NOTE: Genesis has ALREADY ingested 100% of developers.telnyx.com (1,398 pages, 4,831 vectors).
- What additional value could a customer-facing Telnyx mastery agent provide?
- Pain points for Telnyx customers (SIP trunking setup, number porting, AI assistant config, WebRTC)
- Pricing opportunity
- Website name and marketing pitch
- This would be Genesis's FIRST launched platform agent — proof of concept"""
    },
    {
        "id": "M26_target_n8n",
        "prompt": """Deep analysis of n8n as a target for Platform Mastery AI Agent:
- Documentation size (workflow nodes, expressions, self-hosting)
- Customer pain points (expression syntax, error handling, scaling)
- Community size (growing fast, 50K+ GitHub stars)
- Website name and marketing pitch
- Key advantage: n8n is complex enough that users desperately need guidance"""
    },
    {
        "id": "M27_target_make_zapier",
        "prompt": """Deep analysis of Make (Integromat) and Zapier as targets for Platform Mastery AI Agents:
- Documentation size for each
- Customer pain points (scenario complexity, error handling, pricing at scale)
- Existing AI features and gaps
- Combined ecosystem size
- Website names and marketing pitches for each"""
    },
    {
        "id": "M28_target_wordpress_woocommerce",
        "prompt": """Deep analysis of WordPress/WooCommerce as a target for Platform Mastery AI Agent:
- Documentation size (WordPress Codex, WooCommerce docs, Gutenberg, REST API)
- Customer pain points (plugin conflicts, performance, security, migration)
- Ecosystem size (43% of the web)
- Pricing opportunity (millions of non-technical WordPress users)
- Website name and marketing pitch
- This could be the HIGHEST VOLUME target due to sheer market size"""
    },

    # ═══ WAVE 3: WEBSITE NAMES & BRANDING (agents 29-33) ═══
    {
        "id": "M29_brand_master_strategy",
        "prompt": """Design the master branding strategy for Genesis Platform Mastery AI Agents.

Two approaches to evaluate:
A) **Single brand** — one product name covering all platforms (e.g., "PlatformAI", "DocsGenie", "MasterBot")
B) **Vertical brands** — separate names per platform (e.g., "SalesforceGuru.ai", "ShopifyWhiz.ai")
C) **Hybrid** — parent brand with sub-brands (e.g., "Mastery.ai → Salesforce Mastery, Shopify Mastery")

For each approach:
- Domain availability considerations (.ai, .com, .dev)
- SEO advantages
- Brand recognition potential
- Marketing efficiency
- Customer trust signals

Recommend the BEST approach with 10 name options, checking for:
- Memorable, short, professional
- Clear value proposition in the name
- Available as .ai or .com domain
- Not trademarked by competitors"""
    },
    {
        "id": "M30_website_names_crm",
        "prompt": """Generate 10 website name options for AI agents specializing in CRM platforms (Salesforce, HubSpot, Pipedrive, Zoho):
For each name: domain (.ai/.com), tagline, 2-sentence pitch, estimated domain cost.
Names should be: short, memorable, professional, convey AI expertise.
Also suggest the product landing page structure (hero, features, pricing, demo)."""
    },
    {
        "id": "M31_website_names_devtools",
        "prompt": """Generate 10 website name options for AI agents specializing in developer tools (AWS, Vercel, Supabase, Cloudflare, Stripe):
For each: domain, tagline, pitch.
Focus on developer trust signals — these customers are technical and skeptical."""
    },
    {
        "id": "M32_website_names_automation",
        "prompt": """Generate 10 website name options for AI agents specializing in automation platforms (n8n, Make, Zapier, GHL):
For each: domain, tagline, pitch.
Target audience: agencies, marketers, operations managers."""
    },
    {
        "id": "M33_website_names_ecommerce",
        "prompt": """Generate 10 website name options for AI agents specializing in eCommerce (Shopify, WooCommerce, BigCommerce):
For each: domain, tagline, pitch.
Target audience: store owners, agencies, developers."""
    },

    # ═══ WAVE 4: MARKETING COPY (agents 34-40) ═══
    {
        "id": "M34_marketing_hero_copy",
        "prompt": """Write 5 different hero section copy variations for the Platform Mastery AI Agent product page.

Each variation needs:
- Headline (max 10 words)
- Subheadline (max 25 words)
- 3 bullet points highlighting key benefits
- CTA button text
- Social proof line

The product: An AI agent that has ingested an entire platform's documentation, API reference, and knowledge base. It can answer any question, write code, configure settings, debug issues, and guide users through complex workflows. Think "a senior platform expert available 24/7 for $97/month."

Tone: Professional, confident, not hypey. Australian company."""
    },
    {
        "id": "M35_marketing_use_cases",
        "prompt": """Write detailed use case descriptions for Platform Mastery AI Agents, organized by buyer persona:

1. **Solo Developer**: How does the agent help when stuck on a Stripe webhook or AWS IAM policy?
2. **Agency Owner**: How does it help manage 50+ client accounts across Salesforce/GHL/HubSpot?
3. **Enterprise Admin**: How does it reduce support tickets and onboarding time?
4. **Platform Vendor**: How does it improve developer adoption and reduce support costs?
5. **Non-Technical Business Owner**: How does it let them self-serve on Shopify/WordPress without hiring devs?

For each: 200-word narrative, specific example, quantified benefit, quote-ready testimonial template."""
    },
    {
        "id": "M36_marketing_comparison",
        "prompt": """Write a comparison page: "Platform Mastery AI Agent vs Alternatives"

Compare against:
1. ChatGPT with web browsing (generic, no deep platform knowledge, hallucinates APIs)
2. Platform-native AI (Einstein, Sidekick — limited to that one platform)
3. Hiring a consultant ($150-300/hr vs $97/mo)
4. Reading docs yourself (hours vs seconds)
5. Stack Overflow / forums (outdated, fragmented)

Format as a feature comparison table + narrative explanation of each differentiator.
Be specific about what makes a TRAINED platform agent different from generic AI."""
    },
    {
        "id": "M37_marketing_email_sequences",
        "prompt": """Write a 5-email welcome/onboarding sequence for new Platform Mastery AI Agent customers:

Email 1: Welcome + first query prompt (get them using it immediately)
Email 2: Power tips — 5 things the agent can do they probably don't know about
Email 3: Integration guide — connecting the agent to their workflow
Email 4: Success story / case study template
Email 5: Upgrade prompt — show advanced features in higher tier

For each email: subject line, preview text, full body (300 words max), CTA.
Tone: Helpful, professional, Australian."""
    },
    {
        "id": "M38_marketing_launch_post",
        "prompt": """Write launch content for Platform Mastery AI Agents:

1. **Product Hunt launch post**: Title, tagline, description (300 words), 3 key features, maker comment
2. **Hacker News Show HN post**: Technical angle, architecture mention (RAG + full KB ingestion), honest about limitations
3. **Reddit r/SaaS post**: Business angle, revenue numbers placeholder, lessons learned
4. **LinkedIn post** (Kinan's profile): Founder story, why this matters, CTA
5. **Twitter/X thread**: 10-tweet thread telling the story of building this

Each piece optimized for its platform's culture and algorithm."""
    },
    {
        "id": "M39_marketing_seo_content",
        "prompt": """Design an SEO content strategy for Platform Mastery AI Agents:

1. **Head terms** to target (10 keywords with estimated volume):
   - "AI assistant for [platform]"
   - "[platform] AI agent"
   - "[platform] documentation AI"

2. **Long-tail content** (20 blog post titles):
   - "How to [solve specific platform problem] with AI"
   - "[Platform] vs [Platform]: AI Agent Comparison"

3. **Programmatic SEO** opportunity:
   - Auto-generate landing pages for each platform
   - "[Platform] AI Expert" pages (one per platform, 200+ pages)
   - FAQ pages from actual platform documentation

4. **Link building** strategy:
   - Platform community participation
   - Developer blog guest posts
   - Integration marketplace listings"""
    },
    {
        "id": "M40_marketing_video_scripts",
        "prompt": """Write 3 demo video scripts for Platform Mastery AI Agents:

Script 1: "60-Second Overview" — What is it, how does it work, who is it for, CTA
Script 2: "Technical Deep Dive" (3 min) — Architecture, RAG pipeline, KB ingestion, live demo walkthrough
Script 3: "Customer Story" (2 min) — Agency owner struggling with GHL → discovers platform agent → saves 20hrs/week

For each: shot-by-shot breakdown, voiceover text, screen recording instructions, music suggestions.
These should be producible by a solo founder with screen recording software."""
    },

    # ═══ WAVE 5: TECHNICAL ARCHITECTURE (agents 41-46) ═══
    {
        "id": "M41_tech_architecture",
        "prompt": """Design the complete technical architecture for a Platform Mastery AI Agent product at scale:

Frontend:
- Customer dashboard (Next.js + Vercel AI SDK?)
- Chat interface (streaming, code highlighting, action buttons)
- Platform selection and onboarding wizard

Backend:
- KB ingestion pipeline (already built in Genesis: sitemap → fetch → chunk → embed → Qdrant)
- RAG query engine (Gemini embeddings + Qdrant vector search)
- Agent runtime (Claude API / Gemini API for reasoning)
- Action execution layer (MCP tools per platform)
- User management and billing (Stripe)

Infrastructure:
- Cloudflare Workers (edge caching, rate limiting)
- Elestio PostgreSQL (source of truth)
- Qdrant (vector search)
- Redis (sessions)

Scale considerations:
- Cost per query at 1K, 10K, 100K daily queries
- Multi-tenant architecture
- Platform freshness (re-crawling schedule)

Output a Mermaid architecture diagram + component descriptions."""
    },
    {
        "id": "M42_tech_ai_sdk",
        "prompt": """Deep technical analysis of building Platform Mastery AI Agents with the Vercel AI SDK:

1. What is the AI SDK? (ai package from Vercel)
2. Key features: useChat, useCompletion, streamText, generateObject, tool calling
3. How to build a RAG chat interface with AI SDK
4. How to add tool use (platform-specific actions)
5. How to integrate with multiple LLM providers (Anthropic, Google, OpenAI)
6. Streaming architecture for real-time responses
7. AI SDK + Next.js App Router best practices
8. AI SDK RSC (React Server Components) for AI UIs

Include code examples for:
- Chat interface with RAG retrieval
- Tool calling for platform actions
- Streaming response with citations
- Multi-provider model selection"""
    },
    {
        "id": "M43_tech_mcp_per_platform",
        "prompt": """Design the MCP (Model Context Protocol) tool strategy for Platform Mastery AI Agents:

For each major platform, what MCP tools would the agent need?

1. **Salesforce MCP**: SOQL query, record CRUD, workflow trigger, report generation
2. **HubSpot MCP**: Contact/deal CRUD, workflow management, email send
3. **Shopify MCP**: Product management, order lookup, theme editing, app management
4. **Stripe MCP**: Payment lookup, subscription management, webhook config
5. **AWS MCP**: CloudFormation deploy, IAM policy generation, cost analysis
6. **GHL MCP**: Already built (269 tools) — document what exists

For each: list 10 essential tools, API endpoints they'd call, authentication method.
This defines the ACTION capability of each platform agent."""
    },
    {
        "id": "M44_tech_ingestion_pipeline",
        "prompt": """Analyze the Genesis KB ingestion pipeline's capability to scale to 50+ platforms:

Current pipeline: Sitemap → Fetch → Extract → Chunk → Embed (Gemini 3072d) → Qdrant + PostgreSQL

For each step, identify:
1. What works at current scale (1,398 Telnyx pages)?
2. What breaks at 50 platforms × 5,000 pages = 250,000 pages?
3. Cost at scale (Gemini embedding costs, Qdrant storage, PG storage)
4. Time to ingest a new platform (hours? minutes?)
5. Freshness maintenance (re-crawling strategy)

Optimization opportunities:
- Cloudflare Workers for parallel fetch (edge-distributed)
- Incremental updates (only re-embed changed pages)
- Embedding model selection (cheaper alternatives to Gemini 3072d?)
- Compression and deduplication

Calculate the TOTAL COST to ingest the top 20 platforms."""
    },
    {
        "id": "M45_tech_agent_runtime",
        "prompt": """Design the agent runtime for Platform Mastery AI Agents — the system that turns ingested knowledge into intelligent responses:

Components:
1. **Query understanding**: Classify user intent (question, action request, code help, debugging)
2. **RAG retrieval**: Multi-stage retrieval (keyword → semantic → reranker)
3. **Context assembly**: Build the optimal prompt with retrieved knowledge
4. **Reasoning engine**: Claude/Gemini for generating response
5. **Tool execution**: MCP tools for taking platform actions
6. **Response formatting**: Code blocks, links, step-by-step guides
7. **Memory**: Remember user context across conversations
8. **Feedback loop**: Learn from user corrections

For each component: architecture, model selection, cost, latency target.
Total query latency target: <3 seconds for simple questions, <10 seconds for complex actions."""
    },
    {
        "id": "M46_tech_multi_tenant",
        "prompt": """Design the multi-tenant architecture for Platform Mastery AI Agents:

Requirements:
- Each customer gets their own agent with private conversation history
- Agents share the same platform KB (Telnyx KB is shared, not per-customer)
- Customer-specific context (their API keys, their account config, their preferences)
- Usage metering and billing per customer
- Role-based access (admin, user, viewer)
- SSO integration

Database schema:
- tenants, users, conversations, messages, api_keys, usage_events, subscriptions
- Platform KB is SHARED (one Telnyx KB serves all Telnyx customers)
- Customer context is PRIVATE (their specific configuration, history)

Security:
- Row-level security in PostgreSQL
- API key encryption
- Audit logging
- Data isolation guarantees"""
    },

    # ═══ WAVE 6: IMPLEMENTATION PLAN (agents 47-50) ═══
    {
        "id": "M47_launch_plan_week1",
        "prompt": """Detailed Week 1 launch plan for Platform Mastery AI Agents:

Day 1-2: Foundation
- Set up Next.js project with AI SDK
- Deploy to Vercel
- Connect existing Telnyx KB (already 4,831 vectors in Qdrant)
- Basic chat interface with RAG retrieval

Day 3-4: Agent Intelligence
- Add tool calling (Telnyx MCP tools for taking actions)
- Add conversation memory (PostgreSQL)
- Add streaming responses
- Add code syntax highlighting

Day 5-7: Product Polish
- User authentication (Supabase Auth or Clerk)
- Stripe billing integration
- Landing page with pricing
- Demo mode (try before signup)

Deliverables by end of Week 1:
- Live product at [domain].ai
- Telnyx as first platform agent
- Signup → chat → billing working
- 3 pricing tiers live

Include specific file structures, commands, and tech choices."""
    },
    {
        "id": "M48_launch_plan_month1",
        "prompt": """Month 1 launch plan after MVP (Week 1):

Week 2: Add 3 more platforms
- GHL (Genesis already has 269-tool MCP)
- Stripe (well-documented, high developer demand)
- Shopify (massive market)

Week 3: Growth
- Product Hunt launch
- Content marketing (5 blog posts)
- Reddit/HN seeding
- First 10 paying customers target

Week 4: Iteration
- User feedback integration
- Performance optimization
- Add voice interface (Telnyx AI voice agent for platform support calls)
- Add MCP action capabilities (not just knowledge, but DO things)

KPIs for Month 1:
- 100 signups, 10 paid customers, $970 MRR
- 5 platforms live
- <3s average response time
- >80% user satisfaction score"""
    },
    {
        "id": "M49_implementation_roadmap",
        "prompt": """6-month implementation roadmap for Platform Mastery AI Agent product:

Month 1: MVP + Launch (Telnyx, GHL, Stripe, Shopify)
Month 2: Scale (AWS, HubSpot, Salesforce, Supabase) + marketplace listings
Month 3: Enterprise (SSO, audit logs, custom deployments, white-label)
Month 4: Platform partnerships (approach Telnyx, GHL for co-marketing)
Month 5: AI agent marketplace (customers can REQUEST new platforms)
Month 6: API + developer platform (others build ON TOP of our platform agents)

Revenue targets:
- Month 1: $1K MRR (10 customers)
- Month 3: $10K MRR (50 customers)
- Month 6: $50K MRR (200 customers)
- Month 12: $200K MRR (700 customers)

Team scaling:
- Month 1: Solo (Kinan + Genesis AI)
- Month 3: +1 developer
- Month 6: +1 marketer, +1 support
- Month 12: 5-person team

Include milestones, risks, and decision points at each stage."""
    },
    {
        "id": "M50_synthesis_executive_summary",
        "prompt": """Write a 2-page executive summary of the Platform Mastery AI Agent opportunity for Genesis:

Section 1: The Opportunity
- Every SaaS platform has 1000+ pages of docs that users can't navigate
- An AI agent with COMPLETE platform knowledge is 10x more useful than generic AI
- Genesis has already proven this works: 1,398 Telnyx pages ingested, RAG working at 0.80 accuracy
- The pipeline is built: sitemap → fetch → chunk → embed → search. Just add platforms.

Section 2: The Business
- TAM: $X billion (developer tools + customer support + training)
- Revenue model: $97/$297/$997/mo per platform agent
- Unit economics: $X cost per agent, $X margin
- First product: Telnyx AI Expert (already built)
- Path to $100K MRR: X customers across Y platforms

Section 3: Competitive Advantage
- Genesis has the ingestion pipeline BUILT (not vaporware)
- 269-tool GHL MCP already operational
- Cloudflare Workers PRD ready for global edge deployment
- Voice capability via Telnyx AI agents
- Recursive memory (RLM) makes agents SMARTER over time

Section 4: Next Steps
- Week 1: Ship Telnyx agent as MVP
- Month 1: 4 platforms live, 10 paying customers
- Month 6: 20 platforms, $50K MRR
- Month 12: Platform partnerships, $200K MRR

This should be compelling enough to show an investor or partner."""
    },
]


def create_gemini_prompt_file(mission: dict) -> str:
    """Write prompt to file and return path."""
    path = OUTPUT_DIR / f"{mission['id']}_prompt.txt"
    path.write_text(mission["prompt"])
    return str(path)


def launch_gemini_agent(mission: dict, window_idx: int) -> str:
    """Launch a Gemini CLI agent in a tmux window."""
    prompt_file = create_gemini_prompt_file(mission)
    output_file = str(OUTPUT_DIR / f"{mission['id']}_output.md")

    # Gemini CLI command - use prompt from file, output to file
    gemini_cmd = (
        f'export GEMINI_API_KEY="{os.environ.get("GEMINI_API_KEY", "AIzaSyCT_rx0NusUJWoqtT7uxHAKEfHo129SJb8")}"; '
        f'echo "=== MISSION {mission["id"]} ===" > {output_file}; '
        f'echo "Started: $(date)" >> {output_file}; '
        f'cat {prompt_file} | gemini --model gemini-2.5-flash 2>&1 >> {output_file}; '
        f'echo "\\n=== COMPLETED: $(date) ===" >> {output_file}; '
        f'echo "DONE: {mission["id"]}"'
    )

    # Create tmux window
    window_name = mission["id"][:20]
    if window_idx == 0:
        # Create new session with first window
        subprocess.run(
            ["tmux", "new-session", "-d", "-s", TMUX_SESSION, "-n", window_name],
            check=True,
        )
    else:
        subprocess.run(
            ["tmux", "new-window", "-t", TMUX_SESSION, "-n", window_name],
            check=True,
        )

    # Send command to window
    subprocess.run(
        ["tmux", "send-keys", "-t", f"{TMUX_SESSION}:{window_name}", gemini_cmd, "Enter"],
        check=True,
    )

    return output_file


def main():
    print(f"{'='*70}")
    print(f"  GENESIS PLATFORM MASTERY RESEARCH SWARM")
    print(f"  Missions: {len(MISSIONS)}")
    print(f"  Output: {OUTPUT_DIR}")
    print(f"  tmux session: {TMUX_SESSION}")
    print(f"{'='*70}")

    # Kill existing session if any
    subprocess.run(["tmux", "kill-session", "-t", TMUX_SESSION], capture_output=True)

    # Launch in waves with 2-second delays to avoid rate limits
    wave_size = 10
    for wave_start in range(0, len(MISSIONS), wave_size):
        wave_missions = MISSIONS[wave_start:wave_start + wave_size]
        wave_num = (wave_start // wave_size) + 1
        print(f"\n--- Wave {wave_num}: Launching {len(wave_missions)} agents ---")

        for i, mission in enumerate(wave_missions):
            idx = wave_start + i
            output = launch_gemini_agent(mission, idx)
            print(f"  [{idx+1:02d}/{len(MISSIONS)}] {mission['id']} → {output}")
            time.sleep(1)  # Stagger launches

        if wave_start + wave_size < len(MISSIONS):
            print(f"  Waiting 5s before next wave...")
            time.sleep(5)

    print(f"\n{'='*70}")
    print(f"  ALL {len(MISSIONS)} AGENTS LAUNCHED")
    print(f"  Monitor: tmux attach -t {TMUX_SESSION}")
    print(f"  Results: ls {OUTPUT_DIR}/*_output.md")
    print(f"  Count done: grep -l COMPLETED {OUTPUT_DIR}/*_output.md | wc -l")
    print(f"{'='*70}")

    # Write manifest
    manifest = {
        "session": TMUX_SESSION,
        "total_missions": len(MISSIONS),
        "output_dir": str(OUTPUT_DIR),
        "missions": [{"id": m["id"], "output": str(OUTPUT_DIR / f"{m['id']}_output.md")} for m in MISSIONS],
        "launched_at": time.strftime("%Y-%m-%dT%H:%M:%S"),
    }
    manifest_path = OUTPUT_DIR / "MANIFEST.json"
    manifest_path.write_text(json.dumps(manifest, indent=2))
    print(f"  Manifest: {manifest_path}")


if __name__ == "__main__":
    main()
