Source: docs/guides/CLAUDE.md
AltSports League Intelligence Platform - Claude Code Instructions
Task Master AI Instructions
Import Task Master's development workflow commands and guidelines, treat as if import is in the main CLAUDE.md file. @./.taskmaster/CLAUDE.md
Project Overview
This is a sports-focused prediction market platform with comprehensive business intelligence capabilities. At its core, it mirrors the architecture of leading prediction markets like Polymarket and Kalshi, but specialized for sports leagues and betting markets. The system combines AI-powered document processing, contract generation, and partnership acquisition workflows to build the foundational infrastructure for sports prediction markets.
Prediction Market DNA: Like Polymarket (USDC-based, blockchain-enabled) and Kalshi (regulated, real-time sports betting), this platform processes league data through intelligent pipelines to generate market opportunities, contract terms, and business intelligence insights that power sports prediction markets.
Core Architecture
Backend Systems:
apps/backend/- FastAPI backend with MCP (Model Context Protocol) integrationapps/practice_email_assistant_versions/- Email intelligence systems and AppScript variants- Multiple deployment architectures: Google Cloud Run, Vercel, AppScript
Frontend Architectures (in clients/ directory):
- Next.js Variants: 8+ specialized prediction market interfaces
frontend-001-nextjs-ui-grok-chat- Main chat interface with Grok-style UI for market analysisfrontend-001-nextjs-league-owner-portal- League owner management dashboard for market creationfrontend-001-nextjs-ui-grok-chat-polymarket-micro-betting- Direct Polymarket-style betting integrationfrontend-dynamic-games- Real-time sports game interface with live market updates
- Vue.js Alternative:
frontend-018-vue- Vue-based prediction market frontend - Specialized UIs: Player stats, trading interfaces, admin panels, market maker tools
CLI Tools:
client.py- NEW: Intelligent questionnaire-to-contract CLI with sequential thinkingchat_repl.py- Interactive chat REPL with enhanced/simple modes
Key Features
-
Document Intelligence Pipeline (Market Creation Workflow):
- Extract β Classify β Enhance β Tier β Market/Contract generation
- OCR processing for league questionnaires, creating prediction market opportunities
- Multi-dimensional scoring and tier classification (T1-T4) for market prioritization
- Sequential thinking for contract term generation and market parameter setting
-
Sports Prediction Market Infrastructure:
- Real-time event processing similar to Kalshi's sports betting volume (70% of trading)
- Partnership scoring for identifying high-value betting market opportunities
- Market intelligence and competitive analysis (Polymarket vs Kalshi approach)
- Portfolio optimization for balanced sports prediction market offerings
-
Email Intelligence System (Market Signal Processing):
- Gmail integration with AI-powered classification for market opportunities
- Automated email processing and response generation for league partnerships
- Multi-persona evaluation framework for market validation
Deployment Options Comparison
1. Google Cloud Run (Primary)
Best for: Production backend services, scalable frontends
- Pros: Auto-scaling, serverless, containerized, pay-per-use
- Use Cases: FastAPI backend, Next.js frontends
- Configuration:
deploy/deploy-gcloud-run.sh,deploy/Dockerfile.backend - Live Examples:
- Backend:
altsports-email-agent-559065285658.us-central1.run.app - Frontend: Various deployed instances via Cloud Run
- Backend:
2. Vercel (Frontend Focus)
Best for: Next.js frontend deployments, edge computing
- Pros: Optimized for Next.js, edge network, automatic deployments
- Use Cases: Frontend-only deployments, static sites
- Configuration:
deploy/vercel.json,deploy/deploy-vercel.sh - Integration: Connects to Cloud Run backend APIs
3. AppScript (Google Workspace Integration)
Best for: Google Workspace automation, lightweight processing
- Pros: Native Google integration, Gmail/Sheets access, free hosting
- Use Cases: Email automation, Google Sheets data processing
- Configuration:
apps/practice_email_assistant_versions/backend-appscripts-* - Limitations: 6-minute execution limit, limited libraries
Architecture Decision Matrix
| Feature | Cloud Run | Vercel | AppScript |
|---|---|---|---|
| Scalability | βββββ | ββββ | ββ |
| Cost | ββββ | βββ | βββββ |
| Backend Support | βββββ | ββ | βββ |
| Google Integration | βββ | ββ | βββββ |
| Development Speed | βββ | βββββ | ββββ |
Development Workflow
Quick Start Commands
# Backend development
cd apps/backend && uv run python main.py
# Frontend development (Next.js)
cd clients/frontend-001-nextjs-ui-grok-chat && npm run dev
# CLI questionnaire processing
python client.py --file questionnaire.pdf --intelligence-mode full
# Deploy to Cloud Run
./deploy/deploy-gcloud-run.sh frontend-001-nextjs-ui-grok-chat
# Deploy to Vercel
./deploy/deploy-vercel.shTesting Commands
# CLI testing
python test_questionnaire_cli.py
# Frontend testing
cd clients/frontend-* && npm run test:ghost
# Backend testing
cd apps/backend && python -m pytestDeployment Shortcuts
Quick Deploy Commands (recognized by Claude AI):
# Deploy Maged monolith (League Questionnaire to Contract/Termsheet)
# Aliases: "deploy maged", "deploy maged monolith", "deploy contracts", "deploy termsheet"
# See: .claude/commands/deploy-maged.md
cd clients/streamlit-000-league-questionnaire-to-contract-termsheet-maged
./deploy-as-assistant.sh
# Deploy Backend to Google Cloud Run
# Aliases: "deploy backend", "deploy backend to cloud run", "deploy api", "deploy fastapi"
# See: .claude/commands/deploy-backend.md
cd apps/backend
./deploy_to_cloud_run.sh
# Deploy Backend to Local Docker (Sandbox)
# Aliases: "deploy backend local", "deploy backend sandbox", "run backend docker"
# See: .claude/commands/deploy-backend-local.md
cd apps/backend
./deploy-local-docker.shService Account Deployment:
- All Cloud Run deployments use
assistant@altsportsdata.comservice account - Backend service:
altsportsleagues-backend-api - Complete guide:
clients/streamlit-000-league-questionnaire-to-contract-termsheet-maged/.claude/DEPLOYMENT_SERVICE_ACCOUNT.md - Quick start:
clients/streamlit-000-league-questionnaire-to-contract-termsheet-maged/.claude/QUICKSTART_SERVICE_ACCOUNT.md
Technology Stack
Backend:
- Python 3.8+ with FastAPI and FastMCP
- LangGraph for workflow orchestration
- OpenAI/Anthropic for AI processing
- Google Cloud services (Firestore, Storage, Vision)
Frontend:
- Next.js 15+ with TypeScript
- React components with shadcn/ui
- Tailwind CSS for styling
- Firebase/Supabase for data persistence
AI/ML:
- Sequential thinking workflows
- Multi-persona evaluation systems
- Document intelligence with OCR
- Vector embeddings for semantic search
Sports Event Streaming & AI Analytics System
Proof of Concept: Real-Time Sports Event Processing
We want our proof of concept to be just to 'watch basketball' and report not only the score but anything reported in the audio transcript as far as injuries and other indirect events... we want to create an 'event hooks trigger' where we give a event hook observation insight of '+2 points to team a' '+3 points to team b'
So we have like an event stream or bus and then we have a listener of that stream that can interpret it and 'mark the appropriate action' on the ui for the sport that would mark that action or just ... do the function /action / send webhook or other event of player upsert +1 or -1 or player stat or like '+1 player catch of 49yards'
And so there is maybe one master stream of all of the sport league updates in a channel and we can listen to them to update all of the stats in the database in real time. As long as we trust the historical YouTubes, their dates, and we trust the live YouTube vendors... could pretty much auto-populate and train an AI to watch sports and create statistics.
Prediction Market Architecture & Technical Implementation
This platform fundamentally operates as a sports prediction market infrastructure, following proven patterns from Polymarket and Kalshi.
Technical Architecture Alignment with Leading Prediction Markets
Smart Contract & Settlement Layer:
- Event Resolution System: Similar to Polymarket's UMA oracle integration for automated event settlement
- Conditional Token Framework: ERC-1155 token standards for outcome shares (mirroring Gnosis CTF contracts)
- USDC Integration: Stablecoin-based betting using USDC for price stability and user familiarity
- Real-time Settlement: Smart contracts automatically execute payouts when sports data oracles confirm results
Core Market Mechanics:
- Binary Outcome Markets: Yes/No betting on specific sports events (team wins, player performance, etc.)
- Share-based Pricing: Outcome shares priced between $0.01-$1.00 reflecting aggregated probability
- Peer-to-Peer Trading: Users can buy/sell positions before event resolution
- Liquidity Provision: Market maker tools for ensuring deep liquidity across sports markets
Sports-Specific Prediction Market Features
Real-time Sports Data Integration:
- Oracle Systems: Sports data APIs (similar to Chainlink sports feeds) for real-time event confirmation
- Event Stream Processing: Live sports event monitoring for instant market updates
- Multi-event Markets: Complex betting on player stats, team performance, seasonal outcomes
- Micro-betting Markets: In-game betting on individual plays, quarters, specific player actions
League Partnership Pipeline β Market Creation:
- Document Intelligence processes league questionnaires
- AI Analysis identifies optimal betting market opportunities
- Contract Generation creates partnership terms for exclusive market access
- Market Deployment launches prediction markets for league events
Competitive Positioning vs. Existing Platforms
Polymarket Comparison:
- Blockchain: Similar Ethereum/Polygon L2 architecture for low-cost transactions
- Global Scope: Focuses on crypto-native users, regulatory flexibility
- Market Types: Expands beyond politics to sports/entertainment events
Kalshi Comparison:
- Regulation: CFTC-regulated approach for US market compliance
- Sports Focus: 70% of Kalshi's volume is sports betting - direct competition space
- Traditional Finance: Fiat-friendly onboarding and user experience
AltSports Differentiation:
- League Intelligence: Unique AI-powered league analysis and partnership acquisition
- B2B Foundation: Builds prediction markets through direct league partnerships
- Hybrid Architecture: Supports both regulated (Kalshi-style) and decentralized (Polymarket-style) deployment
- Sports Specialization: Deep focus on alternative sports leagues and emerging markets
Technical Implementation Roadmap
Phase 1: Market Infrastructure
- Smart contract deployment (outcome tokens, settlement logic)
- USDC integration and treasury management
- Basic sports data oracle integration
- Simple binary outcome markets
Phase 2: Advanced Features
- Multi-outcome markets and complex betting structures
- Real-time event stream processing and live betting
- Mobile-optimized trading interfaces
- Advanced market maker tools
Phase 3: Scale & Integration
- League partnership API integrations
- Cross-chain deployment (Ethereum, Polygon, Solana)
- Institutional trading tools and liquidity provision
- Advanced analytics and market intelligence dashboards
This architecture positions the platform as the "Polymarket for Sports Leagues" - combining the technical sophistication of leading prediction markets with specialized focus on sports intelligence and league partnerships.
Contract Building Flow - Technical Architecture
Complete end-to-end pipeline from league questionnaire to multi-tier contract generation with AI-powered sequential reasoning.
Entry Point: FastAPI Router
File: apps/backend/routers/contracts.py
Endpoints:
POST /api/contracts/generate- Generate contract from questionnaire dataPOST /api/contracts/generate-from-pdf- Generate contract from PDF file
Input Options:
- Questionnaire data (JSON)
- PDF file upload
Processing Options:
- External Service: Delegates to
MAGED_SERVICE_URL(contracts-termsheet-generator.cloud.run.app) - Full Streamlit service with PDF β Contract pipeline - Local Generation: Uses internal workflow orchestration
Workflow Orchestration Pipeline
File: apps/backend/workflows/league_questionnaire_to_contract_workflow.py
6-Step Processing Pipeline:
Step 1: Extract Questionnaire Data
- Tools:
tools/pdf_questionnaire_processor_tool.py,tools/enhanced_questionnaire_workflow.py - Extracts structured data from PDF questionnaires
Step 2: Generate Structured Extract JSON
- Creates comprehensive league data structure
- Includes: business metrics, tech capabilities, partnership readiness
Step 3: Create League Fingerprint
- Scale Indicators: Market size, organizational scale, revenue tier
- Technical Profile: Digital maturity, API availability, integration readiness
- Partnership Compatibility: Tier classification, opportunity score, readiness level
Step 4: Generate Cross-Comparison Analysis
- Compare vs sport average (benchmarking within sport category)
- Compare vs tier average (benchmarking within tier group)
- Calculate comprehensive opportunity score
Step 5: Create Comprehensive Reports
- Executive Summary: High-level partnership overview
- Business Intelligence Report: Market analysis and revenue projections
- Technical Assessment: Integration capabilities and requirements
- Partnership Recommendation: Strategic fit and engagement strategy
- Financial Analysis: ROI, LTV, and pricing recommendations
- Risk Assessment: Partnership risks and mitigation strategies
Step 6: Generate Final Contracts (DOCX + PDF)
- Tool:
tools/intelligent_contract_generator.py - Outputs professional contract documents in multiple formats
AI-Powered Sequential Contract Generator
File: tools/sequential_contract_generator.py
Sequential Thinking Chain (5 AI Reasoning Steps):
Thought 1: OBSERVATION
- Analyze questionnaire inputs
- Identify: league type, sport, tier classification, data quality score
Thought 2: MARKET ANALYSIS
- Calculate: Market size estimate (users Γ engagement Γ monetization potential)
- Determine: Competition level (low/medium/high based on similar leagues)
- Assess: Growth potential (emerging/stable/declining market dynamics)
Thought 3: RISK ASSESSMENT
- Data Quality Risk: < 60% quality score = HIGH risk
- Partnership Commitment Risk: Eagerness score, previous partnerships
- Technical/API Infrastructure Risk: API availability, integration complexity
- Output: Overall risk level (High/Medium/Low)
Thought 4: VALUE CALCULATION
- Lifetime Value (LTV): 3-year revenue projection
- Break-even Timeline: Months to profitability
- ROI Percentage: Expected return on investment
Thought 5: GENERATE 4 PRICING TIERS
Tier Architecture:
-
FRIENDLY PRICE (60% of base)
- 40% discount for relationship building
- 36-month commitment
- Core features, standard support
- Best for: Emerging/growth leagues
-
DEAL PRICE (80% of base)
- 20% discount, quota-driven
- 24-month commitment
- Complete features + sportsbook introductions
- Best for: Established leagues
-
STICK PRICE (110% of base)
- 10% premium for premium leagues
- 12-month commitment
- Enterprise features + dedicated account manager
- Best for: Premium/growth tier leagues
-
RETAIL PRICE (135% of base)
- 35% premium for elite partnerships
- 12-month commitment + auto-renewal
- Custom development + revenue sharing opportunities
- Best for: Premium tier with proven value
Contract Output Formats
JSON Outputs:
structured_extract.json- League data extractionleague_fingerprint.json- Unique league profilecross_comparison_analysis.json- Competitive benchmarkingcomprehensive_reports.json- 6 detailed reports
Contract Documents:
league_partnership_contract.docx- Editable Word formatleague_partnership_contract.pdf- Final PDF contract
Visualizations (5 Charts):
- Bar Chart: Pricing tier comparison across 4 tiers
- Line Chart: Value projection over 36 months
- Radar Chart: Feature comparison matrix
- Scatter Plot: Risk vs return analysis
- Sankey Diagram: Investment to revenue flow visualization
Email Response:
- Automated email generation with all attachments
- Professional formatting with contract summary
Key Backend Components
Tier Classification:
- File:
tools/onboarding_system/contract_tier_engine.py - Scores: Data quality, eagerness, tier classification
- Outputs: Premium/Growth/Standard/Emerging tier assignment
Contract Templates:
- File:
data/contract_template.txt - Base contract structure with variable substitution
Document Generation:
utils/contract_pdf_generator.py- PDF creationutils/automated_contract_generator.py- Automated pipeline
Contract Services:
services/contract_generation_service.py- Core contract logicservices/professional_contract_generator.py- Enterprise-grade formatting
Contract Generation Flow Summary
PDF Upload β Extract Data β Create Fingerprint β Cross-Compare β
Generate Reports β AI Sequential Reasoning (5 thoughts) β
4 Pricing Tiers β Contracts (DOCX/PDF) β Visualizations β Email ResponseKey Metrics Calculated:
- Data Quality Score (0-100%)
- Market Size Estimate ($USD)
- Risk Level (High/Medium/Low)
- Lifetime Value (3-year projection)
- Break-even Timeline (months)
- ROI Percentage
- Opportunity Score (0-100)