diff --git a/.github/scripts/risk-gate-label.mjs b/.github/scripts/risk-gate-label.mjs new file mode 100644 index 000000000..bafdee9f9 --- /dev/null +++ b/.github/scripts/risk-gate-label.mjs @@ -0,0 +1,81 @@ +// Applies the tier of risk-gate.mjs to a pull request as its one risk:T* label (issue #3393). +// +// node .github/scripts/risk-gate-label.mjs --pr 12 # dry run: print the change, write nothing +// GH_TOKEN=... node .github/scripts/risk-gate-label.mjs --pr 12 --apply +// PR=12 GITHUB_REPOSITORY=owner/repo node .github/scripts/risk-gate-label.mjs --apply # what the workflow passes +// +// The label is the record merge-gate reads (RISK_LABEL in merge-gate-core.mjs): exactly one risk:T0..T3 +// per pull request, written only by the risk-gate workflow. A run converges instead of stacking: labels +// for other tiers are removed, the target is added, and a run that already finds the target alone sends +// no write at all - so a re-run, or the leftovers of a cancelled run, leave one label and nothing else. +// +// No comment is posted. The tier and its reasons go to the run summary through risk-gate.mjs, so there +// is no second copy on the pull request to keep in sync. +import { appendFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { DEFAULT_REPO, createGate, loadRules, prFiles } from './risk-gate.mjs' +import { RISK_LABEL } from './merge-gate-core.mjs' + +// Writes need a token; a dry run does not, and the read in risk-gate.mjs stays anonymous without one. +const apiBase = () => (process.env.GITHUB_API_URL || 'https://api.github.com').replace(/\/+$/, '') +const authToken = () => process.env.GITHUB_TOKEN || process.env.GH_TOKEN || '' + +async function call(method, path, body) { + const headers = { accept: 'application/vnd.github+json', 'user-agent': 'flybot-risk-gate-label' } + const token = authToken() + if (token) headers.authorization = `Bearer ${token}` + if (body) headers['content-type'] = 'application/json' + const res = await fetch(apiBase() + path, { method, headers, body: body ? JSON.stringify(body) : undefined }) + const text = await res.text() + if (!res.ok) { + const body = text.slice(0, 200).replace(/\s+/g, ' ') + throw new Error(`${method} ${path} -> ${res.status} ${res.statusText}${body ? `: ${body}` : ''}`) + } + return text ? JSON.parse(text) : undefined +} + +// What the labels of one pull request must become for this tier. Kept pure so the only write rule is +// testable without a network: the target is the single risk:T* label, every other label is left alone. +export function labelPlan(tier, labels) { + const target = `risk:${tier}` + const risk = labels.filter((n) => RISK_LABEL.test(n)) + return { target, add: risk.includes(target) ? null : target, remove: risk.filter((n) => n !== target) } +} + +function arg(name) { + const i = process.argv.indexOf(name) + return i > 0 ? process.argv[i + 1] : undefined +} + +async function main() { + const rulesPath = arg('--rules') || process.env.RISK_RULES || fileURLToPath(new URL('../agent/risk-rules.json', import.meta.url)) + const gate = createGate(loadRules(rulesPath)) + const repo = arg('--repo') || process.env.GH_REPO || process.env.GITHUB_REPOSITORY || DEFAULT_REPO + const pr = arg('--pr') || process.env.PR + if (!pr) throw new Error('set PR or pass --pr N') + const apply = process.argv.includes('--apply') + + const tier = gate.judge(await prFiles(repo, pr)).tier + const labels = (await call('GET', `/repos/${repo}/issues/${pr}/labels?per_page=100`)).map((l) => l.name) + const plan = labelPlan(tier, labels) + + let verdict + if (!apply) { + verdict = `dry run: would ${plan.add ? `add ${plan.add}` : `keep ${plan.target}`}${plan.remove.length ? `, removing ${plan.remove.join(' ')}` : ''}` + } else { + for (const name of plan.remove) await call('DELETE', `/repos/${repo}/issues/${pr}/labels/${encodeURIComponent(name)}`) + if (plan.add) await call('POST', `/repos/${repo}/issues/${pr}/labels`, { labels: [plan.add] }) + const changed = plan.remove.length > 0 || plan.add !== null + verdict = changed + ? `applied ${plan.target}${plan.remove.length ? `, removed ${plan.remove.join(' ')}` : ''}` + : `unchanged, ${plan.target} was already the only risk label` + } + + const line = `risk-gate-label: PR #${pr} tier ${tier}; ${verdict}` + console.log(line) + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, line + '\n') +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + main().catch((e) => { console.error(`risk-gate-label: ${e.message}`); process.exit(1) }) +} diff --git a/.github/scripts/risk-gate-label.test.mjs b/.github/scripts/risk-gate-label.test.mjs new file mode 100644 index 000000000..55551b073 --- /dev/null +++ b/.github/scripts/risk-gate-label.test.mjs @@ -0,0 +1,131 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import { execFile } from 'node:child_process' +import { promisify } from 'node:util' +import { fileURLToPath } from 'node:url' +import { labelPlan } from './risk-gate-label.mjs' +import { createGate, loadRules } from './risk-tier.mjs' + +const exec = promisify(execFile) +const SCRIPT = fileURLToPath(new URL('./risk-gate-label.mjs', import.meta.url)) +const RULES = fileURLToPath(new URL('../agent/risk-rules.json', import.meta.url)) +const REPO = 'owner/repo' +const PR = '12' +const TIER = createGate(loadRules(RULES)).judge([]).tier // what an empty diff is worth; the fixtures reuse it + +// The command exits 1 when it cannot write; the run helpers keep that exit code instead of throwing. +const runScript = (env, ...args) => exec(process.execPath, [SCRIPT, '--repo', REPO, '--pr', PR, '--rules', RULES, ...args], { + env: { PATH: process.env.PATH, ...env }, + encoding: 'utf8', +}).then(({ stdout, stderr }) => ({ status: 0, stdout, stderr }), (e) => ({ status: e.code ?? 1, stdout: e.stdout || '', stderr: e.stderr || '' })) + +// --- the write rule, without a network --------------------------------------------------------- +test('labelPlan: the first judgement adds the only risk label and keeps other labels', () => { + assert.deepEqual(labelPlan('T2', ['bug', 'agent-pr']), { target: 'risk:T2', add: 'risk:T2', remove: [] }) +}) + +test('labelPlan: a new verdict replaces the old tier, never adds a second one', () => { + assert.deepEqual(labelPlan('T2', ['bug', 'risk:T1']), { target: 'risk:T2', add: 'risk:T2', remove: ['risk:T1'] }) +}) + +test('labelPlan: the verdict already in place is left untouched, so a re-run writes nothing', () => { + assert.deepEqual(labelPlan('T2', ['risk:T2', 'bug']), { target: 'risk:T2', add: null, remove: [] }) +}) + +test('labelPlan: duplicates and a stale second verdict collapse into the one target label', () => { + assert.deepEqual(labelPlan('T2', ['risk:T2', 'risk:T1']), { target: 'risk:T2', add: null, remove: ['risk:T1'] }) +}) + +// --- the command, against a local API (no network, no token) ------------------------------------ +// The stub records the exact write calls, so "idempotent" is a measurement, not a reading of the +// code. GITHUB_API_URL points both scripts at it; nothing leaves the machine. +async function withApi(labels, fn) { + const state = { labels: [...labels], calls: [] } + const server = createServer((req, res) => { + const url = new URL(req.url, 'http://127.0.0.1') + const body = [] + req.on('data', (c) => body.push(c)) + req.on('end', () => { + state.calls.push(`${req.method} ${url.pathname}`) + const send = (status, payload) => { + res.writeHead(status, { 'content-type': 'application/json' }) + res.end(payload === undefined ? '' : JSON.stringify(payload)) + } + if (req.method === 'GET' && url.pathname === `/repos/${REPO}/pulls/${PR}/files`) return send(200, []) + if (req.method === 'GET' && url.pathname === `/repos/${REPO}/issues/${PR}/labels`) { + return send(200, state.labels.map((name) => ({ name }))) + } + if (req.method === 'DELETE' && url.pathname.startsWith(`/repos/${REPO}/issues/${PR}/labels/`)) { + const name = decodeURIComponent(url.pathname.split('/').pop()) + state.labels = state.labels.filter((n) => n !== name) + return send(200, {}) + } + if (req.method === 'POST' && url.pathname === `/repos/${REPO}/issues/${PR}/labels`) { + const { labels: added } = JSON.parse(String(body.join('') || '{}')) + state.labels.push(...added) + return send(200, added.map((name) => ({ name }))) + } + send(404, { message: `no stub for ${req.method} ${url.pathname}` }) + }) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + const env = { GITHUB_API_URL: `http://127.0.0.1:${server.address().port}` } + try { + await fn((...args) => runScript(env, ...args), state) + } finally { + await new Promise((resolve) => server.close(resolve)) + } +} + +const writes = (state) => state.calls.filter((c) => !c.startsWith('GET ')) + +test('command: --apply leaves one risk label and no comment, and a second run writes nothing', async () => { + await withApi(['bug', 'risk:T1'], async (run, state) => { + const first = await run('--apply') + assert.equal(first.status, 0, first.stderr) + assert.deepEqual(writes(state), [`DELETE /repos/${REPO}/issues/${PR}/labels/risk%3AT1`, `POST /repos/${REPO}/issues/${PR}/labels`]) + assert.deepEqual(state.labels, ['bug', `risk:${TIER}`]) + assert.match(first.stdout, new RegExp(`risk-gate-label: PR #${PR} tier ${TIER}; applied risk:${TIER}, removed risk:T1`)) + + const second = await run('--apply') + assert.equal(second.status, 0, second.stderr) + assert.equal(writes(state).length, 2, 'a re-run must send no write') + assert.match(second.stdout, /unchanged, risk:T\d was already the only risk label/) + assert.deepEqual(state.labels, ['bug', `risk:${TIER}`], 'a re-run must not stack labels') + assert.ok(!state.calls.some((c) => c.includes('/comments')), 'no comment is ever posted') + }) +}) + +test('command: without --apply it reports the change and writes nothing', async () => { + await withApi(['risk:T1'], async (run, state) => { + const r = await run() + assert.equal(r.status, 0, r.stderr) + assert.match(r.stdout, /dry run: would add risk:T\d, removing risk:T1/) + assert.equal(writes(state).length, 0) + assert.deepEqual(state.labels, ['risk:T1']) + }) +}) + +test('command: a write the token cannot make fails loudly instead of claiming success', async () => { + const server = createServer((req, res) => { + if (req.method === 'GET' && req.url.includes('/labels')) { + res.writeHead(200, { 'content-type': 'application/json' }) + return res.end(JSON.stringify([])) + } + if (req.method === 'GET' && req.url.includes('/files')) { + res.writeHead(200, { 'content-type': 'application/json' }) + return res.end('[]') + } + res.writeHead(403, { 'content-type': 'application/json' }) + res.end(JSON.stringify({ message: 'Resource not accessible by integration' })) + }) + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + try { + const r = await runScript({ GITHUB_API_URL: `http://127.0.0.1:${server.address().port}` }, '--apply') + assert.equal(r.status, 1) + assert.match(r.stderr, /POST .* -> 403/) + } finally { + await new Promise((resolve) => server.close(resolve)) + } +}) diff --git a/.github/workflows/risk-gate.yml b/.github/workflows/risk-gate.yml new file mode 100644 index 000000000..32f17ca29 --- /dev/null +++ b/.github/workflows/risk-gate.yml @@ -0,0 +1,57 @@ +# The risk tier of a pull request, written as its one risk:T* label (issue #3393). +# +# The label is information, not a gate: merge-gate reads it, and the merge decision stays with the +# FlyBot Lead (user decision, 2026-11-26). This workflow is the only producer of that label - it is +# never hand-written - so the label always matches the rules table in .github/agent/risk-rules.json. +# +# The script and the rules are taken from the base commit, never from the pull request's own head: a +# pull request must not be able to judge its own diff. The same run also removes a label that belongs +# to an older verdict, so a pull request ends up with exactly one risk:T0..T3. +name: Risk tier label +on: + pull_request: + types: [opened, synchronize, reopened] +permissions: + contents: read + pull-requests: write +concurrency: + group: risk-gate-label-${{ github.event.pull_request.number }} + cancel-in-progress: true +jobs: + label: + name: Risk tier label + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + with: + node-version: '22' + # Without --apply the script prints what it would do and writes nothing; the workflow is the one + # caller that passes --apply, so a local run can never change a pull request. + - name: Read the diff and make risk:T* the only risk label + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_REPOSITORY: ${{ github.repository }} + PR: ${{ github.event.pull_request.number }} + run: node .github/scripts/risk-gate-label.mjs --pr "$PR" --apply + - name: Say that no label was applied + if: failure() + env: + PR: ${{ github.event.pull_request.number }} + # The gates in tests.yml are separate workflows and are not affected by this job. What a + # failure means is only this: this pull request has no risk label from this run, and + # merge-gate will refuse it until one arrives. + # + # The two causes this job cannot work around itself: the label risk:T0..T3 must already + # exist in the repository (creating a repository label needs issues: write, which this job + # does not have), and on a pull request from a fork GITHUB_TOKEN is read-only. + run: | + echo "::error::No risk:T* label was applied to PR #${PR}; the label comes only from this job." + { + echo "No risk:T* label was applied to PR #${PR}." + echo "If the write was rejected, check that the labels risk:T0..risk:T3 exist in the repository (this job cannot create them) and that the pull request is not from a fork." + } >> "$GITHUB_STEP_SUMMARY"