diff --git a/.github/tests/pr-risk-labels.test.mjs b/.github/tests/pr-risk-labels.test.mjs new file mode 100644 index 000000000..56940d7b6 --- /dev/null +++ b/.github/tests/pr-risk-labels.test.mjs @@ -0,0 +1,225 @@ +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; + +// Execute the actual workflow script so the tests cannot drift from production. +const workflow = readFileSync( + new URL("../workflows/pr-risk-jev.yml", import.meta.url), + "utf8", +); +const script = workflow.match(/^ {10}script: \|\n((?: {12}.*\n|\n)+)/m)?.[1]; +assert.ok(script, "Publish risk label script must exist"); +const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; +const publish = new AsyncFunction( + "require", + "github", + "context", + "core", + script, +); +const require = createRequire(import.meta.url); +const repo = { owner: "example", repo: "cli" }; +const head = "a".repeat(40); +const base = "b".repeat(40); + +async function withPR(options, check) { + const directory = mkdtempSync(join(tmpdir(), "pr-risk-labels-")); + const previousDirectory = process.cwd(); + const previousNumber = process.env.PR_NUMBER; + const labels = new Set(options.labels ?? ["area: auth", "risk: high"]); + const repositoryLabels = new Set( + options.repositoryLabels ?? ["risk: low", "risk: medium", "risk: high"], + ); + const writes = []; + const warnings = []; + const pr = { + state: "open", + head: { sha: head }, + base: { sha: base }, + title: "Update behavior", + body: "Describe this change", + ...options.pr, + }; + const result = { + repo: "example/cli", + number: 42, + status: "ok", + risk_label: "low", + snapshot: { source_head_sha: head, source_base_sha: base }, + ...options.result, + }; + const error = (status) => + Object.assign(new Error(`GitHub HTTP ${status}`), { status }); + const github = { + rest: { + pulls: { + get: async () => ({ + data: structuredClone({ + ...pr, + labels: [...labels].map((name) => ({ name })), + }), + }), + }, + issues: { + getLabel: async ({ name }) => { + if (!repositoryLabels.has(name)) throw error(404); + return { data: { name } }; + }, + createLabel: async ({ name }) => { + repositoryLabels.add(name); + if (options.createRace) throw error(422); + return { data: { name } }; + }, + addLabels: async ({ labels: added }) => { + writes.push(["add", ...added]); + for (const label of added) labels.add(label); + options.afterAdd?.(pr); + }, + removeLabel: async ({ name }) => { + writes.push(["remove", name]); + if (!labels.delete(name)) throw error(404); + }, + }, + }, + }; + try { + process.chdir(directory); + process.env.PR_NUMBER = "42"; + if (!options.missingResult) + writeFileSync("risk-pr-result.json", JSON.stringify(result)); + await check({ + run: () => + publish( + require, + github, + { repo }, + { warning: (message) => warnings.push(message), info: () => {} }, + ), + labels, + writes, + warnings, + }); + } finally { + process.chdir(previousDirectory); + if (previousNumber === undefined) delete process.env.PR_NUMBER; + else process.env.PR_NUMBER = previousNumber; + rmSync(directory, { recursive: true, force: true }); + } +} + +for (const risk of ["low", "medium", "high"]) { + test(`publishes ${risk}, replacing only risk labels`, async () => { + await withPR( + { + result: { risk_label: risk }, + labels: ["area: auth", "risk: low", "risk: medium", "risk: high"], + }, + async ({ run, labels }) => { + await run(); + assert.deepEqual([...labels].sort(), ["area: auth", `risk: ${risk}`]); + }, + ); + }); +} + +test("context rejection removes stale risk labels and remains unclassified", async () => { + await withPR( + { result: { status: "context_rejected", risk_label: null } }, + async ({ run, labels, warnings }) => { + await run(); + assert.deepEqual([...labels], ["area: auth"]); + assert.ok(warnings.some((message) => message.includes("unclassified"))); + }, + ); +}); + +test("moved or closed PRs are left untouched before publication", async (t) => { + for (const pr of [ + { head: { sha: "c".repeat(40) } }, + { base: { sha: "d".repeat(40) } }, + { state: "closed" }, + ]) { + await t.test(JSON.stringify(pr), async () => { + await withPR({ pr }, async ({ run, labels, writes }) => { + await run(); + assert.deepEqual(writes, []); + assert.deepEqual([...labels], ["area: auth", "risk: high"]); + }); + }); + } +}); + +test("movement or metadata edits during publication roll back the verdict", async (t) => { + for (const [name, afterAdd] of [ + [ + "head", + (pr) => { + pr.head.sha = "c".repeat(40); + }, + ], + [ + "title", + (pr) => { + pr.title = "A different change"; + }, + ], + [ + "closed", + (pr) => { + pr.state = "closed"; + }, + ], + ]) { + await t.test(name, async () => { + await withPR({ afterAdd }, async ({ run, labels }) => { + await run(); + assert.deepEqual([...labels], ["area: auth"]); + }); + }); + } +}); + +test("results for another PR or an invalid risk cannot publish", async (t) => { + for (const result of [ + { repo: "example/another" }, + { number: 43 }, + { risk_label: "critical" }, + { risk_label: "toString" }, + ]) { + await t.test(JSON.stringify(result), async () => { + await withPR({ result }, async ({ run, writes }) => { + await assert.rejects(run, /does not match/); + assert.deepEqual(writes, []); + }); + }); + } +}); + +test("a missing result does not publish or remove labels", async () => { + await withPR({ missingResult: true }, async ({ run, writes, warnings }) => { + await run(); + assert.deepEqual(writes, []); + assert.equal(warnings.length, 1); + }); +}); + +test("concurrent repository label creation still publishes", async () => { + await withPR( + { repositoryLabels: [], createRace: true }, + async ({ run, labels }) => { + await run(); + assert.deepEqual([...labels], ["area: auth", "risk: low"]); + }, + ); +}); + +test("repeated publication leaves one risk label and preserves unrelated labels", async () => { + await withPR({}, async ({ run, labels }) => { + await run(); + await run(); + assert.deepEqual([...labels], ["area: auth", "risk: low"]); + }); +}); diff --git a/.github/workflows/pr-risk-jev.yml b/.github/workflows/pr-risk-jev.yml new file mode 100644 index 000000000..bbfdd56d3 --- /dev/null +++ b/.github/workflows/pr-risk-jev.yml @@ -0,0 +1,120 @@ +name: PR Risk (Jev) + +on: + pull_request_target: + types: [opened, synchronize, reopened, ready_for_review, edited] + workflow_dispatch: + inputs: + pr_number: + description: Pull request number to analyze + required: true + type: number + +permissions: + contents: read + pull-requests: write + +concurrency: + group: pr-risk-jev-${{ github.event.pull_request.number || inputs.pr_number }} + cancel-in-progress: true + +jobs: + risk: + name: PR risk (Jev) + runs-on: ubuntu-latest + timeout-minutes: 10 + if: github.event_name == 'workflow_dispatch' || github.event.pull_request.draft == false + steps: + # The Action reads PR Git objects without checking out or executing PR code. + - name: Classify PR risk + id: risk + uses: getsentry/pr-risk-action@42934115c8d8417f2758462bbf918f71360ac2b1 + env: + AI_GATEWAY_API_KEY: ${{ secrets.AI_GATEWAY_API_KEY }} + with: + repo: ${{ github.repository }} + pr-number: ${{ github.event.pull_request.number || inputs.pr_number }} + expected-head-sha: ${{ github.event.pull_request.head.sha }} + result-path: risk-pr-result.json + + - name: Publish risk label + if: ${{ !cancelled() && steps.risk.outcome != 'skipped' }} + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + env: + PR_NUMBER: ${{ github.event.pull_request.number || inputs.pr_number }} + with: + script: | + // Only this trusted workflow publishes labels; PR source is never executed. + const fs = require('node:fs'); + if (!fs.existsSync('risk-pr-result.json')) { + core.warning('Risk analysis did not produce a result; no label was published.'); + return; + } + const result = JSON.parse(fs.readFileSync('risk-pr-result.json', 'utf8')); + const prNumber = Number(process.env.PR_NUMBER); + const repo = context.repo; + const colors = { low: '0E8A16', medium: 'FBCA04', high: 'B60205' }; + const riskLabels = Object.keys(colors).map(risk => `risk: ${risk}`); + if (!Number.isSafeInteger(prNumber) || prNumber <= 0 + || result.number !== prNumber || result.repo !== `${repo.owner}/${repo.repo}` + || typeof result.status !== 'string' + || (result.status === 'ok' && !Object.hasOwn(colors, result.risk_label))) { + throw new Error('Risk result does not match this PR or a valid risk class.'); + } + const snapshot = result.snapshot; + if (result.status === 'pr_changed' || !snapshot?.source_head_sha || !snapshot?.source_base_sha) { + core.warning('Risk analysis has no current revision; no label was published.'); + return; + } + const { data: pr } = await github.rest.pulls.get({ ...repo, pull_number: prNumber }); + if (pr.state !== 'open' || pr.head.sha !== snapshot.source_head_sha + || pr.base.sha !== snapshot.source_base_sha) { + core.warning('PR changed after risk analysis; no label was published.'); + return; + } + const target = result.status === 'ok' ? `risk: ${result.risk_label}` : null; + const existing = pr.labels.map(label => label.name); + if (target) { + try { + await github.rest.issues.getLabel({ ...repo, name: target }); + } catch (error) { + if (error.status !== 404) throw error; + try { + await github.rest.issues.createLabel({ + ...repo, name: target, color: colors[result.risk_label], + description: `PR risk score: ${result.risk_label}`, + }); + } catch (error) { + if (error.status !== 422) throw error; + // Another PR may have created the shared repository label. + await github.rest.issues.getLabel({ ...repo, name: target }); + } + } + await github.rest.issues.addLabels({ ...repo, issue_number: prNumber, labels: [target] }); + } + // A failed classification must not leave an earlier low/medium/high verdict. + for (const name of existing.filter(name => riskLabels.includes(name) && name !== target)) { + try { + await github.rest.issues.removeLabel({ ...repo, issue_number: prNumber, name }); + } catch (error) { + if (error.status !== 404) throw error; + } + } + const { data: latest } = await github.rest.pulls.get({ ...repo, pull_number: prNumber }); + if (target && (latest.state !== 'open' || latest.head.sha !== pr.head.sha + || latest.base.sha !== pr.base.sha || latest.title !== pr.title || latest.body !== pr.body)) { + await github.rest.issues.removeLabel({ ...repo, issue_number: prNumber, name: target }); + core.warning('PR changed while publishing; removed the outdated risk label.'); + return; + } + if (!target) core.warning(`PR remains unclassified: ${result.status}. Previous risk labels were cleared.`); + core.info(target ? `Published ${target}` : 'No risk label published.'); + + - name: Upload risk result + if: always() + uses: actions/upload-artifact@v7 + with: + name: pr-risk-jev-${{ github.event.pull_request.number || inputs.pr_number }} + path: risk-pr-result.json + if-no-files-found: warn + retention-days: 30 diff --git a/.github/workflows/pr-risk-labels-test.yml b/.github/workflows/pr-risk-labels-test.yml new file mode 100644 index 000000000..eae41c54b --- /dev/null +++ b/.github/workflows/pr-risk-labels-test.yml @@ -0,0 +1,28 @@ +name: PR Risk Label Tests + +on: + pull_request: + paths: + - .github/workflows/pr-risk-jev.yml + - .github/workflows/pr-risk-labels-test.yml + - .github/tests/pr-risk-labels.test.mjs + push: + branches: [main] + paths: + - .github/workflows/pr-risk-jev.yml + - .github/workflows/pr-risk-labels-test.yml + - .github/tests/pr-risk-labels.test.mjs + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-node@v6 + with: + node-version: '24.18.0' + - run: node --test .github/tests/pr-risk-labels.test.mjs diff --git a/docs/operations/github-actions.md b/docs/operations/github-actions.md index 40330c4f5..e0211e040 100644 --- a/docs/operations/github-actions.md +++ b/docs/operations/github-actions.md @@ -20,6 +20,23 @@ Runs after tests pass on main branch: ### eval.yml Runs evaluation tests against the MCP server. +### pr-risk-jev.yml +Classifies PR risk with Jev and publishes one `risk: low`, `risk: medium`, or +`risk: high` label. Runs when a non-draft PR is opened, updated with a push, +reopened, marked ready for review, or edited. Manual dispatch accepts a PR number +and also supports drafts. + +The pinned risk Action reads PR metadata and Git diffs without checking out or +executing PR code. Labels are only published for the analyzed revision; unrelated +labels are preserved. If a current-revision analysis fails, previous risk labels +are cleared and the PR stays unclassified. Results are retained as workflow +artifacts for 30 days. + +### pr-risk-labels-test.yml +Runs the label publisher's regression tests when its workflow or tests change. +Covers label replacement, stale revisions, failed classifications, and concurrent +label creation. + ## Required Secrets Repository secrets (no environment needed): @@ -30,6 +47,7 @@ Repository secrets (no environment needed): - **`SENTRY_CLIENT_SECRET`** - Sentry OAuth client secret - **`COOKIE_SECRET`** - Session cookie encryption secret - **`OPENAI_API_KEY`** - For AI-powered search features +- **`AI_GATEWAY_API_KEY`** - Vercel AI Gateway key for Jev PR risk classification ## Deployment Architecture