diff --git a/.github/workflows/issue-gate.yml b/.github/workflows/issue-gate.yml new file mode 100644 index 000000000..a88735464 --- /dev/null +++ b/.github/workflows/issue-gate.yml @@ -0,0 +1,114 @@ +name: issue-gate + +on: + pull_request_target: + types: [opened, edited, reopened, synchronize, ready_for_review] + issues: + types: [labeled, unlabeled] + +permissions: + contents: read + issues: read + pull-requests: read + checks: write + +jobs: + discover: + name: discover + if: github.event_name == 'issues' + runs-on: ubuntu-22.04 + timeout-minutes: 5 + outputs: + prs: ${{ steps.list.outputs.prs }} + complete: ${{ steps.list.outputs.complete }} + steps: + # Trusted definition: pull_request_target runs this file from the base branch. + # Checkout the base branch only; never check out or run pull request code. + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version-file: .node-version + package-manager-cache: false + - id: list + name: List linked open PRs + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + result=$(node scripts/issue-gate.mjs --discover) + prs=$(printf '%s' "$result" | jq -c '.prs') + complete=$(printf '%s' "$result" | jq -r '.complete') + printf 'prs=%s\n' "$prs" >> "$GITHUB_OUTPUT" + printf 'complete=%s\n' "$complete" >> "$GITHUB_OUTPUT" + + evaluate-pr: + name: evaluate-pr + if: github.event_name == 'pull_request_target' + runs-on: ubuntu-22.04 + timeout-minutes: 5 + concurrency: + group: issue-gate-pr-${{ github.event.pull_request.number }} + cancel-in-progress: true + steps: + # Trusted definition: pull_request_target runs this file from the base branch. + # Checkout the base branch only; never check out or run pull request code. + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version-file: .node-version + package-manager-cache: false + - name: Evaluate linked issue + env: + GITHUB_TOKEN: ${{ github.token }} + TARGET_PR: ${{ github.event.pull_request.number }} + TARGET_HEAD: ${{ github.event.pull_request.head.sha }} + run: node scripts/issue-gate.mjs + + evaluate-issue: + name: evaluate-issue + needs: discover + if: always() && !cancelled() && needs.discover.result == 'success' && needs.discover.outputs.prs != '[]' + runs-on: ubuntu-22.04 + timeout-minutes: 5 + strategy: + fail-fast: false + matrix: + pr: ${{ fromJSON(needs.discover.outputs.prs) }} + concurrency: + group: issue-gate-pr-${{ matrix.pr.number }} + cancel-in-progress: true + steps: + # Trusted definition: pull_request_target runs this file from the base branch. + # Checkout the base branch only; never check out or run pull request code. + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0 + with: + node-version-file: .node-version + package-manager-cache: false + - name: Evaluate linked issue + env: + GITHUB_TOKEN: ${{ github.token }} + TARGET_PR: ${{ matrix.pr.number }} + TARGET_HEAD: ${{ matrix.pr.head }} + run: node scripts/issue-gate.mjs + + coverage: + name: coverage + needs: [discover, evaluate-issue] + if: always() && !cancelled() && github.event_name == 'issues' && needs.discover.result == 'success' && needs.discover.outputs.complete != 'true' + runs-on: ubuntu-22.04 + timeout-minutes: 5 + steps: + - name: Fail on incomplete linked-PR discovery + run: | + echo "::error::Linked-PR discovery was incomplete; some issue-gate checks were not refreshed. Re-run the full issue-gate workflow after the API recovers; rerunning only this job reuses the old discovery result." + exit 1 diff --git a/scripts/issue-gate.mjs b/scripts/issue-gate.mjs new file mode 100644 index 000000000..5f907b6f8 --- /dev/null +++ b/scripts/issue-gate.mjs @@ -0,0 +1,503 @@ +import fs from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const DEFAULT_API = 'https://api.github.com'; +const CHECK_NAME = 'issue-gate'; +const MAX_REFS = 20; +const MAX_PAGES = 10; +const MAX_LINKED_PRS = 20; +const MAX_SUMMARY = 60_000; +const SCAN_BATCH = 10; +const RETRY_STATUS = new Set([429, 500, 502, 503, 504]); + +function apiUrl() { + return (process.env.GITHUB_API_URL || DEFAULT_API).replace(/\/$/, ''); +} + +export function stripNonLinks(body) { + let text = String(body ?? ''); + text = text.replace(/```[\s\S]*?```/g, ''); + text = text.replace(/~~~[\s\S]*?~~~/g, ''); + text = text.replace(//g, ''); + text = text.replace(/`[^`\n]*`/g, ''); + return text + .split(/\r?\n/) + .filter((line) => !/^\s*>/.test(line)) + .join('\n'); +} + +export function parseRefs(body) { + const refs = new Set(); + for (const rawLine of stripNonLinks(body).split(/\r?\n/)) { + const line = rawLine.replace(/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+#\d+/g, ''); + if (/(^|[^A-Za-z0-9_])(fixes|closes|resolves|refs):?\s+#\d+/i.test(line)) { + for (const match of line.matchAll(/#(\d+)/g)) { + if (refs.size >= MAX_REFS) break; + refs.add(Number(match[1])); + } + } + } + return [...refs]; +} + +export function isAccepted(labels) { + return labels.some((label) => label === 'P0' || label === 'P1' || label === 'P2'); +} + +export function sameRepository(source, repository) { + return source?.issue?.repository_url === `${apiUrl()}/repos/${repository}`; +} + +function required(name) { + const value = process.env[name]; + if (!value) throw new Error(`${name} is not set`); + return value; +} + +function retryAttempts() { + const attempts = Number(process.env.ISSUE_GATE_RETRY_ATTEMPTS ?? 3); + return Number.isInteger(attempts) && attempts > 0 ? attempts : 3; +} + +function retryDelayMs() { + const delay = Number(process.env.ISSUE_GATE_RETRY_DELAY_MS ?? 500); + return Number.isFinite(delay) && delay >= 0 ? delay : 500; +} + +function isRetryable(error) { + return RETRY_STATUS.has(error.status) || error.name === 'TypeError'; +} + +async function withRetry(operation) { + const attempts = retryAttempts(); + for (let attempt = 1; ; attempt += 1) { + try { + return await operation(); + } catch (error) { + if (!isRetryable(error) || attempt >= attempts) throw error; + await new Promise((resolve) => setTimeout(resolve, retryDelayMs() * attempt)); + } + } +} + +async function api(path, options = {}) { + return withRetry(async () => { + const response = await fetch(`${apiUrl()}${path}`, { + ...options, + headers: { + Authorization: `Bearer ${required('GITHUB_TOKEN')}`, + Accept: 'application/vnd.github+json', + 'User-Agent': 'dim-issue-gate', + ...(options.headers ?? {}), + }, + }); + if (!response.ok) { + const body = await response.text(); + const error = new Error(`GitHub API ${response.status} ${path}: ${body.slice(0, 300)}`); + error.status = response.status; + throw error; + } + return response.status === 204 ? null : response.json(); + }); +} + +async function pages(path) { + const items = []; + for (let page = 1; page <= MAX_PAGES; page += 1) { + const separator = path.includes('?') ? '&' : '?'; + const batch = await api(`${path}${separator}per_page=100&page=${page}`); + items.push(...batch); + if (batch.length < 100) return items; + } + throw new Error(`Too many pages: ${path}`); +} + +async function getPr(number) { + const pr = await api(`/repos/${required('GITHUB_REPOSITORY')}/pulls/${number}`); + return { number, body: pr.body ?? '', head: pr.head.sha, state: pr.state }; +} + +async function getIssue(number) { + const repo = required('GITHUB_REPOSITORY'); + try { + const issue = await api(`/repos/${repo}/issues/${number}`); + if (issue.pull_request) return { kind: 'pr' }; + return { kind: 'issue', labels: issue.labels.map((label) => label.name) }; + } catch (error) { + if (error.status === 404) return { kind: 'missing' }; + throw error; + } +} + +async function getClosingRefs(number) { + const [owner, repo] = required('GITHUB_REPOSITORY').split('/'); + const query = `query($owner: String!, $repo: String!, $number: Int!) { + repository(owner: $owner, name: $repo) { + pullRequest(number: $number) { + closingIssuesReferences(first: 50) { + nodes { number repository { nameWithOwner } } + } + } + } + }`; + const result = await api('/graphql', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ query, variables: { owner, repo, number } }), + }); + if (result.errors?.length) throw new Error(result.errors.map((error) => error.message).join('; ')); + return result.data.repository.pullRequest.closingIssuesReferences.nodes + .filter((node) => node.repository?.nameWithOwner === required('GITHUB_REPOSITORY')) + .map((node) => node.number); +} + +async function scanOpenPrsForIssue(issueNumber, prs) { + const linked = new Set(); + const problems = []; + for (let index = 0; index < prs.length; index += SCAN_BATCH) { + const batch = prs.slice(index, index + SCAN_BATCH); + const matches = await Promise.all( + batch.map(async (pr) => { + const refs = new Set(parseRefs(pr.body ?? '')); + if (!refs.has(issueNumber)) { + try { + for (const number of await getClosingRefs(pr.number)) refs.add(number); + } catch (error) { + problems.push(`#${pr.number}: ${error.message}`); + console.error(`Could not read closing references for #${pr.number}: ${error.message}`); + return null; + } + } + return refs.has(issueNumber) ? pr.number : null; + }), + ); + for (const number of matches) if (number) linked.add(number); + } + const numbers = [...linked].sort((left, right) => left - right); + if (numbers.length > MAX_LINKED_PRS) { + problems.push(`More than ${MAX_LINKED_PRS} linked open pull requests`); + } + return { + numbers: numbers.slice(0, MAX_LINKED_PRS), + complete: problems.length === 0, + problems, + }; +} + +async function getLinkedOpenPrs(issueNumber) { + const repository = required('GITHUB_REPOSITORY'); + const openPrs = await pages(`/repos/${repository}/pulls?state=open`); + const byNumber = new Map(openPrs.map((pr) => [pr.number, pr])); + let numbers; + let complete = true; + const problems = []; + try { + const events = await pages(`/repos/${repository}/issues/${issueNumber}/timeline`); + const linked = new Set(); + for (const event of events) { + if (event.event !== 'cross-referenced') continue; + const source = event.source; + if (!sameRepository(source, repository)) continue; + if (source.issue.pull_request && source.issue.state === 'open') linked.add(source.issue.number); + } + numbers = [...linked].sort((left, right) => left - right); + if (numbers.length > MAX_LINKED_PRS) { + problems.push(`More than ${MAX_LINKED_PRS} linked open pull requests`); + complete = false; + numbers = numbers.slice(0, MAX_LINKED_PRS); + } + } catch (error) { + console.error(`Timeline read failed (${error.message}); scanning open PRs.`); + const scan = await scanOpenPrsForIssue(issueNumber, openPrs); + numbers = scan.numbers; + complete = scan.complete; + problems.push(...scan.problems); + } + const prs = []; + for (const number of numbers) { + const pr = byNumber.get(number); + if (!pr) { + problems.push(`#${number} is missing from the open pull request list`); + continue; + } + const head = pr.head?.sha; + if (!head) { + problems.push(`#${number} has no head SHA`); + continue; + } + prs.push({ number, head }); + } + return { prs, complete: complete && problems.length === 0, problems }; +} + +async function evaluate(pr) { + let closing; + try { + closing = await getClosingRefs(pr.number); + } catch (error) { + return { + ok: false, + title: 'Could not read closing references', + summary: error.message, + }; + } + const refs = parseRefs(pr.body); + const numbers = [...new Set([...refs, ...closing.slice(0, MAX_REFS)])].slice(0, MAX_REFS * 2); + if (!numbers.length) { + return { + ok: false, + title: 'No linked issue', + summary: 'Add `Fixes #N`, `Closes #N`, `Resolves #N` or `Refs #N` with an accepted issue (P0, P1 or P2).', + }; + } + + const rejected = []; + const unreadable = []; + for (const number of numbers) { + try { + const issue = await getIssue(number); + if (issue.kind === 'pr') { + rejected.push(`#${number} is a pull request, not an issue`); + } else if (issue.kind === 'missing') { + unreadable.push(`#${number} does not exist in this repository`); + } else if (isAccepted(issue.labels)) { + return { + ok: true, + title: 'Linked accepted issue', + summary: `Accepted: #${number}.`, + }; + } else { + rejected.push(`#${number} has [${issue.labels.join(', ') || 'no labels'}]`); + } + } catch (error) { + unreadable.push(`#${number}: ${error.message}`); + } + } + + if (unreadable.length && !rejected.length) { + return { + ok: false, + title: 'Could not read linked issues', + summary: unreadable.join('\n'), + }; + } + return { + ok: false, + title: 'No accepted issue', + summary: [...rejected, ...unreadable].join('\n'), + }; +} + +function checkOutput(result) { + return { + title: String(result.title).slice(0, 200), + summary: String(result.summary ?? '').slice(0, MAX_SUMMARY), + }; +} + +function detailsUrl() { + const server = process.env.GITHUB_SERVER_URL; + const repository = process.env.GITHUB_REPOSITORY; + const run = process.env.GITHUB_RUN_ID; + return server && repository && run ? `${server}/${repository}/actions/runs/${run}` : undefined; +} + +function checkId(pr) { + return `${CHECK_NAME}:${pr.number}`; +} + +async function findCheckRuns(pr) { + const repository = required('GITHUB_REPOSITORY'); + const response = await api( + `/repos/${repository}/commits/${pr.head}/check-runs?check_name=${CHECK_NAME}&filter=all&per_page=100`, + ); + const runs = Array.isArray(response) ? response : response.check_runs ?? []; + return runs + .filter((run) => run.name === CHECK_NAME && (!run.external_id || run.external_id === checkId(pr))) + .sort((left, right) => right.id - left.id); +} + +async function patchCheckRun(id, payload) { + const repository = required('GITHUB_REPOSITORY'); + await api(`/repos/${repository}/check-runs/${id}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + }); +} + +async function markCheckRunsInProgress(pr, runs, output, details) { + try { + await Promise.all( + runs.map((run) => + patchCheckRun(run.id, { + status: 'in_progress', + external_id: checkId(pr), + output, + ...(details ? { details_url: details } : {}), + }), + ), + ); + return runs.map((run) => run.id); + } catch (error) { + if (error.status === 422) return []; + throw error; + } +} + +async function beginCheckRun(pr) { + const repository = required('GITHUB_REPOSITORY'); + const details = detailsUrl(); + const output = { + title: 'Evaluating linked issue', + summary: 'Checking the PR body and linked issue labels.', + }; + let existing = []; + try { + existing = await findCheckRuns(pr); + } catch (error) { + console.error(`Could not read the existing issue-gate check: ${error.message}`); + } + if (existing.length) { + const ids = await markCheckRunsInProgress(pr, existing, output, details); + if (ids.length) return ids; + } + const created = await api(`/repos/${repository}/check-runs`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + name: CHECK_NAME, + head_sha: pr.head, + external_id: checkId(pr), + status: 'in_progress', + output, + ...(details ? { details_url: details } : {}), + }), + }); + const ids = new Set([created.id]); + try { + const reconciled = await findCheckRuns(pr); + if (reconciled.length) { + for (const id of await markCheckRunsInProgress(pr, reconciled, output, details)) ids.add(id); + } + } catch (error) { + console.error(`Could not reconcile issue-gate checks: ${error.message}`); + } + return [...ids]; +} + +async function finishCheckRun(pr, ids, result) { + const details = detailsUrl(); + const targets = new Set(ids); + try { + for (const run of await findCheckRuns(pr)) targets.add(run.id); + } catch (error) { + console.error(`Could not reconcile issue-gate checks: ${error.message}`); + } + const results = await Promise.allSettled( + [...targets].map((id) => + patchCheckRun(id, { + status: 'completed', + conclusion: result.ok ? 'success' : 'failure', + external_id: checkId(pr), + completed_at: new Date().toISOString(), + output: checkOutput(result), + ...(details ? { details_url: details } : {}), + }), + ), + ); + const rejected = results.find((outcome) => outcome.status === 'rejected'); + if (rejected) throw rejected.reason; +} + +async function failCheckRun(pr, ids, error) { + try { + await finishCheckRun(pr, ids, { ok: false, title: 'Gate error', summary: error.message }); + } catch (finishError) { + console.error(`Could not record the gate failure: ${finishError.message}`); + } +} + +async function evaluateStable(pr) { + const result = await evaluate(pr); + const current = await getPr(pr.number); + if (current.head !== pr.head || current.body !== pr.body || current.state !== pr.state) { + return { + ok: false, + title: 'PR changed during evaluation', + summary: 'The pull request changed while the gate evaluated it; the next event re-evaluates the current revision.', + }; + } + return result; +} + +async function main() { + const eventPath = required('GITHUB_EVENT_PATH'); + const event = JSON.parse(fs.readFileSync(eventPath, 'utf8')); + const eventName = required('GITHUB_EVENT_NAME'); + + if (process.argv.includes('--discover')) { + if (eventName !== 'issues') throw new Error(`--discover requires an issues event, got ${eventName}`); + const result = await getLinkedOpenPrs(event.issue.number); + if (!result.complete) { + console.error(`Incomplete linked-PR discovery: ${result.problems.join('; ')}`); + } + console.log(JSON.stringify(result)); + return; + } + + const target = Number(required('TARGET_PR')); + if (!Number.isInteger(target) || target <= 0) throw new Error(`Invalid TARGET_PR: ${target}`); + const eventHead = + eventName === 'pull_request_target' && event.pull_request?.number === target + ? event.pull_request.head?.sha + : undefined; + const knownHead = process.env.TARGET_HEAD || eventHead; + if (!knownHead) throw new Error(`No head SHA for PR #${target}`); + const knownPr = { number: target, head: knownHead }; + + let checks; + let checkedPr = knownPr; + try { + const knownChecks = await beginCheckRun(knownPr); + checks = knownChecks; + const pr = await getPr(target); + if (pr.head !== knownHead) { + const changed = { + ok: false, + title: 'PR head changed', + summary: 'The discovery snapshot was stale; this run evaluates and completes the current revision.', + }; + checks = undefined; + checkedPr = pr; + try { + checks = await beginCheckRun(pr); + const result = await evaluateStable(pr); + await finishCheckRun(pr, checks, result); + console.log(`#${target}: ${result.ok ? 'PASS' : 'FAIL'}: ${result.title}\n${result.summary}`); + process.exitCode = result.ok ? 0 : 1; + } finally { + try { + await finishCheckRun(knownPr, knownChecks, changed); + } catch (error) { + console.error(`Could not complete the stale issue-gate check: ${error.message}`); + } + } + return; + } + const result = await evaluateStable(pr); + await finishCheckRun(pr, checks, result); + console.log(`#${target}: ${result.ok ? 'PASS' : 'FAIL'}: ${result.title}\n${result.summary}`); + process.exitCode = result.ok ? 0 : 1; + } catch (error) { + if (checks) await failCheckRun(checkedPr, checks, error); + throw error; + } +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) { + main().catch((error) => { + console.error(error.message); + process.exitCode = 1; + }); +} diff --git a/scripts/issue-gate.test.mjs b/scripts/issue-gate.test.mjs new file mode 100644 index 000000000..10e715dae --- /dev/null +++ b/scripts/issue-gate.test.mjs @@ -0,0 +1,712 @@ +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import fs from 'node:fs'; +import http from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import test from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { isAccepted, parseRefs, sameRepository, stripNonLinks } from './issue-gate.mjs'; + +const ROOT = fileURLToPath(new URL('..', import.meta.url)); +const REPOSITORY = 'arcships/dim'; + +function reply(status, body) { + return { status, body }; +} + +async function startFakeApi(handler) { + const requests = []; + const server = http.createServer((request, response) => { + let body = ''; + request.on('data', (chunk) => { + body += chunk; + }); + request.on('end', () => { + const url = new URL(request.url, 'http://127.0.0.1'); + const record = { method: request.method, path: url.pathname, search: url.search, body }; + requests.push(record); + let result; + try { + result = handler(record); + } catch (error) { + result = reply(500, { message: error.message }); + } + if (!result) result = reply(404, { message: 'not found' }); + response.writeHead(result.status, { 'Content-Type': 'application/json' }); + response.end(result.status === 204 ? undefined : JSON.stringify(result.body)); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + return { + requests, + url: `http://127.0.0.1:${server.address().port}`, + close: () => new Promise((resolve) => server.close(resolve)), + }; +} + +function runGate(api, { eventName, event, target, targetHead, discover = false }) { + return new Promise((resolve, reject) => { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'dim-issue-gate-')); + const eventPath = path.join(directory, 'event.json'); + fs.writeFileSync(eventPath, JSON.stringify(event)); + const env = { + ...process.env, + GITHUB_API_URL: api.url, + GITHUB_TOKEN: 'test-token', + GITHUB_REPOSITORY: REPOSITORY, + GITHUB_EVENT_NAME: eventName, + GITHUB_EVENT_PATH: eventPath, + GITHUB_SERVER_URL: 'https://github.com', + GITHUB_RUN_ID: '12345', + ISSUE_GATE_RETRY_ATTEMPTS: '1', + ISSUE_GATE_RETRY_DELAY_MS: '0', + }; + if (target !== undefined) { + env.TARGET_PR = String(target); + env.TARGET_HEAD = targetHead ?? 'current-head'; + } + const child = spawn(process.execPath, ['scripts/issue-gate.mjs', ...(discover ? ['--discover'] : [])], { + cwd: ROOT, + env, + }); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', (chunk) => { + stdout += chunk; + }); + child.stderr.on('data', (chunk) => { + stderr += chunk; + }); + const timer = setTimeout(() => { + child.kill(); + reject(new Error('gate script timed out')); + }, 30_000); + child.on('error', (error) => { + clearTimeout(timer); + fs.rmSync(directory, { recursive: true, force: true }); + reject(error); + }); + child.on('close', (status) => { + clearTimeout(timer); + fs.rmSync(directory, { recursive: true, force: true }); + resolve({ status, stdout, stderr }); + }); + }); +} + +function closingRefs(nodes) { + return reply(200, { data: { repository: { pullRequest: { closingIssuesReferences: { nodes } } } } }); +} + +function pullRequest(body = 'Fixes #1', head = 'current-head') { + return { number: 77, body, head: { sha: head }, state: 'open' }; +} + +function issue(labels = ['P1']) { + return { number: 1, labels: labels.map((name) => ({ name })) }; +} + +test('parses closing and reference keywords', () => { + assert.deepEqual(parseRefs('Fixes #1'), [1]); + assert.deepEqual(parseRefs('Closes #2'), [2]); + assert.deepEqual(parseRefs('Resolves #3'), [3]); + assert.deepEqual(parseRefs('Refs #4'), [4]); + assert.deepEqual(parseRefs('fixes: #5'), [5]); +}); + +test('collects multiple references on one keyword line', () => { + assert.deepEqual(parseRefs('Fixes #1257 and #2272'), [1257, 2272]); + assert.deepEqual(parseRefs('Fixes #1, #2, #2'), [1, 2]); +}); + +test('ignores text that is not a link', () => { + assert.deepEqual(parseRefs('prefixes #1'), []); + assert.deepEqual(parseRefs('see #1'), []); + assert.deepEqual(parseRefs('Fixes #1\nRefs #2'), [1, 2]); + assert.deepEqual(parseRefs('Fixes owner/repo#1'), []); + assert.deepEqual(parseRefs('Fixes #1 and owner/repo#2'), [1]); +}); + +test('ignores fenced code, inline code, comments and quotes', () => { + assert.deepEqual(parseRefs('```\nFixes #1\n```'), []); + assert.deepEqual(parseRefs('~~~\nFixes #1\n~~~'), []); + assert.deepEqual(parseRefs('`Fixes #1`'), []); + assert.deepEqual(parseRefs(''), []); + assert.deepEqual(parseRefs(''), []); + assert.deepEqual(parseRefs('> Fixes #1'), []); +}); + +test('keep a real link after stripping non-link contexts', () => { + const body = '```\nFixes #1\n```\n\nRefs #2272'; + assert.deepEqual(parseRefs(body), [2272]); + assert.ok(stripNonLinks(body).includes('Refs #2272')); +}); + +test('caps the number of parsed references', () => { + const refs = Array.from({ length: 25 }, (_, index) => `#${index + 1}`).join(' '); + assert.deepEqual(parseRefs(`Fixes ${refs}`), Array.from({ length: 20 }, (_, index) => index + 1)); +}); + +test('only same-repository timeline sources are gated', () => { + const base = { issue: { repository_url: 'https://api.github.com/repos/arcships/dim' } }; + const foreign = { issue: { repository_url: 'https://api.github.com/repos/other/dim' } }; + assert.equal(sameRepository(base, 'arcships/dim'), true); + assert.equal(sameRepository(foreign, 'arcships/dim'), false); + assert.equal(sameRepository(undefined, 'arcships/dim'), false); +}); + +test('accepted means P0, P1 or P2', () => { + assert.equal(isAccepted(['P0']), true); + assert.equal(isAccepted(['P1', 'design']), true); + assert.equal(isAccepted(['P2', 'P3']), true); + assert.equal(isAccepted(['P3']), false); + assert.equal(isAccepted(['design']), false); + assert.equal(isAccepted([]), false); +}); + +test('evaluates the current PR instead of the event payload', async (t) => { + const checks = []; + const patches = []; + const api = await startFakeApi((request) => { + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/pulls/77`) { + return reply(200, pullRequest()); + } + if (request.method === 'POST' && request.path === '/graphql') { + return closingRefs([]); + } + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/issues/1`) { + return reply(200, issue()); + } + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/commits/current-head/check-runs`) { + return reply(200, { check_runs: checks }); + } + if (request.method === 'POST' && request.path === `/repos/${REPOSITORY}/check-runs`) { + const created = { id: 1, name: 'issue-gate', external_id: 'issue-gate:77' }; + checks.push(created); + return reply(201, created); + } + if (request.method === 'PATCH' && request.path === `/repos/${REPOSITORY}/check-runs/1`) { + patches.push(JSON.parse(request.body)); + return reply(200, {}); + } + return undefined; + }); + t.after(() => api.close()); + + const event = { + pull_request: { number: 77, body: 'Fixes #2', head: { sha: 'event-head' }, state: 'open' }, + }; + const result = await runGate(api, { eventName: 'pull_request_target', event, target: 77 }); + + assert.equal(result.status, 0, result.stderr); + assert.ok(api.requests.some((request) => request.path === `/repos/${REPOSITORY}/pulls/77`)); + assert.ok(!api.requests.some((request) => request.path.includes('event-head'))); + const completed = patches.filter((patch) => patch.status === 'completed'); + assert.equal(completed.length, 1); + assert.equal(completed[0].conclusion, 'success'); + assert.equal(completed[0].output.title, 'Linked accepted issue'); +}); + +test('reconciles a duplicate check after a transient lookup failure', async (t) => { + const runs = [{ id: 1, name: 'issue-gate', external_id: 'issue-gate:77' }]; + const patches = []; + let listCalls = 0; + const api = await startFakeApi((request) => { + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/pulls/77`) { + return reply(200, pullRequest()); + } + if (request.method === 'POST' && request.path === '/graphql') { + return closingRefs([]); + } + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/issues/1`) { + return reply(200, issue()); + } + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/commits/current-head/check-runs`) { + listCalls += 1; + if (listCalls === 1) return reply(500, { message: 'temporary failure' }); + return reply(200, { check_runs: runs }); + } + if (request.method === 'POST' && request.path === `/repos/${REPOSITORY}/check-runs`) { + const created = { id: 2, name: 'issue-gate', external_id: 'issue-gate:77' }; + runs.push(created); + return reply(201, created); + } + if (request.method === 'PATCH' && request.path.startsWith(`/repos/${REPOSITORY}/check-runs/`)) { + patches.push({ + id: Number(request.path.split('/').pop()), + ...JSON.parse(request.body), + }); + return reply(200, {}); + } + return undefined; + }); + t.after(() => api.close()); + + const result = await runGate(api, { + eventName: 'pull_request_target', + event: { pull_request: { number: 77 } }, + target: 77, + }); + + assert.equal(result.status, 0, result.stderr); + const completed = patches.filter((patch) => patch.status === 'completed'); + assert.deepEqual(completed.map((patch) => patch.id).sort(), [1, 2]); + assert.ok(completed.every((patch) => patch.conclusion === 'success')); +}); + +test('completes the check as a failure when evaluation cannot read the issue', async (t) => { + const checks = []; + const patches = []; + const api = await startFakeApi((request) => { + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/pulls/77`) { + return reply(200, pullRequest()); + } + if (request.method === 'POST' && request.path === '/graphql') { + return closingRefs([]); + } + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/issues/1`) { + return reply(500, { message: 'temporary failure' }); + } + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/commits/current-head/check-runs`) { + return reply(200, { check_runs: checks }); + } + if (request.method === 'POST' && request.path === `/repos/${REPOSITORY}/check-runs`) { + const created = { id: 1, name: 'issue-gate', external_id: 'issue-gate:77' }; + checks.push(created); + return reply(201, created); + } + if (request.method === 'PATCH' && request.path === `/repos/${REPOSITORY}/check-runs/1`) { + patches.push(JSON.parse(request.body)); + return reply(200, {}); + } + return undefined; + }); + t.after(() => api.close()); + + const result = await runGate(api, { + eventName: 'pull_request_target', + event: { pull_request: { number: 77 } }, + target: 77, + }); + + assert.equal(result.status, 1); + const completed = patches.filter((patch) => patch.status === 'completed'); + assert.equal(completed.length, 1); + assert.equal(completed[0].conclusion, 'failure'); + assert.equal(completed[0].output.title, 'Could not read linked issues'); +}); + +test('fails discovery when the open PR list cannot be read', async (t) => { + const api = await startFakeApi((request) => { + if (request.path === `/repos/${REPOSITORY}/pulls`) { + return reply(500, { message: 'temporary failure' }); + } + return undefined; + }); + t.after(() => api.close()); + + const result = await runGate(api, { + eventName: 'issues', + event: { issue: { number: 1 } }, + discover: true, + }); + + assert.equal(result.status, 1); + assert.equal(result.stdout.trim(), ''); + assert.match(result.stderr, /GitHub API 500/); +}); + +test('scans open PRs beyond the newest twenty during fallback discovery', async (t) => { + const prs = Array.from({ length: 21 }, (_, index) => ({ + number: index + 1, + body: index === 20 ? 'Refs #1' : 'Refs #999', + head: { sha: `head-${index + 1}` }, + })); + let closingReads = 0; + const api = await startFakeApi((request) => { + if (request.path === `/repos/${REPOSITORY}/issues/1/timeline`) { + return reply(500, { message: 'temporary failure' }); + } + if (request.path === `/repos/${REPOSITORY}/pulls`) { + return reply(200, prs); + } + if (request.method === 'POST' && request.path === '/graphql') { + closingReads += 1; + return closingRefs([]); + } + return undefined; + }); + t.after(() => api.close()); + + const result = await runGate(api, { + eventName: 'issues', + event: { issue: { number: 1 } }, + discover: true, + }); + + assert.equal(result.status, 0, result.stderr); + const discovered = JSON.parse(result.stdout.trim()); + assert.deepEqual(discovered.prs, [{ number: 21, head: 'head-21' }]); + assert.equal(discovered.complete, true); + assert.equal(closingReads, 20); +}); + +test('reports incomplete discovery while still returning known linked PRs', async (t) => { + const prs = Array.from({ length: 21 }, (_, index) => ({ + number: index + 1, + body: index === 20 ? 'Refs #1' : 'Refs #999', + head: { sha: `head-${index + 1}` }, + })); + const api = await startFakeApi((request) => { + if (request.path === `/repos/${REPOSITORY}/issues/1/timeline`) { + return reply(500, { message: 'temporary failure' }); + } + if (request.path === `/repos/${REPOSITORY}/pulls`) { + return reply(200, prs); + } + if (request.method === 'POST' && request.path === '/graphql') { + const { number } = JSON.parse(request.body).variables; + if (number === 1) return reply(500, { message: 'temporary failure' }); + return closingRefs([]); + } + return undefined; + }); + t.after(() => api.close()); + + const result = await runGate(api, { + eventName: 'issues', + event: { issue: { number: 1 } }, + discover: true, + }); + + assert.equal(result.status, 0, result.stderr); + const discovered = JSON.parse(result.stdout.trim()); + assert.deepEqual(discovered.prs, [{ number: 21, head: 'head-21' }]); + assert.equal(discovered.complete, false); + assert.match(result.stderr, /Incomplete linked-PR discovery/); +}); + +test('fails the check when the PR changes during evaluation', async (t) => { + const checks = []; + const patches = []; + let prReads = 0; + const api = await startFakeApi((request) => { + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/pulls/77`) { + prReads += 1; + return reply(200, pullRequest(prReads === 1 ? 'Fixes #1' : 'Fixes #1\n\nedited')); + } + if (request.method === 'POST' && request.path === '/graphql') { + return closingRefs([]); + } + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/issues/1`) { + return reply(200, issue()); + } + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/commits/current-head/check-runs`) { + return reply(200, { check_runs: checks }); + } + if (request.method === 'POST' && request.path === `/repos/${REPOSITORY}/check-runs`) { + const created = { id: 1, name: 'issue-gate', external_id: 'issue-gate:77' }; + checks.push(created); + return reply(201, created); + } + if (request.method === 'PATCH' && request.path === `/repos/${REPOSITORY}/check-runs/1`) { + patches.push(JSON.parse(request.body)); + return reply(200, {}); + } + return undefined; + }); + t.after(() => api.close()); + + const result = await runGate(api, { + eventName: 'pull_request_target', + event: { pull_request: { number: 77 } }, + target: 77, + }); + + assert.equal(result.status, 1); + const completed = patches.filter((patch) => patch.status === 'completed'); + assert.equal(completed.length, 1); + assert.equal(completed[0].conclusion, 'failure'); + assert.equal(completed[0].output.title, 'PR changed during evaluation'); +}); + +test('completes the check as a gate error when the final state read fails', async (t) => { + const checks = []; + const patches = []; + let prReads = 0; + const api = await startFakeApi((request) => { + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/pulls/77`) { + prReads += 1; + if (prReads === 1) return reply(200, pullRequest()); + return reply(500, { message: 'temporary failure' }); + } + if (request.method === 'POST' && request.path === '/graphql') { + return closingRefs([]); + } + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/issues/1`) { + return reply(200, issue()); + } + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/commits/current-head/check-runs`) { + return reply(200, { check_runs: checks }); + } + if (request.method === 'POST' && request.path === `/repos/${REPOSITORY}/check-runs`) { + const created = { id: 1, name: 'issue-gate', external_id: 'issue-gate:77' }; + checks.push(created); + return reply(201, created); + } + if (request.method === 'PATCH' && request.path === `/repos/${REPOSITORY}/check-runs/1`) { + patches.push(JSON.parse(request.body)); + return reply(200, {}); + } + return undefined; + }); + t.after(() => api.close()); + + const result = await runGate(api, { + eventName: 'pull_request_target', + event: { pull_request: { number: 77 } }, + target: 77, + }); + + assert.equal(result.status, 1); + const completed = patches.filter((patch) => patch.status === 'completed'); + assert.equal(completed.length, 1); + assert.equal(completed[0].conclusion, 'failure'); + assert.equal(completed[0].output.title, 'Gate error'); +}); + +test('completes the check as a gate error when the initial PR read fails', async (t) => { + const checks = []; + const patches = []; + const api = await startFakeApi((request) => { + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/pulls/77`) { + return reply(500, { message: 'temporary failure' }); + } + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/commits/current-head/check-runs`) { + return reply(200, { check_runs: checks }); + } + if (request.method === 'POST' && request.path === `/repos/${REPOSITORY}/check-runs`) { + const created = { id: 1, name: 'issue-gate', external_id: 'issue-gate:77' }; + checks.push(created); + return reply(201, created); + } + if (request.method === 'PATCH' && request.path === `/repos/${REPOSITORY}/check-runs/1`) { + patches.push(JSON.parse(request.body)); + return reply(200, {}); + } + return undefined; + }); + t.after(() => api.close()); + + const result = await runGate(api, { + eventName: 'pull_request_target', + event: { pull_request: { number: 77 } }, + target: 77, + }); + + assert.equal(result.status, 1); + assert.ok(api.requests.some((request) => request.path === `/repos/${REPOSITORY}/commits/current-head/check-runs`)); + const completed = patches.filter((patch) => patch.status === 'completed'); + assert.equal(completed.length, 1); + assert.equal(completed[0].conclusion, 'failure'); + assert.equal(completed[0].output.title, 'Gate error'); +}); + +test('marks discovery incomplete when a timeline link is absent from the open PR list', async (t) => { + let api; + api = await startFakeApi((request) => { + if (request.path === `/repos/${REPOSITORY}/pulls`) { + return reply(200, []); + } + if (request.path === `/repos/${REPOSITORY}/issues/1/timeline`) { + return reply(200, [ + { + event: 'cross-referenced', + source: { + issue: { + number: 77, + state: 'open', + pull_request: {}, + repository_url: api.url + '/repos/' + REPOSITORY, + }, + }, + }, + ]); + } + return undefined; + }); + t.after(() => api.close()); + + const result = await runGate(api, { + eventName: 'issues', + event: { issue: { number: 1 } }, + discover: true, + }); + + assert.equal(result.status, 0, result.stderr); + const discovered = JSON.parse(result.stdout.trim()); + assert.deepEqual(discovered.prs, []); + assert.equal(discovered.complete, false); + assert.match(result.stderr, /#77 is missing from the open pull request list/); +}); + +test('treats a missing closing-reference read as incomplete discovery', async (t) => { + const prs = Array.from({ length: 21 }, (_, index) => ({ + number: index + 1, + body: index === 20 ? 'Refs #1' : 'Refs #999', + head: { sha: `head-${index + 1}` }, + })); + const api = await startFakeApi((request) => { + if (request.path === `/repos/${REPOSITORY}/issues/1/timeline`) { + return reply(500, { message: 'temporary failure' }); + } + if (request.path === `/repos/${REPOSITORY}/pulls`) { + return reply(200, prs); + } + if (request.method === 'POST' && request.path === '/graphql') { + const { number } = JSON.parse(request.body).variables; + if (number === 1) return reply(404, { message: 'not found' }); + return closingRefs([]); + } + return undefined; + }); + t.after(() => api.close()); + + const result = await runGate(api, { + eventName: 'issues', + event: { issue: { number: 1 } }, + discover: true, + }); + + assert.equal(result.status, 0, result.stderr); + const discovered = JSON.parse(result.stdout.trim()); + assert.deepEqual(discovered.prs, [{ number: 21, head: 'head-21' }]); + assert.equal(discovered.complete, false); + assert.match(result.stderr, /Incomplete linked-PR discovery/); +}); + +test('completes the current head when the known head is stale', async (t) => { + const runsByHead = new Map([ + ['old-head', []], + ['new-head', [{ id: 2, name: 'issue-gate', external_id: 'issue-gate:77', status: 'in_progress' }]], + ]); + const patches = []; + let nextId = 1; + const api = await startFakeApi((request) => { + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/pulls/77`) { + return reply(200, pullRequest('Fixes #1', 'new-head')); + } + if (request.method === 'POST' && request.path === '/graphql') { + return closingRefs([]); + } + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/issues/1`) { + return reply(200, issue()); + } + const prefix = `/repos/${REPOSITORY}/commits/`; + const suffix = '/check-runs'; + if (request.method === 'GET' && request.path.startsWith(prefix) && request.path.endsWith(suffix)) { + const head = request.path.slice(prefix.length, -suffix.length); + return reply(200, { check_runs: runsByHead.get(head) ?? [] }); + } + if (request.method === 'POST' && request.path === `/repos/${REPOSITORY}/check-runs`) { + const payload = JSON.parse(request.body); + const created = { id: nextId, name: 'issue-gate', external_id: 'issue-gate:77' }; + nextId += 1; + runsByHead.get(payload.head_sha).push(created); + return reply(201, created); + } + if (request.method === 'PATCH' && request.path.startsWith(`/repos/${REPOSITORY}/check-runs/`)) { + patches.push({ + id: Number(request.path.split('/').pop()), + ...JSON.parse(request.body), + }); + return reply(200, {}); + } + return undefined; + }); + t.after(() => api.close()); + + const result = await runGate(api, { + eventName: 'pull_request_target', + event: { pull_request: { number: 77 } }, + target: 77, + targetHead: 'old-head', + }); + + assert.equal(result.status, 0, result.stderr); + const completed = patches.filter((patch) => patch.status === 'completed'); + assert.deepEqual(completed.map((patch) => patch.id).sort((a, b) => a - b), [1, 2]); + const byId = new Map(completed.map((patch) => [patch.id, patch])); + assert.equal(byId.get(1).conclusion, 'failure'); + assert.equal(byId.get(1).output.title, 'PR head changed'); + assert.equal(byId.get(2).conclusion, 'success'); +}); + +test('settles the current head when the stale-head update fails', async (t) => { + const runsByHead = new Map([ + ['old-head', []], + ['new-head', [{ id: 2, name: 'issue-gate', external_id: 'issue-gate:77', status: 'in_progress' }]], + ]); + const patches = []; + let nextId = 1; + const api = await startFakeApi((request) => { + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/pulls/77`) { + return reply(200, pullRequest('Fixes #1', 'new-head')); + } + if (request.method === 'POST' && request.path === '/graphql') { + return closingRefs([]); + } + if (request.method === 'GET' && request.path === `/repos/${REPOSITORY}/issues/1`) { + return reply(200, issue()); + } + const prefix = `/repos/${REPOSITORY}/commits/`; + const suffix = '/check-runs'; + if (request.method === 'GET' && request.path.startsWith(prefix) && request.path.endsWith(suffix)) { + const head = request.path.slice(prefix.length, -suffix.length); + return reply(200, { check_runs: runsByHead.get(head) ?? [] }); + } + if (request.method === 'POST' && request.path === `/repos/${REPOSITORY}/check-runs`) { + const payload = JSON.parse(request.body); + const created = { id: nextId, name: 'issue-gate', external_id: 'issue-gate:77' }; + nextId += 1; + runsByHead.get(payload.head_sha).push(created); + return reply(201, created); + } + if (request.method === 'PATCH' && request.path.startsWith(`/repos/${REPOSITORY}/check-runs/`)) { + const id = Number(request.path.split('/').pop()); + const payload = JSON.parse(request.body); + if (id === 1 && payload.status === 'completed') { + return reply(500, { message: 'temporary failure' }); + } + patches.push({ id, ...payload }); + return reply(200, {}); + } + return undefined; + }); + t.after(() => api.close()); + + const result = await runGate(api, { + eventName: 'pull_request_target', + event: { pull_request: { number: 77 } }, + target: 77, + targetHead: 'old-head', + }); + + assert.equal(result.status, 0, result.stderr); + const completed = patches.filter((patch) => patch.status === 'completed'); + assert.deepEqual(completed.map((patch) => patch.id), [2]); + assert.equal(completed[0].conclusion, 'success'); + assert.match(result.stderr, /Could not complete the stale issue-gate check/); +}); + +test('the discovery step propagates a gate script failure', () => { + const workflow = fs.readFileSync(path.join(ROOT, '.github', 'workflows', 'issue-gate.yml'), 'utf8'); + assert.match(workflow, /set -euo pipefail/); + assert.match(workflow, /result=\$\(node scripts\/issue-gate\.mjs --discover\)/); + assert.doesNotMatch(workflow, /echo "prs=\$\(node/); + assert.ok(workflow.includes('TARGET_HEAD: ${{ matrix.pr.head }}')); + assert.ok(workflow.includes('TARGET_HEAD: ${{ github.event.pull_request.head.sha }}')); + assert.match(workflow, /name: coverage/); + assert.match(workflow, /needs\.discover\.outputs\.complete != 'true'/); +}); \ No newline at end of file