cursorflow 2.8.7
🔥 Complete page intelligence for AI-driven development with Hot Reload Intelligence - captures DOM, network, console, performance, HMR events, and comprehensive page analysis
Requires Python: >=3.8
Keywords: ui-testing, automation, cursor, ai, web-testing, css-iteration, hot-reload, hmr, element-intelligence, page-analysis, error-context

# CursorFlow

**The measurement tool for web testing - we capture reality, not fiction**

CursorFlow is a pure data collection engine that captures comprehensive web application intelligence. Unlike simulation tools that let you control reality, CursorFlow measures actual reality - giving you complete trust in your test results.

## 🎯 The CursorFlow Philosophy

### **📊 We Collect Reality, Not Fiction**

**Other tools are simulation tools** - they let you control reality:
- Mock network responses
- Simulate user interactions  
- Create test environments

**CursorFlow is a measurement tool** - we capture reality as-is:
- Real API response times
- Actual network failures
- Genuine browser behavior
- Complete page intelligence

### **🔬 Pure Observation Principle**

**CursorFlow is like a scientific instrument:**
- **Microscopes** don't create the cells they observe
- **Telescopes** don't generate the stars they capture  
- **CursorFlow** doesn't mock the web it measures

When CursorFlow reports `"average_response_time": 416.58ms`, you can tell stakeholders: **"This is what actually happened"** - not "this is what happened in our test simulation."

### **🌟 The Trust Factor**

**Complete Reliability:** Every data point reflects real application behavior
- No mocked responses hiding slow APIs
- No simulated interactions missing real edge cases
- No test environments different from production

**Documentary vs Movie:** Both are valuable, but if you're trying to understand reality, you watch the documentary. CursorFlow is the documentary of web testing.

## 🎯 Pass-Through Architecture

CursorFlow doesn't limit you - it exposes the full power of Playwright:

**94+ Playwright actions available:**
```bash
# Any Playwright Page method works
cursorflow test --actions '[
  {"hover": ".menu"},
  {"dblclick": ".editable"},
  {"press": "Enter"},
  {"drag_and_drop": {"source": ".item", "target": ".zone"}},
  {"check": "#checkbox"},
  {"evaluate": "window.scrollTo(0, 500)"}
]'
```

**Full configuration pass-through:**
```json
{
  "browser_config": {
    "browser_launch_options": {"devtools": true, "channel": "chrome"}
  },
  "context_options": {
    "color_scheme": "dark",
    "geolocation": {"latitude": 40.7128, "longitude": -74.0060},
    "timezone_id": "America/Los_Angeles"
  }
}
```

**Forward-compatible:** New Playwright features work immediately without CursorFlow updates.

**See:** [Playwright API Documentation](https://playwright.dev/python/docs/api/class-page)

---

## 🧹 Artifact Management

CursorFlow generates valuable debugging data (screenshots, traces, sessions). Manage disk space:

```bash
# Clean old artifacts (>7 days)
cursorflow cleanup --artifacts --old-only

# Clean all artifacts
cursorflow cleanup --artifacts

# Clean saved sessions
cursorflow cleanup --sessions

# Clean everything
cursorflow cleanup --all

# Preview before deleting
cursorflow cleanup --all --dry-run
```

**See:** [Complete Usage Guide](docs/user/USAGE_GUIDE.md#artifact-management)

---

## 🔐 Authentication & Testing Protected Pages

Test authenticated pages with automatic session management.

### **Quick Start: Simple Username/Password Login**

No configuration needed - just login with inline actions:

```bash
# Step 1: Login once and save session
cursorflow test --base-url http://localhost:3000 --actions '[
  {"navigate": "/login"},
  {"fill": {"selector": "#username", "value": "myuser"}},
  {"fill": {"selector": "#password", "value": "mypass"}},
  {"click": "#login-button"},
  {"wait_for": ".dashboard"},
  {"screenshot": "logged-in"}
]' --save-session "myuser"

# Step 2: Reuse session for all future tests (no re-login!)
cursorflow test --use-session "myuser" \
  --path /admin/settings \
  --screenshot "admin-panel"

# Step 3: Test another protected page
cursorflow test --use-session "myuser" \
  --path /profile \
  --screenshot "user-profile"
```

**What's saved:**
- All cookies (session cookies, auth tokens)
- localStorage and sessionStorage
- Complete authentication state

**Session persists across tests** - login once, test forever (until session expires).

### **Alternative: Config-Based Authentication**

For repeated testing, configure auth once in `.cursorflow/config.json`:

```bash
# 1. Configure auth in .cursorflow/config.json
{
  "base_url": "http://localhost:3000",
  "auth": {
    "method": "form",
    "username": "test@example.com",
    "password": "testpass",
    "username_selector": "#email",
    "password_selector": "#password",
    "submit_selector": "#login-button"
  }
}

# 2. Login once and save session
cursorflow test --base-url http://localhost:3000 \
  --path /login \
  --save-session "user"

# 3. Reuse session for protected pages (no re-login!)
cursorflow test --use-session "user" \
  --path /dashboard \
  --screenshot "dashboard"
```

**Supports:**
- Form authentication (username/password)
- Cookie authentication (JWT tokens, session cookies)
- Header authentication (Bearer tokens, API keys)
- SSO authentication (Google, Microsoft, Okta, Auth0)

**SSO/OAuth Quick Start (Streamlined - No Manual Steps!):**
```bash
# RECOMMENDED: Capture and save session in one command
cursorflow capture-auth --base-url http://localhost:3001 \
  --path /dashboard \
  --save-as-session "sso"

# Session is immediately ready to use!
cursorflow test --use-session "sso" --path /dashboard

# Or capture + test in one command:
cursorflow capture-auth --base-url http://localhost:3001 \
  --path /dashboard \
  --save-as-session "sso" \
  --test-immediately
```

**Features:**
- ✅ Saves directly to `.cursorflow/sessions/sso_session.json` (no manual copying!)
- ✅ Captures cookies + localStorage + sessionStorage
- ✅ Works with Microsoft Azure AD, Google, Okta, Auth0
- ✅ `--test-immediately` validates session works
- ✅ `--debug-session` for troubleshooting

**Tip:** Use `--browser chrome` on macOS for better window visibility

**See:** [Complete Authentication Guide](docs/user/USAGE_GUIDE.md#authentication--session-management)

---

## 🚀 Complete Page Intelligence

Every test captures everything needed for debugging:

### **📊 Comprehensive Data Collection**
- **DOM**: All elements with 7 selector strategies + event handlers
- **Network**: Requests, responses, and complete request/response bodies  
- **Console**: All logs, errors, warnings - displayed prominently
- **JavaScript**: Global functions, variables, specific window objects
- **Storage**: localStorage, sessionStorage, cookies (sensitive data masked)
- **Forms**: All field values at capture time (passwords masked)
- **Performance**: Load times, memory usage, reliability indicators
- **Visual**: Screenshots with comprehensive page analysis
- **Sessions**: Save/restore authenticated browser state (requires auth_config - see Authentication below)

### **🔄 Hot Reload Intelligence**
- **Framework auto-detection** (Vite, Webpack, Next.js, Parcel, Laravel Mix)
- **Perfect timing** for CSS change detection
- **HMR event correlation** for understanding change impact
- **Persistent sessions** that survive code changes

### **🎯 Enhanced Screenshot Options**
```python
# Clip to specific components
{"screenshot": {"name": "header", "options": {"clip": {"selector": "#header"}}}}

# Hide sensitive information
{"screenshot": {"name": "profile", "options": {"mask": [".user-email", ".api-key"]}}}

# Full page with quality control
{"screenshot": {"name": "page", "options": {"full_page": True, "quality": 90}}}
```

### **📱 Parallel Viewport Testing**
```python
# Test across multiple viewports simultaneously
await flow.test_responsive([
    {"width": 375, "height": 667, "name": "mobile"},
    {"width": 768, "height": 1024, "name": "tablet"},
    {"width": 1440, "height": 900, "name": "desktop"}
], [
    {"navigate": "/dashboard"},
    {"screenshot": "responsive-test"}
])
```

### **🤖 AI-First Design**
All data structured for AI consumption:
- Consistent JSON format across all features
- **Multi-selector element identification** for robust automation
- **Accessibility-aware** element analysis  
- Error correlation with **smart screenshot deduplication**
- Performance insights with **reliability metadata**

## ✨ What's New in v2.7.1

**AI-Optimized Output with Complete Data Type Coverage** - All CursorFlow features now organized for AI consumption:

- **Multi-File Structure**: Split 3.7M token JSON → organized files under 100K tokens each
- **Complete Coverage**: Browser console, server logs, network, DOM, screenshots - all queryable
- **AI Data Digest**: Auto-generated markdown summary with server logs included
- **Query Interface**: Fast data extraction for ALL data types without manual JSON parsing
- **Session Comparison**: Compare test results to detect regressions
- **Export Formats**: JSON, Markdown, CSV outputs for any use case

```bash
# Test generates AI-optimized output automatically
cursorflow test --base-url http://localhost:3000 --path /app --logs local

# Query ANY data type instantly
cursorflow query session_123 --errors              # Console errors
cursorflow query session_123 --server-logs         # Server logs
cursorflow query session_123 --network --failed    # Network failures
cursorflow query session_123 --screenshots         # Screenshot index
cursorflow query session_123 --responsive          # Responsive results
cursorflow query session_123 --css-iterations      # CSS iterations

# Enhanced filtering
cursorflow query session_123 --errors --from-file "app.js" --contains "undefined"
cursorflow query session_123 --network --url-contains "/api/" --over 500ms
cursorflow query session_123 --server-logs --level error --pattern "database"

# Cross-referencing (time-based correlation)
cursorflow query session_123 --errors --with-network --with-server-logs

# Contextual queries
cursorflow query session_123 --context-for-error 2 --window 10
cursorflow query session_123 --group-by-url "/api/users"

# Enhanced comparison
cursorflow query session_A --compare-with session_B --errors
```

**Impact:**
- ✅ 100% AI-readable results (vs 0% before - exceeded context limits)
- ✅ 90% faster error diagnosis with AI assistants
- ✅ Zero manual JSON parsing required
- ✅ Complete backend + frontend visibility (server logs included)

**Complete Data Coverage:**
```
.cursorflow/artifacts/sessions/session_XXX/
├── server_logs.json   # ⭐ Server-side logs (SSH/local/Docker)
├── errors.json        # Browser console errors
├── network.json       # Network requests/responses
├── screenshots.json   # ⭐ Screenshot metadata
├── data_digest.md     # AI summary (includes server logs)
└── + 6 more data files covering all CursorFlow features
```

---

## 🤖 **For AI Agents: Start Here**

### 3-Second Decision Guide

| User Says | Command | What You Get |
|-----------|---------|--------------|
| "Debug this error" | `cursorflow test` → `query session_X --errors --with-network` | Error + network + server logs correlated |
| "Fix this CSS" | Python: `css_iteration_persistent()` | Visual comparison of CSS variations |
| "Why is this slow?" | `query session_X --network --over 500ms` | Slow requests identified |
| "Test login flow" | `cursorflow test --actions '[...]'` | Complete flow with server correlation |

### Complete Debugging Example

```bash
# User: "There's a JavaScript error on the dashboard"

# 1. Capture (5 seconds)
cursorflow test --base-url http://localhost:3000 --path /dashboard

# 2. Diagnose (10 seconds)
cat .cursorflow/artifacts/sessions/session_XXX/data_digest.md
cursorflow query session_XXX --errors

# 3. Get context (5 seconds)
cursorflow query session_XXX --context-for-error 0 --export markdown

# 4. Fix based on correlated data
# (You now have: error message, stack trace, network requests, server logs)
```

**Total time: 20 seconds from problem to actionable diagnosis**

### When User Mentions...

**"Error", "Broken", "Not working"**
1. `cursorflow test` to capture
2. `query --errors` to identify
3. `query --context-for-error` to understand
4. Fix based on correlated data

**"Slow", "Performance", "Takes forever"**
1. `cursorflow test` to baseline
2. `query --network --over 500ms` to find bottlenecks
3. `query --performance` for metrics
4. Optimize slow requests

**"CSS", "Styling", "Layout", "Spacing"**
1. Python API: `css_iteration_persistent()`
2. Test 2-3 CSS approaches
3. Compare screenshots
4. Apply best result

**"Login", "Auth", "Session"**
1. `cursorflow test --actions '[...]'` with login flow
2. `--save-session` to preserve auth
3. `--use-session` for subsequent tests
4. Check auth errors with `query --errors --contains "auth"`

**"Responsive", "Mobile", "Tablet"**
1. `cursorflow test --responsive`
2. `query --responsive --viewport mobile`
3. Compare viewport results
4. Fix mobile-specific issues

**"Compare", "Regression", "What changed"**
1. `query session_before --compare-with session_after`
2. Focus on `new_errors` and `timing_changes`
3. Investigate specific regressions

---

## 🚀 Quick Start

### Step 1: Install CursorFlow Package
```bash
pip install cursorflow
playwright install chromium
```

### Step 2: Initialize Your Project (One-Time Setup)
```bash
cd /path/to/your/project
cursorflow install-rules

# Or skip prompts for automation/CI
cursorflow install-rules --yes
```

This creates:
- `.cursor/rules/` - Cursor AI integration rules
- `.cursorflow/config.json` - Project-specific configuration
- `.cursorflow/` - Artifacts and session storage
- `.gitignore` entries for CursorFlow artifacts

### Step 3: Start Testing

**Simple page capture:**
```bash
cursorflow test --base-url http://localhost:3000 --path /dashboard
```

**Interactive testing with inline actions:**
```bash
cursorflow test --base-url http://localhost:3000 \
  --path /messages \
  --wait-for ".message-item" \
  --hover ".message-item:first-child" \
  --click ".message-item:first-child" \
  --screenshot "clicked" \
  --show-console \
  --open-trace

# Full page screenshot (captures entire scrollable content)
cursorflow test --base-url http://localhost:3000 \
  --path /dashboard \
  --screenshot "complete-page" \
  --full-page
```

**Custom actions with JSON:**
```bash
cursorflow test --base-url http://localhost:3000 --actions '[
  {"navigate": "/login"},
  {"fill": {"selector": "#email", "value": "test@example.com"}},
  {"click": "#login-btn"},
  {"screenshot": {"name": "result", "options": {"mask": [".sensitive-data"]}}}
]'
```

## 💻 Python API Examples

### **Complete Page Intelligence**
```python
from cursorflow import CursorFlow

async def capture_reality():
    flow = CursorFlow("http://localhost:3000", {"source": "local", "paths": ["logs/app.log"]})
    
    # Capture everything
    results = await flow.execute_and_collect([
        {"navigate": "/dashboard"},
        {"screenshot": "complete-analysis"}
    ])
    
    # Access comprehensive data
    screenshot = results['artifacts']['screenshots'][0]
    print(f"Real load time: {screenshot['performance_data']['page_load_time']}ms")
    print(f"Actual memory usage: {screenshot['performance_data']['memory_usage_mb']}MB")
    print(f"Elements found: {len(screenshot['dom_analysis']['elements'])}")
```

### **Enhanced Screenshot Options**
```python
# Component-focused testing
await flow.execute_and_collect([
    {"navigate": "/components"},
    {"screenshot": {
        "name": "button-component",
        "options": {"clip": {"selector": ".component-demo"}}
    }}
])

# Privacy-aware testing
await flow.execute_and_collect([
    {"navigate": "/admin"},
    {"screenshot": {
        "name": "admin-safe",
        "options": {
            "full_page": True,
            "mask": [".api-key", ".user-data", ".sensitive-info"]
        }
    }}
])
```

### **Hot Reload Intelligence**
```python
# Perfect CSS iteration timing
async def hmr_workflow():
    flow = CursorFlow("http://localhost:5173", {"headless": False})
    
    # Auto-detect and monitor HMR
    await flow.browser.start_hmr_monitoring()
    
    # Baseline capture
    await flow.execute_and_collect([{"screenshot": "baseline"}])
    
    # Wait for real CSS changes with perfect timing
    hmr_event = await flow.browser.wait_for_css_update()
    print(f"🔥 {hmr_event['framework']} detected real change!")
    
    # Capture immediately after actual change
    await flow.execute_and_collect([{"screenshot": "updated"}])
```

### **Parallel Viewport Testing**
```python
# Test responsive design across multiple viewports
async def test_responsive_design():
    flow = CursorFlow("http://localhost:3000", {"source": "local", "paths": ["logs/app.log"]})
    
    # Define viewports
    viewports = [
        {"width": 375, "height": 667, "name": "mobile"},
        {"width": 768, "height": 1024, "name": "tablet"},
        {"width": 1440, "height": 900, "name": "desktop"}
    ]
    
    # Test same actions across all viewports
    results = await flow.test_responsive(viewports, [
        {"navigate": "/dashboard"},
        {"click": "#menu-toggle"},
        {"screenshot": {"name": "navigation", "options": {"clip": {"selector": "#nav"}}}}
    ])
    
    # Analyze responsive behavior
    print(f"Tested {results['execution_summary']['successful_viewports']} viewports")
    print(f"Fastest: {results['responsive_analysis']['performance_analysis']['fastest_viewport']}")
```

## 🔧 CLI Commands

### **⚠️ Two Ways to Specify Actions**

**1. Inline CLI Flags** (use `=` separator for fill):
```bash
cursorflow test --base-url http://localhost:3000 \
  --path /login \
  --fill "#email=test@example.com" \
  --fill "#password=mypass" \
  --click "button[type='submit']" \
  --screenshot "result"
```

**2. JSON Actions** (use dict with `selector` and `value`):
```bash
cursorflow test --base-url http://localhost:3000 --actions '[
  {"navigate": "/login"},
  {"fill": {"selector": "#email", "value": "test@example.com"}},
  {"fill": {"selector": "#password", "value": "mypass"}},
  {"click": "button[type=\"submit\"]"},
  {"screenshot": "result"}
]'
```

**❌ Don't mix formats!** Using `|` or `=` inside JSON actions won't work.

### **Universal Testing**
```bash
# Simple page test with complete intelligence
cursorflow test --base-url http://localhost:3000 --path "/dashboard"

# Responsive testing across multiple viewports
cursorflow test --base-url http://localhost:3000 --path "/dashboard" --responsive

# Complex interaction testing
cursorflow test --base-url http://localhost:3000 --actions '[
  {"navigate": "/form"},
  {"fill": {"selector": "#name", "value": "Test User"}},
  {"click": "#submit"},
  {"screenshot": {"name": "result", "options": {"clip": {"selector": ".result-area"}}}}
]'

# Responsive testing with custom actions
cursorflow test --base-url http://localhost:3000 --responsive --actions '[
  {"navigate": "/products"},
  {"fill": {"selector": "#search", "value": "laptop"}},
  {"screenshot": "search-results"}
]'

# Custom output location
cursorflow test --base-url http://localhost:3000 --path "/api" --output "api-test-results.json"

# Inline action flags
cursorflow test --base-url http://localhost:3000 \
  --path /dashboard \
  --screenshot "full-page-capture" \
  --full-page  # Captures entire scrollable page
```

### **Design Comparison** (Pure Measurement)
```bash
# Compare mockup to implementation - get similarity metrics
cursorflow compare-mockup https://mockup.com/design \
  --base-url http://localhost:3000 \
  --implementation-actions '[{"navigate": "/dashboard"}]'
# Output: 87.3% similarity, diff images, element measurements

# Test CSS variations - observe real rendering
cursorflow iterate-mockup https://mockup.com/design \
  --base-url http://localhost:5173 \
  --css-improvements '[
    {"name": "spacing-fix", "css": ".container { gap: 2rem; }"},
    {"name": "tighter-spacing", "css": ".container { gap: 1rem; }"}
  ]'
# Output: Similarity data for each variation (Cursor decides which to apply)
```

### **Element Analysis & CSS Debugging**
```bash
# Comprehensive element inspection with full CSS analysis
cursorflow inspect --base-url http://localhost:3000 --selector "#messages-panel"

# Show all computed CSS properties
cursorflow inspect -u http://localhost:3000 -s ".card" --verbose

# Quick dimension check (surgical precision)
cursorflow measure --base-url http://localhost:3000 --selector "#panel"

# Measure multiple elements at once
cursorflow measure -u http://localhost:3000 -s "#panel1" -s "#panel2"

# Verify CSS changes with all properties
cursorflow measure -u http://localhost:3000 -s ".button" --verbose
```

### **AI Integration**
```bash
# Install Cursor AI rules
cursorflow install-rules

# Update to latest version and rules
cursorflow update
```

## 🧠 Why This Matters

### **For Any Web Application:**
- **Trust your test results** - they reflect actual behavior
- **Find real performance bottlenecks** - no artificial speed boosts
- **Discover actual edge cases** - no simulation gaps
- **Debug genuine issues** - real errors, real timing, real context

## 🌟 Framework Support

**Universal Compatibility:**
- Works with **any web application** regardless of technology
- **Framework-agnostic** core operations  
- **Smart adaptation** to different environments

**HMR Auto-Detection:**
- ✅ **Vite** (port 5173)
- ✅ **Webpack Dev Server** (port 3000)  
- ✅ **Next.js** (port 3000)
- ✅ **Parcel** (port 1234)
- ✅ **Laravel Mix** (port 3000)

## 📖 Documentation

- **[Usage Guide](docs/user/USAGE_GUIDE.md)** - Complete usage documentation (included in pip install)
- **[Examples](examples/)** - Practical usage examples (included in pip install)

## 🎪 The CursorFlow Advantage

### **Other Tools Say:**
*"We let you mock and simulate"*

### **CursorFlow Says:**  
*"We tell you the truth"*

**When you need to understand reality, choose the measurement tool - not the simulation tool.**

---

**Complete page intelligence • Real behavior measurement • AI-first design • Pure observation**