High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.
feat: add automated AI code review with Claude
Datad1c65ec173d6
diff --git a/.github/scripts/ai-review.js b/.github/scripts/ai-review.jsnew file mode 100644index 00000000..65533e91--- /dev/null+++ b/.github/scripts/ai-review.js@@ -0,0 +1,107 @@+#!/usr/bin/env node+/**+ * AI Code Review Script+ * Sends PR diff to Claude for review and posts results as a comment+ */++const https = require('https');+const fs = require('fs');+const { execSync } = require('child_process');++const ANTHROPIC_API_KEY = process.env.ANTHROPIC_API_KEY;+const GH_TOKEN = process.env.GH_TOKEN;+const PR_NUMBER = process.env.PR_NUMBER;++if (!ANTHROPIC_API_KEY || !GH_TOKEN || !PR_NUMBER) {+ console.error('Missing required environment variables');+ process.exit(1);+}++// Read PR diff+const diff = fs.readFileSync('pr.diff', 'utf8');++// Prepare Claude API request+const payload = JSON.stringify({+ model: 'claude-sonnet-4-5',+ max_tokens: 4096,+ messages: [{+ role: 'user',+ content: `You are a code reviewer for the pinchtab project. Review this PR diff and provide concise, actionable feedback.++Focus on:+1. Bugs or logic errors+2. Security issues (especially command injection, path traversal)+3. Performance concerns+4. Code clarity and maintainability+5. Violations of project conventions (no redundant comments, proper error handling)++Be specific about line numbers. If the code looks good, say so briefly. Keep response under 2000 characters.++PR Diff:++${diff}`+ }]+});++// Call Claude API+const options = {+ hostname: 'api.anthropic.com',+ path: '/v1/messages',+ method: 'POST',+ headers: {+ 'x-api-key': ANTHROPIC_API_KEY,+ 'anthropic-version': '2023-06-01',+ 'content-type': 'application/json',+ 'Content-Length': Buffer.byteLength(payload)+ }+};++console.log('Calling Claude API for code review...');++const req = https.request(options, (res) => {+ let data = '';++ res.on('data', (chunk) => {+ data += chunk;+ });++ res.on('end', () => {+ try {+ const response = JSON.parse(data);++ if (response.error) {+ console.error('Claude API error:', response.error);+ process.exit(1);+ }++ const reviewText = response.content[0].text;+ console.log('Review received from Claude');++ // Post comment to PR+ const comment = `## π€ AI Code Review (Claude)++${reviewText}++---+*Automated review using Claude Sonnet 4.5*`;++ execSync(`gh pr comment ${PR_NUMBER} --body ${JSON.stringify(comment)}`, {+ env: { ...process.env, GH_TOKEN }+ });++ console.log('Review posted to PR');+ } catch (err) {+ console.error('Error processing response:', err);+ console.error('Response:', data);+ process.exit(1);+ }+ });+});++req.on('error', (err) => {+ console.error('Request error:', err);+ process.exit(1);+});++req.write(payload);+req.end();diff --git a/.github/workflows/ai-code-review.yml b/.github/workflows/ai-code-review.ymlnew file mode 100644index 00000000..55c01efd--- /dev/null+++ b/.github/workflows/ai-code-review.yml@@ -0,0 +1,51 @@+name: AI Code Review++on:+ pull_request:+ types: [opened, synchronize, reopened, ready_for_review]++permissions:+ contents: read+ pull-requests: write++jobs:+ review:+ name: Claude Code Review+ runs-on: ubuntu-latest+ if: github.event.pull_request.draft == false+ steps:+ - uses: actions/checkout@v4+ with:+ fetch-depth: 0++ - name: Get PR diff+ id: diff+ run: |+ # Get the diff for this PR+ gh pr diff ${{ github.event.pull_request.number }} > pr.diff++ # Check if diff is too large (Claude has token limits)+ DIFF_SIZE=$(wc -c < pr.diff)+ if [ "$DIFF_SIZE" -gt 100000 ]; then+ echo "skip=true" >> $GITHUB_OUTPUT+ echo "Diff too large ($DIFF_SIZE bytes), skipping AI review"+ exit 0+ fi++ echo "skip=false" >> $GITHUB_OUTPUT+ env:+ GH_TOKEN: ${{ github.token }}++ - name: Setup Node.js+ if: steps.diff.outputs.skip == 'false'+ uses: actions/setup-node@v4+ with:+ node-version: '22'++ - name: Review with Claude+ if: steps.diff.outputs.skip == 'false'+ run: node .github/scripts/ai-review.js+ env:+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}+ GH_TOKEN: ${{ github.token }}+ PR_NUMBER: ${{ github.event.pull_request.number }}diff --git a/docs/guides/ai-code-review.md b/docs/guides/ai-code-review.mdnew file mode 100644index 00000000..fd51c5b1--- /dev/null+++ b/docs/guides/ai-code-review.md@@ -0,0 +1,176 @@+# AI Code Review Setup++Automated code review using Claude after CI checks pass.++## How It Works++1. PR is opened/updated and marked "Ready for review"+2. CI checks run (tests, lint, etc.)+3. **After CI completes**, Claude reviews the PR diff+4. Claude posts review as a PR comment++## Setup++### 1. Add Anthropic API Key++Get an API key from https://console.anthropic.com/++Add to repo secrets:+```bash+# Via GitHub CLI+gh secret set ANTHROPIC_API_KEY --body "sk-ant-..."++# Or via web UI:+# Settings β Secrets and variables β Actions β New repository secret+# Name: ANTHROPIC_API_KEY+# Value: sk-ant-...+```++### 2. Enable the Workflow++The workflow is already configured in `.github/workflows/ai-code-review.yml`.++It runs automatically on:+- PR opened+- PR synchronized (new commits)+- PR reopened+- PR marked "Ready for review"++**Skips draft PRs** β no review until you mark as ready.++## Cost Estimation++**Per PR review:**+- Input: ~5K-50K tokens (depending on diff size)+- Output: ~1K tokens (review text)+- Cost: ~$0.05-$0.30 per review (Sonnet 4.5 pricing)++**Monthly estimate:**+- 50 PRs/month Γ $0.15 average = ~$7.50/month++**Large diffs (>100KB) are automatically skipped** to avoid excessive costs.++## Customization++### Change Model++Edit `.github/scripts/ai-review.js`:+```javascript+model: 'claude-sonnet-4-5', // Fast, cheaper+// OR+model: 'claude-opus-4', // More thorough, expensive+```++### Change Review Focus++Edit the prompt in `.github/scripts/ai-review.js`:+```javascript+content: `Review this PR focusing on:+1. Security issues+2. Performance+3. Maintainability+...`+```++### Skip Certain Files++Edit `.github/workflows/ai-code-review.yml`:+```yaml+- name: Get PR diff+ run: |+ # Exclude generated files, vendor, etc.+ gh pr diff ${{ github.event.pull_request.number }} \+ -- ':!vendor/**' ':!*.gen.go' ':!dashboard/dist/**' > pr.diff+```++## Disabling++### Temporarily (per PR)++Add `[skip ai-review]` to PR title or description.++Edit workflow to check for this:+```yaml+if: |+ github.event.pull_request.draft == false &&+ !contains(github.event.pull_request.title, '[skip ai-review]')+```++### Permanently++Delete or rename `.github/workflows/ai-code-review.yml`++## Example Output++```markdown+## π€ AI Code Review (Claude)++**Security:** Line 327 - exec.Command with user-controlled input. The #nosec+directive is appropriate here since chromeBinary comes from config/env vars,+but consider validating the path exists before execution.++**Performance:** Consider caching the Chrome binary lookup result in+findChromeBinary() to avoid repeated filesystem checks.++**Code Quality:** Well-documented! The goroutine+timer pattern for startup+timeout is elegant and avoids the context cancellation issue.++Overall this is solid work. The fallback strategy for Chrome 145 is robust+and backwards compatible.++---+*Automated review using Claude Sonnet 4.5*+```++## Troubleshooting++### "ANTHROPIC_API_KEY not set"++Secret not configured or workflow doesn't have access.+- Check: Settings β Secrets β ANTHROPIC_API_KEY exists+- Verify workflow has `permissions: pull-requests: write`++### "Diff too large, skipping AI review"++PR changes >100KB. Options:+1. Split into smaller PRs+2. Increase limit in workflow (line 26)+3. Review manually++### "Claude API error: rate_limit_error"++API rate limit hit. Options:+1. Wait a few minutes and re-run workflow+2. Upgrade Anthropic plan+3. Reduce review frequency (skip draft PRs, etc.)++## Alternative: OpenAI++Don't have Anthropic API? Use OpenAI instead:++Edit `.github/scripts/ai-review.js`:+```javascript+// Change API endpoint+hostname: 'api.openai.com',+path: '/v1/chat/completions',++// Change headers+headers: {+ 'Authorization': `Bearer ${OPENAI_API_KEY}`,+ 'Content-Type': 'application/json'+}++// Change payload+const payload = JSON.stringify({+ model: 'gpt-4-turbo',+ messages: [{ role: 'user', content: `...` }]+});+```++Update secret name in workflow: `OPENAI_API_KEY`++## Further Reading++- [Anthropic API Docs](https://docs.anthropic.com)+- [GitHub Actions Docs](https://docs.github.com/actions)+- [Definition of Done](../../DEFINITION_OF_DONE.md) β What Claude checks fordiff --git a/docs/index.json b/docs/index.jsonindex 5c02d728..46d456a0 100644--- a/docs/index.json+++ b/docs/index.json@@ -28,7 +28,8 @@"guides/agent-optimization.md","guides/memory-monitoring.md","guides/data-storage.md",- "guides/raspberry-pi.md"+ "guides/raspberry-pi.md",+ "guides/ai-code-review.md"],"proposals": ["proposals/default-instance.md",