DEV Community

Cover image for Automated GitHub Code Reviews Using Google Gemini Update: Enterprise-Ready, Multimodal, and Battle-Hardened
Darren "Dazbo" Lester for Google Developer Experts

Posted on Originally published at Medium on

Automated GitHub Code Reviews Using Google Gemini Update: Enterprise-Ready, Multimodal, and Battle-Hardened

You are in Part 2 of the series "Automated GitHub Code Reviews Using Google Gemini"

πŸ—ΊοΈ Series Navigation

  • Part 1: Automated GitHub Code Reviews Using Google Gemini β€” Why I built a super-fast, native composite GitHub Action to replace Google's sunsetted run-gemini-cli and Gemini Code Assist integrations, and how to get up and running in three minutes.
  • Part 2: Enterprise-Ready AI Code Reviews & Issue Triage with Google Gemini (This Article) β€” How the action evolved from a fast weekend replacement into an enterprise-grade, multimodal code review and triage engine β€” featuring Gemini 3.8 Flash, visual PR diffing, bounded dynamic context selection, Gemini Enterprise Agent Platform billing attribution, supply-chain hardening, and battle-tested production fixes.

Back for the Update!

Howdy friends, and welcome back!

When I published Part 1 back in July, I had a very specific itch to scratch. Google had just turned off the lights on both run-gemini-cli and the consumer Gemini Code Assist GitHub integration as part of the transition to the Google Antigravity suite. And consequently, my automated agentic pull request reviews stopped working. Sad times.

So, I rolled up my sleeves...

Darren: Sleeves rolled up, ready to review code

(Okay, that's actually an attempt at using AI to put me in a Don Johnson outfit.)

... And built a drop-in replacement: the Gemini PR Review & Triage Action (also available directly on the GitHub Marketplace).

Since launching Part 1, something awesome happened. Not only did I start dogfooding the action heavily across every single repository I maintain, but developers in the community started adopting it β€” and it is now actively running in production inside at least one enterprise organisation!

A massive shoutout here goes to my fellow Google Developer Expert (GDE), Sascha Heyer. Sascha rolled the action out across real production repositories, battle-tested it against enterprise edge cases, and contributed a phenomenal series of pull requests β€” from real-dollar cost estimation and Gemini Enterprise Agent Platform billing labels to automated review thread resolution, per-file content caps, competing bot filtering, and supply-chain lockfile hardening.

Through dozens of releases (taking us from v1.4 all the way to v1.8.3), this collaboration has transformed the tool from a "fast drop-in replacement" into what I genuinely believe is the de facto Google Gemini-based code reviewer and issue triager for GitHub.

Even better: it is 100% free and open-source. There are no SaaS subscriptions and no per-seat licensing fees. You simply bring your own Gemini API key or Google Cloud project, and you pay only for the raw tokens you consume β€” which, thanks to our built-in context caching, typically works out to $0.02 to $0.04 per review!

In this post, I'm going to:

  1. Recap the What, the Why, and the Unique Selling Points (USPs) for anyone new to the party.
  2. Share the complete current feature list so you can see everything the action packs under the bonnet today.
  3. Deep-dive into the major new features, architectural upgrades, and battle-hardened bug fixes we've shipped since Part 1 β€” including why this solution is now thoroughly enterprise-ready.

Grab a piΓ±a colada (or a strong coffee), and let's dive in!


Recap: The What, The Why, and The USPs

If you missed Part 1, here is the sixty-second elevator pitch on why automated AI code reviews in CI/CD are such a game-changer β€” and why this specific action hits different.

Automated Code Review Pipeline with Gemini AI

The Problem with Traditional (and Local AI) Code Reviews

In a traditional workflow, you open a Pull Request and wait hours (or days) for a human colleague to context-switch away from their own work and review your code. When they finally get to it, human reviews are notoriously variable: some reviewers rubber-stamp a 500-line diff with "LGTM", while others bikeshed variable names and miss a glaring SQL injection vulnerability.

"Ah," you might say, "but I already use an AI coding assistant in my IDE!"

Me too! I live in Google Antigravity every day. But relying solely on your local IDE agent to review the code it just helped you write introduces a massive blind spot: Session Bias.

1. The "Clean Slate" Advantage

When you pair-programme with an AI assistant in your IDE, that agent accumulates your entire conversational history. It knows what you tried, why you took a shortcut, and what compromises you made to get the tests passing. Because it understands your intent so well, it frequently forgives subtle regressions, missing edge cases, or architectural drift.

By running our Gemini code reviewer inside a GitHub Action on every Pull Request, the reviewer starts with a completely clean slate. It has zero knowledge of your local chat history or how much you struggled with a module. It objectively evaluates the raw git diff against your repository's codebase context and coding standards. Time and time again, this stateless reviewer catches bugs, security gaps, and documentation discrepancies that my local IDE session glossed right over!

2. Blazing Speed: Native Composite Action + Astral's uv

Legacy actions (like the old run-gemini-cli) built or pulled hefty Docker containers on every single run, or used sluggish pip install steps that burned through GitHub Actions runner minutes before a single token was ever sent to Gemini.

I architected gemini-review-action as a native Composite Action powered by Astral's blazingly fast uv package manager. There are no Docker container builds and no slow dependency resolution phases. The environment boots in a couple of seconds and posts line-specific review feedback almost immediately.

3. Deep Context + 90% Cost Savings via Gemini Context Caching

Most basic AI review scripts only feed the raw git diff to the model. Without knowing what the rest of your repository looks like, an LLM can't tell if a change breaks an interface defined in another module or violates your project's architectural patterns.

Our action features a Hybrid Codebase Context Engine paired with Stateless Gemini Context Caching:

  • For repositories under 1.5 MB of text, it loads the entire codebase into context (Full Context Mode).
  • For massive repositories and monorepos over 1.5 MB, it switches to Sparse Context Mode, feeding the full directory tree, core manifests/documentation (README.md, ARCHITECTURE.md, AGENTS.md, pyproject.toml, etc.), and dynamically selecting the most relevant sister modules.
  • Whenever repository context exceeds ~32k tokens (about 100K characters), the action provisions an ephemeral, server-side Gemini Context Cache (CachedContent). Subsequent PR pushes and multi-turn tool calls reuse that cache handle automatically β€” delivering a 90% discount on cached input tokens without requiring any local runner disk persistence. (Enterprise DLP Note: On Gemini Enterprise Agent Platform, the cache is strictly tenant-isolated within your Google Cloud project and region, bounded by an automatic 1-hour TTL, and fully covered by Google Cloud's zero-training enterprise data governance commitments.)

The Complete Feature Matrix (What's in the Box Today)

Before we unpack the new engineering deep-dives, here is the complete summary of what Dazbo's Gemini PR Review & Triage Action (currently at version 1.8.3) gives you right out of the box:

Gemini PR Review & Triage Features Overview

Core Review & Triage Capabilities

  • AI-Powered Pull Request Reviews: Constructive, severity-graded (πŸ”΄ Critical, 🟠 High, 🟑 Medium, 🟒 Low), line-specific inline feedback powered by the latest Gemini Flash model (currently gemini-3.8-flash) by default.
  • One-Click Interactive Suggestions: Formats exact code fixes inside native GitHub suggestion blocks so developers can commit fixes directly in the GitHub UI with a single click.
  • Multi-Axis Quality Framework: Evaluates every PR systematically across five core engineering axes: Correctness & Verification, Readability & Simplicity, Architecture & System Design, Security & Data Hardening, and Performance & Efficiency.
  • Holistic Documentation & Blog Review: Evaluates Markdown documentation, READMEs, ADRs, and technical articles alongside source code for accuracy and completeness.
  • Automated Issue Triage: Dynamically classifies, prioritises, and applies repository labels to incoming or reopened GitHub issues based on issue descriptions, discussion comments, and attached screenshots.
  • On-Demand /gemini-review Trigger: Re-trigger reviews at any time via PR comments, protected by strict OWNER, MEMBER, and COLLABORATOR authorisation guards so random internet strangers can't drain your API quota.

Multimodal & Context Intelligence

  • Multimodal Context & Visual PR Diffing: Automatically extracts local images and PDFs referenced in Markdown files, and performs side-by-side visual PR diffing (base_sha vs head_sha) whenever images (.png, .jpg, .webp, .gif, .svg) are modified in a PR.
  • Multimodal Issue Triage (Remote Screenshots): Automatically extracts and securely fetches remote screenshots embedded in GitHub issues (including private repo user-attachments) so Gemini can visually inspect UI bug reports and stack-trace screenshots.
  • Deterministic Image Downscaling: Automatically resizes large images (>600 KB) down to a maximum of 300 KB before sending to Gemini, protecting your token budget and keeping latency low while passing SVGs and PDFs through lossless.
  • Hybrid Codebase Context & Bounded Dynamic Selection: Seamless switching between Full Context Mode and Sparse Context Mode, using proximity/import heuristics and a 4-tier architectural selector to pick the best sister files in large monorepos.
  • Per-File Content Truncation & Token Budget Safeguards: Caps individual massive files (like generated OpenAPI schemas) at 128 KB and runs preflight token checks so a single huge file never crashes your review.
  • Google Developer Knowledge MCP Integration: Queries official, live Google documentation (for Google Cloud, Gemini, Firebase, Android, etc.) via Model Context Protocol (MCP) during the review (automatically activated when the Developer Knowledge API is enabled on your API key or GCP project).
  • On-Demand Agent Skills Registry: Dynamically discovers and loads relevant coding standards from .agents/skills/. And a curated set of starter skills for Google Cloud, ADK, and Gemini APIs are already bundled.

Conversational Memory & Workflow Automation

  • PR Comment & Discussion Thread History: Retrieves prior inline review threads and PR comments across commits. Follows an opinionated resolution matrix: celebrates resolved items (### βœ… Resolved Items from Prior Reviews), respects developer deferrals and architectural justifications, and re-flags silently ignored issues.
  • Auto-Resolving Addressed GitHub Threads: Optionally resolves GitHub review conversation threads automatically (resolve_addressed_threads: 'true') once Gemini verifies the fix, unblocking "Require conversation resolution before merging" branch protection rules.
  • Competing Bot Author Exclusion: Filter out comments from secondary bots (exclude_comment_authors: 'claude[bot]') so your Gemini review remains genuinely independent and you don't pay input tokens to process another bot's prose.
  • Smart Inline-Suggestion Commit Skipping: Automatically detects commits generated by clicking "Commit suggestion" in the GitHub UI and skips redundant re-reviews (skip_inline_suggestions: 'true').

Customisation, FinOps & Enterprise Security

  • Zero-Config Agentic Installation Skill: Equip your IDE agent via npx skills add derailed-dash/gemini-review-action -y -g --skill install-gemini-code-review-action, then simply ask it to "Set up Gemini review in this repo" β€” your agent handles configuration preferences, template generation, and secret setup guidance automatically.
  • Extending vs Replacing Guardrails: Easily append organisation- or team-specific rules via .github/review-instruction-additions.md or the custom_instructions workflow input without losing the built-in quality framework β€” or you can override the entire prompt via .github/commands/gemini-review.toml.
  • Configurable Personas & Locales: Choose your reviewer's language (English (UK) by default) and personality (straight, dazbo, palpatine, or rick). Careful now... Palpatine is not very forgiving.

Vader reviewing code:

  • Reasoning & Thinking Budget Control: Defaults to dynamic thinking (the recommended out-of-the-box setting for PR reviews, letting Gemini scale reasoning to match diff complexity). You can also clamp thinking_level (low, medium, high, or an exact integer token budget) for predictable FinOps cost ceilings, or set it to 'off' to make Issue Triage blazing fast and ultra-cheap.
  • Tokenomics & Dollar Cost Telemetry: Appends a collapsible table to every review breaking down uncached input, cached input, comment history, thinking tokens, output tokens, and the estimated dollar cost.
  • Enterprise Keyless Authentication (WIF): Full support for Google Cloud Workload Identity Federation (WIF) and Application Default Credentials (ADC) via Gemini Enterprise Agent Platform (formerly Vertex AI) β€” zero long-lived API keys required!
  • Gemini Enterprise Agent Platform Billing Labels: Automatically tags Enterprise Agent Platform requests with component and repo (plus custom billing_labels like team=platform,cost_centre=engineering) for granular FinOps chargeback in BigQuery billing exports.
  • Supply-Chain & Runtime Hardening: Enforces immutable dependency lockfiles (uv run --locked), SHA-pinned internal actions, path-traversal containment, and automatic fork PR skipping.

Enterprise-Ready by Design: Security, Governance, and FinOps

When hobbyists pick a GitHub Action, they just want to paste an API key into a secret and see comments appear on their PR. When enterprise platform and security teams evaluate a GitHub Action, they ask a very different set of questions:

  • "How do we authenticate without storing static, long-lived API keys across 200 repositories?"
  • "How do we attribute AI spend back to specific business units, teams, and repositories in our Cloud Billing export?"
  • "What stops a malicious dependency drift or an untrusted fork PR from exfiltrating credentials?"

These aren't theoretical questions β€” this reviewer is already deployed in production at an enterprise organisation, and many of the capabilities below were forged directly from real-world enterprise governance requirements. Let's look at the key pillars.

Enterprise Governance: Keyless WIF & FinOps Attribution

1. Keyless Enterprise Auth with Workload Identity Federation (WIF)

Static API keys (GEMINI_API_KEY) are great for quick personal setups. But in an enterprise environment, long-lived credentials stored in GitHub Secrets are a compliance headache. Somebody has to rotate them, audit them, and worry about them leaking.

Because our action is built on the modern google-genai SDK, it natively supports Google Cloud Workload Identity Federation (WIF) with Application Default Credentials (ADC) with Gemini Enterprise Agent Platform (formerly Vertex AI).

Instead of generating a static key, your GitHub Actions runner requests a short-lived OIDC token from GitHub and exchanges it via google-github-actions/auth for an ephemeral Google Cloud access token scoped to a specific Service Account:

jobs:
  review:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      pull-requests: write
      id-token: write # Required for WIF OIDC token exchange

    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          ref: ${{ github.event.pull_request.head.sha || format('refs/pull/{0}/head', github.event.issue.number) }}

      - name: Authenticate to Google Cloud via WIF
        uses: google-github-actions/auth@v2
        with:
          workload_identity_provider: 'projects/123456789012/locations/global/workloadIdentityPools/${{ secrets.WIF_POOL_ID }}/providers/${{ secrets.WIF_PROVIDER_ID }}'
          service_account: '${{ secrets.GCP_SERVICE_ACCOUNT }}'

      - name: Run Gemini Review Action
        uses: derailed-dash/gemini-review-action@v1
        env:
          GOOGLE_GENAI_USE_VERTEXAI: "True"
          GOOGLE_CLOUD_PROJECT: "my-enterprise-project-id"
          GOOGLE_CLOUD_LOCATION: "global"
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          gemini_model: 'gemini-3.8-flash'
Enter fullscreen mode Exit fullscreen mode

Why this matters for the enterprise:

  • Zero static secrets: Credentials live for minutes and expire automatically when the job finishes.
  • IAM & VPC-SC Governance: All Gemini API calls route through your Google Cloud project, meaning they respect your organisation's IAM policies, data residency regions, Cloud Audit Logs, and VPC Service Controls.

2. FinOps Transparency: Real Dollar Cost Estimation & Gemini Enterprise Agent Platform Billing Labels

ROI is paramount. If a solution costs too much or you can't measure what it costs, it's bad architecture.

In Part 1, our telemetry block reported raw token counts. That was useful, but as fellow GDE Sascha Heyer rightly pointed out when he contributed PR #33, developers and engineering leaders don't pay their cloud bills in tokens β€” they pay in dollars!

We upgraded the telemetry engine (gemini_review/pricing.py) to calculate and print the estimated dollar cost on every single review, broken down by uncached input, cached input (at the 90% discount rate), thinking/reasoning tokens, and response output tokens:

Automated PR Review Output with Dollar Cost Telemetry

Notice a couple of deliberate engineering choices here:

  • No Silent Guessing: If you configure an experimental or future model that isn't in our pricing table yet, the action reports the token counts and omits the dollar figure rather than borrowing another model's rate. A missing number is obvious; a wrong number is dangerous.
  • Time-Boxed Introductory Rates: Models like gemini-3.8-flash have promotional introductory pricing ($0.75 / $3.75 per 1M tokens through 2026-12-31, reverting to $1.50 / $7.50 afterwards). We encoded the promotional expiry dates directly into the pricing engine data structures, and the review footnote explicitly states which rate was applied. And if your enterprise has negotiated custom flat rates or uses Batch/Flex tiers, you can override the table via GEMINI_RATE_INPUT and GEMINI_RATE_OUTPUT.

Answering the FinOps Question at Scale: Cloud Billing Labels (billing_labels)

Knowing that PR #42 cost $0.03 is great for a developer. But a Head of Platform Engineering needs to answer a different question: "What did AI code reviews cost across our 150 repositories this month, broken down by engineering team?"

You shouldn't have to scrape GitHub PR comments to answer a FinOps question. So we added native Gemini Enterprise Agent Platform Billing Labels (gemini_review/billing_labels.py).

Whenever you run on Gemini Enterprise Agent Platform (Vertex AI), the action automatically attaches sanitised GCP billing labels to every generate_content request:

  • component: gemini-review-action
  • repo: owner_repo

Even better, you can pass custom chargeback dimensions via the billing_labels workflow input:

      - name: Run Gemini Review Action
        uses: derailed-dash/gemini-review-action@v1
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          billing_labels: 'team=platform,cost_centre=engineering,env=ci'
Enter fullscreen mode Exit fullscreen mode

(Pro-Tip: We deliberately did not make the PR number a default label, because high-cardinality labels turn your BigQuery billing export into a noisy mess. And if you're using a Google AI Studio API key instead of Gemini Enterprise Agent Platform, the action cleanly omits the labels parameter.)

3. Supply-Chain Security & Fork PR Hardening

A code review action holds pull-requests: write permissions and runs against untrusted PR branches. If you aren't careful, that's a prime target for supply-chain attacks. Here is how we locked it down:

  1. Enforced Lockfiles (uv run --locked): Previously, running uv run --project would silently resolve and rewrite uv.lock at runtime if pyproject.toml drifted. That meant even if an enterprise consumer pinned our action to an immutable 40-character Git commit SHA, a transitive PyPI dependency could theoretically change at runtime. So we enforced uv run --locked and pinned all nested setup actions (actions/setup-python and astral-sh/setup-uv) to exact commit SHAs.
  2. Untrusted Fork PR Safeguards: By default, GitHub strips repository secrets from fork PRs to prevent untrusted contributors from accessing API keys. If an action tries to run automatically on a fork without secrets, it crashes with an authentication error and paints the contributor's PR with an ugly red ❌. Our starter workflows solve this gracefully:
    • Clean skips on forks: The workflow guards automatic runs (github.event.pull_request.head.repo.full_name == github.repository), quietly skipping external forks so CI status checks stay green.
    • Maintainer on-demand trigger: Once a repository maintainer (OWNER, MEMBER, COLLABORATOR) inspects the fork code, they can safely trigger Gemini by typing /gemini-review in a PR comment β€” which runs under their authenticated context with full access to secrets.
  3. Path Traversal Containment: Every file path, Markdown image link, and skill reference loaded by the action is strictly validated against the workspace root. An attacker cannot craft a malicious Markdown link like ![diagram](../../../../etc/passwd) or a custom instruction path to trick the runner into reading files outside the repository.

Major Feature Deep-Dives Since Part 1

Now let's get into the really fun stuff! Here are the major architectural features we've engineered since publishing Part 1.

1. Multimodal Context Inspection, Visual PR Diffing & Screenshot Triage

Until recently, AI code reviewers had a massive blind spot: they were completely blind to anything that wasn't plain text.

If you updated an architecture diagram in docs/architecture.png, tweaked a UI component screenshot, attached a PDF specification, or opened a GitHub Issue with a screenshot of a broken button, a text-only reviewer saw nothing.

In our solution, we've unlocked Gemini's native multimodal superpowers across three distinct workflows:

Multimodal Context & Visual PR Diffing Engine

A. Automatic Markdown Image & PDF Resolution

Whenever a Markdown file (README.md, DESIGN.md, ARCHITECTURE.md, or a blog post!) is included in the review context or modified in a PR diff, we scan the document for standard Markdown and HTML image references. We resolve the paths relative to the Markdown file, verify containment inside the repo, and attach the visual assets directly to the Gemini request. Now, when Gemini reviews your documentation updates, it actually looks at your architecture diagrams to verify that the diagram matches your code and prose!

B. Side-by-Side Visual PR Diffing

What happens when a PR modifies an existing architecture diagram, UI component snapshot, or application icon?

Most AI reviewers either ignore modified images completely or summarise them in separate, isolated passes β€” which completely loses subtle visual regressions.

Instead, our action retrieves both the "before" and "after" versions of any modified graphic and passes them side-by-side into a single Gemini turn. Because both images sit together in the same multimodal attention window, Gemini performs direct visual diffing β€” spotting accidentally cropped text, resolution degradation, broken UI alignment, or missing arrows in an updated architecture diagram!

C. Multimodal Issue Triage for Remote Screenshots

When users report bugs in GitHub Issues, they love pasting screenshots directly into the issue editor (which GitHub hosts at extensionless URLs like https://github.com/user-attachments/assets/<uuid>).

We upgraded our triage to extract remote HTTPS image URLs from both the issue body and discussion comments:

  • Safe Token Handling: Images in private repositories require GitHub credentials to view. The downloader attaches your GITHUB_TOKEN only to trusted GitHub domains β€” and strips it immediately if a link redirects to an external site.
  • Attack-Proof Downloads: Because issue descriptions are untrusted user input, we block risky URLs (like internal network IPs or cloud metadata endpoints), cap downloads at 20 MB, and fall back cleanly to text triage if an image is missing or unreachable.

D. Deterministic Image Downscaling (Saving Your Token Budget!)

Here's a classic "gotcha" from production: high-resolution screenshots and uncompressed PNGs can easily top several megabytes each. Shoving dozens of multi-megabyte images into a review prompt is a recipe for pain. Review request latency can spike towards GitHub Action timeout thresholds, you risk slamming into API request limits, and you waste tokens on pixels that add no extra value to the review.

To fix this, we added automated, deterministic downscaling using Pillow. Any image (.png, .jpg, .webp, .gif) larger than 600 KB is compressed to a much smaller file size. Cool, right?

2. Upgraded Default Model (gemini-3.8-flash) & Thinking Budget Controls

When I wrote Part 1, our default model was gemini-3.6-flash. Since then, we upgraded through gemini-3.7-flash and now default to gemini-3.8-flash.

We also introduced granular Reasoning & Thinking Budget Control via the thinking_level input:

      - name: Run Gemini Review Action
        uses: derailed-dash/gemini-review-action@v1
        with:
          gemini_api_key: ${{ secrets.GEMINI_API_KEY }}
          github_token: ${{ secrets.GITHUB_TOKEN }}
          thinking_level: 'low' # Options: low, medium, high, off, or integer budget (e.g. 2048)
Enter fullscreen mode Exit fullscreen mode

How thinking budgets work:

  • Dynamic by Default (Recommended for PRs): When omitted, Gemini runs in dynamic mode, automatically allocating reasoning tokens based on the complexity of your diff.
  • FinOps Token Budget Limits (e.g. low or medium): Because thinking tokens are billed at the higher output token rate, cost-conscious teams can cap the maximum reasoning headroom to ensure predictable per-review spending on massive diffs.
  • Blazing Fast Issue Triage (thinking_level: 'off'): When running in triage mode (command: 'triage'), the model only needs to classify an issue and pick labels. Deep reasoning is complete overkill here. Setting thinking_level: 'off' forces thinking_budget=0, slashing triage latency to near-instant and cutting triage costs to fractions of a cent!

3. Smarter Sparse Mode: Bounded Dynamic Context Selection

In Part 1, when a repository exceeded 1.5 MB (Sparse Context Mode), the action attached the directory tree and static core files (README.md, pyproject.toml, etc.), and left it at that.

But what if your PR modifies, say, src/payments/stripe_webhook.py inside a 50 MB monorepo, but you also have relevant additional files in the repo, like src/payments/models.py and tests/payments/test_stripe.py?

Monorepo Context & Self-Healing Engine

To solve this, we introduced Bounded Dynamic Context Selection (gemini_review/context.py and gemini_review/repo.py):

  1. Prioritised Rule Files & Core Context Budget Cap (max_core_context_bytes): In Sparse Mode, the action loads your core project documents. But what if a repository has a 2 MB README.md or dozens of markdown files? To prevent bulky documentation from blowing your token budget before code is even evaluated, we cap total core context at 500 KB and enforce strict intake ordering:
    • Agent rules take precedence: Coding instructions and team guidelines (AGENTS.md, GEMINI.md, CLAUDE.md, .cursorrules) are prioritised at the very front of the queue so the reviewer always respects your project's rules.
    • Manifests & architecture next: Core build manifests (pyproject.toml, package.json, go.mod) and root docs (README.md, ARCHITECTURE.md) fill the remaining budget up to the 500 KB ceiling.
  2. Two-Stage Dynamic Sister Context Selection: In a 10,000-file monorepo, feeding every file path to an LLM wastes massive tokens before the review even starts. So we built a two-stage funnel:
    • Stage 1 (Deterministic Ranking): A Python ranker parses the PR diff for import statements, directory proximity, and sister test/implementation filenames to bound the candidate pool to the top 500 files (max_candidate_files).
    • Stage 2 (4-Tier Architectural Selection): A fast, structured call to Gemini picks up to 8 of the highest-value sister files from that pool across four architectural tiers: Tier 1 (direct import dependencies and base classes), Tier 2 (sister unit tests, fixtures, and schemas), Tier 3 (domain precedents in sibling modules), and Tier 4 (shared utilities and configuration helpers).
  3. Static Override (extra_context_files): If you already know specific files you always want attached alongside every review, you can pass extra_context_files: 'src/core/security.py,docs/api-spec.pdf' and bypass the dynamic selector call entirely!

4. Extending Guardrails vs Replacing Prompts + Curated Skills Synchroniser

Originally, if you wanted to add a single team rule β€” like "All SQL queries must use parameterised inputs" β€” you had to copy the entire .github/commands/gemini-review.toml file into your repo. The problem? As soon as you forked the base prompt into your repo, you missed out on all the upstream prompt engineering improvements we shipped in later versions (like our 5-Axis Quality Evaluation Framework)!

AI Code Reviewer: Upgraded Intelligence Architecture with Skills & MCP

The answer is to cleanly separate extending instructions from replacing them:

  • Extend (Recommended): Simply drop a Markdown file at .github/review-instruction-additions.md in your repo, or pass inline rules via the custom_instructions workflow input:
      with:
        custom_instructions: |
          - Ensure all database queries use parameterised inputs.
          - Verify that new API endpoints include Pydantic request validation.
Enter fullscreen mode Exit fullscreen mode
  • The action keeps the full built-in 5-axis quality rubric, persona overlays, and schema rules, and cleanly appends your custom guardrails!
  • Equip Custom Agent Skills (.agents/skills/): Beyond simple markdown rules, you can mount full Agent Skills directly into your repository. The action automatically discovers skills placed in .agents/skills/ β€” whether they are custom coding guidelines, security checks, or official skills from the google/skills catalog β€” and equips Gemini to enforce those exact domain practices during reviews.
  • Bundled One-Command Installer Skill: I had already created an agent skill called install-gemini-code-review-action, in my dazbo-agent-skills repo. Now, we also mirror this skill directly inside our reviewer repo. You can install the skill straight from the action repo:
npx skills add derailed-dash/gemini-review-action -y -g --skill install-gemini-code-review-action
Enter fullscreen mode Exit fullscreen mode

Once installed, simply prompt your agent: "Set up Gemini code review in this repository." The agent detects any existing workflows, interviews you on your preferred model, auth method (WIF vs API key), and persona, and generates the workflow files for you!

5. Workflow Polish: Auto-Resolving Threads & Filtering Competing Bots

Two of my favourite quality-of-life improvements came directly from real-world friction on busy pull requests:

A. Auto-Resolving Addressed Review Threads

When you push a fix to a PR, the action re-examines prior review comments, confirms the issue has been resolved, and marks it fixed.

However, if your repository enforces GitHub's "Require conversation resolution before merging" rule, someone still has to manually click "Resolve conversation" on every single thread before you can merge β€” even though the bot already agreed you fixed it!

With resolve_addressed_threads: 'true', the action automatically clicks "Resolve" on its own threads as soon as Gemini verifies the fix. It stays strictly in its lane: it only touches threads the bot created, never touches human comments, and gracefully warns you if your GitHub token needs additional permissions to resolve conversations.

B. Excluding Another Bot's Comments (exclude_comment_authors)

What happens if your team runs two AI reviewers on the same repo (for instance, claude[bot] alongside gemini-review-action)?

Because our action inspects existing PR comments to avoid repeating itself, it was picking up the other bot's review notes too. That meant Gemini ended up reading the other bot's homework and parroting the exact same points! You lost your independent second opinion, and you paid for hundreds of extra prompt tokens just to re-digest the other bot's prose.

Adding exclude_comment_authors: 'claude[bot]' filters out specified bots before building the prompt. Human feedback stays intact, and Gemini delivers a genuine, unbiased second opinion.


Battle-Hardened in Production: War Stories & Bug Fixes

Here are a few real-world production bugs we hit since Part 1 β€” and how we engineered permanent fixes for them.

War Story 1: The Generated Schema That Blew the Token Budget

  • The Problem: A pull request touching 30 files crashed without posting a review, failing with a token limit error. The culprit? A tiny 4 KB diff buried inside a 2.9 MB auto-generated openapi.json file. Because our prompt builder attached the entire current content of every modified file alongside its diff, that single generated file consumed the entire Gemini token window on its own!
  • The Fix: Rather than playing whack-a-mole adding filenames to an ignore list, we capped all attached source files at 128 KB with a clean truncation marker (diff patches themselves are never capped). If a massive prompt still approaches the model's budget, the action gracefully sheds peripheral repo context first, ensuring the core diff review always succeeds.

War Story 2: GitHub's Concurrency Trap (and How Our Bot Caught It)

  • The Problem: If a developer pushes three commits in quick succession, you don't want to pay Gemini to review all three. We added a standard GitHub Actions concurrency block with cancel-in-progress: true to kill redundant runs. But we hit a snag: whenever someone left an ordinary comment on the PR, GitHub cancelled the running review! Workflow-level concurrency evaluates before the job filters kick in, treating any comment as a new run.
  • Caught by Our Own Bot: We tried tweaking the concurrency key, but when we opened the pull request, our own Gemini Review Action reviewed it and pointed out our fix created a new race condition in the opposite direction!
  • The Fix: Moving concurrency down to the job level ensures GitHub only cancels runs for actual review triggers on the same PR:
jobs:
  review:
    concurrency:
      group: gemini-review-${{ github.event.pull_request.number || github.event.issue.number }}
      cancel-in-progress: true
Enter fullscreen mode Exit fullscreen mode

War Story 3: Making "Commit Suggestion" Actually Work

  • The Problem: Developers love clicking GitHub's "Commit suggestion" button directly from an inline review comment. But LLMs are notorious for trimming leading whitespace or getting multiline replacement ranges slightly wrong β€” meaning a one-click commit can easily botch your indentation or overwrite the wrong lines.
  • The Fix: Before posting an inline suggestion, we run a deterministic sanitiser over it. It matches the source file lines, restores stripped indentation, and corrects any off-by-one replacement ranges. When a developer clicks that button, the resulting commit is clean, properly indented, and builds first time.

War Story 4: Surviving Transient GitHub Outages

  • The Problem: During an incident where the GitHub API threw intermittent 503 Service Unavailable errors, the action successfully generated reviews from Gemini, only to crash when posting them to GitHub. We’d paid for the tokens, but the reviews were lost into the ether.
  • The Fix: We wrapped all GitHub comment and review posting in an exponential backoff retry. A review you've already paid for is never thrown away over a temporary API hiccup.

Wrapping Up

Looking back at how far Gemini PR Review & Triage Action has come since that first weekend build in July, I'm genuinely blown away. What started as an emergency lifeboat after the sunsetting of run-gemini-cli has grown into a comprehensive, multimodal, enterprise-grade engineering harness.

Whether you're a solo hobbyist who wants Emperor Palpatine or Rick Sanchez roasting your Python diffs for $0.02 a pop, or an Enterprise Cloud Architect rolling out keyless WIF authentication, BigQuery billing attribution, and architectural guardrails across hundreds of corporate repositories β€” this action is built for you:

Rick Sanchez Persona Review Output

Beyond CI/CD: Bringing Gemini Review into Your Agentic Loops

While we designed this action primarily to automate GitHub pull request reviews, the modular architecture we've engineered under gemini_review/ unlocks an exciting new frontier: inner-loop agent verification.

In my recent deep dive, Loop Engineering in the Harness: Autonomous, Self-Correcting Systems, I explored how reliable agentic architectures rely on tight, deterministic feedback loops (Generate β†’ Verify β†’ Correct β†’ Converge) to eliminate hallucinated code and regressions before human intervention.

Because gemini_review is structured as a standalone, lightweight Python package executable via uv, you don't have to wait for a remote CI push to run it. You can wire the review engine directly into your local development harness as a pre-commit or pre-push verification step. Your local coding agent can execute a local review pass against its own unstaged git diff, parse the structured severity findings, and self-correct regressions with zero session bias β€” before anyone else ever inspects the code!

Install It!

If you haven't tried it yet (or if you installed v1.1 back in July and haven't looked at the new inputs since!), now is the perfect time to upgrade:

  1. Equip your AI agent in seconds, then prompt it: "Set up Gemini code review in this repo":
npx skills add derailed-dash/gemini-review-action -y -g --skill install-gemini-code-review-action
Enter fullscreen mode Exit fullscreen mode
  1. Or grab the starter workflows directly from derailed-dash/gemini-review-action.
  2. Give the repository a star ⭐ on GitHub β€” it massively helps others discover the project, and it helps me too!

Let me know in the comments how you get on, what persona you're running in your pipelines, and what features you'd love to see next!


Before You Go

  • Please share πŸ“’ this with anyone that you think will be interested. It might help them, and it really helps me!
  • Please leave a reaction or comment πŸ’¬. Interaction is good!
  • Add a star ⭐ on my repos!
  • Follow πŸ‘‰ and subscribe πŸ””, so you don’t miss my content.

References and Useful Links

Top comments (0)