Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
241 changes: 241 additions & 0 deletions .github/workflows/ai-review-merge.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
name: AI review + auto-merge (reusable)

# Org-level autonomous review-and-merge gate for Cervais repos, adapted from
# Verjson/.github ai-review-merge.yml (see that org's viager-docs ADR-018 and
# new-guardian docs/decisions/0003 for the design record).
#
# Cost-lane design:
# 1. `classify` (free, deterministic bash) routes the PR into a lane:
# - fast: deletions-only or docs-only diffs, and Renovate/Dependabot
# non-major updates (bot-authored, manifest/lockfile-only diff).
# No model is invoked.
# - ai: everything else gets a Claude review — but only AFTER the rest of
# CI is green, so red PRs cost $0.
# 2. Model tiering: routine PRs are reviewed by Haiku; PRs touching sensitive
# paths (workflows, auth, payments, secrets, policies) get Sonnet.
# 3. Reviews run once per ready PR, not per push. Re-run with the `re-review`
# label (auto-removed).
# Either lane merges only on green CI (squash + branch delete) using the org
# admin token. Humans opt a PR out with the `hold` label, a "DO NOT MERGE"
# title marker, or by keeping it draft — re-checked at merge time.
#
# Adopt in a repo with a thin stub:
#
# name: AI review + auto-merge
# on:
# pull_request:
# types: [opened, reopened, ready_for_review, labeled]
# jobs:
# gate:
# uses: Cervais/.github/.github/workflows/ai-review-merge.yml@main
# secrets: inherit
#
# Repos with a specialized gate (e.g. new-guardian's cyber-review) keep their
# own workflow and should NOT also adopt this one.

on:
workflow_call:
inputs:
review_prompt_extra:
description: Repo-specific review focus appended to the review prompt
type: string
required: false
default: ""
secrets:
ANTHROPIC_API_KEY:
required: true
TOKEN:
required: true

concurrency:
group: ai-review-${{ github.event.pull_request.number }}
cancel-in-progress: true

permissions:
contents: read

env:
PR_NUMBER: ${{ github.event.pull_request.number }}
REPO: ${{ github.repository }}

jobs:
classify:
name: Classify PR lane
if: >-
(github.event.action != 'labeled' || github.event.label.name == 're-review') &&
!github.event.pull_request.draft &&
!contains(github.event.pull_request.labels.*.name, 'hold') &&
!contains(github.event.pull_request.title, 'DO NOT MERGE')
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
pull-requests: write
outputs:
lane: ${{ steps.classify.outputs.lane }}
reason: ${{ steps.classify.outputs.reason }}
model: ${{ steps.classify.outputs.model }}
head_sha: ${{ steps.classify.outputs.head_sha }}
steps:
- name: Classify
id: classify
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
out() { echo "$1=$2" >> "$GITHUB_OUTPUT"; }

meta=$(gh pr view "$PR_NUMBER" --repo "$REPO" --json labels,title,isDraft,author,headRefOid)
out head_sha "$(jq -r .headRefOid <<<"$meta")"
gh pr edit "$PR_NUMBER" --repo "$REPO" --remove-label re-review 2>/dev/null || true

files=$(gh api "repos/$REPO/pulls/$PR_NUMBER/files" --paginate --jq '.[]' | jq -s .)
nfiles=$(jq length <<<"$files")
if [ "$nfiles" -eq 0 ]; then
out lane ai; out reason "empty diff — needs a look"; out model claude-haiku-4-5
exit 0
fi

# Fast lane A: deletions-only.
if jq -e 'all(.[]; .additions == 0)' <<<"$files" >/dev/null; then
out lane fast; out reason "deletions-only diff"; out model none
exit 0
fi
# Fast lane B: docs-only.
if jq -e '[.[].filename] | all(test("(^docs/|\\.(md|txt)$)"))' <<<"$files" >/dev/null; then
out lane fast; out reason "docs-only diff"; out model none
exit 0
fi
Comment on lines +104 to +108

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Docs-only pattern also matches non-doc files under docs/.

^docs/ matches any file whose path starts with docs/, regardless of extension — a script, image, or config committed under a top-level docs/ folder would be classified fast-lane and skip AI review entirely, not just cost savings.

🐛 Proposed fix
-          if jq -e '[.[].filename] | all(test("(^docs/|\\.(md|txt)$)"))' <<<"$files" >/dev/null; then
+          if jq -e '[.[].filename] | all(test("\\.(md|mdx|txt|rst)$"))' <<<"$files" >/dev/null; then
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# Fast lane B: docs-only.
if jq -e '[.[].filename] | all(test("(^docs/|\\.(md|txt)$)"))' <<<"$files" >/dev/null; then
out lane fast; out reason "docs-only diff"; out model none
exit 0
fi
# Fast lane B: docs-only.
if jq -e '[.[].filename] | all(test("\\.(md|mdx|txt|rst)$"))' <<<"$files" >/dev/null; then
out lane fast; out reason "docs-only diff"; out model none
exit 0
fi
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/ai-review-merge.yml around lines 104 - 108, Update the
docs-only condition in the Fast lane B block to require both a path under the
top-level docs/ directory and a documentation extension, while retaining the
existing .md/.txt matching for files elsewhere. Ensure scripts, images, and
configuration files under docs/ do not qualify as docs-only.

# Fast lane C: bot non-major dependency update — bot-authored,
# manifest/lockfile-only diff, non-major update-type label.
author=$(jq -r .author.login <<<"$meta")
if [[ "$author" =~ ^(app/)?(renovate|dependabot)(\[bot\])?$ ]]; then
commit_ok=$(gh api "repos/$REPO/pulls/$PR_NUMBER/commits" --paginate \
--jq '.[] | (.author.login // "MISSING")' \
| jq -Rs 'split("\n") | map(select(length > 0)) | all(test("^(renovate|dependabot)(\\[bot\\])?$"))')
manifest_only=$(jq '[.[].filename] | all(test("(^|/)(package\\.json|package-lock\\.json|pnpm-lock\\.yaml|yarn\\.lock|Cargo\\.(toml|lock)|go\\.(mod|sum)|pyproject\\.toml|poetry\\.lock|uv\\.lock)$"))' <<<"$files")
nonmajor=$(jq '.labels | map(.name) | any(test("^(update/(patch|minor|pin|digest|pinDigest|lockFileMaintenance)|dependencies)$"))' <<<"$meta")
if [ "$commit_ok" = true ] && [ "$manifest_only" = true ] && [ "$nonmajor" = true ]; then
out lane fast; out model none
out reason "bot non-major dependency update: bot-authored commits only, manifest/lockfile-only diff"
exit 0
fi
fi
Comment on lines +109 to +123

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- workflow excerpt ---'
sed -n '90,140p' .github/workflows/ai-review-merge.yml

echo
echo '--- candidate config files ---'
git ls-files '.github/dependabot.yml' '.github/dependabot.yaml' 'renovate.json' 'renovate.json5' 'package.json' '.github/*renovate*' '.github/*dependabot*' '.github/labels*' '.github/*label*' | sed 's/^/FILE: /'

echo
echo '--- search label/config references ---'
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' \
  'dependencies|update/(major|minor|patch|pin|digest|pinDigest|lockFileMaintenance)|dependabot|renovate|renovate\[bot\]|app/dependabot|app/renovate' \
  .github package.json . 2>/dev/null | sed -n '1,240p'

Repository: Cervais/.github

Length of output: 4425


🌐 Web query:

GitHub Dependabot default label dependencies major minor patch labels only if labels already exist repository docs

💡 Result:

When using Dependabot, the behavior regarding labels depends on whether you are relying on default labels or defining your own [1][2]. Default Labels Dependabot automatically creates and applies certain default labels if they do not already exist in your repository [3][1][2]. These include: - The dependencies label [3][2]. - Ecosystem or language-specific labels (e.g., java, npm, submodules) when more than one package manager is configured [3][2]. Custom Labels If you configure custom labels in your dependabot.yml file using the labels option, Dependabot will not create these labels for you [3][1]. These labels must already exist in your repository [3][2]. If any of the labels specified in your configuration do not exist in the repository, they will be ignored [2][4]. Semantic Versioning (SemVer) Labels Dependabot can automatically apply SemVer labels (major, minor, or patch) to indicate the type of version update, but only if those labels are already present in your repository [1][2]. Dependabot does not create SemVer labels automatically if they are missing [2][5]. Summary - Default system labels (dependencies and ecosystem labels): Dependabot creates these if they do not exist [3][1]. - Custom labels defined in dependabot.yml: Dependabot does not create these; they must exist in the repository beforehand [3][1]. - SemVer labels (major, minor, patch): Dependabot does not create these; they must exist in the repository beforehand [1][2].

Citations:


🌐 Web query:

Renovate default labels dependencies major minor patch docs

💡 Result:

Renovate does not have pre-configured default labels for different dependency update types [1]. By default, no labels are added to Renovate pull requests unless explicitly configured by the user [1]. To automatically apply labels based on the update type (major, minor, patch, etc.), you can use the labels configuration option combined with Renovate's templating system [2][3]. You can set this in your renovate.json or configuration file using the updateType template field: { "addLabels": ["renovate-update-{{updateType}}"] } The available updateType values recognized by Renovate include: - major [4] - minor [4] - patch [4] - pin [4] - digest [4] - pinDigest [4] - lockFileMaintenance [4] - rollback [4] - replacement [4] If you want more granular control, you can use packageRules to apply specific labels only to certain update types: { "packageRules": [ { "matchUpdateTypes": ["major"], "addLabels": ["breaking-change"] }, { "matchUpdateTypes": ["minor", "patch"], "addLabels": ["routine-update"] } ] } Renovate also distinguishes between update types programmatically using booleans like isMajor, isMinor, and isPatch, which can be used in templates or advanced configurations [2]. Regarding dependency handling, Renovate separates major and minor releases by default, while patch releases are typically grouped with minor ones unless separateMinorPatch is set to true [5].

Citations:


Drop the bare dependencies fallback

dependencies is too broad here: Dependabot applies it to every PR, so a major update can still satisfy nonmajor and take the fast lane. Only keep this branch if you have an org-wide label scheme that explicitly separates non-major updates; otherwise require a non-major semver label instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/ai-review-merge.yml around lines 109 - 123, Update the
nonmajor label check in the fast-lane branch to remove the bare dependencies
fallback from the accepted labels. Require an explicit non-major semver label
such as update/patch, update/minor, or the existing approved equivalent, while
preserving the commit and manifest-only checks in the surrounding condition.


# AI lane — tier by sensitivity of touched paths.
if jq -e '[.[].filename] | any(test("(^|/)\\.github/|abac|(^|/|[._-])auth|polic|payment|ledger|webhook|secret|middleware|rbac|rls|crypto|key"; "i"))' <<<"$files" >/dev/null; then
out model claude-sonnet-5
else
out model claude-haiku-4-5
fi
out lane ai; out reason "code diff — AI review"

ai-review:
name: AI review
needs: classify
if: needs.classify.outputs.lane == 'ai'
runs-on: ubuntu-latest
timeout-minutes: 45
permissions:
contents: read
pull-requests: write
steps:
# CI-first: never spend model tokens on a red PR.
- name: Wait for the rest of CI to be green
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
for i in $(seq 1 60); do
rollup=$(gh pr view "$PR_NUMBER" --repo "$REPO" --json statusCheckRollup \
--jq '[.statusCheckRollup[]? | select(.name != "Classify PR lane" and .name != "AI review" and .name != "Merge on green")]')
failed=$(jq '[.[] | select((.conclusion // "") | IN("FAILURE","CANCELLED","TIMED_OUT","ACTION_REQUIRED"))] | length' <<<"$rollup")
pending=$(jq '[.[] | select(.status != "COMPLETED" and .status != null)] | length' <<<"$rollup")
if [ "$failed" -gt 0 ]; then
echo "CI is red on PR #$PR_NUMBER — not reviewing."; exit 1
fi
[ "$pending" -eq 0 ] && exit 0
echo "waiting on $pending check(s)…"; sleep 30
done
echo "Timed out waiting for CI; not reviewing."; exit 1
Comment on lines +144 to +160

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

git ls-files '.github/workflows/*' | sed -n '1,200p'
printf '\n--- ai-review-merge.yml (relevant sections) ---\n'
nl -ba .github/workflows/ai-review-merge.yml | sed -n '1,240p'

printf '\n--- search for statusCheckRollup / workflow_call / similar wait loops ---\n'
rg -n 'statusCheckRollup|workflow_call|Wait for the rest of CI to be green|Merge on green|Classify PR lane|AI review' .github/workflows

Repository: Cervais/.github

Length of output: 280


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n--- ai-review-merge.yml (lines 1-260) ---\n'
cat -n .github/workflows/ai-review-merge.yml | sed -n '1,260p'

printf '\n--- search for workflow/job names and statusCheckRollup usage ---\n'
rg -n 'workflow_call|statusCheckRollup|Wait for the rest of CI to be green|Classify PR lane|AI review|Merge on green|jobs:' .github/workflows/ai-review-merge.yml

Repository: Cervais/.github

Length of output: 13680


🌐 Web query:

GitHub Actions reusable workflow check run name statusCheckRollup caller job name called job name workflow_call prefix

💡 Result:

In GitHub Actions, the status check name for a job—including those that call reusable workflows—is determined by the jobs.<job_id> identifier in the workflow YAML file [1][2]. When a job uses the uses keyword to call a reusable workflow, the status check registered in the statusCheckRollup (viewable via the API or CLI) typically displays the name of the job in the caller workflow that initiated the workflow_call [3][4]. There is no native mechanism to explicitly customize the "check run name" independently of the job ID from within a reusable workflow itself. The following points summarize the current behavior and common workarounds: 1. Job Name Identification: The GITHUB_JOB environment variable represents the jobs.<job_id> identifier [1]. In a reusable workflow, this variable holds the ID of the job defined in the caller workflow [3][1]. There is no native environment variable that provides the full, hierarchical path (e.g., CallerJob / CalledJob) of a complex pipeline [1]. 2. Status Check Visibility: Because status checks are tied to the caller's job_id, using the same caller job ID to call multiple reusable workflows or calling a reusable workflow multiple times within a single caller workflow can lead to check run name collisions or ambiguous status rollups [5][6]. 3. Common Workarounds: - Follow-up Jobs: To mirror results or create a distinct status check, many users define a follow-up job in the caller workflow that needs the reusable workflow job [7][8]. This follow-up job can then perform a specific action (like exit 1 or exit 0) to register a final status check with a desired name, effectively acting as an aggregator [7][4]. - Run Name vs. Check Name: While you can customize the run-name of the entire workflow using the run-name property (which supports contexts like github and inputs), this controls the display name of the workflow run in the Actions UI, not the individual status check names registered against a commit or pull request [9][10][11]. For monitoring purposes, the GitHub API (via statusCheckRollup in GraphQL) provides the name field for each check run, which corresponds to the caller job's ID, and workflowName to identify the workflow file [12][4]. If you are encountering issues with check run collisions, appending a unique suffix or using dedicated follow-up jobs are the standard industry approaches [7][6].

Citations:


🌐 Web query:

GitHub reusable workflow statusCheckRollup check run name example caller job id internal job name prefix

💡 Result:

In GitHub Actions, when a reusable workflow is triggered, the status check (or check run) name is generated by combining the job name from the caller workflow and the job name defined within the reusable workflow [1][2][3]. The standard format for this name is: [Caller Job Name] / [Reusable Workflow Job Name] For example, if your caller workflow has a job named "deploy" and it calls a reusable workflow that defines a job named "build", the resulting check run name displayed in the GitHub UI and within the statusCheckRollup will be "deploy / build" [1]. Key points regarding this behavior include: - Internal Job Name Prefix: GitHub automatically prefixes the internal job name of the reusable workflow with the caller's job name to ensure traceability and uniqueness across the run [2]. - StatusCheckRollup: The statusCheckRollup (often accessed via the REST API) will reflect these combined names [4]. This is significant if you are building tooling that requires programmatic interaction with specific check runs, as you must account for this concatenated naming convention when filtering or identifying runs [4]. - UI Rendering: This nested naming structure is intentional to clarify the origin of the job in complex pipeline configurations [3]. - Customization: While you cannot directly override the automatic prefixing behavior (as it is intrinsic to how reusable workflows are tracked), you can influence the resulting name by explicitly setting the name of the caller job and the reusable job using the name keyword [5]. If you are programmatically parsing statusCheckRollup data, it is recommended to group or filter by these logical check names, accounting for the possibility that the strings may contain the "caller / called" pattern [4].

Citations:


Exclude the reusable-workflow check names here

statusCheckRollup will name these checks as <caller job> / <job name> (for example, gate / AI review), so matching only Classify PR lane, AI review, and Merge on green won’t filter out the running workflow’s own checks. That leaves pending nonzero until this loop times out. Update this filter here and in the merge job.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/ai-review-merge.yml around lines 144 - 160, Update the
statusCheckRollup filter in the “Wait for the rest of CI to be green” step and
the corresponding merge job to exclude reusable-workflow checks by matching the
caller-prefixed names (for example, checks ending in “/ Classify PR lane”, “/ AI
review”, and “/ Merge on green”), while preserving all unrelated CI checks.


- name: Checkout PR head
uses: actions/checkout@v4
with:
ref: ${{ needs.classify.outputs.head_sha }}
fetch-depth: 0
Comment on lines +162 to +166

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Set persist-credentials: false on this checkout.

This checkout is only used as read-only context for the review (no push happens from this job), so the default persisted git credential in .git/config is unnecessary exposure — especially since the subsequent step gives the Claude action's Bash tool filesystem access to this checkout.

🛡️ Proposed fix
       - name: Checkout PR head
         uses: actions/checkout@v4
         with:
           ref: ${{ needs.classify.outputs.head_sha }}
           fetch-depth: 0
+          persist-credentials: false
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- name: Checkout PR head
uses: actions/checkout@v4
with:
ref: ${{ needs.classify.outputs.head_sha }}
fetch-depth: 0
- name: Checkout PR head
uses: actions/checkout@v4
with:
ref: ${{ needs.classify.outputs.head_sha }}
fetch-depth: 0
persist-credentials: false
🧰 Tools
🪛 zizmor (1.26.1)

[warning] 162-166: credential persistence through GitHub Actions artifacts (artipacked): does not set persist-credentials: false

(artipacked)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/ai-review-merge.yml around lines 162 - 166, Update the
“Checkout PR head” actions/checkout@v4 step to set persist-credentials to false,
while preserving the existing ref and fetch-depth settings.

Source: Linters/SAST tools


- name: Claude review (merge gate)
uses: anthropics/claude-code-action@v1
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ secrets.TOKEN }}
allowed_bots: 'renovate,renovate[bot],dependabot,dependabot[bot]'
claude_args: "--model ${{ needs.classify.outputs.model }} --max-turns 12 --allowedTools Bash,Read,Grep,Glob"
prompt: |
You are the autonomous merge gate for ${{ github.repository }}.
Review PR #${{ env.PR_NUMBER }} (use `gh pr view`/`gh pr diff` for
metadata and the diff; read surrounding files for context).

Review in priority order:
1. Correctness bugs and behavioral regressions.
2. Security: authn/authz changes, secret handling, input
validation at boundaries, injection.
3. Missing or weakened tests for changed behavior.
Style-only nits are not blocking; mention at most briefly.
${{ inputs.review_prompt_extra }}

Then submit exactly ONE PR review:
- No blocking findings:
gh pr review ${{ env.PR_NUMBER }} --repo ${{ env.REPO }} --approve --body "<short summary of what was checked>"
- Blocking findings:
gh pr review ${{ env.PR_NUMBER }} --repo ${{ env.REPO }} --request-changes --body "<the concrete findings>"
and then exit non-zero (`exit 1`) so the merge job cannot run.
Comment on lines +168 to +193

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

sed -n '150,205p' .github/workflows/ai-review-merge.yml

Repository: Cervais/.github

Length of output: 2974


🌐 Web query:

anthropic claude-code-action github_token Bash environment isolated docs

💡 Result:

In the claude-code-action, the github_token parameter is an optional input used to provide the action with specific GitHub API permissions [1][2]. When you provide a github_token (such as one generated via actions/create-github-app-token), the action uses this token for its operations, overriding the default GITHUB_TOKEN in various contexts [3][4]. This is particularly necessary when the action needs higher permissions (e.g., repository write access) that the default job-scoped GITHUB_TOKEN may lack, or when using custom GitHub App authentication [5][6]. Regarding Bash environment and isolation: 1. Environment Variables: When the action runs, it sets GITHUB_TOKEN and GH_TOKEN in the process environment (process.env), ensuring that downstream commands (including those executed within Bash) can access the provided token [3]. 2. Subprocess Isolation: The action includes security features, such as optional bubblewrap support on Linux, to provide subprocess isolation when running user-defined scripts [7]. 3. Security Guidance: For workflows using allowed_non_write_users (a configuration that allows users without direct write access to trigger the action), the documentation strongly advises passing github_token: ${{ secrets.GITHUB_TOKEN }} (or an appropriate scoped token) and recommends restricting allowed tools via claude_args to minimize potential security risks associated with prompt injection or unauthorized access [5]. If you are setting up this action, the recommended approach for authentication is often to use the GitHub App flow [1][8]. If you must use a custom token, ensure it is passed through the github_token input rather than relying on environment variable injection alone, as the action's internal run.ts logic specifically collects and validates this input before populating the process environment for subsequent tool execution [3][4].

Citations:


🌐 Web query:

site:github.com anthropics/claude-code-action github_token env GH_TOKEN Bash tool

💡 Result:

In the context of the official anthropics/claude-code-action and the Claude Code CLI, the handling of GITHUB_TOKEN and GH_TOKEN environment variables is as follows: 1. Relationship between GITHUB_TOKEN and GH_TOKEN: The GitHub CLI (gh) prioritizes the GH_TOKEN environment variable over GITHUB_TOKEN [1][2]. To ensure consistency, the claude-code-action explicitly sets both GH_TOKEN and GITHUB_TOKEN when a token is provided [1][2]. This prevents conflicts where the CLI might otherwise fall back to a default workflow token instead of the specific token provided to the action [1][2]. 2. Usage in Actions: The github_token input for the claude-code-action is intended only for users connecting their own custom GitHub App [3]. For standard usage, the action uses built-in authentication, and users are advised not to provide a github_token unless they have a specific need to override this behavior, as doing so can cause issues with features like sticky comments and bot-based attribution [4]. 3. Bash Tool Environment: Claude Code's Bash tool executes commands within an environment that often inherits the user's shell variables [5]. In local environments, it has been noted that Claude Code may inject a GITHUB_TOKEN (or similar) into the shell environment [6]. This can sometimes conflict with existing local authentication (such as gh CLI credentials stored in a system keychain) [6][7]. A common manual workaround for CLI command conflicts is to unset the variable within the specific command: unset GITHUB_TOKEN && gh ... [6]. 4. Security Best Practices: Because GITHUB_TOKEN and other secrets are exposed as environment variables, they are technically readable by processes within the shell environment [7][5]. It is recommended to use specific, least-privilege tokens when configuring custom access for Claude Code [7]. For GitHub Actions, always use GitHub Secrets for any required tokens rather than hardcoding them [4]. Top results: [6][1][2][7][3][4]

Citations:


🏁 Script executed:

rg -n "claude-code-action|github_token|GH_TOKEN|allowedTools|Bash" -S .github README* .

Repository: Cervais/.github

Length of output: 736


🏁 Script executed:

sed -n '60,95p' .github/workflows/ai-review-merge.yml && printf '\n---\n' && sed -n '135,220p' .github/workflows/ai-review-merge.yml

Repository: Cervais/.github

Length of output: 5487


🏁 Script executed:

rg -n "secrets\.TOKEN|org admin token|admin token|github_token:" .github/workflows/ai-review-merge.yml

Repository: Cervais/.github

Length of output: 327


🏁 Script executed:

sed -n '1,30p' .github/workflows/ai-review-merge.yml

Repository: Cervais/.github

Length of output: 1542


Scope the review step to ${{ github.token }}
claude-code-action exports github_token into the process environment, so Bash can read it. This step only needs to inspect the PR and submit a review; passing the org-admin token widens the blast radius of prompt-injected commands. Use ${{ github.token }} here and keep secrets.TOKEN for the merge step.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/ai-review-merge.yml around lines 168 - 193, Update the
“Claude review (merge gate)” step’s github_token input to use the scoped ${{
github.token }} value instead of secrets.TOKEN. Leave the merge step’s token
configuration unchanged so only this review action’s permissions are narrowed.


merge:
name: Merge on green
needs: [ classify, ai-review ]
if: >-
always() && needs.classify.result == 'success' &&
(needs.classify.outputs.lane == 'fast' ||
(needs.classify.outputs.lane == 'ai' && needs.ai-review.result == 'success'))
runs-on: ubuntu-latest
timeout-minutes: 50
permissions:
contents: read
env:
LANE: ${{ needs.classify.outputs.lane }}
LANE_REASON: ${{ needs.classify.outputs.reason }}
steps:
- name: Wait for green CI, then squash-merge
env:
GH_TOKEN: ${{ secrets.TOKEN }}
run: |
set -euo pipefail
# Re-check opt-outs at merge time.
meta=$(gh pr view "$PR_NUMBER" --repo "$REPO" --json labels,title,isDraft,state)
if jq -e '(.labels | map(.name) | index("hold")) or (.title | contains("DO NOT MERGE")) or .isDraft' <<<"$meta" >/dev/null; then
echo "PR #$PR_NUMBER held (label/title/draft); not merging."; exit 0
fi
if [ "$(jq -r .state <<<"$meta")" != "OPEN" ]; then
echo "PR #$PR_NUMBER no longer open; nothing to do."; exit 0
fi
for i in $(seq 1 80); do
rollup=$(gh pr view "$PR_NUMBER" --repo "$REPO" --json statusCheckRollup \
--jq '[.statusCheckRollup[]? | select(.name != "Classify PR lane" and .name != "AI review" and .name != "Merge on green")]')
failed=$(jq '[.[] | select((.conclusion // "") | IN("FAILURE","CANCELLED","TIMED_OUT","ACTION_REQUIRED"))] | length' <<<"$rollup")
pending=$(jq '[.[] | select(.status != "COMPLETED" and .status != null)] | length' <<<"$rollup")
if [ "$failed" -gt 0 ]; then
echo "CI failed on PR #$PR_NUMBER; not merging."; exit 1
fi
if [ "$pending" -eq 0 ]; then
if [ "$LANE" = "fast" ]; then
gh pr comment "$PR_NUMBER" --repo "$REPO" \
--body "🤖 Fast-lane merge (no AI review needed): ${LANE_REASON}. CI green; squash-merging."
fi
gh pr merge "$PR_NUMBER" --repo "$REPO" --squash --admin --delete-branch
exit 0
fi
echo "waiting on $pending check(s)…"; sleep 30
done
echo "Timed out waiting for CI on PR #$PR_NUMBER."; exit 1
Comment on lines +210 to +241

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🔴 Critical | ⚡ Quick win

Merge can land commits that were never classified or reviewed (stale-approval TOCTOU).

The re-check at lines 216-222 re-reads labels,title,isDraft,state but never re-fetches headRefOid and never compares it against needs.classify.outputs.head_sha. Combined with the adoption stub's trigger list (opened, reopened, ready_for_review, labeled — no synchronize), a push landed after classification/AI-review will not start a new run, so the in-flight merge job keeps polling the same PR and will squash-merge whatever the current head is once its CI turns green — even though that head was never classified (fast vs ai) nor reviewed by Claude. This applies to both lanes: a fast-lane PR (e.g. docs-only) that gets amended with real code before merge completes bypasses AI review entirely.

🐛 Proposed fix — pin the merge to the reviewed commit
-          meta=$(gh pr view "$PR_NUMBER" --repo "$REPO" --json labels,title,isDraft,state)
+          meta=$(gh pr view "$PR_NUMBER" --repo "$REPO" --json labels,title,isDraft,state,headRefOid)
           if jq -e '(.labels | map(.name) | index("hold")) or (.title | contains("DO NOT MERGE")) or .isDraft' <<<"$meta" >/dev/null; then
             echo "PR #$PR_NUMBER held (label/title/draft); not merging."; exit 0
           fi
           if [ "$(jq -r .state <<<"$meta")" != "OPEN" ]; then
             echo "PR #$PR_NUMBER no longer open; nothing to do."; exit 0
           fi
+          if [ "$(jq -r .headRefOid <<<"$meta")" != "${{ needs.classify.outputs.head_sha }}" ]; then
+            echo "PR #$PR_NUMBER head moved since classification; not merging a stale review."; exit 0
+          fi

(See the consolidated comment for the separate, unrelated self-referential CI-wait bug also present in this step.)

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- name: Wait for green CI, then squash-merge
env:
GH_TOKEN: ${{ secrets.TOKEN }}
run: |
set -euo pipefail
# Re-check opt-outs at merge time.
meta=$(gh pr view "$PR_NUMBER" --repo "$REPO" --json labels,title,isDraft,state)
if jq -e '(.labels | map(.name) | index("hold")) or (.title | contains("DO NOT MERGE")) or .isDraft' <<<"$meta" >/dev/null; then
echo "PR #$PR_NUMBER held (label/title/draft); not merging."; exit 0
fi
if [ "$(jq -r .state <<<"$meta")" != "OPEN" ]; then
echo "PR #$PR_NUMBER no longer open; nothing to do."; exit 0
fi
for i in $(seq 1 80); do
rollup=$(gh pr view "$PR_NUMBER" --repo "$REPO" --json statusCheckRollup \
--jq '[.statusCheckRollup[]? | select(.name != "Classify PR lane" and .name != "AI review" and .name != "Merge on green")]')
failed=$(jq '[.[] | select((.conclusion // "") | IN("FAILURE","CANCELLED","TIMED_OUT","ACTION_REQUIRED"))] | length' <<<"$rollup")
pending=$(jq '[.[] | select(.status != "COMPLETED" and .status != null)] | length' <<<"$rollup")
if [ "$failed" -gt 0 ]; then
echo "CI failed on PR #$PR_NUMBER; not merging."; exit 1
fi
if [ "$pending" -eq 0 ]; then
if [ "$LANE" = "fast" ]; then
gh pr comment "$PR_NUMBER" --repo "$REPO" \
--body "🤖 Fast-lane merge (no AI review needed): ${LANE_REASON}. CI green; squash-merging."
fi
gh pr merge "$PR_NUMBER" --repo "$REPO" --squash --admin --delete-branch
exit 0
fi
echo "waiting on $pending check(s)…"; sleep 30
done
echo "Timed out waiting for CI on PR #$PR_NUMBER."; exit 1
- name: Wait for green CI, then squash-merge
env:
GH_TOKEN: ${{ secrets.TOKEN }}
run: |
set -euo pipefail
# Re-check opt-outs at merge time.
meta=$(gh pr view "$PR_NUMBER" --repo "$REPO" --json labels,title,isDraft,state,headRefOid)
if jq -e '(.labels | map(.name) | index("hold")) or (.title | contains("DO NOT MERGE")) or .isDraft' <<<"$meta" >/dev/null; then
echo "PR #$PR_NUMBER held (label/title/draft); not merging."; exit 0
fi
if [ "$(jq -r .state <<<"$meta")" != "OPEN" ]; then
echo "PR #$PR_NUMBER no longer open; nothing to do."; exit 0
fi
if [ "$(jq -r .headRefOid <<<"$meta")" != "${{ needs.classify.outputs.head_sha }}" ]; then
echo "PR #$PR_NUMBER head moved since classification; not merging a stale review."; exit 0
fi
for i in $(seq 1 80); do
rollup=$(gh pr view "$PR_NUMBER" --repo "$REPO" --json statusCheckRollup \
--jq '[.statusCheckRollup[]? | select(.name != "Classify PR lane" and .name != "AI review" and .name != "Merge on green")]')
failed=$(jq '[.[] | select((.conclusion // "") | IN("FAILURE","CANCELLED","TIMED_OUT","ACTION_REQUIRED"))] | length' <<<"$rollup")
pending=$(jq '[.[] | select(.status != "COMPLETED" and .status != null)] | length' <<<"$rollup")
if [ "$failed" -gt 0 ]; then
echo "CI failed on PR #$PR_NUMBER; not merging."; exit 1
fi
if [ "$pending" -eq 0 ]; then
if [ "$LANE" = "fast" ]; then
gh pr comment "$PR_NUMBER" --repo "$REPO" \
--body "🤖 Fast-lane merge (no AI review needed): ${LANE_REASON}. CI green; squash-merging."
fi
gh pr merge "$PR_NUMBER" --repo "$REPO" --squash --admin --delete-branch
exit 0
fi
echo "waiting on $pending check(s)…"; sleep 30
done
echo "Timed out waiting for CI on PR #$PR_NUMBER."; exit 1
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.github/workflows/ai-review-merge.yml around lines 210 - 241, Update the
“Wait for green CI, then squash-merge” step to fetch the current headRefOid and
compare it with needs.classify.outputs.head_sha before and immediately before
merging. Abort without merging if the PR head changed, and pass the reviewed SHA
as the merge command’s expected-head constraint so the squash merge cannot
target an unreviewed commit in either lane.