Skip to content
Merged
Show file tree
Hide file tree
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
204 changes: 197 additions & 7 deletions .github/workflows/openrouter-code-review.yml

Large diffs are not rendered by default.

124 changes: 124 additions & 0 deletions .github/workflows/openrouter-review-gate-check.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
# Head-bound gate check for trusted default-branch review callers.
#
# Default-branch runs (workflow_dispatch, repository_dispatch) attach their
# native job checks to the default-branch tip, not to the reviewed PR head.
# This workflow repeats openrouter-code-review.yml's first-pass gate result as a
# check run (GitHub Actions app) on the exact head that gate evaluated, so a
# required `review / openrouter-first-pass-gate` check is satisfied, or fails,
# on that commit. Pull-request runs, including pull_request_target, already
# report on the PR head, so `auto` mode leaves them to the native job check.
#
# It is a separate entry point because only this job needs `checks: write`.
# GitHub validates every reusable-job permission against the caller before
# runtime conditions, so adding the permission to the review workflow would
# reject existing callers that do not grant it.
#
# jobs:
# review:
# uses: RetireGolden/.github/.github/workflows/openrouter-code-review.yml@<sha>
# ...
# gate-check:
# needs: review
# if: always() && needs.review.outputs.gate_head_sha != ''
# uses: RetireGolden/.github/.github/workflows/openrouter-review-gate-check.yml@<sha>
# permissions:
# actions: read
# checks: write
# contents: read
# pull-requests: read
# with:
# pr_number: ${{ needs.review.outputs.gate_pr_number }}
# head_sha: ${{ needs.review.outputs.gate_head_sha }}
# conclusion: ${{ needs.review.outputs.gate_conclusion }}
# review_url: ${{ needs.review.outputs.gate_review_url }}
#
# It never checks out or executes pull-request content.
name: OpenRouter review gate check

on:
workflow_call:
inputs:
pr_number:
description: Pull request the first-pass gate evaluated
required: true
type: string
head_sha:
description: Exact PR head commit the first-pass gate evaluated
required: true
type: string
conclusion:
description: First-pass gate result; anything except success publishes failure
required: false
type: string
default: ''
review_url:
description: Optional review the gate accepted, linked from the check summary
required: false
type: string
default: ''
gate_check_name:
description: Check run name; match the required check on the target branch
required: false
type: string
default: 'review / openrouter-first-pass-gate'
publish_mode:
description: auto publishes only for default-branch runs; always also repeats pull-request results
required: false
type: string
default: 'auto'

permissions:
actions: read
checks: write
contents: read
pull-requests: read

jobs:
publish:
name: Publish head-bound gate check
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: read
checks: write
contents: read
pull-requests: read
steps:
- name: Resolve this reusable workflow's immutable source
id: source
env:
GH_TOKEN: ${{ github.token }}
shell: bash
run: |
set -euo pipefail
source_sha="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" \
--jq '[.referenced_workflows[] | select(.path | startswith("RetireGolden/.github/.github/workflows/openrouter-review-gate-check.yml@")) | .sha] | unique | if length == 1 then .[0] else error("ambiguous reusable workflow source") end')"
[[ "$source_sha" =~ ^[0-9a-f]{40}$ ]] || exit 1
echo "sha=$source_sha" >> "$GITHUB_OUTPUT"
- name: Checkout the trusted gate check helper
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: RetireGolden/.github
ref: ${{ steps.source.outputs.sha }}
path: .trusted-review-org
persist-credentials: false
- name: Publish the gate result on the reviewed head
uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8
env:
GATE_PR_NUMBER: ${{ inputs.pr_number }}
GATE_HEAD_SHA: ${{ inputs.head_sha }}
GATE_CONCLUSION: ${{ inputs.conclusion }}
GATE_REVIEW_URL: ${{ inputs.review_url }}
GATE_CHECK_NAME: ${{ inputs.gate_check_name }}
GATE_PUBLISH_MODE: ${{ inputs.publish_mode }}
with:
script: |
const { publishGateCheck } = await import(`${process.env.GITHUB_WORKSPACE}/.trusted-review-org/scripts/gate_check.mjs`)
await publishGateCheck(github, core, context, {
prNumber: process.env.GATE_PR_NUMBER,
headSha: process.env.GATE_HEAD_SHA,
conclusion: process.env.GATE_CONCLUSION,
reviewUrl: process.env.GATE_REVIEW_URL,
name: process.env.GATE_CHECK_NAME,
mode: process.env.GATE_PUBLISH_MODE,
})
104 changes: 103 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,108 @@ Minimum secret: `OPENROUTER_API_KEY` passed explicitly (never `secrets: inherit`

Branch protection should require `review / openrouter-first-pass-gate`.

### Trusted default-branch review callers (optional)

The same review workflow also accepts two default-branch caller events. Existing
`pull_request` and `workflow_dispatch` callers need no change.

- `pull_request_target` (`opened`, `reopened`, `ready_for_review`,
`synchronize`) keeps the `pull_request` split: `synchronize` is a follow-up,
the others are first passes. It runs only when the PR targets the default
branch, so the caller file comes from that branch. GitHub records these runs,
and their native job checks, on the PR head commit.
- `repository_dispatch` from the default branch is a first pass, like
`workflow_dispatch`. A called workflow sees no `github.event.inputs`, and this
workflow never reads `client_payload`; map payload fields into `with:`.
`expected_head_sha` makes the review and gate fail closed when the live PR
head differs from the head the dispatcher saw. Explicit `deep` and `cancel`
levels still require a maintainer and the default branch.

Under both events the reviewed head is checked out as inert data in jobs that
hold the OpenRouter key. No step runs its code, hooks, submodules, LFS
filters, package scripts or configuration, and a commit that contains the
reserved `.trusted-review-org` or `.trusted-review-action` paths is refused.

Default-branch dispatch runs attach native job checks to the default-branch
tip, so the required `review / openrouter-first-pass-gate` never reaches the PR
head on its own. `openrouter-review-gate-check.yml` repeats the gate result
(success or failure) as a GitHub Actions check run on the exact head the gate
evaluated. It reads the `gate_*` outputs of the review workflow, publishes only
from default-branch runs, skips heads that moved, and in `auto` mode leaves
pull-request runs to their native check. It is a separate entry point because
it is the only job that needs `checks: write`: GitHub checks reusable-job
permissions against the caller before runtime conditions, and current callers
do not grant that scope.

```yaml
name: OpenRouter code review
run-name: "${{ format('OpenRouter PR #{0}: {1}', github.event.pull_request.number || github.event.client_payload.pr_number || inputs.pr_number, github.event.client_payload.review_level || inputs.review_level || 'auto') }}"

on:
pull_request_target:
types: [opened, synchronize, reopened, ready_for_review]
repository_dispatch:
types: [openrouter-review]
workflow_dispatch:
inputs:
pr_number: { required: true, type: string }
review_level: { default: auto, type: choice, options: [auto, deep, cancel] }

permissions:
actions: write
checks: write
contents: read
pull-requests: write
statuses: write

jobs:
review:
if: github.event_name != 'pull_request_target' || !github.event.pull_request.draft
uses: RetireGolden/.github/.github/workflows/openrouter-code-review.yml@<ORG_WORKFLOW_SHA>
secrets:
OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }}
permissions:
actions: write
contents: read
pull-requests: write
statuses: write
with:
pr_number: ${{ github.event.pull_request.number || github.event.client_payload.pr_number || inputs.pr_number }}
review_level: ${{ github.event.client_payload.review_level || inputs.review_level || 'auto' }}
expected_head_sha: ${{ github.event.client_payload.head_sha || '' }}
review_profiles_enabled: false
review_policy: off
gate-check:
needs: review
if: always() && needs.review.outputs.gate_head_sha != ''
uses: RetireGolden/.github/.github/workflows/openrouter-review-gate-check.yml@<ORG_WORKFLOW_SHA>
permissions:
actions: read
checks: write
contents: read
pull-requests: read
with:
pr_number: ${{ needs.review.outputs.gate_pr_number }}
head_sha: ${{ needs.review.outputs.gate_head_sha }}
conclusion: ${{ needs.review.outputs.gate_conclusion }}
review_url: ${{ needs.review.outputs.gate_review_url }}
```

Keep the review job id `review`; profile evidence names its jobs
`review / ...`. `gate_check_name` defaults to
`review / openrouter-first-pass-gate`. Bot-sent `repository_dispatch` reviews
wake profile completion the same way bot-sent `workflow_dispatch` reviews do.

Profile evidence admits these events with the same bounds as before.
`repository_dispatch` runs must be on the default branch, and their caller
blob at the run's default-branch commit must match the trusted caller. A
`pull_request_target` run reports the PR head rather than the commit whose
caller ran. Evidence from it therefore requires every same-repository PR from
that head branch to target the default branch with no recorded base change,
the exact trusted reusable pin, a run head equal to the receipt head, and a PR
whose head branch matches the run. A receipt for an older head never satisfies
a newer one. If a PR was retargeted, push the change on a fresh branch.

### Thin completion caller (example)

Runs only on the default branch. Never executes PR code.
Expand Down Expand Up @@ -242,7 +344,7 @@ git clone --no-checkout https://github.com/FlyOverCoderKY/openrouter-pr-review-a
git -C .trusted-review-action checkout 212775ffea22e806cddcb706c73a3df26fbcb6d0
export PYTHONPATH="$PWD/.trusted-review-action/src"
uv run --with jq --with pyyaml python -m unittest discover -s tests
node --test tests/profile-consumer.test.mjs tests/workflow-wakeup.test.mjs
node --test tests/profile-consumer.test.mjs tests/workflow-wakeup.test.mjs tests/gate-check.test.mjs
```

`scripts/profile_consumer.mjs` is the shared Node validator used by existing
Expand Down
137 changes: 137 additions & 0 deletions scripts/gate_check.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// Publishes the first-pass gate result as a check run on the reviewed PR head.
//
// Default-branch dispatch runs (workflow_dispatch, repository_dispatch) attach
// their native job checks to the default-branch tip, so a required
// `review / openrouter-first-pass-gate` check never reaches the PR head. This
// helper repeats the gate's own conclusion on the exact head the gate evaluated.
// Pull-request runs (including pull_request_target) already attach their native
// job checks to the PR head; in `auto` mode they are left alone to avoid
// duplicate check runs with the same name.

export const DEFAULT_GATE_CHECK_NAME = 'review / openrouter-first-pass-gate';
export const GITHUB_ACTIONS_APP_ID = 15368;
const SHA_RE = /^[0-9a-f]{40}$/;
const PR_RE = /^[1-9][0-9]{0,9}$/;
const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9 ._/#:()-]{0,99}$/;
const MODES = new Set(['auto', 'always']);
const PULL_REQUEST_EVENTS = new Set(['pull_request', 'pull_request_target']);

function fail(message) {
throw new Error(message);
}

export function normalizeGateInputs({ prNumber, headSha, conclusion, reviewUrl, name, mode }, repository) {
const number = String(prNumber ?? '');
if (!PR_RE.test(number) || !Number.isSafeInteger(Number(number))) fail('pr_number must be a positive integer');
const sha = String(headSha ?? '');
if (!SHA_RE.test(sha)) fail('head_sha must be a lowercase full commit SHA');
const checkName = name === undefined || name === '' ? DEFAULT_GATE_CHECK_NAME : String(name);
if (!NAME_RE.test(checkName)) fail('gate_check_name is invalid');
const publishMode = mode === undefined || mode === '' ? 'auto' : String(mode);
if (!MODES.has(publishMode)) fail('publish_mode must be auto or always');
// Anything other than an explicit success is a failed gate (fail closed).
const result = conclusion === 'success' ? 'success' : 'failure';
const reviewPattern = new RegExp(
`^https://github\\.com/${repository.replace(/[.]/g, '\\.')}/pull/${number}#pullrequestreview-[1-9][0-9]*$`,
);
const review = typeof reviewUrl === 'string' && reviewPattern.test(reviewUrl) ? reviewUrl : '';
return { prNumber: Number(number), headSha: sha, conclusion: result, reviewUrl: review, name: checkName, mode: publishMode };
}

async function existingCheckRun(github, { owner, repo, headSha, name, externalId }) {
for (let page = 1; page <= 10; page += 1) {
const { data } = await github.request('GET /repos/{owner}/{repo}/commits/{ref}/check-runs', {
owner, repo, ref: headSha, check_name: name, filter: 'all', per_page: 100, page,
});
const runs = Array.isArray(data?.check_runs) ? data.check_runs : fail('check-run listing is invalid');
const match = runs.find((run) => run?.external_id === externalId && run?.app?.id === GITHUB_ACTIONS_APP_ID);
if (match) return match;
if (runs.length < 100) return null;
}
fail('check-run listing exceeds its bound');
}

/**
* Returns { published, reason, checkRunId? }. Never publishes for a PR head
* other than the one the gate evaluated, and only from default-branch runs.
*/
export async function publishGateCheck(github, core, context, inputs) {
const { owner, repo } = context.repo;
const repository = `${owner}/${repo}`;
const gate = normalizeGateInputs(inputs, repository);
const { data: repoData } = await github.request('GET /repos/{owner}/{repo}', { owner, repo });
const defaultBranch = repoData?.default_branch;
if (repoData?.full_name !== repository || typeof defaultBranch !== 'string' || !defaultBranch) {
fail('repository identity is invalid');
}
// A PR-branch caller (pull_request) cannot borrow this publisher: only
// workflows that GitHub ran from the default branch may publish.
if (context.ref !== `refs/heads/${defaultBranch}`) {
return skip(core, 'only default-branch callers publish head-bound gate checks');
}
if (!Number.isSafeInteger(context.runId) || context.runId <= 0) fail('invalid workflow run id');
const { data: run } = await github.request('GET /repos/{owner}/{repo}/actions/runs/{run_id}', {
owner, repo, run_id: context.runId,
});
if (run?.id !== context.runId || run?.repository?.full_name !== repository) fail('workflow run identity is invalid');
// Native job checks attach to the run's head. For PR events that is already
// the PR head; for default-branch dispatches it is the default-branch tip.
const nativeCoversHead = PULL_REQUEST_EVENTS.has(run.event) || run.head_sha === gate.headSha;
if (gate.mode === 'auto' && nativeCoversHead) {
return skip(core, 'the native gate job check already reports on the pull request head');
}
const { data: pr } = await github.request('GET /repos/{owner}/{repo}/pulls/{pull_number}', {
owner, repo, pull_number: gate.prNumber,
});
if (pr?.number !== gate.prNumber || pr?.base?.repo?.full_name !== repository) {
fail('pull request does not belong to this repository');
}
if (pr.head?.sha !== gate.headSha) {
// The newer head is evaluated by its own run; never move this result onto it.
return skip(core, `pull request head moved from ${gate.headSha}; leaving the newer head to its own run`);
}
const runUrl = `${context.serverUrl}/${repository}/actions/runs/${context.runId}`;
const externalId = `openrouter-first-pass-gate:${context.runId}`;
const passed = gate.conclusion === 'success';
const lines = [
passed
? `The OpenRouter first-pass gate passed for \`${gate.headSha}\`.`
: `The OpenRouter first-pass gate did not pass for \`${gate.headSha}\`.`,
'',
`Evaluated by [workflow run ${context.runId}](${runUrl}) (${run.event}).`,
];
if (gate.reviewUrl) lines.push(`Review: ${gate.reviewUrl}`);
const summary = lines.join('\n');
const payload = {
owner,
repo,
name: gate.name,
head_sha: gate.headSha,
status: 'completed',
conclusion: gate.conclusion,
completed_at: new Date().toISOString(),
details_url: runUrl,
external_id: externalId,
output: {
title: passed ? 'OpenRouter first-pass gate passed' : 'OpenRouter first-pass gate failed',
summary,
},
};
const existing = await existingCheckRun(github, { owner, repo, headSha: gate.headSha, name: gate.name, externalId });
let data;
if (existing) {
({ data } = await github.request('PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}', {
...payload, check_run_id: existing.id,
}));
} else {
({ data } = await github.request('POST /repos/{owner}/{repo}/check-runs', payload));
}
if (data?.head_sha !== gate.headSha || data?.name !== gate.name) fail('check run response does not match the request');
core.info(`Published ${gate.name}=${gate.conclusion} on ${gate.headSha} (check run ${data.id}).`);
return { published: true, reason: 'published', checkRunId: data.id };
}

function skip(core, reason) {
core.info(`Gate check not published: ${reason}.`);
return { published: false, reason };
}
Loading
Loading