In fast-paced software organizations, the pull request queue is where momentum goes to die. Senior engineers and tech leads routinely spend 15 to 20 hours each week wading through mechanical diffs, checking boilerplate conventions, verifying database migrations, and drafting release notes. Worse, in modern distributed microservice systems, human reviewers operating on an isolated git diff routinely miss breaking schema shifts or subtle contract violations in downstream repositories.
At 365Finds, we believe turning your most expensive senior developers into human linters is an organizational failure. Yet most teams that attempt to automate PR reviews with generic AI bots quickly abandon them. Why? Because off-the-shelf bots treat every pull request like a disconnected 500-line snippet, inundating pull requests with superficial style complaints, hallucinated syntax advice, and notification spam.
Sourcegraph Cody changes this equation entirely. Because it sits on top of Sourcegraph's code graph and search engine, Cody evaluates git diffs against the living reality of your entire codebase—including remote shared contracts, dependent services, and organizational patterns. Here is how DevOps and platform engineers can wire Sourcegraph Cody directly into GitHub Actions and GitLab CI pipelines to automate structured PR summaries and context-grounded inline code reviews.
1. Architectural Foundations: How Cody CI Integration Differs from Generic LLM Bots
A standard AI code review script takes git diff, stuffs it into an OpenAI or Anthropic API payload, and posts the text response back to the PR. That approach fails in production because diffs lack context. A removed function parameter might look clean in isolation, but it silently breaks three microservices maintained by separate teams.
Sourcegraph Cody operates on a different architecture:
- Global Code Graph Retrieval: Through the headless Cody CLI (
@sourcegraph/cody), Cody queries your Sourcegraph Enterprise instance. When inspecting a modified RPC signature or public interface, it cross-references call sites across repositories using flags like--context-repo. - Deterministic Diff Pipeline: Instead of relying on webhooks or black-box SaaS bots, DevOps teams run Cody headlessly in the CI runner using ephemeral execution tokens (
SRC_ACCESS_TOKENandSRC_ENDPOINT). - Structured Dual-Pass Output: The pipeline executes two distinct tasks:
- PR Description & Architectural Impact Assessment: A top-level sticky markdown comment explaining the "what," "why," and cross-service blast radius.
- Targeted Inline Review Comments: Line-specific, actionable findings filtered by severity to prevent developer alert fatigue.
+-----------------------------------------------------------------------+
| CI/CD Runner (GitHub Actions / GitLab CI) |
| |
| 1. Fetch base/head commit ref --> git diff base...head |
| 2. Filter out lockfiles & generated files (*.pb.go, dist/*) |
| 3. Cody CLI Headless Execution: |
| - Pass diff via STDIN |
| - Query Sourcegraph instance for cross-repo context |
| 4. Process structured JSON / Markdown output |
| 5. Post / Update Sticky PR Summary & Post Critical Inline Comments |
+-----------------------------------------------------------------------+
|
v
+-----------------------------------------------------------------------+
| Sourcegraph Enterprise Instance (Code Search & Multi-Repo Index) |
+-----------------------------------------------------------------------+
2. Prerequisites and Non-Interactive Authentication
To execute Sourcegraph Cody inside an automated CI runner without human intervention, you must bypass browser-based OAuth (cody auth login --web) and rely entirely on environment variables.
Required Secrets
Set the following secrets in your repository or organization settings (e.g., GitHub Secrets or GitLab CI/CD Variables):
SRC_ENDPOINT: The full URL to your Sourcegraph instance (e.g.,https://sourcegraph.company.internal).SRC_ACCESS_TOKEN: A Sourcegraph Personal Access Token (PAT) provisioned with repository read permissions.GITHUB_TOKENorGITLAB_TOKEN: Standard platform credentials withpull-requests: writeorapipermissions to publish comments.
The Cody CLI requires Node.js version 20 or higher and installs cleanly via npm:
npm install -g @sourcegraph/cody
Once installed, running cody auth whoami in an environment where SRC_ENDPOINT and SRC_ACCESS_TOKEN are populated confirms authentication instantly:
export SRC_ENDPOINT="https://sourcegraph.company.internal"
export SRC_ACCESS_TOKEN="sgp_v2_xxxxxxxxxxxx"
cody auth whoami
# Output: ✔ Authenticated as platform-bot on https://sourcegraph.company.internal
3. End-to-End Implementation: GitHub Actions Pipeline
Here is a complete, battle-tested GitHub Actions workflow (.github/workflows/cody-pr-automation.yml). It extracts the true merge-base diff, filters out noise, queries Cody with cross-repository context, and updates a single persistent PR comment.
name: Sourcegraph Cody Automated PR Review
on:
pull_request:
types: [opened, synchronize, ready_for_review]
permissions:
contents: read
pull-requests: write
jobs:
cody-review:
if: github.event.pull_request.draft == false
runs-on: ubuntu-latest
env:
SRC_ENDPOINT: ${{ secrets.SRC_ENDPOINT }}
SRC_ACCESS_TOKEN: ${{ secrets.SRC_ACCESS_TOKEN }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
steps:
- name: Checkout Code Repository
uses: actions/checkout@v4
with:
fetch-depth: 0 # Full git history required for accurate merge-base diff
- name: Setup Node.js Runtime
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install Sourcegraph Cody CLI
run: npm install -g @sourcegraph/cody
- name: Verify Headless Cody Authentication
run: cody auth whoami
- name: Extract Clean Git Diff
id: diff
run: |
# Calculate diff against target base branch, excluding lockfiles and assets
git diff origin/${{ github.base_ref }}...HEAD \
-- . \
':(exclude)*.lock' \
':(exclude)*-lock.json' \
':(exclude)*.sum' \
':(exclude)*.min.js' \
':(exclude)dist/*' \
':(exclude)vendor/*' > pr_diff.patch
DIFF_SIZE=$(wc -c < pr_diff.patch)
echo "diff_size=$DIFF_SIZE" >> $GITHUB_OUTPUT
- name: Generate PR Summary via Cody CLI
if: steps.diff.outputs.diff_size > 0
run: |
SUMMARY_PROMPT="You are a principal engineer conducting a code review. Analyze the provided git diff.
Provide a structured summary in Markdown with the following sections:
### 📌 High-Level Intent
Concise explanation of what this PR accomplishes and why.
### 🔍 Key Architectural Changes
Bullet points describing structural changes, modified APIs, and altered database models.
### ⚠️ Breaking Changes & Cross-Repo Blast Radius
Identify backwards-incompatible API changes, deprecated endpoints, or altered data contracts.
### 🛡️ Security & Performance Impact
Flag any unindexed queries, missing authorization checks, resource leaks, or unhandled concurrency."
# Pipe diff into Cody CLI with standard input and pass remote shared repo context
cat pr_diff.patch | cody chat --stdin \
--context-repo github.com/my-org/shared-contracts \
-m "$SUMMARY_PROMPT" > cody_summary.md
- name: Publish or Update Sticky PR Summary Comment
if: steps.diff.outputs.diff_size > 0
run: |
PR_NUMBER="${{ github.event.pull_request.number }}"
IDENTIFIER="<!-- 365finds-cody-pr-summary -->"
COMMENT_BODY=$(printf "%s\n\n## 🤖 Sourcegraph Cody AI Review\n\n%s" "$IDENTIFIER" "$(cat cody_summary.md)")
# Search for existing comment with this identifier
EXISTING_COMMENT_ID=$(gh api repos/${{ github.repository }}/pulls/$PR_NUMBER/comments \
--jq ".[] | select(.body | contains(\"$IDENTIFIER\")) | .id" | head -n 1)
if [ -z "$EXISTING_COMMENT_ID" ]; then
# Check issue comments as well (top-level PR discussion)
EXISTING_COMMENT_ID=$(gh api repos/${{ github.repository }}/issues/$PR_NUMBER/comments \
--jq ".[] | select(.body | contains(\"$IDENTIFIER\")) | .id" | head -n 1)
fi
if [ -n "$EXISTING_COMMENT_ID" ]; then
echo "Updating existing comment $EXISTING_COMMENT_ID"
gh api \
--method PATCH \
-H "Accept: application/vnd.github+json" \
/repos/${{ github.repository }}/issues/comments/$EXISTING_COMMENT_ID \
-f body="$COMMENT_BODY"
else
echo "Posting new summary comment"
gh pr comment $PR_NUMBER --body "$COMMENT_BODY"
fi
4. Generating Automated Inline PR Comments with Guardrails
Top-level summaries are great for context, but developers fix bugs when feedback appears directly on the offending line of code. However, posting inline AI comments without strict filters will turn your development team into vocal opponents of automated review.
At 365Finds, we advocate for the "Blocker or Silent" rule: Cody should post an inline comment if and only if it spots a confirmed bug, security risk, or high-severity violation. It must never post subjective comments like "Consider renaming this variable" or "You could rewrite this with map()."
Scripting Inline Comment Injection
To produce structured inline comments, instruct Cody to output strict JSON matching GitHub’s review API payload:
INLINE_PROMPT="Analyze this diff line by line. Identify ONLY critical bugs, SQL injections, race conditions, or breaking contract modifications.
Do NOT report formatting, stylistic choices, or minor documentation omissions.
Return ONLY a valid JSON array of objects with no Markdown backticks or wrapping text. Each object must contain:
- 'path': file path relative to repo root
- 'line': right-side line number where the issue occurs
- 'body': concise explanation of the defect and a recommended fix"
cat pr_diff.patch | cody chat --stdin -m "$INLINE_PROMPT" > inline_reviews.json
Then, use a lightweight Python or Node.js step to parse the JSON and invoke GitHub's pull request review endpoint:
import json, os, subprocess
with open("inline_reviews.json") as f:
try:
raw_comments = json.load(f)
except Exception:
raw_comments = []
valid_comments = []
for c in raw_comments:
if c.get("path") and c.get("line") and c.get("body"):
valid_comments.append({
"path": c["path"],
"line": int(c["line"]),
"body": f"⚠️ **Sourcegraph Cody Audit**: {c['body']}"
})
if valid_comments:
payload = {
"event": "COMMENT",
"comments": valid_comments[:5] # Hard limit to prevent comment flooding
}
with open("review_payload.json", "w") as out:
json.dump(payload, out)
pr_num = os.environ["PR_NUMBER"]
repo = os.environ["GITHUB_REPOSITORY"]
subprocess.run([
"gh", "api", "--method", "POST",
f"/repos/{repo}/pulls/{pr_num}/reviews",
"--input", "review_payload.json"
], check=True)
5. Integrating with GitLab CI/CD
If your organization runs on self-managed GitLab or GitLab.com, the pattern remains identical. You can use the official glab CLI or GitLab's merge request discussions API:
stages:
- review
cody_mr_review:
stage: review
image: node:20-bookworm-slim
only:
- merge_requests
variables:
SRC_ENDPOINT: $SRC_ENDPOINT
SRC_ACCESS_TOKEN: $SRC_ACCESS_TOKEN
GITLAB_TOKEN: $GITLAB_TOKEN
before_script:
- apt-get update && apt-get install -y git curl jq
- npm install -g @sourcegraph/cody
- curl -s https://gitlab.com/gitlab-org/cli/-/releases/v1.40.0/downloads/glab_1.40.0_linux_amd64.deb -o glab.deb && dpkg -i glab.deb
script:
- cody auth whoami
- git fetch origin $CI_MERGE_REQUEST_TARGET_BRANCH_NAME
- git diff origin/$CI_MERGE_REQUEST_TARGET_BRANCH_NAME...HEAD > mr_diff.patch
- |
cat mr_diff.patch | cody chat --stdin \
--context-repo internal-gitlab.company.com/core/shared-api \
-m "Summarize this MR, evaluate backward compatibility, and identify edge cases." > summary.md
- glab mr note $CI_MERGE_REQUEST_IID -m "$(cat summary.md)"
6. Real-World Lessons: Lessons from Building "Sherlock"
Sourcegraph’s own internal security team documented their experience automating PR security reviews with Cody in a system they named Sherlock. Their production findings highlight nuances every platform engineer must prepare for:
- Context-Aware SAST Triaging: Traditional SAST scanners dump dozens of false positives on developers. Sourcegraph fed scanner outputs directly into Cody alongside repository metadata. By correlating the scanner alert with the actual call graph, Cody confirmed real vulnerabilities and ignored false alarms, cutting manual triage by at least 30 minutes per engineer per day.
- Combating Hallucinations: Standard LLMs love to recommend generic security best practices instead of pinpointing bugs in the actual code change. The solution is aggressive prompt scoping: feed the model threat model documents, PR metadata, and explicit cross-repository context rather than letting it guess.
- Diff Threshold Safety: When a developer opens a 4,000-line dependency upgrade or database dump, running deep semantic analysis is both costly and prone to prompt truncation. Configure your CI script to bypass detailed inline review if
pr_diff.patchexceeds 150KB, falling back to a lightweight top-level advisory.
7. The 365Finds Engineering Verdict
Should your platform team implement automated Cody PR reviews tomorrow?
Our answer is yes—with one non-negotiable condition: Treat Cody as a relentless tier-1 junior auditor, never as a silent auto-approver or a nagging style linter.
| Feature / Strategy | Recommended Practice | Failure Mode to Avoid |
|---|---|---|
| Comment Frequency | Single updated sticky summary per PR | Posting duplicate summary comments on every git push |
| Inline Review Guardrail | Cap at 5 high-confidence critical findings | Emitting 40 nitpicks about variable naming or formatting |
| Context Scope | Target --context-repo on central API contracts | Omitting context and forcing the LLM to hallucinate dependencies |
| Security Boundary | Never execute on untrusted public forks | Exposing SRC_ACCESS_TOKEN in untrusted workflow runs |
When configured with merge-base diff filtering, idempotent sticky comments, and targeted cross-repo context, Sourcegraph Cody transforms pull request reviews. It eliminates mechanical triage, surfaces cross-microservice breaking changes before they hit staging, and gives senior engineers their hours back.