continue-custom/docs/guides/posthog-github-continuous-ai.mdx
2025-09-15 13:00:36 -04:00

786 lines
22 KiB
Text
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: "Building a Continuous AI Workflow with PostHog and GitHub"
description: "This guide shows you how to build an automated system that continuously monitors PostHog session recordings, analyzes user experience issues using AI, and automatically creates GitHub issues for your development team to address."
sidebarTitle: "PostHog Session Analysis with Continue CLI"
---
<Card title="What You'll Build" icon="robot">
A fully automated workflow that fetches PostHog session data, uses Continue
CLI to identify UX problems, and creates GitHub issues with specific technical
recommendations
</Card>
## Prerequisites
Before starting, ensure you have:
- GitHub repository where you want to create issues
- PostHog account with **[session recordings enabled and collecting data](https://posthog.com/docs/session-replay/installation)**
- Node.js 18+ installed locally
- Continue CLI account with **active credits** (required for API usage)
<Steps>
<Step title="Install Continue CLI">
```bash
npm i -g @continuedev/cli
```
</Step>
<Step title="Set up Continue CLI Account & API Key">
1. Visit [Continue Organizations](https://hub.continue.dev/settings/organizations)
2. Sign up or log in to your Continue account
3. Navigate to your organization settings
4. Click **"API Keys"** and then **"+ New API Key"**
5. Copy the API key immediately (you won't see it again!)
6. Login to the CLI with `cn login`
</Step>
<Step title="Install & Setup GitHub CLI">
```bash
# macOS
brew install gh
# Ubuntu/Debian
sudo apt install gh
# Windows
winget install --id GitHub.cli
```
Then authenticate: `gh auth login`
</Step>
<Step title="Set up PostHog API access">
Get your Personal API Key from PostHog settings
</Step>
</Steps>
<Tip>Now you're ready to start building your workflow!</Tip>
## Step 1: Environment Setup
### Get Your PostHog API Credentials
You need a **Personal API Key** (not a Project API key) to access session recordings:
1. Go to [Personal API Keys](https://app.posthog.com/settings/user-api-keys) in PostHog
2. Click **+ Create a personal API Key**
3. Name it "Continue CLI Session Analysis"
4. Select these scopes:
- `session_recording:read` - **Required** for accessing session data
- `insight:read` - Optional, for additional analytics
5. Copy the key immediately (you won't see it again!)
### Set Up Your Environment Variables
<CodeGroup>
```bash Environment Setup
# Create working directory
mkdir posthog-continuous-ai
cd posthog-continuous-ai
# Create environment file
cat > .env << EOF
# Continue CLI Configuration (REQUIRED)
CONTINUE_API_KEY=your_continue_api_key_here
# PostHog Configuration
POSTHOG_API_KEY=your_personal_api_key_here
POSTHOG_PROJECT_ID=your_project_id_here
POSTHOG_HOST=https://us.posthog.com
# GitHub Configuration (auto-detected from git, or set manually)
GITHUB_OWNER=YourUsername
GITHUB_REPO=your-repository-name
EOF
# Load environment
source .env
```
```bash Security Setup
# Protect sensitive files
cat > .gitignore << EOF
# Environment variables - contains API keys
.env
.env.local
# Continue CLI authentication
.continue/
# Generated data files
*.json
analysis-results.txt
daily-analysis.log
.created_issues.json
# Temporary files
*.tmp
/tmp/
EOF
```
</CodeGroup>
<Info>
**Auto-Detection**: The scripts can automatically detect your GitHub owner and
repo from your git remote origin URL. Manual configuration in `.env` overrides
auto-detection.
</Info>
<Tip>
**Find Your Project Details**: Your Project ID is in your PostHog URL:
`https://app.posthog.com/project/YOUR_PROJECT_ID`
</Tip>
### GitHub CLI Setup
<Card title="Why GitHub CLI?" icon="github">
GitHub CLI provides secure authentication without needing to manage Personal
Access Tokens in your environment files.
</Card>
**Verify GitHub CLI is ready:**
```bash
# Check if GitHub CLI is installed
gh --version
# Check authentication status
gh auth status
# If not authenticated, login
gh auth login
```
## Step 2: Session Analysis Script
Create the main analysis script that fetches PostHog session recordings, filters for problematic sessions, and uses Continue CLI to analyze them.
<Info>
**How It Works:**
- **Fetches** recent session recordings from PostHog API
- **Filters** for problematic sessions (errors or long durations)
- **Authenticates** with Continue CLI using your API key
- **Analyzes** session data and generates exactly 3 structured GitHub issues
</Info>
<CodeGroup>
```bash analyze-sessions.sh
#!/bin/bash
# analyze-sessions.sh - Fetches PostHog sessions and analyzes them with Continue CLI
set -e
# Load .env if it exists
if [ -f .env ]; then
source .env
fi
# Check for required environment variables
if [ -z "$POSTHOG_API_KEY" ] || [ -z "$POSTHOG_PROJECT_ID" ] || [ -z "$POSTHOG_HOST" ]; then
echo "❌ Missing required PostHog environment variables"
exit 1
fi
if [ -z "$CONTINUE_API_KEY" ]; then
echo "❌ Missing CONTINUE_API_KEY environment variable"
echo "Get your API key from: https://hub.continue.dev/settings/organizations"
exit 1
fi
echo "🎬 Fetching session recordings from PostHog..."
# Fetch recent session recordings
curl -s -H "Authorization: Bearer $POSTHOG_API_KEY" \
"$POSTHOG_HOST/api/projects/$POSTHOG_PROJECT_ID/session_recordings/?limit=20" \
| jq '.results[] | {
id: .id,
duration: .recording_duration,
start_url: .start_url,
click_count: .click_count,
console_error_count: .console_error_count,
person_distinct_id: .person.distinct_ids[0],
start_time: .start_time
}' > sessions.json
echo "📊 Found $(cat sessions.json | jq -s length) sessions"
# Filter for problematic sessions
cat sessions.json | jq -s 'map(select(.console_error_count > 0 or .recording_duration > 300))' > problem-sessions.json
echo "🚨 Found $(cat problem-sessions.json | jq length) problematic sessions"
# Verify Continue CLI authentication
if ! cn auth status > /dev/null 2>&1; then
echo "🔑 Continue CLI not authenticated, attempting login..."
export CONTINUE_API_KEY="$CONTINUE_API_KEY"
if ! cn auth login --api-key "$CONTINUE_API_KEY"; then
echo "❌ Failed to authenticate with Continue CLI"
exit 1
fi
fi
echo "✅ Continue CLI authenticated"
# Analyze with Continue CLI using structured format for easy parsing
cat problem-sessions.json | cn -p "
Analyze these PostHog session recordings and create exactly 3 GitHub issues for the most critical user experience problems.
Session data format:
- duration: session length in seconds
- start_url: starting page URL
- click_count: total clicks in session
- console_error_count: JavaScript errors
Format your response with EXACTLY 3 issues using this structure:
### 1. **Issue Title Here**
**Problem**: One sentence describing the user problem
**Technical Causes**: Brief technical explanation
**Affected Pages**: List the URLs
**Recommended Fix**:
- Specific action item 1
- Specific action item 2
**Priority**: **HIGH** or **MEDIUM** or **LOW**
**Impact**: Quantify the impact (e.g., 'Affects 80% of sessions')
### 2. **Second Issue Title**
[Same format as above]
### 3. **Third Issue Title**
[Same format as above]
Base all issues on actual patterns in the provided session data.
" > analysis-results.txt 2>&1
echo "✅ Analysis complete!"
# Display the analysis
echo ""
echo "📋 Analysis Results:"
echo "=================="
cat analysis-results.txt
echo "=================="
```
```bash Environment Check Script
#!/bin/bash
# check-requirements.sh - Verify all requirements are met
set -e
echo "🔍 Checking requirements..."
# Check Continue CLI
if ! command -v cn &> /dev/null; then
echo "❌ Continue CLI not found. Install with: npm i -g @continuedev/cli"
exit 1
fi
echo "✅ Continue CLI installed"
# Check GitHub CLI
if ! command -v gh &> /dev/null; then
echo "❌ GitHub CLI not found. Install from: https://cli.github.com/"
exit 1
fi
echo "✅ GitHub CLI installed"
# Check jq
if ! command -v jq &> /dev/null; then
echo "❌ jq not found. Install with: brew install jq"
exit 1
fi
echo "✅ jq installed"
# Check Continue CLI auth
if ! cn auth status &> /dev/null; then
echo "⚠️ Continue CLI not authenticated"
echo "Run: cn auth login --api-key YOUR_API_KEY"
else
echo "✅ Continue CLI authenticated"
fi
# Check GitHub CLI auth
if ! gh auth status &> /dev/null; then
echo "⚠️ GitHub CLI not authenticated"
echo "Run: gh auth login"
else
echo "✅ GitHub CLI authenticated"
fi
# Check .env file
if [ ! -f .env ]; then
echo "⚠️ .env file not found"
echo "Create .env with required environment variables"
else
echo "✅ .env file exists"
fi
echo ""
echo "🎉 Requirements check complete!"
```
</CodeGroup>
Make the scripts executable:
```bash
chmod +x analyze-sessions.sh
chmod +x check-requirements.sh
# Test your requirements
./check-requirements.sh
```
## Step 3: Automated GitHub Issue Creation
Create a smart script that parses the AI analysis and automatically creates GitHub issues:
<Card title="Intelligent Issue Creation" icon="github">
This script automatically extracts issues from Continue CLI analysis,
determines priority levels, assigns appropriate labels, and creates
well-formatted GitHub issues using GitHub CLI
</Card>
```bash create-github-issues.sh
#!/bin/bash
# create-github-issues.sh - Creates GitHub issues from Continue CLI analysis
set -e
# Load .env if it exists
if [ -f .env ]; then
source .env
fi
# Input file
ANALYSIS_FILE="analysis-results.txt"
# Check requirements
if [ -z "$GITHUB_OWNER" ] || [ -z "$GITHUB_REPO" ]; then
echo "❌ Missing GITHUB_OWNER or GITHUB_REPO"
echo "These can be auto-detected from git remote or set in .env"
exit 1
fi
if [ ! -f "$ANALYSIS_FILE" ]; then
echo "❌ Analysis file not found: $ANALYSIS_FILE"
echo "Run analyze-sessions.sh first to generate analysis results"
exit 1
fi
# Check GitHub CLI authentication
if ! gh auth status > /dev/null 2>&1; then
echo "❌ GitHub CLI not authenticated"
echo "Run: gh auth login"
exit 1
fi
echo "✅ GitHub CLI authenticated for $GITHUB_OWNER/$GITHUB_REPO"
# Function to create GitHub issue using GitHub CLI
create_github_issue() {
local title="$1"
local body="$2"
local labels="$3"
echo " Creating issue: $title"
# Check if issue with similar title already exists
existing_issues=$(gh issue list --repo "$GITHUB_OWNER/$GITHUB_REPO" \
--search "$title in:title" --json title,state --limit 5)
if echo "$existing_issues" | jq -r '.[].title' | grep -q "$title" 2>/dev/null; then
echo " ℹ️ Issue with similar title already exists, skipping"
return 0
fi
# Create the issue
if issue_url=$(gh issue create \
--repo "$GITHUB_OWNER/$GITHUB_REPO" \
--title "🔍 UX Issue: $title" \
--body "$body" \
--label "$labels"); then
echo " ✅ Created: $issue_url"
return 0
else
echo " ❌ Failed to create issue"
return 1
fi
}
# Parse and create issues
echo "🔍 Parsing analysis results for issues..."
issues_created=0
current_title=""
current_body=""
current_priority=""
# Process the analysis file looking for structured issues
while IFS= read -r line || [ -n "$line" ]; do
# Check for issue header pattern: ### N. **Title**
if [[ $line =~ ^###\ [0-9]+\.\ \*\*(.+)\*\* ]]; then
# Create previous issue if exists
if [ -n "$current_title" ] && [ -n "$current_body" ]; then
# Determine labels based on priority
case "$current_priority" in
"HIGH")
labels="bug,high-priority,user-experience,automated"
;;
"MEDIUM")
labels="enhancement,medium-priority,user-experience,automated"
;;
*)
labels="low-priority,user-experience,automated"
;;
esac
if create_github_issue "$current_title" "$current_body" "$labels"; then
((issues_created++))
fi
fi
# Start new issue
current_title="${BASH_REMATCH[1]}"
current_body=""
current_priority=""
else
# Part of current issue body
if [ -n "$current_title" ]; then
# Extract priority if found
if [[ $line =~ \*\*Priority\*\*:\ \*\*(HIGH|MEDIUM|LOW)\*\* ]]; then
current_priority="${BASH_REMATCH[1]}"
fi
current_body="${current_body}${line}"$'\n'
fi
fi
done < "$ANALYSIS_FILE"
# Create last issue
if [ -n "$current_title" ] && [ -n "$current_body" ]; then
case "$current_priority" in
"HIGH")
labels="bug,high-priority,user-experience,automated"
;;
"MEDIUM")
labels="enhancement,medium-priority,user-experience,automated"
;;
*)
labels="low-priority,user-experience,automated"
;;
esac
if create_github_issue "$current_title" "$current_body" "$labels"; then
((issues_created++))
fi
fi
echo "✅ GitHub issues creation complete!"
echo "📊 Created $issues_created issue(s)"
# Show created issues
if [ $issues_created -gt 0 ]; then
echo ""
echo "📋 Recent automated issues:"
gh issue list --repo "$GITHUB_OWNER/$GITHUB_REPO" --label "automated" --limit 5
fi
```
Make it executable:
```bash
chmod +x create-github-issues.sh
```
<Warning>
**Repository Labels Required**: The script uses these labels which must exist in your GitHub repository:
- `bug`, `enhancement`
- `high-priority`, `medium-priority`, `low-priority`
- `user-experience`, `automated`
Create missing labels in your repo at: **Settings → Labels → New label** or edit the `labels=` lines in the script to match your repository's existing label system.
</Warning>
## Step 4: Complete Automated Workflow
Create the main orchestration script that runs the entire process:
```bash daily-analysis.sh
#!/bin/bash
# daily-analysis.sh - Main entry point for PostHog analysis and GitHub issue creation
set -e
# Load .env for local development
if [ -f .env ]; then
echo "🔧 Loading .env file for local development..."
source .env
fi
# Detect environment
if [ -n "$GITHUB_ACTIONS" ]; then
echo "🚀 Running in GitHub Actions"
export GITHUB_OWNER="${GITHUB_REPOSITORY_OWNER}"
export GITHUB_REPO="${GITHUB_REPOSITORY##*/}"
else
echo "💻 Running locally"
# Auto-detect from git if not set
if [ -z "$GITHUB_OWNER" ] || [ -z "$GITHUB_REPO" ]; then
if git remote get-url origin > /dev/null 2>&1; then
REMOTE_URL=$(git remote get-url origin)
if [[ $REMOTE_URL =~ github.com[:/]([^/]+)/([^/.]+)(\.git)?$ ]]; then
export GITHUB_OWNER="${BASH_REMATCH[1]}"
export GITHUB_REPO="${BASH_REMATCH[2]}"
echo "📍 Auto-detected: $GITHUB_OWNER/$GITHUB_REPO"
fi
fi
fi
fi
# Validate required environment variables
MISSING_VARS=()
[ -z "$CONTINUE_API_KEY" ] && MISSING_VARS+=("CONTINUE_API_KEY")
[ -z "$POSTHOG_API_KEY" ] && MISSING_VARS+=("POSTHOG_API_KEY")
[ -z "$POSTHOG_PROJECT_ID" ] && MISSING_VARS+=("POSTHOG_PROJECT_ID")
[ -z "$POSTHOG_HOST" ] && MISSING_VARS+=("POSTHOG_HOST")
[ -z "$GITHUB_OWNER" ] && MISSING_VARS+=("GITHUB_OWNER")
[ -z "$GITHUB_REPO" ] && MISSING_VARS+=("GITHUB_REPO")
if [ ${#MISSING_VARS[@]} -ne 0 ]; then
echo "❌ Missing required environment variables:"
for var in "${MISSING_VARS[@]}"; do
echo " - $var"
done
exit 1
fi
# Check GitHub CLI authentication
if ! gh auth status > /dev/null 2>&1; then
echo "❌ GitHub CLI not authenticated"
echo "Run: gh auth login"
exit 1
fi
echo "✅ GitHub CLI authenticated"
# Determine script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Run the analysis
echo "🎬 Running PostHog session analysis..."
if ! bash "$SCRIPT_DIR/analyze-sessions.sh"; then
echo "❌ Analysis failed"
exit 1
fi
# Create GitHub issues
echo "📝 Creating GitHub issues from analysis..."
if ! bash "$SCRIPT_DIR/create-github-issues.sh"; then
echo "❌ Issue creation failed"
exit 1
fi
echo "✅ Daily analysis complete!"
# Show created issues
echo ""
echo "📊 Recent issues in $GITHUB_OWNER/$GITHUB_REPO:"
gh issue list --repo "$GITHUB_OWNER/$GITHUB_REPO" --limit 5 --label "automated"
```
Make it executable and test:
```bash
chmod +x daily-analysis.sh
./daily-analysis.sh
```
## Step 5: Automation Options
<Tabs>
<Tab title="GitHub Actions (Recommended)">
Perfect for teams already using GitHub workflows.
<Info>
**Required GitHub Secrets:**
- `CONTINUE_API_KEY`: Your Continue API key from hub.continue.dev
- `POSTHOG_API_KEY`: Your PostHog Personal API Key
- `POSTHOG_PROJECT_ID`: Your PostHog Project ID
Add these in: **Repository Settings → Secrets and variables → Actions**
</Info>
Create `.github/workflows/daily-analysis.yml`:
```yaml
name: Daily Session Analysis
on:
schedule:
- cron: "0 6 * * *" # Run at 6 AM UTC daily
workflow_dispatch: # Allow manual triggering
jobs:
analyze:
runs-on: ubuntu-latest
permissions:
contents: read
issues: write
steps:
- uses: actions/checkout@v3
with:
# Deploy key is REQUIRED for Continue CLI integration
ssh-key: ${{ secrets.CONTINUE_DEPLOY_KEY }}
- name: Set up environment
run: |
# Export environment variables for the entire job
echo "CONTINUE_API_KEY=${{ secrets.CONTINUE_API_KEY }}" >> $GITHUB_ENV
echo "POSTHOG_API_KEY=${{ secrets.POSTHOG_API_KEY }}" >> $GITHUB_ENV
echo "POSTHOG_PROJECT_ID=${{ secrets.POSTHOG_PROJECT_ID }}" >> $GITHUB_ENV
echo "POSTHOG_HOST=${{ secrets.POSTHOG_HOST || 'https://us.posthog.com' }}" >> $GITHUB_ENV
echo "GH_PAT=${{ secrets.GH_PAT }}" >> $GITHUB_ENV
echo "GITHUB_OWNER=${{ github.repository_owner }}" >> $GITHUB_ENV
echo "GITHUB_REPO=$(echo ${{ github.repository }} | cut -d'/' -f2)" >> $GITHUB_ENV
- name: Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y jq curl
# Install Continue CLI for AI analysis
npm install -g @continuedev/cli
# GitHub CLI is pre-installed on GitHub-hosted runners
- name: Make scripts executable
run: |
chmod +x ./posthog-continuous-ai/daily-analysis.sh
chmod +x ./posthog-continuous-ai/analyze-sessions.sh
chmod +x ./posthog-continuous-ai/create-github-issues.sh
- name: Run analysis and create issues
env:
GITHUB_TOKEN: ${{ secrets.GH_PAT }}
GH_TOKEN: ${{ secrets.GH_PAT }}
run: ./posthog-continuous-ai/daily-analysis.sh
```
</Tab>
<Tab title="Cron Job (Server)">
For running on your own server or VPS:
```bash
# Add to crontab (run 'crontab -e')
0 6 * * * cd /path/to/your/project && ./daily-analysis.sh >> ~/logs/analysis.log 2>&1
```
</Tab>
<Tab title="Local Development">
For testing and development:
```bash
# Run manually
./daily-analysis.sh
# Or set up a simple loop for testing
while true; do
./daily-analysis.sh
sleep 3600 # Run every hour
done
```
</Tab>
</Tabs>
## Step 6: Testing Your Workflow
<Steps title="Testing Steps">
<Step title="Run Session Analysis">
```bash ./analyze-sessions.sh ``` Expected: JSON files with session data and
AI analysis output
</Step>
<Step title="Test Issue Creation">
```bash ./create-github-issues.sh ``` Expected: New issues created in your
GitHub repository
</Step>
<Step title="Full Workflow Test">
```bash ./daily-analysis.sh ``` Expected: Complete end-to-end execution with
GitHub issues created
</Step>
</Steps>
<Check>
**Success Indicators:**
- PostHog API returns session data (not empty)
- Continue CLI generates analysis with identified issues
- GitHub issues are created with proper labels and formatting
- No error messages in the console output
</Check>
## What You've Built
After completing this guide, you have a complete **Continuous AI system** that:
✅ **Monitors user experience** - Automatically fetches and analyzes PostHog session data
✅ **Identifies problems intelligently** - Uses AI to spot patterns and technical issues
✅ **Creates actionable tasks** - Generates GitHub issues with specific recommendations
✅ **Runs autonomously** - Operates daily without manual intervention
✅ **Scales with your team** - Handles growing amounts of session data automatically
<Card title="Continuous AI" icon="rocket">
Your system now operates at **[Level 2 Continuous
AI](https://blog.continue.dev/what-is-continuous-ai-a-developers-guide/)** -
AI handles routine analysis tasks with human oversight through GitHub issue
review and prioritization.
</Card>
## Security Best Practices
<Warning>
**Protect Your API Keys:**
- Never commit `.env` files or secrets to version
control
- Use GitHub Secrets for automation workflows
- Limit token scopes to
minimum required permissions
- Rotate API keys regularly (every 90 days
recommended)
- Monitor token usage for unusual activity
</Warning>
## Continue Your Workflow
Consider these additions:
<CardGroup cols={2}>
<Card title="Advanced Features?" icon="star">
Enhance this workflow with additional PostHog data sources (funnel analysis,
feature flags, etc.)
</Card>
<Card title="Custom Analysis Rules" icon="rules">
Train the AI on your specific codebase patterns and conventions
</Card>
<Card title="Slack Integration" icon="slack">
Get notifications when critical issues are detected
</Card>
<Card title="Performance Monitoring" icon="chart-line">
Track how fixes improve user experience metrics over time
</Card>
</CardGroup>
## Next Steps
1. **Monitor your first issues** - Review the GitHub issues created and implement fixes
2. **Measure impact** - Track how resolved issues improve PostHog metrics
3. **Refine analysis** - Adjust the Continue CLI prompts based on issue quality
4. **Scale the system** - Add more data sources or create specialized analysis workflows