diff --git a/.github/workflows/continue-detailed-review.yaml b/.github/workflows/continue-detailed-review.yaml index 488856df3..3d314ff37 100644 --- a/.github/workflows/continue-detailed-review.yaml +++ b/.github/workflows/continue-detailed-review.yaml @@ -16,295 +16,10 @@ jobs: name: Continue Detailed Review runs-on: ubuntu-latest timeout-minutes: 10 - # Only run if: - # - It's a PR event from a team member (with write/admin permissions) - # - OR it's a comment with @continue-detailed-review on a PR from a team member - if: > - (github.event_name == 'pull_request' && - (github.event.pull_request.author_association == 'OWNER' || - github.event.pull_request.author_association == 'MEMBER' || - github.event.pull_request.author_association == 'COLLABORATOR')) || - (github.event_name == 'issue_comment' && - github.event.issue.pull_request && - contains(github.event.comment.body, '@continue-detailed-review') && - (github.event.comment.author_association == 'OWNER' || - github.event.comment.author_association == 'MEMBER' || - github.event.comment.author_association == 'COLLABORATOR')) - steps: - - name: Checkout Repository - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + - name: Run Detailed PR Review + uses: continuedev/continue/actions/detailed-review@23d9260536372acf4eb57a41e6ab62bc5869b070 with: - fetch-depth: 0 # Fetch full history for better context - - - name: Setup Node.js - uses: actions/setup-node@v4 - with: - node-version: 20 - - - name: Install Continue CLI - run: npm install -g @continuedev/cli@1.4.25 - - - name: Build Inline Review Prompt - run: | - # Get PR number based on event type - if [ "${{ github.event_name }}" = "pull_request" ]; then - PR_NUMBER="${{ github.event.number }}" - else - # For issue_comment event on a PR - PR_NUMBER="${{ github.event.issue.number }}" - fi - - # Get PR files with line numbers - gh api repos/${{ github.repository }}/pulls/$PR_NUMBER/files > pr_files.json - - # Get PR diff with context - gh pr diff $PR_NUMBER --color=never > pr_diff.txt - - # Annotate diff with position numbers for easy reference - awk ' - /^@@/ { - pos = 0 - print - next - } - /^diff --git/ || /^index / || /^--- / || /^\+\+\+ / { - print - next - } - { - pos++ - printf "[POS:%d] %s\n", pos, $0 - } - ' pr_diff.txt > pr_diff_annotated.txt - - # Create review prompt for inline comments - cat > inline_review_prompt.txt << 'EOF' - You are conducting a detailed inline code review for a pull request. - - Your task is to analyze the code changes and generate specific, actionable review comments for individual lines or small sections of code. - - IMPORTANT: The diff below has been annotated with [POS:N] markers showing the exact position for each line. - - Example of how to use the position markers: - ``` - diff --git a/src/app.js b/src/app.js - index abc123..def456 100644 - --- a/src/app.js - +++ b/src/app.js - @@ -10,4 +10,6 @@ function example() { - [POS:1] console.log("context"); - [POS:2] - const old = "remove this"; - [POS:3] + const new = "add this"; - [POS:4] + const risky = eval(userInput); <-- To comment here, use position: 4 - [POS:5] return result; - [POS:6] + console.log("done"); - @@ -20,3 +22,4 @@ function another() { - [POS:1] let x = 1; - [POS:2] + let y = 2; <-- To comment here, use position: 2 - ``` - - To comment on a line, simply use the number from its [POS:N] marker as the position value. - For example: {"path": "src/app.js", "position": 4, "body": "Avoid using eval with user input"} - - Below is the annotated PR diff: - - EOF - - cat pr_diff_annotated.txt >> inline_review_prompt.txt - - cat >> inline_review_prompt.txt << 'EOF' - - Please analyze these changes and provide inline review comments in the following JSON format: - - { - "review_summary": "Overall assessment of the PR", - "comments": [ - { - "path": "path/to/file.js", - "position": 4, - "body": "Brief, specific comment about this line or section" - } - ] - } - - Focus on: - 1. **Critical Issues**: Security vulnerabilities, bugs that will break functionality - 2. **High Priority**: Performance problems, incorrect logic, missing error handling - 3. **Medium Priority**: Code style violations, potential edge cases, unclear code - 4. **Low Priority**: Suggestions for improvement, refactoring opportunities - - Guidelines for comments: - - Be specific and actionable - - Use the [POS:N] number shown in the diff as the position value - - Keep comments concise but informative - - Suggest concrete improvements when pointing out issues - - Only comment on actual problems or important improvements - - Important: - - Output ONLY valid JSON, no additional text - - Use the exact number from [POS:N] markers as the position - - Only comment on changed lines (lines with + or - prefix) - - Comment on the most important issues first - - Limit to maximum 20 most relevant comments - EOF - env: - GH_TOKEN: ${{ github.token }} - - - name: Run Continue CLI Inline Review - run: | - echo "Running Continue CLI for inline review..." - - # Log the prompt for debugging - echo "===== START REVIEW PROMPT =====" - head -n 50 inline_review_prompt.txt - echo "... [diff content] ..." - tail -n 20 inline_review_prompt.txt - echo "===== END REVIEW PROMPT =====" - - # Run the CLI and capture JSON output - cat inline_review_prompt.txt | cn --readonly --format json --org continuedev --config continuedev/review-bot -p > inline_review_raw.json - - # Log the output for debugging - echo "Initial Continue CLI output:" - cat inline_review_raw.json - - # Validate JSON output - if ! jq empty inline_review_raw.json 2>/dev/null; then - echo "Invalid JSON output from Continue CLI" - echo "{\"review_summary\": \"Failed to generate review\", \"comments\": []}" > inline_review.json - else - # Use the output directly since positions are already correct - cp inline_review_raw.json inline_review.json - echo "Review output:" - cat inline_review.json - fi - env: - CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} - - - name: Post Inline Review Comments - uses: actions/github-script@v7 - with: - script: | - const fs = require('fs'); - - try { - // Read the review output - let reviewData; - try { - const reviewContent = fs.readFileSync('inline_review.json', 'utf8'); - reviewData = JSON.parse(reviewContent); - } catch (parseError) { - console.log('Failed to parse review JSON:', parseError); - reviewData = { - review_summary: 'AI review completed but failed to parse output', - comments: [] - }; - } - - // Get PR number - let prNumber; - if (context.eventName === 'pull_request') { - prNumber = context.payload.pull_request.number; - } else { - prNumber = context.payload.issue.number; - } - - // Get the latest commit SHA - const { data: pr } = await github.rest.pulls.get({ - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: prNumber - }); - - const commitSha = pr.head.sha; - - // Prepare review comments - filter out comments without required fields - const allComments = reviewData.comments || []; - const validComments = allComments.filter(comment => - comment.position && - comment.path && - comment.body && - typeof comment.position === 'number' && - comment.position > 0 - ); - - if (validComments.length < allComments.length) { - console.log(`Filtered out ${allComments.length - validComments.length} comments due to missing/invalid position, path, or body`); - const invalidComments = allComments.filter(c => !validComments.includes(c)); - console.log('Invalid comments:', JSON.stringify(invalidComments, null, 2)); - } - - const comments = validComments.map(comment => ({ - path: comment.path, - position: comment.position, - body: comment.body - })); - - // Create the review - if (comments.length > 0) { - try { - await github.rest.pulls.createReview({ - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: prNumber, - commit_id: commitSha, - body: reviewData.review_summary || 'AI Code Review', - event: 'COMMENT', - comments: comments - }); - console.log(`Successfully created review with ${comments.length} inline comments`); - } catch (reviewError) { - console.log('Failed to create review:', reviewError.message); - - // Fallback: post as a regular comment if review creation fails - const fallbackBody = `## AI Code Review\n\n${reviewData.review_summary}\n\n` + - `*Failed to post ${comments.length} inline comments. Please review the changes manually.*`; - - await github.rest.issues.createComment({ - issue_number: prNumber, - owner: context.repo.owner, - repo: context.repo.repo, - body: fallbackBody - }); - } - } else { - // No inline comments, just post the summary - await github.rest.issues.createComment({ - issue_number: prNumber, - owner: context.repo.owner, - repo: context.repo.repo, - body: `## AI Code Review\n\n${reviewData.review_summary}\n\n*No specific line comments generated.*` - }); - } - - // Add triggered by note if from comment - if (context.eventName === 'issue_comment') { - await github.rest.issues.createComment({ - issue_number: prNumber, - owner: context.repo.owner, - repo: context.repo.repo, - body: `*Inline review triggered by @${context.payload.comment.user.login}*` - }); - } - - } catch (error) { - console.log('Failed to post review:', error.message); - console.log('Error details:', error); - } - env: - GITHUB_TOKEN: ${{ github.token }} - - - name: Upload Review Artifacts - uses: actions/upload-artifact@v4 - if: always() - with: - name: inline-review-results - path: | - inline_review_raw.json - inline_review.json - inline_review_prompt.txt - pr_files.json - pr_diff.txt - pr_diff_annotated.txt - retention-days: 7 + continue-api-key: ${{ secrets.CONTINUE_API_KEY }} + continue-org: continuedev + continue-config: continuedev/review-bot diff --git a/.github/workflows/continue-general-review.yaml b/.github/workflows/continue-general-review.yaml index b78a8c810..3030c6fdf 100644 --- a/.github/workflows/continue-general-review.yaml +++ b/.github/workflows/continue-general-review.yaml @@ -16,171 +16,10 @@ jobs: name: Continue General Review runs-on: ubuntu-latest timeout-minutes: 10 - # Only run if: - # - It's a PR event from a team member (with write/admin permissions) - # - OR it's a comment with @continue-general-review on a PR from a team member - if: | - (github.event_name == 'pull_request' && - (github.event.pull_request.author_association == 'OWNER' || - github.event.pull_request.author_association == 'MEMBER' || - github.event.pull_request.author_association == 'COLLABORATOR')) || - (github.event_name == 'issue_comment' && - github.event.issue.pull_request && - contains(github.event.comment.body, '@continue-general-review') && - (github.event.comment.author_association == 'OWNER' || - github.event.comment.author_association == 'MEMBER' || - github.event.comment.author_association == 'COLLABORATOR')) - steps: - - name: Checkout Repository - uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0 + - name: Run Continue PR Review Action + uses: continuedev/continue/actions/general-review@23d9260536372acf4eb57a41e6ab62bc5869b070 with: - fetch-depth: 0 # Fetch full history for better context - - - name: Setup Node.js - uses: actions/setup-node@v4 - with: - node-version: 20 - - - name: Install Continue CLI - run: npm install -g @continuedev/cli@1.4.25 - - - name: Build PR Review Prompt - run: | - # Get PR number based on event type - if [ "${{ github.event_name }}" = "pull_request" ]; then - PR_NUMBER="${{ github.event.number }}" - else - # For issue_comment event on a PR - PR_NUMBER="${{ github.event.issue.number }}" - fi - - # Get PR diff - gh pr diff $PR_NUMBER > pr_diff.txt - - # Create review prompt - cat > review_prompt.txt << 'EOF' - You are conducting a code review for a pull request. Below is the git diff showing all the changes: - - EOF - - echo "--- PR DIFF START ---" >> review_prompt.txt - cat pr_diff.txt >> review_prompt.txt - echo "--- PR DIFF END ---" >> review_prompt.txt - - cat >> review_prompt.txt << 'EOF' - - Please analyze these changes and provide a comprehensive code review. Consider: - - 1. **Code Quality**: Are there any bugs, performance issues, or code smells? - 2. **Best Practices**: Does the code follow established patterns and conventions? - 3. **Security**: Are there any potential security vulnerabilities? - 4. **Testing**: Are appropriate tests included or updated? - 5. **Documentation**: Is documentation adequate for the changes? - 6. **Architecture**: Do the changes fit well with the existing codebase structure? - - You can use the available tools to explore the codebase and understand context better. - - Format your response as a markdown code review with the following structure: - - ## Code Review Summary - - ### ✅ Strengths - - **[Aspect]**: [Description of what was done well] - - ### ⚠️ Issues Found - - Only include the severity subheaders below if you actually found issues at that level: - - #### Critical - - **[Issue Title]**: [Description of critical issues that must be fixed before merging] - - #### High - - **[Issue Title]**: [Description of high-priority issues that should be fixed] - - #### Medium - - **[Issue Title]**: [Description of issues that should be addressed] - - #### Low - - **[Issue Title]**: [Description of minor issues or nice-to-have improvements] - - - ### 💡 Suggestions - - **[Suggestion Title]**: [Description of improvement recommendations] - - ### 🚀 Overall Assessment - [Provide overall recommendation: APPROVE, REQUEST_CHANGES, or COMMENT] - - Only call the 'exit' tool if you find critical security vulnerabilities or bugs that would break production. - EOF - env: - GH_TOKEN: ${{ github.token }} - - - name: Run Continue CLI Review - run: | - echo "Running Continue CLI with prompt:" - echo "==================================" - cat review_prompt.txt - echo "==================================" - echo "" - - # Run the CLI with hardcoded assistant and pipe output to code_review.md - cat review_prompt.txt | cn --readonly --org continuedev --config continuedev/review-bot -p > code_review.md - env: - CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} - - - name: Upload Review Results - uses: actions/upload-artifact@v4 - if: always() - with: - name: code-review-results - path: | - code_review.md - review_prompt.txt - pr_diff.txt - retention-days: 30 - - - name: Comment PR with Review - if: always() - uses: actions/github-script@v7 - with: - script: | - const fs = require('fs'); - - try { - let reviewContent = ''; - - if (fs.existsSync('code_review.md') && fs.statSync('code_review.md').size > 0) { - reviewContent = fs.readFileSync('code_review.md', 'utf8'); - } else { - reviewContent = '⚠️ AI review completed but no review output was generated. Check the action logs for details.'; - } - - // Get PR number based on event type - let prNumber; - if (context.eventName === 'pull_request') { - prNumber = context.payload.pull_request.number; - } else { - // For issue_comment event - prNumber = context.payload.issue.number; - } - - // Add a header if triggered by comment - if (context.eventName === 'issue_comment') { - reviewContent = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${reviewContent}`; - } - - // Create new comment - await github.rest.issues.createComment({ - issue_number: prNumber, - owner: context.repo.owner, - repo: context.repo.repo, - body: reviewContent - }); - console.log(`Successfully created new comment on PR #${prNumber}`); - } catch (error) { - console.log('Failed to post comment:', error.message); - console.log('Error details:', error); - } - env: - GITHUB_TOKEN: ${{ github.token }} + continue-api-key: ${{ secrets.CONTINUE_API_KEY }} + continue-org: "continuedev" + continue-config: "continuedev/review-bot" diff --git a/.github/workflows/pr-checks.yaml b/.github/workflows/pr-checks.yaml index 6aa1429a8..fb91e8d97 100644 --- a/.github/workflows/pr-checks.yaml +++ b/.github/workflows/pr-checks.yaml @@ -312,6 +312,32 @@ jobs: # GitHub does not have a way of requiring that all checks pass (you must manually select each job) # This action at least lets us manage the list of required tests via source control + pr-review-action-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v5 + - uses: actions/setup-node@v4 + with: + node-version: 20 + + - name: Cache PR review action node modules + uses: actions/cache@v4 + id: pr-review-cache + with: + path: actions/detailed-review/node_modules + key: ${{ runner.os }}-pr-review-action-${{ hashFiles('actions/detailed-review/package.json') }} + + - name: Install dependencies + if: steps.pr-review-cache.outputs.cache-hit != 'true' + run: | + cd actions/detailed-review + npm install + + - name: Run tests + run: | + cd actions/detailed-review + npm test + # so that creators of new jobs can add them to this list require-all-checks-to-pass: if: always() @@ -328,6 +354,7 @@ jobs: - vscode-package-extension-linux - vscode-e2e-tests - jetbrains-tests + - pr-review-action-tests steps: - name: Decide whether the needed jobs succeeded or failed diff --git a/actions/README.md b/actions/README.md new file mode 100644 index 000000000..464867658 --- /dev/null +++ b/actions/README.md @@ -0,0 +1,251 @@ +# Continue PR Review Actions + +GitHub Actions that provide automated code reviews for pull requests using Continue CLI. + +## Available Actions + +This repository provides two GitHub Actions for different review styles: + +### 1. General Review Action + +Provides high-level PR assessment with overall feedback and recommendations. + +- **Path:** `continuedev/continue/actions/general-review@` +- **Trigger:** `@continue-general-review` +- **Output:** Summary comment with strengths, issues, and recommendations + +### 2. Detailed Review Action + +Provides line-by-line inline comments on specific code changes. + +- **Path:** `continuedev/continue/actions/detailed-review@` +- **Trigger:** `@continue-detailed-review` +- **Output:** Inline review comments on specific lines of code + +## Quick Start + +### Using Both Actions Together + +```yaml +name: PR Reviews +on: + pull_request: + types: [opened, ready_for_review] + issue_comment: + types: [created] + +permissions: + contents: read + pull-requests: write + issues: write + +jobs: + general-review: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: continuedev/continue/actions/general-review@ + with: + continue-api-key: ${{ secrets.CONTINUE_API_KEY }} + continue-org: "your-org-name" + continue-config: "your-org-name/review-bot" + + detailed-review: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: continuedev/continue/actions/detailed-review@ + with: + continue-api-key: ${{ secrets.CONTINUE_API_KEY }} + continue-org: "your-org-name" + continue-config: "your-org-name/review-bot" +``` + +### General Review Only + +```yaml +name: PR General Review +on: + pull_request: + types: [opened, ready_for_review] + issue_comment: + types: [created] + +permissions: + contents: read + pull-requests: write + issues: write + +jobs: + review: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: continuedev/continue/actions/general-review@ + with: + continue-api-key: ${{ secrets.CONTINUE_API_KEY }} + continue-org: "your-org-name" + continue-config: "your-org-name/review-bot" +``` + +### Detailed Review Only + +```yaml +name: PR Detailed Review +on: + pull_request: + types: [opened, ready_for_review] + issue_comment: + types: [created] + +permissions: + contents: read + pull-requests: write + issues: write + +jobs: + review: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: continuedev/continue/actions/detailed-review@ + with: + continue-api-key: ${{ secrets.CONTINUE_API_KEY }} + continue-org: "your-org-name" + continue-config: "your-org-name/review-bot" +``` + +## Inputs + +Both actions accept the same inputs: + +| Input | Description | Required | +| ------------------ | -------------------------------------- | -------- | +| `continue-api-key` | API key for Continue service | Yes | +| `continue-org` | Organization for Continue config | Yes | +| `continue-config` | Config path (e.g., "myorg/review-bot") | Yes | + +## Setup Requirements + +### 1. Continue API Key + +Add your Continue API key as a secret named `CONTINUE_API_KEY` in your repository: + +1. Go to your repository's Settings +2. Navigate to Secrets and variables → Actions +3. Click "New repository secret" +4. Name: `CONTINUE_API_KEY` +5. Value: Your Continue API key + +### 2. Continue Configuration + +Set up your review bot configuration in Continue: + +1. Create a configuration for your organization +2. Configure the review bot settings +3. Note your organization name and config path + +### 3. Workflow Permissions + +The workflow requires these permissions: + +- `contents: read` - To checkout and read repository code +- `pull-requests: write` - To post review comments on PRs +- `issues: write` - To respond to comment triggers + +## Triggering Reviews + +Both actions can be triggered in two ways: + +### Automatic Triggers + +- When a PR is opened by a team member (OWNER, MEMBER, or COLLABORATOR) +- When a PR is marked as "ready for review" by a team member + +### Manual Triggers + +Team members can trigger reviews by commenting on any pull request: + +- `@continue-general-review` - Triggers a general review +- `@continue-detailed-review` - Triggers a detailed inline review + +## Review Outputs + +### General Review Output + +The general review provides a structured comment that includes: + +- **Strengths**: What was done well in the PR +- **Issues Found**: Categorized by severity (Critical, High, Medium, Low) +- **Suggestions**: Improvement recommendations +- **Overall Assessment**: Final recommendation (APPROVE, REQUEST_CHANGES, or COMMENT) + +### Detailed Review Output + +The detailed review provides: + +- **Inline Comments**: Specific feedback on individual lines of code +- **Position Markers**: Comments appear directly on the changed lines +- **Review Summary**: Overall assessment of the changes +- **Actionable Feedback**: Specific suggestions for each issue found + +## How It Works + +### General Review Process + +1. Checks out repository code +2. Fetches PR diff using GitHub CLI +3. Generates a comprehensive review prompt +4. Runs Continue CLI with specified configuration +5. Posts review as a PR comment + +### Detailed Review Process + +1. Checks out repository code +2. Fetches PR diff with GitHub API positions +3. Annotates diff with position markers +4. Generates inline review prompt +5. Runs Continue CLI for detailed analysis +6. Posts inline comments using GitHub's review API + +## Versioning + +We recommend using a specific commit SHA for stability and predictability: + +- `@` - Pins to a specific commit for maximum stability (recommended) +- `@main` - Uses the latest code from the main branch (for bleeding edge) +- `@v1` - Uses a version tag when available + +Example: + +```yaml +uses: continuedev/continue/actions/general-review@17fe39cc4f1760838ce4428aad0a984af13f8266 +``` + +## Troubleshooting + +### Review not triggering + +- Ensure the PR author or commenter has appropriate permissions (OWNER, MEMBER, or COLLABORATOR) +- Check that the workflow file is in the default branch +- Verify the Continue API key is correctly set as a repository secret + +### No review output generated + +- Check the action logs for any errors +- Verify your Continue configuration is correct +- Ensure your Continue API key is valid + +### Inline comments not appearing (Detailed Review) + +- Check that the PR has a valid diff +- Verify GitHub API permissions are correct +- Review action logs for position calculation errors + +## Support + +For issues or questions: + +- [Continue Documentation](https://docs.continue.dev) +- [GitHub Issues](https://github.com/continuedev/continue/issues) +- [Discord Community](https://discord.gg/vapESyrFmJ) diff --git a/actions/detailed-review/action.yml b/actions/detailed-review/action.yml new file mode 100644 index 000000000..e0280fa28 --- /dev/null +++ b/actions/detailed-review/action.yml @@ -0,0 +1,350 @@ +name: 'Continue Detailed PR Review' +description: 'Automated inline code review for pull requests using Continue CLI' +author: 'Continue Dev, Inc.' + +inputs: + continue-api-key: + description: 'API key for Continue service' + required: true + continue-org: + description: 'Organization for Continue config' + required: true + continue-config: + description: 'Config path to use (e.g., "myorg/review-bot")' + required: true + +runs: + using: 'composite' + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + + - name: Check Authorization + shell: bash + env: + # Only move the dangerous check to env to prevent shell injection + HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-detailed-review') }} + run: | + # Check if this action should run based on event type and user permissions + SHOULD_RUN="false" + + if [ "${{ github.event_name }}" = "pull_request" ]; then + # Check PR author association + AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}" + if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then + SHOULD_RUN="true" + else + echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)" + fi + elif [ "${{ github.event_name }}" = "issue_comment" ]; then + # Check if it's a PR comment with the trigger phrase + if [ "${{ github.event.issue.pull_request }}" != "" ] && [ "$HAS_TRIGGER_PHRASE" = "true" ]; then + COMMENTER_ASSOC="${{ github.event.comment.author_association }}" + if [ "$COMMENTER_ASSOC" = "OWNER" ] || [ "$COMMENTER_ASSOC" = "MEMBER" ] || [ "$COMMENTER_ASSOC" = "COLLABORATOR" ]; then + SHOULD_RUN="true" + else + echo "::notice::Skipping review - Commenter is not a team member (association: $COMMENTER_ASSOC)" + fi + else + echo "::notice::Skipping review - Comment does not contain @continue-detailed-review trigger, or is not on a PR" + fi + else + echo "::notice::Skipping review - Event type ${{ github.event_name }} is not supported" + fi + + if [ "$SHOULD_RUN" != "true" ]; then + echo "SKIP_REVIEW=true" >> $GITHUB_ENV + exit 0 + fi + + echo "SKIP_REVIEW=false" >> $GITHUB_ENV + + - name: Setup Node.js + if: env.SKIP_REVIEW != 'true' + uses: actions/setup-node@v4 + with: + node-version: 20 + + - name: Install Continue CLI + if: env.SKIP_REVIEW != 'true' + shell: bash + run: npm install -g @continuedev/cli@1.4.25 + + - name: Build Inline Review Prompt + if: env.SKIP_REVIEW != 'true' + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + # Get PR number based on event type + if [ "${{ github.event_name }}" = "pull_request" ]; then + PR_NUMBER="${{ github.event.number }}" + else + # For issue_comment event on a PR + PR_NUMBER="${{ github.event.issue.number }}" + fi + + # Get PR files with line numbers + gh api repos/${{ github.repository }}/pulls/$PR_NUMBER/files > pr_files.json + + # Get PR diff with context + gh pr diff $PR_NUMBER --color=never > pr_diff.txt + + # Annotate diff with GitHub API positions + node ${{ github.action_path }}/annotate-diff.js pr_diff.txt > pr_diff_annotated.txt + + # Debug: Show sample of annotated diff + echo "=== SAMPLE OF ANNOTATED DIFF ===" + head -100 pr_diff_annotated.txt | grep -E "^\[POS:|^@@|^diff --git" || head -50 pr_diff_annotated.txt + echo "=== END SAMPLE ===" + + # Create review prompt for inline comments + cat > inline_review_prompt.txt << 'EOF' + You are conducting a detailed inline code review for a pull request. + + Your task is to analyze the code changes and generate specific, actionable review comments for individual lines or small sections of code. + + IMPORTANT: The diff below has been annotated with [POS:N] markers showing the exact position for each line. + + Example of how to use the position markers: + ``` + diff --git a/src/app.js b/src/app.js + index abc123..def456 100644 + --- a/src/app.js + +++ b/src/app.js + @@ -10,4 +10,6 @@ function example() { + [POS:1] console.log("context"); + [POS:2] - const old = "remove this"; + [POS:3] + const new = "add this"; + [POS:4] + const risky = eval(userInput); <-- To comment here, use position: 4 + [POS:5] return result; + [POS:6] + console.log("done"); + @@ -20,3 +22,4 @@ function another() { + [POS:1] let x = 1; + [POS:2] + let y = 2; <-- To comment here, use position: 2 + ``` + + To comment on a line, simply use the number from its [POS:N] marker as the position value. + For example: {"path": "src/app.js", "position": 4, "body": "Avoid using eval with user input"} + + Below is the annotated PR diff: + + EOF + + cat pr_diff_annotated.txt >> inline_review_prompt.txt + + cat >> inline_review_prompt.txt << 'EOF' + + Please analyze these changes and provide inline review comments in the following JSON format: + + { + "review_summary": "Overall assessment of the PR", + "comments": [ + { + "path": "path/to/file.js", + "position": 4, + "body": "Brief, specific comment about this line or section" + } + ] + } + + Focus on: + 1. **Critical Issues**: Security vulnerabilities, bugs that will break functionality + 2. **High Priority**: Performance problems, incorrect logic, missing error handling + 3. **Medium Priority**: Code style violations, potential edge cases, unclear code + 4. **Low Priority**: Suggestions for improvement, refactoring opportunities + + Guidelines for comments: + - Be specific and actionable + - Use the [POS:N] number shown in the diff as the position value + - Keep comments concise but informative + - Suggest concrete improvements when pointing out issues + - Only comment on actual problems or important improvements + + Important: + - Output ONLY valid JSON, no markdown code blocks or backticks + - Start your response with { and end with } + - Use the exact number from [POS:N] markers as the position + - Only comment on changed lines (lines with + or - prefix) + - Comment on the most important issues first + - Limit to maximum 20 most relevant comments + EOF + + - name: Run Continue CLI Inline Review + if: env.SKIP_REVIEW != 'true' + shell: bash + env: + CONTINUE_API_KEY: ${{ inputs.continue-api-key }} + run: | + echo "Running Continue CLI for inline review..." + + # Validate required inputs + if [ -z "${{ inputs.continue-org }}" ]; then + echo "Error: continue-org input is required" + exit 1 + fi + + if [ -z "${{ inputs.continue-config }}" ]; then + echo "Error: continue-config input is required" + exit 1 + fi + + # Log the prompt for debugging + echo "===== START REVIEW PROMPT =====" + head -n 50 inline_review_prompt.txt + echo "... [diff content] ..." + tail -n 20 inline_review_prompt.txt + echo "===== END REVIEW PROMPT =====" + + # Run the CLI and capture JSON output + cn --readonly --format json --org "${{ inputs.continue-org }}" --config "${{ inputs.continue-config }}" -p "$(cat inline_review_prompt.txt)" > inline_review_raw.json + + # Log the output for debugging + echo "Initial Continue CLI output:" + cat inline_review_raw.json + + # Validate JSON output and use it directly + if ! jq empty inline_review_raw.json 2>/dev/null; then + echo "Error: Invalid JSON output from Continue CLI" + exit 1 + fi + + # Use the JSON output directly + cp inline_review_raw.json inline_review.json + echo "Review output:" + cat inline_review.json + + - name: Post Inline Review Comments + if: env.SKIP_REVIEW != 'true' + uses: actions/github-script@v7 + with: + script: | + const fs = require('fs'); + + try { + // Read the review output + let reviewData; + try { + const reviewContent = fs.readFileSync('inline_review.json', 'utf8'); + reviewData = JSON.parse(reviewContent); + } catch (parseError) { + console.log('Failed to parse review JSON:', parseError); + reviewData = { + review_summary: 'AI review completed but failed to parse output', + comments: [] + }; + } + + // Get PR number + let prNumber; + if (context.eventName === 'pull_request') { + prNumber = context.payload.pull_request.number; + } else { + prNumber = context.payload.issue.number; + } + + // Get the latest commit SHA + const { data: pr } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: prNumber + }); + + const commitSha = pr.head.sha; + + // Prepare review comments - filter out comments without required fields + const allComments = reviewData.comments || []; + const validComments = allComments.filter(comment => + comment.position && + comment.path && + comment.body && + typeof comment.position === 'number' && + comment.position > 0 + ); + + if (validComments.length < allComments.length) { + console.log(`Filtered out ${allComments.length - validComments.length} comments due to missing/invalid position, path, or body`); + const invalidComments = allComments.filter(c => !validComments.includes(c)); + console.log('Invalid comments:', JSON.stringify(invalidComments, null, 2)); + } + + const comments = validComments.map(comment => ({ + path: comment.path, + position: comment.position, + body: comment.body + })); + + // Debug: Log the positions we're trying to use + console.log('Attempting to post comments with positions:'); + comments.forEach(c => { + console.log(` ${c.path}: position ${c.position}`); + }); + + // Create the review + if (comments.length > 0) { + try { + await github.rest.pulls.createReview({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: prNumber, + commit_id: commitSha, + body: `${reviewData.review_summary || 'AI Code Review'}\n\n---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`, + event: 'COMMENT', + comments: comments + }); + console.log(`Successfully created review with ${comments.length} inline comments`); + } catch (reviewError) { + console.log('Failed to create review:', reviewError.message); + + // Fallback: post as a regular comment if review creation fails + const fallbackBody = `## AI Code Review\n\n${reviewData.review_summary}\n\n` + + `*Failed to post ${comments.length} inline comments. Please review the changes manually.*\n\n` + + `---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*`; + + await github.rest.issues.createComment({ + issue_number: prNumber, + owner: context.repo.owner, + repo: context.repo.repo, + body: fallbackBody + }); + } + } else { + // No inline comments, just post the summary + await github.rest.issues.createComment({ + issue_number: prNumber, + owner: context.repo.owner, + repo: context.repo.repo, + body: `## AI Code Review\n\n${reviewData.review_summary}\n\n*No specific line comments generated.*\n\n` + + `---\n*💡 To request a new detailed review, comment \`@continue-detailed-review\`*` + }); + } + + // Add triggered by note if from comment + if (context.eventName === 'issue_comment') { + await github.rest.issues.createComment({ + issue_number: prNumber, + owner: context.repo.owner, + repo: context.repo.repo, + body: `*Inline review triggered by @${context.payload.comment.user.login}*` + }); + } + + } catch (error) { + console.log('Failed to post review:', error.message); + console.log('Error details:', error); + } + env: + GITHUB_TOKEN: ${{ github.token }} + + - name: Upload Review Artifacts + if: env.SKIP_REVIEW != 'true' && always() + uses: actions/upload-artifact@v4 + with: + name: inline-review-results + path: | + inline_review_raw.json + inline_review.json + inline_review_prompt.txt + pr_diff.txt + pr_diff_annotated.txt + retention-days: 7 \ No newline at end of file diff --git a/actions/detailed-review/annotate-diff.js b/actions/detailed-review/annotate-diff.js new file mode 100644 index 000000000..b4bdb803e --- /dev/null +++ b/actions/detailed-review/annotate-diff.js @@ -0,0 +1,96 @@ +#!/usr/bin/env node + +/** + * Annotates a git diff with GitHub API positions + * + * Takes a raw diff and adds [POS:N] markers with the correct + * GitHub API positions (cumulative, with +1 between hunks) + */ + +const fs = require("fs"); + +function annotateDiff(diffContent) { + const lines = diffContent.split("\n"); + const output = []; + let githubPos = 0; + let inHunk = false; + + for (const line of lines) { + // Handle new file - reset position counter + if (line.startsWith("diff --git")) { + githubPos = 0; + inHunk = false; + output.push(line); + continue; + } + + // Pass through other git headers unchanged + if ( + line.startsWith("index ") || + line.startsWith("---") || + line.startsWith("+++") || + line.startsWith("rename ") || + line.startsWith("similarity ") || + line.startsWith("new file") || + line.startsWith("deleted file") || + line.startsWith("old mode") || + line.startsWith("new mode") || + line.startsWith("Binary files") + ) { + output.push(line); + continue; + } + + // Handle hunk headers + if (line.startsWith("@@")) { + if (inHunk) { + githubPos++; // GitHub's +1 between hunks + } + inHunk = true; + output.push(line); + continue; + } + + // Handle "no newline" marker - it counts as a position but isn't annotated + if (line.startsWith("\\ No newline")) { + if (inHunk) { + githubPos++; // GitHub counts this as a position + } + output.push(line); // Don't annotate it + continue; + } + + // Annotate actual diff lines with GitHub positions + if (inHunk) { + githubPos++; + output.push(`[POS:${githubPos}] ${line}`); + } else { + output.push(line); + } + } + + return output.join("\n"); +} + +// Main +function main() { + // Read diff from stdin or file + let input = ""; + + if (process.argv.length > 2) { + // Read from file + input = fs.readFileSync(process.argv[2], "utf8"); + } else { + // Read from stdin + input = fs.readFileSync(0, "utf8"); + } + + const annotated = annotateDiff(input); + console.log(annotated); +} + +if (require.main === module) { + main(); +} + +module.exports = { annotateDiff }; diff --git a/actions/detailed-review/annotate-diff.test.js b/actions/detailed-review/annotate-diff.test.js new file mode 100644 index 000000000..e13c66068 --- /dev/null +++ b/actions/detailed-review/annotate-diff.test.js @@ -0,0 +1,363 @@ +const { annotateDiff } = require("./annotate-diff.js"); + +describe("annotateDiff", () => { + test("single file, single hunk", () => { + const diff = `diff --git a/file.js b/file.js +index abc123..def456 100644 +--- a/file.js ++++ b/file.js +@@ -1,3 +1,4 @@ + line1 + line2 ++added line + line3`; + + const result = annotateDiff(diff); + expect(result).toContain("[POS:1] line1"); + expect(result).toContain("[POS:2] line2"); + expect(result).toContain("[POS:3] +added line"); + expect(result).toContain("[POS:4] line3"); + }); + + test("single file, multiple hunks with +1 between", () => { + const diff = `diff --git a/file.js b/file.js +index abc123..def456 100644 +--- a/file.js ++++ b/file.js +@@ -1,3 +1,3 @@ + line1 +-old line ++new line + line3 +@@ -10,3 +10,3 @@ + line10 +-old line 11 ++new line 11 + line12`; + + const result = annotateDiff(diff); + + // First hunk + expect(result).toContain("[POS:1] line1"); + expect(result).toContain("[POS:2] -old line"); + expect(result).toContain("[POS:3] +new line"); + expect(result).toContain("[POS:4] line3"); + + // Second hunk (should start at 6, because 4 lines + 1 for between hunks) + expect(result).toContain("[POS:6] line10"); + expect(result).toContain("[POS:7] -old line 11"); + expect(result).toContain("[POS:8] +new line 11"); + expect(result).toContain("[POS:9] line12"); + }); + + test("multiple files reset position counter", () => { + const diff = `diff --git a/file1.js b/file1.js +index abc123..def456 100644 +--- a/file1.js ++++ b/file1.js +@@ -1,2 +1,2 @@ + line1 +-old ++new +diff --git a/file2.js b/file2.js +index abc123..def456 100644 +--- a/file2.js ++++ b/file2.js +@@ -1,2 +1,2 @@ + first +-old2 ++new2`; + + const result = annotateDiff(diff); + + // File 1 + expect(result).toContain("[POS:1] line1"); + expect(result).toContain("[POS:2] -old"); + expect(result).toContain("[POS:3] +new"); + + // File 2 - positions should reset + const file2Section = result.split("diff --git a/file2.js")[1]; + expect(file2Section).toContain("[POS:1] first"); + expect(file2Section).toContain("[POS:2] -old2"); + expect(file2Section).toContain("[POS:3] +new2"); + }); + + test("handles new file", () => { + const diff = `diff --git a/newfile.js b/newfile.js +new file mode 100644 +index 0000000..abc123 +--- /dev/null ++++ b/newfile.js +@@ -0,0 +1,3 @@ ++line1 ++line2 ++line3`; + + const result = annotateDiff(diff); + expect(result).toContain("new file mode 100644"); + expect(result).toContain("[POS:1] +line1"); + expect(result).toContain("[POS:2] +line2"); + expect(result).toContain("[POS:3] +line3"); + }); + + test("handles deleted file", () => { + const diff = `diff --git a/deleted.js b/deleted.js +deleted file mode 100644 +index abc123..0000000 +--- a/deleted.js ++++ /dev/null +@@ -1,3 +0,0 @@ +-line1 +-line2 +-line3`; + + const result = annotateDiff(diff); + expect(result).toContain("deleted file mode 100644"); + expect(result).toContain("[POS:1] -line1"); + expect(result).toContain("[POS:2] -line2"); + expect(result).toContain("[POS:3] -line3"); + }); + + test("handles renamed file with changes", () => { + const diff = `diff --git a/old-name.js b/new-name.js +similarity index 95% +rename from old-name.js +rename to new-name.js +index abc123..def456 100644 +--- a/old-name.js ++++ b/new-name.js +@@ -1,3 +1,3 @@ + line1 +-old line ++new line + line3`; + + const result = annotateDiff(diff); + expect(result).toContain("rename from old-name.js"); + expect(result).toContain("rename to new-name.js"); + expect(result).toContain("[POS:1] line1"); + expect(result).toContain("[POS:2] -old line"); + expect(result).toContain("[POS:3] +new line"); + }); + + test("handles no newline at end of file", () => { + const diff = `diff --git a/file.js b/file.js +index abc123..def456 100644 +--- a/file.js ++++ b/file.js +@@ -1,2 +1,2 @@ + line1 +-old line +\\ No newline at end of file ++new line +\\ No newline at end of file`; + + const result = annotateDiff(diff); + expect(result).toContain("[POS:1] line1"); + expect(result).toContain("[POS:2] -old line"); + // Position 3 is the first "No newline" marker (not annotated but counted) + expect(result).toContain("\\ No newline at end of file"); + expect(result).toContain("[POS:4] +new line"); // Position 4 due to "No newline" at position 3 + // Position 5 is the second "No newline" marker (not annotated but counted) + expect(result).toContain("\\ No newline at end of file"); + // No newline markers should not get [POS:N] annotations + expect(result).not.toContain("[POS:3] \\"); + expect(result).not.toContain("[POS:5] \\"); + }); + + test("handles file mode changes", () => { + const diff = `diff --git a/script.sh b/script.sh +old mode 100644 +new mode 100755 +index abc123..def456 100644 +--- a/script.sh ++++ b/script.sh +@@ -1,2 +1,2 @@ + #!/bin/bash +-echo "old" ++echo "new"`; + + const result = annotateDiff(diff); + expect(result).toContain("old mode 100644"); + expect(result).toContain("new mode 100755"); + expect(result).toContain("[POS:1] #!/bin/bash"); + expect(result).toContain('[POS:2] -echo "old"'); + expect(result).toContain('[POS:3] +echo "new"'); + }); + + test("empty diff returns empty", () => { + const diff = ""; + const result = annotateDiff(diff); + expect(result).toBe(""); + }); + + test("handles binary files - modified", () => { + const diff = `diff --git a/image.png b/image.png +index abc123..def456 100644 +Binary files a/image.png and b/image.png differ`; + + const result = annotateDiff(diff); + expect(result).toContain("diff --git a/image.png b/image.png"); + expect(result).toContain("Binary files a/image.png and b/image.png differ"); + // Binary files line should not be annotated + expect(result).not.toContain("[POS:"); + }); + + test("handles binary files - added", () => { + const diff = `diff --git a/newimage.png b/newimage.png +new file mode 100644 +index 0000000..abc123 +Binary files /dev/null and b/newimage.png differ`; + + const result = annotateDiff(diff); + expect(result).toContain("diff --git a/newimage.png b/newimage.png"); + expect(result).toContain("new file mode 100644"); + expect(result).toContain( + "Binary files /dev/null and b/newimage.png differ", + ); + // Binary files line should not be annotated + expect(result).not.toContain("[POS:"); + }); + + test("handles binary files - deleted", () => { + const diff = `diff --git a/oldimage.png b/oldimage.png +deleted file mode 100644 +index abc123..0000000 +Binary files a/oldimage.png and /dev/null differ`; + + const result = annotateDiff(diff); + expect(result).toContain("diff --git a/oldimage.png b/oldimage.png"); + expect(result).toContain("deleted file mode 100644"); + expect(result).toContain( + "Binary files a/oldimage.png and /dev/null differ", + ); + // Binary files line should not be annotated + expect(result).not.toContain("[POS:"); + }); + + test("handles mixed text and binary files", () => { + const diff = `diff --git a/text.js b/text.js +index abc123..def456 100644 +--- a/text.js ++++ b/text.js +@@ -1,2 +1,2 @@ + line1 +-old ++new +diff --git a/image.png b/image.png +index 111111..222222 100644 +Binary files a/image.png and b/image.png differ +diff --git a/another.js b/another.js +index 333333..444444 100644 +--- a/another.js ++++ b/another.js +@@ -1,1 +1,1 @@ +-foo ++bar`; + + const result = annotateDiff(diff); + + // First file (text) + expect(result).toContain("[POS:1] line1"); + expect(result).toContain("[POS:2] -old"); + expect(result).toContain("[POS:3] +new"); + + // Second file (binary) - no positions + expect(result).toContain("Binary files a/image.png and b/image.png differ"); + + // Third file (text) - positions reset + const lastFileSection = result.split("diff --git a/another.js")[1]; + expect(lastFileSection).toContain("[POS:1] -foo"); + expect(lastFileSection).toContain("[POS:2] +bar"); + }); + + test("multiple no newline markers accumulate positions", () => { + const diff = `diff --git a/file.js b/file.js +index abc123..def456 100644 +--- a/file.js ++++ b/file.js +@@ -1,3 +1,3 @@ + line1 +-old1 +\\ No newline at end of file ++new1 +\\ No newline at end of file +@@ -10,3 +10,3 @@ + line10 +-old2 +\\ No newline at end of file ++new2 +\\ No newline at end of file`; + + const result = annotateDiff(diff); + + // First hunk + expect(result).toContain("[POS:1] line1"); + expect(result).toContain("[POS:2] -old1"); + // Position 3 is the first "No newline" marker + expect(result).toContain("[POS:4] +new1"); + // Position 5 is the second "No newline" marker + + // Second hunk (starts at position 7 = 5 + 1 for between hunks + 1) + expect(result).toContain("[POS:7] line10"); + expect(result).toContain("[POS:8] -old2"); + // Position 9 is the third "No newline" marker + expect(result).toContain("[POS:10] +new2"); + // Position 11 is the fourth "No newline" marker + + // Verify "No newline" markers are not annotated + expect(result).not.toContain("[POS:3] \\"); + expect(result).not.toContain("[POS:5] \\"); + expect(result).not.toContain("[POS:9] \\"); + expect(result).not.toContain("[POS:11] \\"); + }); + + test("complex multi-file, multi-hunk diff", () => { + const diff = `diff --git a/src/app.js b/src/app.js +index abc123..def456 100644 +--- a/src/app.js ++++ b/src/app.js +@@ -10,4 +10,5 @@ function example() { + console.log("start"); + const x = 1; +- const y = 2; ++ const y = 3; ++ const z = 4; + return x + y; +@@ -20,3 +21,4 @@ function another() { + let a = 1; + let b = 2; ++ let c = 3; + return a + b; +diff --git a/src/util.js b/src/util.js +index 111111..222222 100644 +--- a/src/util.js ++++ b/src/util.js +@@ -1,2 +1,3 @@ ++import fs from 'fs'; + export function util() { + return true;`; + + const result = annotateDiff(diff); + + // src/app.js - first hunk + expect(result).toContain('[POS:1] console.log("start");'); + expect(result).toContain("[POS:2] const x = 1;"); + expect(result).toContain("[POS:3] - const y = 2;"); + expect(result).toContain("[POS:4] + const y = 3;"); + expect(result).toContain("[POS:5] + const z = 4;"); + expect(result).toContain("[POS:6] return x + y;"); + + // src/app.js - second hunk (7 = 6 + 1 for between hunks) + expect(result).toContain("[POS:8] let a = 1;"); + expect(result).toContain("[POS:9] let b = 2;"); + expect(result).toContain("[POS:10] + let c = 3;"); + expect(result).toContain("[POS:11] return a + b;"); + + // src/util.js - new file, positions reset + const utilSection = result.split("diff --git a/src/util.js")[1]; + expect(utilSection).toContain("[POS:1] +import fs from 'fs';"); + expect(utilSection).toContain("[POS:2] export function util() {"); + expect(utilSection).toContain("[POS:3] return true;"); + }); +}); diff --git a/actions/detailed-review/package.json b/actions/detailed-review/package.json new file mode 100644 index 000000000..4ca8aee1c --- /dev/null +++ b/actions/detailed-review/package.json @@ -0,0 +1,19 @@ +{ + "name": "@continue/pr-review-scripts", + "version": "1.0.0", + "private": true, + "description": "Scripts for Continue PR Review Action", + "scripts": { + "test": "jest", + "test:watch": "jest --watch" + }, + "devDependencies": { + "jest": "^29.7.0" + }, + "jest": { + "testEnvironment": "node", + "testMatch": [ + "**/*.test.js" + ] + } +} diff --git a/actions/general-review/action.yml b/actions/general-review/action.yml new file mode 100644 index 000000000..060494b94 --- /dev/null +++ b/actions/general-review/action.yml @@ -0,0 +1,228 @@ +name: 'Continue PR Review' +description: 'Automated code review for pull requests using Continue CLI' +author: 'Continue Dev, Inc.' + +inputs: + continue-api-key: + description: 'API key for Continue service' + required: true + continue-org: + description: 'Organization for Continue config' + required: true + continue-config: + description: 'Config path to use (e.g., "myorg/review-bot")' + required: true + +runs: + using: 'composite' + steps: + - name: Checkout Repository + uses: actions/checkout@v4 + + - name: Check Authorization + shell: bash + env: + # Only move the dangerous check to env to prevent shell injection + HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-general-review') }} + run: | + # Check if this action should run based on event type and user permissions + SHOULD_RUN="false" + + if [ "${{ github.event_name }}" = "pull_request" ]; then + # Check PR author association + AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}" + if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then + SHOULD_RUN="true" + else + echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)" + fi + elif [ "${{ github.event_name }}" = "issue_comment" ]; then + # Check if it's a PR comment with the trigger phrase + if [ "${{ github.event.issue.pull_request }}" != "" ] && [ "$HAS_TRIGGER_PHRASE" = "true" ]; then + COMMENTER_ASSOC="${{ github.event.comment.author_association }}" + if [ "$COMMENTER_ASSOC" = "OWNER" ] || [ "$COMMENTER_ASSOC" = "MEMBER" ] || [ "$COMMENTER_ASSOC" = "COLLABORATOR" ]; then + SHOULD_RUN="true" + else + echo "::notice::Skipping review - Commenter is not a team member (association: $COMMENTER_ASSOC)" + fi + else + echo "::notice::Skipping review - Comment does not contain @continue-general-review trigger, or is not on a PR" + fi + else + echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}" + fi + + echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV + + - name: Setup Node.js + if: env.SHOULD_RUN == 'true' + uses: actions/setup-node@v4 + with: + node-version: 20 + + - name: Install Continue CLI + if: env.SHOULD_RUN == 'true' + shell: bash + run: npm install -g @continuedev/cli@1.4.25 + + - name: Build PR Review Prompt + if: env.SHOULD_RUN == 'true' + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + # Get PR number based on event type + if [ "${{ github.event_name }}" = "pull_request" ]; then + PR_NUMBER="${{ github.event.number }}" + else + # For issue_comment event on a PR + PR_NUMBER="${{ github.event.issue.number }}" + fi + + # Get PR diff + gh pr diff $PR_NUMBER > pr_diff.txt + + # Create review prompt + cat > review_prompt.txt << 'EOF' + You are conducting a code review for a pull request. Below is the git diff showing all the changes: + + EOF + + echo "--- PR DIFF START ---" >> review_prompt.txt + cat pr_diff.txt >> review_prompt.txt + echo "--- PR DIFF END ---" >> review_prompt.txt + + cat >> review_prompt.txt << 'EOF' + + Please analyze these changes and provide a comprehensive code review. Consider: + + 1. **Code Quality**: Are there any bugs, performance issues, or code smells? + 2. **Best Practices**: Does the code follow established patterns and conventions? + 3. **Security**: Are there any potential security vulnerabilities? + 4. **Testing**: Are appropriate tests included or updated? + 5. **Documentation**: Is documentation adequate for the changes? + 6. **Architecture**: Do the changes fit well with the existing codebase structure? + + You can use the available tools to explore the codebase and understand context better. + + Format your response as a markdown code review with the following structure: + + ## Code Review Summary + + ### ✅ Strengths + - **[Aspect]**: [Description of what was done well] + + ### ⚠️ Issues Found + + Only include the severity subheaders below if you actually found issues at that level: + + #### Critical + - **[Issue Title]**: [Description of critical issues that must be fixed before merging] + + #### High + - **[Issue Title]**: [Description of high-priority issues that should be fixed] + + #### Medium + - **[Issue Title]**: [Description of issues that should be addressed] + + #### Low + - **[Issue Title]**: [Description of minor issues or nice-to-have improvements] + + + ### 💡 Suggestions + - **[Suggestion Title]**: [Description of improvement recommendations] + + ### 🚀 Overall Assessment + [Provide overall recommendation: APPROVE, REQUEST_CHANGES, or COMMENT] + + Only call the 'exit' tool if you find critical security vulnerabilities or bugs that would break production. + EOF + + - name: Run Continue CLI Review + if: env.SHOULD_RUN == 'true' + shell: bash + env: + CONTINUE_API_KEY: ${{ inputs.continue-api-key }} + CONTINUE_ORG: ${{ inputs.continue-org }} + CONTINUE_CONFIG: ${{ inputs.continue-config }} + run: | + echo "Running Continue CLI with prompt:" + echo "==================================" + cat review_prompt.txt + echo "==================================" + echo "" + + # Validate inputs to prevent command injection + if [[ ! "$CONTINUE_ORG" =~ ^[a-zA-Z0-9_-]+$ ]]; then + echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores." + exit 1 + fi + + if [[ ! "$CONTINUE_CONFIG" =~ ^[a-zA-Z0-9_/-]+$ ]]; then + echo "Error: Invalid config path. Must contain only alphanumeric characters, hyphens, underscores, and forward slashes." + exit 1 + fi + + # Run the CLI with validated config + cn --readonly --org "$CONTINUE_ORG" --config "$CONTINUE_CONFIG" -p "$(cat review_prompt.txt)" > code_review.md + + - name: Upload Review Results + if: env.SHOULD_RUN == 'true' && always() + uses: actions/upload-artifact@v4 + with: + name: code-review-results + path: | + code_review.md + review_prompt.txt + pr_diff.txt + retention-days: 30 + + - name: Comment PR with Review + if: env.SHOULD_RUN == 'true' && always() + uses: actions/github-script@v7 + with: + script: | + const fs = require('fs'); + + try { + let reviewContent = ''; + + if (fs.existsSync('code_review.md') && fs.statSync('code_review.md').size > 0) { + reviewContent = fs.readFileSync('code_review.md', 'utf8'); + } else { + reviewContent = '⚠️ AI review completed but no review output was generated. Check the action logs for details.'; + } + + // Get PR number based on event type + let prNumber; + if (context.eventName === 'pull_request') { + prNumber = context.payload.pull_request.number; + } else { + // For issue_comment event + prNumber = context.payload.issue.number; + } + + // Add a header if triggered by comment + if (context.eventName === 'issue_comment') { + reviewContent = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${reviewContent}`; + } + + // Add instructions for re-review + reviewContent += '\n\n---\n*💡 To request a new review, comment `@continue-general-review`*'; + + // Create new comment + await github.rest.issues.createComment({ + issue_number: prNumber, + owner: context.repo.owner, + repo: context.repo.repo, + body: reviewContent + }); + console.log(`Successfully created new comment on PR #${prNumber}`); + } catch (error) { + console.log('Failed to post comment:', error.message); + console.log('Error details:', error); + } + +branding: + icon: 'code' + color: 'blue' \ No newline at end of file