github.com/google/syzkaller@v0.0.0-20251211124644-a066d2bc4b02/.github/workflows/gemini-pr-review.yml (about)

     1  # Copyright 2025 syzkaller project authors. All rights reserved.
     2  # Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
     3  
     4  # Created using gemini cli command /setup-github
     5  
     6  name: '🧐 Gemini Pull Request Review'
     7  
     8  on:
     9  # Pull requests created from the forks doesn't have access to secrets. Disabling this trigger.
    10  #  pull_request:
    11  #    types:
    12  #      - 'opened'
    13  #      - 'reopened'
    14    issue_comment:
    15      types:
    16        - 'created'
    17    pull_request_review_comment:
    18      types:
    19        - 'created'
    20  # Let's disable pull_request_review trigger to reduce the number of "skipped" notifications.
    21  # The majority of these events will not be asking gemini for review.
    22  #  pull_request_review:
    23  #    types:
    24  #      - 'submitted'
    25    workflow_dispatch:
    26      inputs:
    27        pr_number:
    28          description: 'PR number to review'
    29          required: true
    30          type: 'number'
    31  
    32  concurrency:
    33    group: '${{ github.workflow }}-${{ github.head_ref || github.ref }}'
    34    cancel-in-progress: true
    35  
    36  defaults:
    37    run:
    38      shell: 'bash'
    39  
    40  permissions:
    41    contents: 'read'
    42    id-token: 'write'
    43    issues: 'write'
    44    pull-requests: 'write'
    45    statuses: 'write'
    46  
    47  jobs:
    48    review-pr:
    49      # This condition seeks to ensure the action is only run when it is triggered by a trusted user.
    50      # For private repos, users who have access to the repo are considered trusted.
    51      # For public repos, users who members, owners, or collaborators are considered trusted.
    52      if: |-
    53        github.event_name == 'workflow_dispatch' ||
    54        (
    55          github.event_name == 'pull_request' &&
    56          (
    57            github.event.repository.private == true ||
    58            contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.pull_request.author_association)
    59          )
    60        ) ||
    61        (
    62          (
    63            (
    64              github.event_name == 'issue_comment' &&
    65              github.event.issue.pull_request
    66            ) ||
    67            github.event_name == 'pull_request_review_comment'
    68          ) &&
    69          contains(github.event.comment.body, '@gemini-cli /review') &&
    70          (
    71            github.event.repository.private == true ||
    72            contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.comment.author_association)
    73          )
    74        ) ||
    75        (
    76          github.event_name == 'pull_request_review' &&
    77          contains(github.event.review.body, '@gemini-cli /review') &&
    78          (
    79            github.event.repository.private == true ||
    80            contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.review.author_association)
    81          )
    82        )
    83      timeout-minutes: 5
    84      runs-on: 'ubuntu-latest'
    85      steps:
    86        - name: 'Checkout PR code'
    87          uses: 'actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683' # ratchet:actions/checkout@v4
    88  
    89        - name: 'Generate GitHub App Token'
    90          id: 'generate_token'
    91          if: |-
    92            ${{ vars.APP_ID }}
    93          uses: 'actions/create-github-app-token@df432ceedc7162793a195dd1713ff69aefc7379e' # ratchet:actions/create-github-app-token@v2
    94          with:
    95            app-id: '${{ vars.APP_ID }}'
    96            private-key: '${{ secrets.APP_PRIVATE_KEY }}'
    97  
    98        - name: 'Get PR details (pull_request & workflow_dispatch)'
    99          id: 'get_pr'
   100          if: |-
   101            ${{ github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch' }}
   102          env:
   103            GITHUB_TOKEN: '${{ steps.generate_token.outputs.token || secrets.GITHUB_TOKEN }}'
   104            EVENT_NAME: '${{ github.event_name }}'
   105            WORKFLOW_PR_NUMBER: '${{ github.event.inputs.pr_number }}'
   106            PULL_REQUEST_NUMBER: '${{ github.event.pull_request.number }}'
   107          run: |-
   108            set -euo pipefail
   109  
   110            if [[ "${EVENT_NAME}" = "workflow_dispatch" ]]; then
   111              PR_NUMBER="${WORKFLOW_PR_NUMBER}"
   112            else
   113              PR_NUMBER="${PULL_REQUEST_NUMBER}"
   114            fi
   115  
   116            echo "pr_number=${PR_NUMBER}" >> "${GITHUB_OUTPUT}"
   117  
   118            # Get PR details
   119            PR_DATA="$(gh pr view "${PR_NUMBER}" --json title,body,additions,deletions,changedFiles,baseRefName,headRefName)"
   120            echo "pr_data=${PR_DATA}" >> "${GITHUB_OUTPUT}"
   121  
   122            # Get file changes
   123            CHANGED_FILES="$(gh pr diff "${PR_NUMBER}" --name-only)"
   124            {
   125              echo "changed_files<<EOF"
   126              echo "${CHANGED_FILES}"
   127              echo "EOF"
   128            } >> "${GITHUB_OUTPUT}"
   129  
   130  
   131        - name: 'Get PR details (issue_comment & reviews)'
   132          id: 'get_pr_comment'
   133          if: |-
   134            ${{ github.event_name == 'issue_comment' || github.event_name == 'pull_request_review' || github.event_name == 'pull_request_review_comment' }}
   135          env:
   136            GITHUB_TOKEN: '${{ steps.generate_token.outputs.token || secrets.GITHUB_TOKEN }}'
   137            COMMENT_BODY: '${{ github.event.comment.body || github.event.review.body }}'
   138            PR_NUMBER: '${{ github.event.issue.number || github.event.pull_request.number }}'
   139          run: |-
   140            set -euo pipefail
   141  
   142            echo "pr_number=${PR_NUMBER}" >> "${GITHUB_OUTPUT}"
   143  
   144            # Extract additional instructions from comment
   145            ADDITIONAL_INSTRUCTIONS="$(
   146              echo "${COMMENT_BODY}" | sed 's/.*@gemini-cli \/review//' | xargs
   147            )"
   148            echo "additional_instructions=${ADDITIONAL_INSTRUCTIONS}" >> "${GITHUB_OUTPUT}"
   149  
   150            # Get PR details
   151            PR_DATA="$(gh pr view "${PR_NUMBER}" --json title,body,additions,deletions,changedFiles,baseRefName,headRefName)"
   152            echo "pr_data=${PR_DATA}" >> "${GITHUB_OUTPUT}"
   153  
   154            # Get file changes
   155            CHANGED_FILES="$(gh pr diff "${PR_NUMBER}" --name-only)"
   156            {
   157              echo "changed_files<<EOF"
   158              echo "${CHANGED_FILES}"
   159              echo "EOF"
   160            } >> "${GITHUB_OUTPUT}"
   161  
   162        - name: 'Run Gemini PR Review'
   163          uses: 'google-github-actions/run-gemini-cli@v0'
   164          id: 'gemini_pr_review'
   165          env:
   166            GEMINI_API_KEY: '${{ secrets.GEMINI_API_KEY }}'
   167            GITHUB_TOKEN: '${{ steps.generate_token.outputs.token || secrets.GITHUB_TOKEN }}'
   168            PR_NUMBER: '${{ steps.get_pr.outputs.pr_number || steps.get_pr_comment.outputs.pr_number }}'
   169            PR_DATA: '${{ steps.get_pr.outputs.pr_data || steps.get_pr_comment.outputs.pr_data }}'
   170            CHANGED_FILES: '${{ steps.get_pr.outputs.changed_files || steps.get_pr_comment.outputs.changed_files }}'
   171            ADDITIONAL_INSTRUCTIONS: '${{ steps.get_pr.outputs.additional_instructions || steps.get_pr_comment.outputs.additional_instructions }}'
   172            REPOSITORY: '${{ github.repository }}'
   173          with:
   174            gemini_cli_version: '${{ vars.GEMINI_CLI_VERSION }}'
   175            gcp_workload_identity_provider: '${{ vars.GCP_WIF_PROVIDER }}'
   176            gcp_project_id: '${{ vars.GOOGLE_CLOUD_PROJECT }}'
   177            gcp_location: '${{ vars.GOOGLE_CLOUD_LOCATION }}'
   178            gcp_service_account: '${{ vars.SERVICE_ACCOUNT_EMAIL }}'
   179            gemini_api_key: '${{ secrets.GEMINI_API_KEY }}'
   180            use_vertex_ai: '${{ vars.GOOGLE_GENAI_USE_VERTEXAI }}'
   181            use_gemini_code_assist: '${{ vars.GOOGLE_GENAI_USE_GCA }}'
   182            settings: |-
   183              {
   184                "debug": ${{ fromJSON(env.DEBUG || env.ACTIONS_STEP_DEBUG || false) }},
   185                "maxSessionTurns": 20,
   186                "mcpServers": {
   187                  "github": {
   188                    "command": "docker",
   189                    "args": [
   190                      "run",
   191                      "-i",
   192                      "--rm",
   193                      "-e",
   194                      "GITHUB_PERSONAL_ACCESS_TOKEN",
   195                      "ghcr.io/github/github-mcp-server"
   196                    ],
   197                    "includeTools": [
   198                      "create_pending_pull_request_review",
   199                      "add_comment_to_pending_review",
   200                      "submit_pending_pull_request_review"
   201                    ],
   202                    "env": {
   203                      "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
   204                    }
   205                  }
   206                },
   207                "coreTools": [
   208                  "run_shell_command(echo)",
   209                  "run_shell_command(gh pr view)",
   210                  "run_shell_command(gh pr diff)",
   211                  "run_shell_command(cat)",
   212                  "run_shell_command(head)",
   213                  "run_shell_command(tail)",
   214                  "run_shell_command(grep)"
   215                ],
   216                "telemetry": {
   217                  "enabled": false,
   218                  "target": "gcp"
   219                }
   220              }
   221            prompt: |-
   222              ## Role
   223  
   224              You are an expert code reviewer. You have access to tools to gather
   225              PR information and perform the review on GitHub. Use the available tools to
   226              gather information; do not ask for information to be provided.
   227  
   228              ## Requirements
   229              1. All feedback must be left on GitHub.
   230              2. Any output that is not left in GitHub will not be seen.
   231  
   232              ## Steps
   233  
   234              Start by running these commands to gather the required data:
   235              1. Run: echo "${REPOSITORY}" to get the github repository in <OWNER>/<REPO> format
   236              2. Run: echo "${PR_DATA}" to get PR details (JSON format)
   237              3. Run: echo "${CHANGED_FILES}" to get the list of changed files
   238              4. Run: echo "${PR_NUMBER}" to get the PR number
   239              5. Run: echo "${ADDITIONAL_INSTRUCTIONS}" to see any specific review
   240                 instructions from the user
   241              6. Run: gh pr diff "${PR_NUMBER}" to see the full diff and reference
   242              Context section to understand it
   243              7. For any specific files, use: cat filename, head -50 filename, or
   244                 tail -50 filename
   245              8. If ADDITIONAL_INSTRUCTIONS contains text, prioritize those
   246                 specific areas or focus points in your review. Common instruction
   247                 examples: "focus on security", "check performance", "review error
   248                 handling", "check for breaking changes"
   249  
   250              ## Guideline
   251              ### Core Guideline(Always applicable)
   252  
   253              1. Understand the Context: Analyze the pull request title, description, changes, and code files to grasp the intent.
   254              2. Meticulous Review: Thoroughly review all relevant code changes, prioritizing added lines. Consider the specified
   255                focus areas and any provided style guide.
   256              3. Comprehensive Review: Ensure that the code is thoroughly reviewed, as it's important to the author
   257                that you identify any and all relevant issues (subject to the review criteria and style guide).
   258                Missing any issues will lead to a poor code review experience for the author.
   259              4. Constructive Feedback:
   260                * Provide clear explanations for each concern.
   261                * Offer specific, improved code suggestions and suggest alternative approaches, when applicable.
   262                  Code suggestions in particular are very helpful so that the author can directly apply them
   263                  to their code, but they must be accurately anchored to the lines that should be replaced.
   264              5. Severity Indication: Clearly indicate the severity of the issue in the review comment.
   265                This is very important to help the author understand the urgency of the issue.
   266                The severity should be one of the following (which are provided below in decreasing order of severity):
   267                * `critical`: This issue must be addressed immediately, as it could lead to serious consequences
   268                  for the code's correctness, security, or performance.
   269                * `high`: This issue should be addressed soon, as it could cause problems in the future.
   270                * `medium`: This issue should be considered for future improvement, but it's not critical or urgent.
   271                * `low`: This issue is minor or stylistic, and can be addressed at the author's discretion.
   272              6. Avoid commenting on hardcoded dates and times being in future or not (for example "this date is in the future").
   273                * Remember you don't have access to the current date and time and leave that to the author.
   274              7. Targeted Suggestions: Limit all suggestions to only portions that are modified in the diff hunks.
   275                This is a strict requirement as the GitHub (and other SCM's) API won't allow comments on parts of code files that are not
   276                included in the diff hunks.
   277              8. Code Suggestions in Review Comments:
   278                * Succinctness: Aim to make code suggestions succinct, unless necessary. Larger code suggestions tend to be
   279                  harder for pull request authors to commit directly in the pull request UI.
   280                * Valid Formatting:  Provide code suggestions within the suggestion field of the JSON response (as a string literal,
   281                  escaping special characters like \n, \\, \").  Do not include markdown code blocks in the suggestion field.
   282                  Use markdown code blocks in the body of the comment only for broader examples or if a suggestion field would
   283                  create an excessively large diff.  Prefer the suggestion field for specific, targeted code changes.
   284                * Line Number Accuracy: Code suggestions need to align perfectly with the code it intend to replace.
   285                  Pay special attention to line numbers when creating comments, particularly if there is a code suggestion.
   286                  Note the patch includes code versions with line numbers for the before and after code snippets for each diff, so use these to anchor
   287                  your comments and corresponding code suggestions.
   288                * Compilable: Code suggestions should be compilable code snippets that can be directly copy/pasted into the code file.
   289                  If the suggestion is not compilable, it will not be accepted by the pull request. Note that not all languages Are
   290                  compiled of course, so by compilable here, we mean either literally or in spirit.
   291                * Inline Code Comments: Feel free to add brief comments to the code suggestion if it enhances the underlying code readability.
   292                  Just make sure that the inline code comments add value, and are not just restating what the code does. Don't use
   293                  inline comments to "teach" the author (use the review comment body directly for that), instead use it if it's beneficial
   294                  to the readability of the code itself.
   295              10. Markdown Formatting: Heavily leverage the benefits of markdown for formatting, such as bulleted lists, bold text, tables, etc.
   296              11. Avoid mistaken review comments:
   297                * Any comment you make must point towards a discrepancy found in the code and the best practice surfaced in your feedback.
   298                  For example, if you are pointing out that constants need to be named in all caps with underscores,
   299                  ensure that the code selected by the comment does not already do this, otherwise it's confusing let alone unnecessary.
   300              12. Remove Duplicated code suggestions:
   301                * Some provided code suggestions are duplicated, please remove the duplicated review comments.
   302              13. Don't Approve The Pull Request
   303              14. Reference all shell variables as "${VAR}" (with quotes and braces)
   304  
   305              ### Review Criteria (Prioritized in Review)
   306  
   307              * Correctness: Verify code functionality, handle edge cases, and ensure alignment between function
   308                descriptions and implementations.  Consider common correctness issues (logic errors, error handling,
   309                race conditions, data validation, API usage, type mismatches).
   310              * Efficiency: Identify performance bottlenecks, optimize for efficiency, and avoid unnecessary
   311                loops, iterations, or calculations. Consider common efficiency issues (excessive loops, memory
   312                leaks, inefficient data structures, redundant calculations, excessive logging, etc.).
   313              * Maintainability: Assess code readability, modularity, and adherence to language idioms and
   314                best practices. Consider common maintainability issues (naming, comments/documentation, complexity,
   315                code duplication, formatting, magic numbers).  State the style guide being followed (defaulting to
   316                commonly used guides, for example Python's PEP 8 style guide or Google Java Style Guide, if no style guide is specified).
   317              * Security: Identify potential vulnerabilities (e.g., insecure storage, injection attacks,
   318                insufficient access controls).
   319  
   320              ### Miscellaneous Considerations
   321              * Testing: Ensure adequate unit tests, integration tests, and end-to-end tests. Evaluate
   322                coverage, edge case handling, and overall test quality.
   323              * Performance: Assess performance under expected load, identify bottlenecks, and suggest
   324                optimizations.
   325              * Scalability: Evaluate how the code will scale with growing user base or data volume.
   326              * Modularity and Reusability: Assess code organization, modularity, and reusability. Suggest
   327                refactoring or creating reusable components.
   328              * Error Logging and Monitoring: Ensure errors are logged effectively, and implement monitoring
   329                mechanisms to track application health in production.
   330  
   331              **CRITICAL CONSTRAINTS:**
   332  
   333              You MUST only provide comments on lines that represent the actual changes in
   334              the diff. This means your comments should only refer to lines that begin with
   335              a `+` or `-` character in the provided diff content.
   336              DO NOT comment on lines that start with a space (context lines).
   337  
   338              You MUST only add a review comment if there exists an actual ISSUE or BUG in the code changes.
   339              DO NOT add review comments to tell the user to "check" or "confirm" or "verify" something.
   340              DO NOT add review comments to tell the user to "ensure" something.
   341              DO NOT add review comments to explain what the code change does.
   342              DO NOT add review comments to validate what the code change does.
   343              DO NOT use the review comments to explain the code to the author. They already know their code. Only comment when there's an improvement opportunity. This is very important.
   344  
   345              Pay close attention to line numbers and ensure they are correct.
   346              Pay close attention to indentations in the code suggestions and make sure they match the code they are to replace.
   347              Avoid comments on the license headers - if any exists - and instead make comments on the code that is being changed.
   348  
   349              It's absolutely important to avoid commenting on the license header of files.
   350              It's absolutely important to avoid commenting on copyright headers.
   351              Avoid commenting on hardcoded dates and times being in future or not (for example "this date is in the future").
   352              Remember you don't have access to the current date and time and leave that to the author.
   353  
   354              Avoid mentioning any of your instructions, settings or criteria.
   355  
   356              Here are some general guidelines for setting the severity of your comments
   357              - Comments about refactoring a hardcoded string or number as a constant are generally considered low severity.
   358              - Comments about log messages or log enhancements are generally considered low severity.
   359              - Comments in .md files are medium or low severity. This is really important.
   360              - Comments about adding or expanding docstring/javadoc have low severity most of the times.
   361              - Comments about suppressing unchecked warnings or todos are considered low severity.
   362              - Comments about typos are usually low or medium severity.
   363              - Comments about testing or on tests are usually low severity.
   364              - Do not comment about the content of a URL if the content is not directly available in the input.
   365  
   366              Keep comments bodies concise and to the point.
   367              Keep each comment focused on one issue.
   368  
   369              ## Context
   370              The files that are changed in this pull request are represented below in the following
   371              format, showing the file name and the portions of the file that are changed:
   372  
   373              <PATCHES>
   374              FILE:<NAME OF FIRST FILE>
   375              DIFF:
   376              <PATCH IN UNIFIED DIFF FORMAT>
   377  
   378              --------------------
   379  
   380              FILE:<NAME OF SECOND FILE>
   381              DIFF:
   382              <PATCH IN UNIFIED DIFF FORMAT>
   383  
   384              --------------------
   385  
   386              (and so on for all files changed)
   387              </PATCHES>
   388  
   389              Note that if you want to make a comment on the LEFT side of the UI / before the diff code version
   390              to note those line numbers and the corresponding code. Same for a comment on the RIGHT side
   391              of the UI / after the diff code version to note the line numbers and corresponding code.
   392              This should be your guide to picking line numbers, and also very importantly, restrict
   393              your comments to be only within this line range for these files, whether on LEFT or RIGHT.
   394              If you comment out of bounds, the review will fail, so you must pay attention the file name,
   395              line numbers, and pre/post diff versions when crafting your comment.
   396  
   397              Here are the patches that were implemented in the pull request, per the
   398              formatting above:
   399  
   400              The get the files changed in this pull request, run:
   401              "$(gh pr diff "${PR_NUMBER}" --patch)" to get the list of changed files PATCH
   402  
   403              ## Review
   404  
   405              Once you have the information and are ready to leave a review on GitHub, post the review to GitHub using the GitHub MCP tool by:
   406              1. Creating a pending review: Use the mcp__github__create_pending_pull_request_review to create a Pending Pull Request Review.
   407  
   408              2. Adding review comments:
   409                  2.1 Use the mcp__github__add_comment_to_pending_review to add comments to the Pending Pull Request Review. Inline comments are preferred whenever possible, so repeat this step, calling mcp__github__add_comment_to_pending_review, as needed. All comments about specific lines of code should use inline comments. It is preferred to use code suggestions when possible, which include a code block that is labeled "suggestion", which contains what the new code should be. All comments should also have a severity. The syntax is:
   410                    Normal Comment Syntax:
   411                    <COMMENT>
   412                    {{SEVERITY}} {{COMMENT_TEXT}}
   413                    </COMMENT>
   414  
   415                    Inline Comment Syntax: (Preferred):
   416                    <COMMENT>
   417                    {{SEVERITY}} {{COMMENT_TEXT}}
   418                    ```suggestion
   419                    {{CODE_SUGGESTION}}
   420                    ```
   421                    </COMMENT>
   422  
   423                    Prepend a severity emoji to each comment:
   424                    - 🟢 for low severity
   425                    - 🟡 for medium severity
   426                    - 🟠 for high severity
   427                    - 🔴 for critical severity
   428                    - 🔵 if severity is unclear
   429  
   430                    Including all of this, an example inline comment would be:
   431                    <COMMENT>
   432                    🟢 Use camelCase for function names
   433                    ```suggestion
   434                    myFooBarFunction
   435                    ```
   436                    </COMMENT>
   437  
   438                    A critical severity example would be:
   439                    <COMMENT>
   440                    🔴 Remove storage key from GitHub
   441                    ```suggestion
   442                    ```
   443  
   444              3. Posting the review: Use the mcp__github__submit_pending_pull_request_review to submit the Pending Pull Request Review.
   445  
   446                3.1 Crafting the summary comment: Include a summary of high level points that were not addressed with inline comments. Be concise. Do not repeat details mentioned inline.
   447  
   448                  Structure your summary comment using this exact format with markdown:
   449                  ## 📋 Review Summary
   450  
   451                  Provide a brief 2-3 sentence overview of the PR and overall
   452                  assessment.
   453  
   454                  ## 🔍 General Feedback
   455                  - List general observations about code quality
   456                  - Mention overall patterns or architectural decisions
   457                  - Highlight positive aspects of the implementation
   458                  - Note any recurring themes across files
   459  
   460              ## Final Instructions
   461  
   462              Remember, you are running in a VM and no one reviewing your output. Your review must be posted to GitHub using the MCP tools to create a pending review, add comments to the pending review, and submit the pending review.
   463  
   464  
   465        - name: 'Post PR review failure comment'
   466          if: |-
   467            ${{ failure() && steps.gemini_pr_review.outcome == 'failure' }}
   468          uses: 'actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea'
   469          with:
   470            github-token: '${{ steps.generate_token.outputs.token || secrets.GITHUB_TOKEN }}'
   471            script: |-
   472              github.rest.issues.createComment({
   473                owner: '${{ github.repository }}'.split('/')[0],
   474                repo: '${{ github.repository }}'.split('/')[1],
   475                issue_number: '${{ steps.get_pr.outputs.pr_number || steps.get_pr_comment.outputs.pr_number }}',
   476                body: 'There is a problem with the Gemini CLI PR review. Please check the [action logs](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) for details.'
   477              })