# Context CLI - Complete Usage Guide & Productivity Hacks

## Table of Contents
1. [Quick Start](#quick-start)
2. [Core Features & Commands](#core-features--commands)
3. [Real-World Scenarios](#real-world-scenarios)
4. [Productivity Hacks](#productivity-hacks)
5. [AI-Powered Features](#ai-powered-features)
6. [Advanced Workflows](#advanced-workflows)
7. [Team Collaboration](#team-collaboration)
8. [Troubleshooting](#troubleshooting)

## Quick Start

### Installation (30 seconds)
```bash
# Install globally from npm
npm install -g context-cli

# Install shell hooks (REQUIRED)
context install --shell zsh  # or bash, fish

# Restart terminal or reload config
source ~/.zshrc  # or ~/.bashrc

# Verify it's working
echo $CONTEXT_ENABLED  # Should show: 1
```

### First Experience
```bash
# Create a test project to see Context CLI in action
mkdir test-project && cd test-project
npm init -y

# Add a dependency
echo '{"dependencies": {"express": "^4.18.0"}}' > package.json

# Try to run without installing (Context CLI will warn you!)
npm start
# ⚠️ package.json exists but node_modules is missing
# Suggested: npm install
```

## Core Features & Commands

### 1. Enable/Disable Context
```bash
# Temporarily disable (useful for scripts or CI)
context-off
echo $CONTEXT_ENABLED  # Empty

# Re-enable
context-on
echo $CONTEXT_ENABLED  # 1
```

### 2. View Your Patterns & Stats
```bash
# See what Context CLI has learned about you
context stats

# Output example:
# 📊 Context CLI Statistics
# 
# Total commands tracked: 1,247
# Patterns detected: 23
# 
# Top Patterns:
# • git add → git commit → git push (47x)
# • npm test → npm run build → npm publish (12x)
# • cd backend → docker-compose up (31x)
```

### 3. Configuration Management
```bash
# View all settings
context config --show

# Enable AI features (highly recommended!)
context config --set-openai-key YOUR_API_KEY
context config --enable-ai

# Choose AI model
context config --set-model gpt-4o  # or gpt-3.5-turbo for speed

# Check configuration
context config --show
```

## Real-World Scenarios

### Scenario 1: The Monday Morning Pull
```bash
# It's Monday, you pull latest changes
git pull
# Context CLI notices: "87 commits since Friday"

# You try to run the app
npm start
# ⚠️ package-lock.json changed - 12 new dependencies added
# ⚠️ Database migrations pending (3 new files in migrations/)
# Suggested: npm install && npm run db:migrate

# Following the suggestion saves you from cryptic errors!
```

### Scenario 2: The Deployment Safety Net
```bash
# You're about to deploy
npm run deploy

# Context CLI warns:
# ⚠️ You're on branch 'feature/new-api' but usually deploy from 'main'
# ⚠️ 4 tests are failing (last test run had 0 failures)
# ⚠️ .env.production was modified but not committed
# 
# Are you sure you want to continue?
```

### Scenario 3: The New Developer Onboarding
```bash
# New dev tries to run tests
npm test

# Context CLI helps:
# ℹ️ First time running tests in this project
# ℹ️ You'll need:
#   1. Docker running (for test database)
#   2. .env.test file (copy from .env.test.example)
#   3. Run: npm run db:test:setup
```

### Scenario 4: The Framework Switch
```bash
# In a React project, someone types Vue commands
vue create my-app

# Context CLI notices:
# ⚠️ This appears to be a React project (found: package.json with react)
# ℹ️ Did you mean: npx create-react-app my-app
```

### Scenario 5: The Production Database Save
```bash
# Connecting to database
psql -h prod.db.com -U admin -d production

# Context CLI warns:
# 🚨 PRODUCTION DATABASE DETECTED
# 🚨 Last time you accidentally ran: DROP TABLE users;
# ℹ️ Consider using read-only user or adding --read-only flag
```

## Productivity Hacks

### Hack 1: Morning Routine Automation
```bash
# Context CLI learns your morning routine and suggests it
cd ~/work/main-project
# ℹ️ Morning routine detected. Run your usual sequence?
# git pull && npm install && npm run dev && code .
```

### Hack 2: Branch-Specific Warnings
```bash
# Set up branch conventions
git checkout -b hotfix/critical-bug

# Later, trying to add features
npm run add-feature
# ⚠️ You're on a hotfix branch but running feature commands
```

### Hack 3: Time-Based Suggestions
```bash
# Friday afternoon
git commit -m "WIP: Refactoring auth system"
# ⚠️ It's Friday 4:47 PM. Committing WIP on main branch.
# ℹ️ Consider creating a feature branch for Monday
```

### Hack 4: Dependency Awareness
```bash
# After pulling changes
npm run dev
# ⚠️ New dependency 'redis' in package.json but Redis not running
# Suggested: docker-compose up redis
```

### Hack 5: Command Composition Learning
```bash
# Context CLI learns your testing workflow
npm run lint
# ℹ️ You usually run these together:
# npm run lint && npm run test && npm run build
# Run all? [Enter to confirm]
```

### Hack 6: Environment Switching
```bash
# Switching between projects
cd ~/work/project-b
# ℹ️ Different Node version required (v16 vs current v18)
# ℹ️ Different package manager (yarn vs npm)
# Suggested: nvm use 16 && yarn install
```

### Hack 7: Mistake Prevention
```bash
# Common typos
npm tset
# ❓ Command not found. Did you mean: npm test
```

### Hack 8: Smart Git Workflows
```bash
# Committing without staging
git commit -m "Fix bug"
# ⚠️ No files staged for commit
# ℹ️ Changed files: src/app.js, src/utils.js
# Suggested: git add -A && git commit -m "Fix bug"
```

## AI-Powered Features

### Enable AI for Smarter Suggestions
```bash
# One-time setup
context config --set-openai-key sk-...your-key...
context config --enable-ai
context config --set-model gpt-4o  # Best for accuracy
```

### AI Scenario 1: Complex Debugging Help
```bash
# After a failed build
npm run build
# Build fails with webpack error

# AI-Enhanced Context CLI:
# ❌ Build failed due to circular dependency
# 📍 Detected in: src/components/Header.js ← → src/utils/auth.js
# 
# Suggested fixes:
# 1. Move shared logic to src/utils/common.js
# 2. Use dynamic imports: const auth = () => import('./utils/auth')
# 
# Similar issue was fixed in commit a3f24b last month
```

### AI Scenario 2: Learning From Your Style
```bash
# After several commits
git commit -m "updated code"

# AI notices your pattern:
# ℹ️ Your commit style usually follows conventional commits:
# - feat: for new features (32% of commits)
# - fix: for bug fixes (28% of commits)
# - chore: for maintenance (21% of commits)
# 
# Suggested: git commit -m "fix: resolve authentication issue"
```

### AI Scenario 3: Project-Specific Knowledge
```bash
# In a microservices project
docker-compose up

# AI-enhanced warning:
# ⚠️ Services 'auth-service' and 'user-service' have pending migrations
# ⚠️ Redis not configured - auth-service will fail
# 
# Run this sequence:
# 1. docker-compose up -d postgres redis
# 2. npm run migrate:all
# 3. docker-compose up
```

## Advanced Workflows

### Workflow 1: CI/CD Integration Awareness
```bash
# Before pushing
git push origin feature/new-api

# Context CLI with AI:
# ℹ️ This will trigger CI pipeline:
#   - Unit tests (avg: 3m 20s)
#   - Integration tests (avg: 8m 15s)
#   - Deploy to staging
# 
# ⚠️ Last 2 pipeline runs failed on this branch
# Issue: Missing environment variable API_KEY in .env.ci
```

### Workflow 2: Multi-Project Management
```bash
# Context CLI tracks patterns across projects
cd ~/work/frontend
npm start
# ℹ️ Backend API not running (usually at localhost:3001)
# Suggested: cd ~/work/backend && npm run dev (in new terminal)
```

### Workflow 3: Database Safety
```bash
# Production database operations
npm run db:migrate:prod

# Context CLI checks:
# ✓ You're on main branch
# ✓ All tests passing
# ✓ Migration is reversible
# ⚠️ Last production deploy was 2 hours ago
# ⚠️ 127 active users currently online
# 
# Proceed with caution!
```

### Workflow 4: Review Preparation
```bash
# Before creating PR
git diff main..HEAD

# Context CLI summarizes:
# 📊 PR Impact Analysis:
# - 23 files changed (+1,234 -567 lines)
# - Touches critical paths: auth, payments
# - Test coverage: decreased by 2.3%
# - Conflicts with 2 other open PRs
# 
# Suggested pre-PR checklist:
# □ Add tests for new auth logic
# □ Update API documentation
# □ Rebase on latest main
```

## Team Collaboration

### Share Your Context Patterns
```bash
# Export your patterns (coming in v2)
context export --patterns > team-patterns.json

# Team members can import
context import --patterns team-patterns.json
```

### Project-Specific Rules
```bash
# Create .context-cli.json in project root
{
  "rules": [
    {
      "pattern": "npm run deploy",
      "requires": ["branch:main", "tests:passing"],
      "message": "Deployment requires main branch and passing tests"
    }
  ]
}
```

## Performance Tips

### 1. Disable for Scripts
```bash
# In automated scripts
CONTEXT_ENABLED=0 ./deploy.sh

# Or in script header
#!/bin/bash
export CONTEXT_ENABLED=0
```

### 2. Selective Directories
```bash
# Disable in specific directories (coming in v2)
echo "/very/large/monorepo" >> ~/.context-cli/ignore
```

### 3. Check Performance Impact
```bash
# Measure overhead
time ls  # with context-on
context-off
time ls  # without context

# Should be < 50ms difference
```

## Troubleshooting

### Context CLI Not Working?

#### 1. Check Installation
```bash
# Verify context command exists
which context
# Should show: /usr/local/bin/context or similar

# Check version
context --version
```

#### 2. Verify Shell Hooks
```bash
# For zsh
grep -i "context" ~/.zshrc

# For bash  
grep -i "context" ~/.bashrc

# Should see context integration code
```

#### 3. Test Manually
```bash
# Test analyzer directly
context analyze --pre "npm test" --dir "$PWD"

# Should see suggestions if applicable
```

#### 4. Check Database
```bash
# Verify database exists
ls -la ~/.context-cli/
# Should see: context.db

# Check if it's recording
sqlite3 ~/.context-cli/context.db "SELECT COUNT(*) FROM command_history;"
```

#### 5. Debug Mode
```bash
# Enable debug logging (coming in v2)
export CONTEXT_DEBUG=1
npm test  # Run any command
# Will show detailed analysis steps
```

### Common Issues

#### "No suggestions appearing"
```bash
# 1. Check if enabled
echo $CONTEXT_ENABLED

# 2. Manually trigger
context analyze --pre "your command here"

# 3. Reset database if corrupted
rm -rf ~/.context-cli/
context install --shell zsh
```

#### "Slowing down my terminal"
```bash
# Temporarily disable
context-off

# Check for large command history
sqlite3 ~/.context-cli/context.db "SELECT COUNT(*) FROM command_history;"
# If > 100,000, consider cleanup
```

#### "AI features not working"
```bash
# Verify API key is set
context config --show

# Test AI directly
OPENAI_API_KEY=your-key node -e "console.log('Key is set')"

# Check for errors in response
export CONTEXT_DEBUG=1
npm test  # Any command
```

## Best Practices

### 1. Let It Learn
- Use Context CLI for at least a week to build patterns
- Don't disable it immediately when suggestions seem off
- It improves with more data

### 2. Configure for Your Workflow
```bash
# Adjust AI model based on needs
context config --set-model gpt-3.5-turbo  # Faster, cheaper
context config --set-model gpt-4o         # Smarter, better context
```

### 3. Use in Development Only
```bash
# Don't install on production servers
# Add to development dependencies if needed
npm install --save-dev context-cli
```

### 4. Combine with Other Tools
```bash
# Works great with:
# - direnv (for environment switching)
# - nvm (for Node version management)  
# - docker-compose (for service dependencies)
```

### 5. Report Issues
```bash
# Help improve Context CLI
# Report issues at: https://github.com/josharsh/context-cli/issues
```

## Quick Reference Card

```bash
# Installation
npm install -g context-cli
context install --shell zsh

# Daily Commands
context-on                           # Enable
context-off                          # Disable  
context stats                        # View patterns
context config --show                # View settings

# AI Setup
context config --set-openai-key KEY  # Set API key
context config --enable-ai           # Enable AI
context config --set-model gpt-4o    # Choose model

# Troubleshooting
context analyze --pre "cmd"          # Test manually
echo $CONTEXT_ENABLED               # Check if enabled
which context                       # Verify installation
```

## Summary

Context CLI is your terminal's co-pilot, learning from your patterns to prevent mistakes and boost productivity. The more you use it, the smarter it gets. With AI enabled, it becomes like having a senior developer watching over your shoulder, but without the judgment!

Happy coding with Context CLI! 🚀