From e376f1d0465acd01fde0ab7315ee63d3218d78f9 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 27 Nov 2026 17:27:51 +0800 Subject: [PATCH 01/11] ci: gate pull requests on a linked accepted issue --- .github/workflows/issue-gate.yml | 49 ++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 .github/workflows/issue-gate.yml diff --git a/.github/workflows/issue-gate.yml b/.github/workflows/issue-gate.yml new file mode 100644 index 000000000..eafb6b685 --- /dev/null +++ b/.github/workflows/issue-gate.yml @@ -0,0 +1,49 @@ +name: issue-gate + +on: + pull_request: + types: [opened, edited, reopened, synchronize, ready_for_review] + +permissions: + contents: read + issues: read + pull-requests: read + +jobs: + issue-gate: + name: issue-gate + runs-on: ubuntu-22.04 + timeout-minutes: 5 + steps: + - name: Require a linked accepted issue + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + BODY: ${{ github.event.pull_request.body }} + run: | + set -euo pipefail + links=$(printf '%s\n' "${BODY:-}" | grep -oiE '(fixes|closes|resolves|refs):?[[:space:]]+#[0-9]+' | grep -oE '[0-9]+' | sort -u || true) + if [ -z "$links" ]; then + echo "::error::Link an accepted issue with Fixes #N, Closes #N, Resolves #N or Refs #N." + exit 1 + fi + + accepted="" + for n in $links; do + labels=$(gh api "repos/$REPO/issues/$n" --jq '[.labels[].name] | join(",")' 2>/dev/null || true) + if [ -z "$labels" ]; then + echo "Linked issue #$n could not be read; check the number and repository." + continue + fi + if printf '%s' "$labels" | grep -qE '(^|,)(P0|P1|P2)(,|$)'; then + echo "Linked issue #$n is accepted: $labels" + accepted="$n" + else + echo "Linked issue #$n is not accepted: $labels" + fi + done + + if [ -z "$accepted" ]; then + echo "::error::At least one linked issue must carry P0, P1 or P2. P3 and unlabelled issues are not accepted." + exit 1 + fi From 0ccc30b883deca3a321497cc1348d2fe51f49e7c Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 27 Nov 2026 17:58:17 +0800 Subject: [PATCH 02/11] ci: make issue gate trusted and re-evaluate label changes --- .github/workflows/issue-gate.yml | 45 ++---- scripts/issue-gate.mjs | 238 +++++++++++++++++++++++++++++++ scripts/issue-gate.test.mjs | 48 +++++++ 3 files changed, 299 insertions(+), 32 deletions(-) create mode 100644 scripts/issue-gate.mjs create mode 100644 scripts/issue-gate.test.mjs diff --git a/.github/workflows/issue-gate.yml b/.github/workflows/issue-gate.yml index eafb6b685..ad1c296de 100644 --- a/.github/workflows/issue-gate.yml +++ b/.github/workflows/issue-gate.yml @@ -1,13 +1,16 @@ name: issue-gate on: - pull_request: + 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: issue-gate: @@ -15,35 +18,13 @@ jobs: runs-on: ubuntu-22.04 timeout-minutes: 5 steps: - - name: Require a linked accepted issue + # 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 + - name: Evaluate linked issue env: - GH_TOKEN: ${{ github.token }} - REPO: ${{ github.repository }} - BODY: ${{ github.event.pull_request.body }} - run: | - set -euo pipefail - links=$(printf '%s\n' "${BODY:-}" | grep -oiE '(fixes|closes|resolves|refs):?[[:space:]]+#[0-9]+' | grep -oE '[0-9]+' | sort -u || true) - if [ -z "$links" ]; then - echo "::error::Link an accepted issue with Fixes #N, Closes #N, Resolves #N or Refs #N." - exit 1 - fi - - accepted="" - for n in $links; do - labels=$(gh api "repos/$REPO/issues/$n" --jq '[.labels[].name] | join(",")' 2>/dev/null || true) - if [ -z "$labels" ]; then - echo "Linked issue #$n could not be read; check the number and repository." - continue - fi - if printf '%s' "$labels" | grep -qE '(^|,)(P0|P1|P2)(,|$)'; then - echo "Linked issue #$n is accepted: $labels" - accepted="$n" - else - echo "Linked issue #$n is not accepted: $labels" - fi - done - - if [ -z "$accepted" ]; then - echo "::error::At least one linked issue must carry P0, P1 or P2. P3 and unlabelled issues are not accepted." - exit 1 - fi + GITHUB_TOKEN: ${{ github.token }} + run: node scripts/issue-gate.mjs diff --git a/scripts/issue-gate.mjs b/scripts/issue-gate.mjs new file mode 100644 index 000000000..3e68b98fb --- /dev/null +++ b/scripts/issue-gate.mjs @@ -0,0 +1,238 @@ +import fs from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const API = 'https://api.github.com'; + +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)) refs.add(Number(match[1])); + } + } + return [...refs]; +} + +export function isAccepted(labels) { + return labels.some((label) => label === 'P0' || label === 'P1' || label === 'P2'); +} + +function required(name) { + const value = process.env[name]; + if (!value) throw new Error(`${name} is not set`); + return value; +} + +async function api(path, options = {}) { + const response = await fetch(`${API}${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 += 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; + } +} + +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 getLinkedOpenPrs(issueNumber) { + const events = await pages(`/repos/${required('GITHUB_REPOSITORY')}/issues/${issueNumber}/timeline`); + const numbers = new Set(); + for (const event of events) { + if (event.event !== 'cross-referenced') continue; + const source = event.source?.issue; + if (source?.pull_request && source.state === 'open') numbers.add(source.number); + } + return [...numbers]; +} + +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([...closing, ...refs])]; + 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 accepted = []; + 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)) { + accepted.push(number); + } else { + rejected.push(`#${number} has [${issue.labels.join(', ') || 'no labels'}]`); + } + } catch (error) { + unreadable.push(`#${number}: ${error.message}`); + } + } + + if (accepted.length) { + return { + ok: true, + title: 'Linked accepted issue', + summary: `Accepted: ${accepted.map((number) => `#${number}`).join(', ')}.`, + }; + } + 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'), + }; +} + +async function createCheckRun(head, result) { + await api(`/repos/${required('GITHUB_REPOSITORY')}/check-runs`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + name: 'issue-gate', + head_sha: head, + status: 'completed', + conclusion: result.ok ? 'success' : 'failure', + output: { title: result.title, summary: result.summary }, + }), + }); +} + +async function main() { + const eventPath = required('GITHUB_EVENT_PATH'); + const event = JSON.parse(fs.readFileSync(eventPath, 'utf8')); + const eventName = required('GITHUB_EVENT_NAME'); + + if (eventName === 'pull_request_target') { + const pr = await getPr(event.pull_request.number); + const result = await evaluate(pr); + console.log(`${result.ok ? 'PASS' : 'FAIL'}: ${result.title}\n${result.summary}`); + process.exitCode = result.ok ? 0 : 1; + return; + } + + if (eventName === 'issues') { + const issueNumber = event.issue.number; + const prs = await getLinkedOpenPrs(issueNumber); + if (!prs.length) { + console.log(`No open linked PR for #${issueNumber}.`); + return; + } + let failed = false; + for (const number of prs) { + try { + const pr = await getPr(number); + const result = await evaluate(pr); + await createCheckRun(pr.head, result); + console.log(`#${number}: ${result.ok ? 'PASS' : 'FAIL'} — ${result.title}`); + } catch (error) { + console.error(`#${number}: could not update issue-gate: ${error.message}`); + failed = true; + } + } + if (failed) process.exitCode = 1; + return; + } + + throw new Error(`Unsupported event: ${eventName}`); +} + +if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) { + main().catch((error) => { + console.error(error.message); + process.exit(1); + }); +} diff --git a/scripts/issue-gate.test.mjs b/scripts/issue-gate.test.mjs new file mode 100644 index 000000000..7476b5d0e --- /dev/null +++ b/scripts/issue-gate.test.mjs @@ -0,0 +1,48 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { isAccepted, parseRefs, stripNonLinks } from './issue-gate.mjs'; + +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('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); +}); From ec5ec172ae627e07b5bf9ab5e8a834f36683baf5 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 27 Nov 2026 17:59:05 +0800 Subject: [PATCH 03/11] ci: use the repository Node version for the gate --- .github/workflows/issue-gate.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/issue-gate.yml b/.github/workflows/issue-gate.yml index ad1c296de..37a026176 100644 --- a/.github/workflows/issue-gate.yml +++ b/.github/workflows/issue-gate.yml @@ -24,6 +24,10 @@ jobs: 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 }} From 92f318f9188a3f8a81944761a5f1302e2891d58e Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 27 Nov 2026 18:25:37 +0800 Subject: [PATCH 04/11] ci: refresh one issue-gate check across events --- .github/workflows/issue-gate.yml | 9 +- scripts/issue-gate.mjs | 142 ++++++++++++++++++++++++++----- scripts/issue-gate.test.mjs | 15 +++- 3 files changed, 140 insertions(+), 26 deletions(-) diff --git a/.github/workflows/issue-gate.yml b/.github/workflows/issue-gate.yml index 37a026176..8a45f926c 100644 --- a/.github/workflows/issue-gate.yml +++ b/.github/workflows/issue-gate.yml @@ -12,14 +12,19 @@ permissions: pull-requests: read checks: write +concurrency: + group: issue-gate + cancel-in-progress: true + jobs: - issue-gate: - name: issue-gate + evaluate: + name: evaluate runs-on: ubuntu-22.04 timeout-minutes: 5 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. + # The script owns the required issue-gate check on the PR head for both events. - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.repository.default_branch }} diff --git a/scripts/issue-gate.mjs b/scripts/issue-gate.mjs index 3e68b98fb..90ecf2c0d 100644 --- a/scripts/issue-gate.mjs +++ b/scripts/issue-gate.mjs @@ -2,6 +2,9 @@ import fs from 'node:fs'; import { fileURLToPath } from 'node:url'; const API = 'https://api.github.com'; +const CHECK_NAME = 'issue-gate'; +const MAX_REFS = 20; +const MAX_SUMMARY = 60_000; export function stripNonLinks(body) { let text = String(body ?? ''); @@ -20,7 +23,10 @@ export function parseRefs(body) { 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)) refs.add(Number(match[1])); + for (const match of line.matchAll(/#(\d+)/g)) { + if (refs.size >= MAX_REFS) break; + refs.add(Number(match[1])); + } } } return [...refs]; @@ -30,6 +36,10 @@ export function isAccepted(labels) { return labels.some((label) => label === 'P0' || label === 'P1' || label === 'P2'); } +export function sameRepository(source, repository) { + return source?.issue?.repository_url === `${API}/repos/${repository}`; +} + function required(name) { const value = process.env[name]; if (!value) throw new Error(`${name} is not set`); @@ -105,12 +115,14 @@ async function getClosingRefs(number) { } async function getLinkedOpenPrs(issueNumber) { - const events = await pages(`/repos/${required('GITHUB_REPOSITORY')}/issues/${issueNumber}/timeline`); + const repository = required('GITHUB_REPOSITORY'); + const events = await pages(`/repos/${repository}/issues/${issueNumber}/timeline`); const numbers = new Set(); for (const event of events) { if (event.event !== 'cross-referenced') continue; - const source = event.source?.issue; - if (source?.pull_request && source.state === 'open') numbers.add(source.number); + const source = event.source; + if (!sameRepository(source, repository)) continue; + if (source.issue.pull_request && source.issue.state === 'open') numbers.add(source.issue.number); } return [...numbers]; } @@ -127,7 +139,7 @@ async function evaluate(pr) { }; } const refs = parseRefs(pr.body); - const numbers = [...new Set([...closing, ...refs])]; + const numbers = [...new Set([...closing, ...refs])].slice(0, MAX_REFS); if (!numbers.length) { return { ok: false, @@ -136,7 +148,6 @@ async function evaluate(pr) { }; } - const accepted = []; const rejected = []; const unreadable = []; for (const number of numbers) { @@ -147,7 +158,11 @@ async function evaluate(pr) { } else if (issue.kind === 'missing') { unreadable.push(`#${number} does not exist in this repository`); } else if (isAccepted(issue.labels)) { - accepted.push(number); + return { + ok: true, + title: 'Linked accepted issue', + summary: `Accepted: #${number}.`, + }; } else { rejected.push(`#${number} has [${issue.labels.join(', ') || 'no labels'}]`); } @@ -156,13 +171,6 @@ async function evaluate(pr) { } } - if (accepted.length) { - return { - ok: true, - title: 'Linked accepted issue', - summary: `Accepted: ${accepted.map((number) => `#${number}`).join(', ')}.`, - }; - } if (unreadable.length && !rejected.length) { return { ok: false, @@ -177,20 +185,96 @@ async function evaluate(pr) { }; } -async function createCheckRun(head, result) { - await api(`/repos/${required('GITHUB_REPOSITORY')}/check-runs`, { +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 findCheckRun(pr) { + const repository = required('GITHUB_REPOSITORY'); + const response = await api( + `/repos/${repository}/commits/${pr.head}/check-runs?check_name=${CHECK_NAME}&per_page=100`, + ); + const runs = Array.isArray(response) ? response : response.check_runs ?? []; + return ( + runs.find((run) => run.name === CHECK_NAME && run.external_id === checkId(pr)) ?? + runs.find((run) => run.name === CHECK_NAME && !run.external_id) ?? + null + ); +} + +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.', + }; + const existing = await findCheckRun(pr); + if (existing) { + try { + await api(`/repos/${repository}/check-runs/${existing.id}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ status: 'in_progress', external_id: checkId(pr), output, ...(details ? { details_url: details } : {}) }), + }); + return existing.id; + } catch (error) { + if (error.status !== 422) throw error; + } + } + const created = await api(`/repos/${repository}/check-runs`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ - name: 'issue-gate', - head_sha: head, + name: CHECK_NAME, + head_sha: pr.head, + external_id: checkId(pr), + status: 'in_progress', + output, + ...(details ? { details_url: details } : {}), + }), + }); + return created.id; +} + +async function finishCheckRun(id, result) { + const repository = required('GITHUB_REPOSITORY'); + const details = detailsUrl(); + await api(`/repos/${repository}/check-runs/${id}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ status: 'completed', conclusion: result.ok ? 'success' : 'failure', - output: { title: result.title, summary: result.summary }, + completed_at: new Date().toISOString(), + output: checkOutput(result), + ...(details ? { details_url: details } : {}), }), }); } +async function failCheckRun(id, error) { + try { + await finishCheckRun(id, { ok: false, title: 'Gate error', summary: error.message }); + } catch (finishError) { + console.error(`Could not record the gate failure: ${finishError.message}`); + } +} + async function main() { const eventPath = required('GITHUB_EVENT_PATH'); const event = JSON.parse(fs.readFileSync(eventPath, 'utf8')); @@ -198,9 +282,17 @@ async function main() { if (eventName === 'pull_request_target') { const pr = await getPr(event.pull_request.number); - const result = await evaluate(pr); - console.log(`${result.ok ? 'PASS' : 'FAIL'}: ${result.title}\n${result.summary}`); - process.exitCode = result.ok ? 0 : 1; + let check; + try { + check = await beginCheckRun(pr); + const result = await evaluate(pr); + await finishCheckRun(check, result); + console.log(`${result.ok ? 'PASS' : 'FAIL'}: ${result.title}\n${result.summary}`); + process.exitCode = result.ok ? 0 : 1; + } catch (error) { + if (check) await failCheckRun(check, error); + throw error; + } return; } @@ -213,12 +305,16 @@ async function main() { } let failed = false; for (const number of prs) { + let check; try { const pr = await getPr(number); + check = await beginCheckRun(pr); const result = await evaluate(pr); - await createCheckRun(pr.head, result); + await finishCheckRun(check, result); console.log(`#${number}: ${result.ok ? 'PASS' : 'FAIL'} — ${result.title}`); + if (!result.ok) failed = true; } catch (error) { + if (check) await failCheckRun(check, error); console.error(`#${number}: could not update issue-gate: ${error.message}`); failed = true; } diff --git a/scripts/issue-gate.test.mjs b/scripts/issue-gate.test.mjs index 7476b5d0e..23ba08e6c 100644 --- a/scripts/issue-gate.test.mjs +++ b/scripts/issue-gate.test.mjs @@ -1,6 +1,6 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { isAccepted, parseRefs, stripNonLinks } from './issue-gate.mjs'; +import { isAccepted, parseRefs, sameRepository, stripNonLinks } from './issue-gate.mjs'; test('parses closing and reference keywords', () => { assert.deepEqual(parseRefs('Fixes #1'), [1]); @@ -38,6 +38,19 @@ test('keep a real link after stripping non-link contexts', () => { 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); From 33d5e3069a0fb0d1ddb3e6fd9c70be6b5aece768 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 27 Nov 2026 18:41:26 +0800 Subject: [PATCH 05/11] ci: address issue-gate freshness review --- .github/workflows/issue-gate.yml | 2 +- scripts/issue-gate.mjs | 13 +++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/.github/workflows/issue-gate.yml b/.github/workflows/issue-gate.yml index 8a45f926c..acee8f8ff 100644 --- a/.github/workflows/issue-gate.yml +++ b/.github/workflows/issue-gate.yml @@ -13,7 +13,7 @@ permissions: checks: write concurrency: - group: issue-gate + group: issue-gate-${{ github.event.pull_request.number || github.event.issue.number }} cancel-in-progress: true jobs: diff --git a/scripts/issue-gate.mjs b/scripts/issue-gate.mjs index 90ecf2c0d..1692eac93 100644 --- a/scripts/issue-gate.mjs +++ b/scripts/issue-gate.mjs @@ -223,7 +223,10 @@ async function beginCheckRun(pr) { title: 'Evaluating linked issue', summary: 'Checking the PR body and linked issue labels.', }; - const existing = await findCheckRun(pr); + const existing = await findCheckRun(pr).catch((error) => { + console.error(`Could not read the existing issue-gate check: ${error.message}`); + return null; + }); if (existing) { try { await api(`/repos/${repository}/check-runs/${existing.id}`, { @@ -281,7 +284,13 @@ async function main() { const eventName = required('GITHUB_EVENT_NAME'); if (eventName === 'pull_request_target') { - const pr = await getPr(event.pull_request.number); + const eventPr = event.pull_request; + const pr = { + number: eventPr.number, + body: eventPr.body ?? '', + head: eventPr.head.sha, + state: eventPr.state, + }; let check; try { check = await beginCheckRun(pr); From 49221d410d24ff54587b96b589eaf67e20153a6f Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 27 Nov 2026 19:24:15 +0800 Subject: [PATCH 06/11] ci: serialize issue-gate refreshes per pull request --- .github/workflows/issue-gate.yml | 68 +++++++++-- scripts/issue-gate.mjs | 195 +++++++++++++++++-------------- 2 files changed, 169 insertions(+), 94 deletions(-) diff --git a/.github/workflows/issue-gate.yml b/.github/workflows/issue-gate.yml index acee8f8ff..ddc1fe783 100644 --- a/.github/workflows/issue-gate.yml +++ b/.github/workflows/issue-gate.yml @@ -12,19 +12,72 @@ permissions: pull-requests: read checks: write -concurrency: - group: issue-gate-${{ github.event.pull_request.number || github.event.issue.number }} - cancel-in-progress: true - jobs: - evaluate: - name: evaluate + discover: + name: discover + if: github.event_name == 'issues' + runs-on: ubuntu-22.04 + timeout-minutes: 5 + outputs: + prs: ${{ steps.list.outputs.prs }} + 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: echo "prs=$(node scripts/issue-gate.mjs --discover)" >> "$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 }} + 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 }} + 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. - # The script owns the required issue-gate check on the PR head for both events. - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 with: ref: ${{ github.event.repository.default_branch }} @@ -36,4 +89,5 @@ jobs: - name: Evaluate linked issue env: GITHUB_TOKEN: ${{ github.token }} + TARGET_PR: ${{ matrix.pr }} run: node scripts/issue-gate.mjs diff --git a/scripts/issue-gate.mjs b/scripts/issue-gate.mjs index 1692eac93..98d31d777 100644 --- a/scripts/issue-gate.mjs +++ b/scripts/issue-gate.mjs @@ -4,6 +4,8 @@ import { fileURLToPath } from 'node:url'; const 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; export function stripNonLinks(body) { @@ -67,12 +69,13 @@ async function api(path, options = {}) { async function pages(path) { const items = []; - for (let page = 1; ; page += 1) { + 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) { @@ -114,17 +117,41 @@ async function getClosingRefs(number) { .map((node) => node.number); } +async function scanOpenPrsForIssue(issueNumber) { + const repository = required('GITHUB_REPOSITORY'); + const prs = await pages(`/repos/${repository}/pulls?state=open`); + const linked = new Set(); + for (const pr of prs.slice(0, MAX_LINKED_PRS)) { + 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) { + if (error.status === 404) continue; + throw error; + } + } + if (refs.has(issueNumber)) linked.add(pr.number); + } + return [...linked]; +} + async function getLinkedOpenPrs(issueNumber) { const repository = required('GITHUB_REPOSITORY'); - const events = await pages(`/repos/${repository}/issues/${issueNumber}/timeline`); - const numbers = 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') numbers.add(source.issue.number); + try { + const events = await pages(`/repos/${repository}/issues/${issueNumber}/timeline`); + const numbers = 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') numbers.add(source.issue.number); + } + return [...numbers].slice(0, MAX_LINKED_PRS); + } catch (error) { + console.error(`Timeline read failed (${error.message}); scanning open PRs.`); + return scanOpenPrsForIssue(issueNumber); } - return [...numbers]; } async function evaluate(pr) { @@ -139,7 +166,7 @@ async function evaluate(pr) { }; } const refs = parseRefs(pr.body); - const numbers = [...new Set([...closing, ...refs])].slice(0, MAX_REFS); + const numbers = [...new Set([...refs, ...closing.slice(0, MAX_REFS)])].slice(0, MAX_REFS * 2); if (!numbers.length) { return { ok: false, @@ -203,17 +230,26 @@ function checkId(pr) { return `${CHECK_NAME}:${pr.number}`; } -async function findCheckRun(pr) { +async function findCheckRuns(pr) { const repository = required('GITHUB_REPOSITORY'); const response = await api( - `/repos/${repository}/commits/${pr.head}/check-runs?check_name=${CHECK_NAME}&per_page=100`, + `/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.find((run) => run.name === CHECK_NAME && run.external_id === checkId(pr)) ?? - runs.find((run) => run.name === CHECK_NAME && !run.external_id) ?? - null - ); + const own = runs + .filter((run) => run.name === CHECK_NAME && run.external_id === checkId(pr)) + .sort((left, right) => right.id - left.id); + if (own.length) return own; + return runs.filter((run) => run.name === CHECK_NAME && !run.external_id).slice(0, 1); +} + +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 beginCheckRun(pr) { @@ -223,18 +259,23 @@ async function beginCheckRun(pr) { title: 'Evaluating linked issue', summary: 'Checking the PR body and linked issue labels.', }; - const existing = await findCheckRun(pr).catch((error) => { + const existing = await findCheckRuns(pr).catch((error) => { console.error(`Could not read the existing issue-gate check: ${error.message}`); - return null; + return []; }); - if (existing) { + if (existing.length) { try { - await api(`/repos/${repository}/check-runs/${existing.id}`, { - method: 'PATCH', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ status: 'in_progress', external_id: checkId(pr), output, ...(details ? { details_url: details } : {}) }), - }); - return existing.id; + await Promise.all( + existing.map((run) => + patchCheckRun(run.id, { + status: 'in_progress', + external_id: checkId(pr), + output, + ...(details ? { details_url: details } : {}), + }), + ), + ); + return existing.map((run) => run.id); } catch (error) { if (error.status !== 422) throw error; } @@ -251,28 +292,27 @@ async function beginCheckRun(pr) { ...(details ? { details_url: details } : {}), }), }); - return created.id; + return [created.id]; } -async function finishCheckRun(id, result) { - const repository = required('GITHUB_REPOSITORY'); +async function finishCheckRun(ids, result) { const details = detailsUrl(); - await api(`/repos/${repository}/check-runs/${id}`, { - method: 'PATCH', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - status: 'completed', - conclusion: result.ok ? 'success' : 'failure', - completed_at: new Date().toISOString(), - output: checkOutput(result), - ...(details ? { details_url: details } : {}), - }), - }); + await Promise.all( + ids.map((id) => + patchCheckRun(id, { + status: 'completed', + conclusion: result.ok ? 'success' : 'failure', + completed_at: new Date().toISOString(), + output: checkOutput(result), + ...(details ? { details_url: details } : {}), + }), + ), + ); } -async function failCheckRun(id, error) { +async function failCheckRun(ids, error) { try { - await finishCheckRun(id, { ok: false, title: 'Gate error', summary: error.message }); + await finishCheckRun(ids, { ok: false, title: 'Gate error', summary: error.message }); } catch (finishError) { console.error(`Could not record the gate failure: ${finishError.message}`); } @@ -283,56 +323,37 @@ async function main() { const event = JSON.parse(fs.readFileSync(eventPath, 'utf8')); const eventName = required('GITHUB_EVENT_NAME'); - if (eventName === 'pull_request_target') { - const eventPr = event.pull_request; - const pr = { - number: eventPr.number, - body: eventPr.body ?? '', - head: eventPr.head.sha, - state: eventPr.state, - }; - let check; - try { - check = await beginCheckRun(pr); - const result = await evaluate(pr); - await finishCheckRun(check, result); - console.log(`${result.ok ? 'PASS' : 'FAIL'}: ${result.title}\n${result.summary}`); - process.exitCode = result.ok ? 0 : 1; - } catch (error) { - if (check) await failCheckRun(check, error); - throw error; - } + if (process.argv.includes('--discover')) { + if (eventName !== 'issues') throw new Error(`--discover requires an issues event, got ${eventName}`); + const prs = await getLinkedOpenPrs(event.issue.number); + console.log(JSON.stringify(prs)); return; } - if (eventName === 'issues') { - const issueNumber = event.issue.number; - const prs = await getLinkedOpenPrs(issueNumber); - if (!prs.length) { - console.log(`No open linked PR for #${issueNumber}.`); - return; - } - let failed = false; - for (const number of prs) { - let check; - try { - const pr = await getPr(number); - check = await beginCheckRun(pr); - const result = await evaluate(pr); - await finishCheckRun(check, result); - console.log(`#${number}: ${result.ok ? 'PASS' : 'FAIL'} — ${result.title}`); - if (!result.ok) failed = true; - } catch (error) { - if (check) await failCheckRun(check, error); - console.error(`#${number}: could not update issue-gate: ${error.message}`); - failed = true; + const target = Number(required('TARGET_PR')); + if (!Number.isInteger(target) || target <= 0) throw new Error(`Invalid TARGET_PR: ${target}`); + const eventPr = + eventName === 'pull_request_target' && event.pull_request?.number === target ? event.pull_request : null; + const pr = eventPr + ? { + number: target, + body: eventPr.body ?? '', + head: eventPr.head.sha, + state: eventPr.state, } - } - if (failed) process.exitCode = 1; - return; - } + : await getPr(target); - throw new Error(`Unsupported event: ${eventName}`); + let checks; + try { + checks = await beginCheckRun(pr); + const result = await evaluate(pr); + await finishCheckRun(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(checks, error); + throw error; + } } if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) { From 69286c3e57a596009bb4733d476a13ac5d7e8115 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 27 Nov 2026 22:25:21 +0800 Subject: [PATCH 07/11] ci: evaluate current issue-gate state and fail closed Read the current PR, linked issues and labels after the per-PR concurrency lock instead of the event payload, and fail the check if the PR changes during evaluation. Retry transient API failures, reconcile every matching issue-gate check run to one conclusion, and complete the check on evaluation errors. Propagate discovery failures and scan all open PRs in the fallback. Add fake-API flow tests for freshness, reconciliation and failure handling. --- .github/workflows/issue-gate.yml | 5 +- scripts/issue-gate.mjs | 217 +++++++++++------ scripts/issue-gate.test.mjs | 385 +++++++++++++++++++++++++++++++ 3 files changed, 535 insertions(+), 72 deletions(-) diff --git a/.github/workflows/issue-gate.yml b/.github/workflows/issue-gate.yml index ddc1fe783..e636cb936 100644 --- a/.github/workflows/issue-gate.yml +++ b/.github/workflows/issue-gate.yml @@ -35,7 +35,10 @@ jobs: name: List linked open PRs env: GITHUB_TOKEN: ${{ github.token }} - run: echo "prs=$(node scripts/issue-gate.mjs --discover)" >> "$GITHUB_OUTPUT" + run: | + set -euo pipefail + prs=$(node scripts/issue-gate.mjs --discover) + printf 'prs=%s\n' "$prs" >> "$GITHUB_OUTPUT" evaluate-pr: name: evaluate-pr diff --git a/scripts/issue-gate.mjs b/scripts/issue-gate.mjs index 98d31d777..d332a2ee5 100644 --- a/scripts/issue-gate.mjs +++ b/scripts/issue-gate.mjs @@ -1,12 +1,18 @@ import fs from 'node:fs'; import { fileURLToPath } from 'node:url'; -const API = 'https://api.github.com'; +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 ?? ''); @@ -39,7 +45,7 @@ export function isAccepted(labels) { } export function sameRepository(source, repository) { - return source?.issue?.repository_url === `${API}/repos/${repository}`; + return source?.issue?.repository_url === `${apiUrl()}/repos/${repository}`; } function required(name) { @@ -48,23 +54,51 @@ function required(name) { 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 = {}) { - const response = await fetch(`${API}${path}`, { - ...options, - headers: { - Authorization: `Bearer ${required('GITHUB_TOKEN')}`, - Accept: 'application/vnd.github+json', - 'User-Agent': 'dim-issue-gate', - ...(options.headers ?? {}), - }, + 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(); }); - 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) { @@ -121,19 +155,32 @@ async function scanOpenPrsForIssue(issueNumber) { const repository = required('GITHUB_REPOSITORY'); const prs = await pages(`/repos/${repository}/pulls?state=open`); const linked = new Set(); - for (const pr of prs.slice(0, MAX_LINKED_PRS)) { - 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) { - if (error.status === 404) continue; - throw error; - } - } - if (refs.has(issueNumber)) linked.add(pr.number); + const unreadable = []; + for (let index = 0; index < prs.length && linked.size < MAX_LINKED_PRS; 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) { + if (error.status !== 404) { + unreadable.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); } - return [...linked]; + if (!linked.size && unreadable.length) { + throw new Error(`Could not read linked pull requests: ${unreadable.join('; ')}`); + } + return [...linked].slice(0, MAX_LINKED_PRS); } async function getLinkedOpenPrs(issueNumber) { @@ -236,11 +283,9 @@ async function findCheckRuns(pr) { `/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 ?? []; - const own = runs - .filter((run) => run.name === CHECK_NAME && run.external_id === checkId(pr)) + return runs + .filter((run) => run.name === CHECK_NAME && (!run.external_id || run.external_id === checkId(pr))) .sort((left, right) => right.id - left.id); - if (own.length) return own; - return runs.filter((run) => run.name === CHECK_NAME && !run.external_id).slice(0, 1); } async function patchCheckRun(id, payload) { @@ -252,6 +297,25 @@ async function patchCheckRun(id, 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(); @@ -259,26 +323,15 @@ async function beginCheckRun(pr) { title: 'Evaluating linked issue', summary: 'Checking the PR body and linked issue labels.', }; - const existing = await findCheckRuns(pr).catch((error) => { + let existing = []; + try { + existing = await findCheckRuns(pr); + } catch (error) { console.error(`Could not read the existing issue-gate check: ${error.message}`); - return []; - }); + } if (existing.length) { - try { - await Promise.all( - existing.map((run) => - patchCheckRun(run.id, { - status: 'in_progress', - external_id: checkId(pr), - output, - ...(details ? { details_url: details } : {}), - }), - ), - ); - return existing.map((run) => run.id); - } catch (error) { - if (error.status !== 422) throw error; - } + const ids = await markCheckRunsInProgress(pr, existing, output, details); + if (ids.length) return ids; } const created = await api(`/repos/${repository}/check-runs`, { method: 'POST', @@ -292,32 +345,63 @@ async function beginCheckRun(pr) { ...(details ? { details_url: details } : {}), }), }); - return [created.id]; + 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(ids, result) { +async function finishCheckRun(pr, ids, result) { const details = detailsUrl(); - await Promise.all( - ids.map((id) => + 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(ids, error) { +async function failCheckRun(pr, ids, error) { try { - await finishCheckRun(ids, { ok: false, title: 'Gate error', summary: error.message }); + 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')); @@ -332,26 +416,17 @@ async function main() { const target = Number(required('TARGET_PR')); if (!Number.isInteger(target) || target <= 0) throw new Error(`Invalid TARGET_PR: ${target}`); - const eventPr = - eventName === 'pull_request_target' && event.pull_request?.number === target ? event.pull_request : null; - const pr = eventPr - ? { - number: target, - body: eventPr.body ?? '', - head: eventPr.head.sha, - state: eventPr.state, - } - : await getPr(target); + const pr = await getPr(target); let checks; try { checks = await beginCheckRun(pr); - const result = await evaluate(pr); - await finishCheckRun(checks, result); + 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(checks, error); + if (checks) await failCheckRun(pr, checks, error); throw error; } } @@ -359,6 +434,6 @@ async function main() { if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) { main().catch((error) => { console.error(error.message); - process.exit(1); + process.exitCode = 1; }); } diff --git a/scripts/issue-gate.test.mjs b/scripts/issue-gate.test.mjs index 23ba08e6c..63de785c6 100644 --- a/scripts/issue-gate.test.mjs +++ b/scripts/issue-gate.test.mjs @@ -1,7 +1,109 @@ 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, 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); + 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]); @@ -59,3 +161,286 @@ test('accepted means P0, P1 or P2', () => { 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 neither the timeline nor the PR scan can be read', async (t) => { + 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(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', + })); + 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); + assert.deepEqual(JSON.parse(result.stdout.trim()), [21]); + assert.equal(closingReads, 20); +}); + +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('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, /prs=\$\(node scripts\/issue-gate\.mjs --discover\)/); + assert.doesNotMatch(workflow, /echo "prs=\$\(node/); +}); \ No newline at end of file From 097b8283260f0a0c38cf7cda92b2be80e8376bfb Mon Sep 17 00:00:00 2001 From: eric8810 Date: Fri, 27 Nov 2026 23:12:05 +0800 Subject: [PATCH 08/11] ci: fail closed on partial issue-gate discovery Start the check from the event or discovery head before reading the PR, so an initial read failure completes the check as a failure and a head change fails both revisions. Return linked PR heads and a completeness flag from discovery. Known PRs still evaluate; an incomplete scan fails a coverage job, and a re-run after recovery refreshes the remaining PRs. Add tests for the initial read failure, a head change, and partial discovery. --- .github/workflows/issue-gate.yml | 24 +++++++- scripts/issue-gate.mjs | 87 +++++++++++++++++++++++------ scripts/issue-gate.test.mjs | 95 +++++++++++++++++++++++++++++--- 3 files changed, 177 insertions(+), 29 deletions(-) diff --git a/.github/workflows/issue-gate.yml b/.github/workflows/issue-gate.yml index e636cb936..b95d96f27 100644 --- a/.github/workflows/issue-gate.yml +++ b/.github/workflows/issue-gate.yml @@ -20,6 +20,7 @@ jobs: 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. @@ -37,8 +38,11 @@ jobs: GITHUB_TOKEN: ${{ github.token }} run: | set -euo pipefail - prs=$(node scripts/issue-gate.mjs --discover) + 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 @@ -63,6 +67,7 @@ jobs: 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: @@ -76,7 +81,7 @@ jobs: matrix: pr: ${{ fromJSON(needs.discover.outputs.prs) }} concurrency: - group: issue-gate-pr-${{ matrix.pr }} + group: issue-gate-pr-${{ matrix.pr.number }} cancel-in-progress: true steps: # Trusted definition: pull_request_target runs this file from the base branch. @@ -92,5 +97,18 @@ jobs: - name: Evaluate linked issue env: GITHUB_TOKEN: ${{ github.token }} - TARGET_PR: ${{ matrix.pr }} + 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 after the API recovers." + exit 1 diff --git a/scripts/issue-gate.mjs b/scripts/issue-gate.mjs index d332a2ee5..54d174eb2 100644 --- a/scripts/issue-gate.mjs +++ b/scripts/issue-gate.mjs @@ -151,12 +151,10 @@ async function getClosingRefs(number) { .map((node) => node.number); } -async function scanOpenPrsForIssue(issueNumber) { - const repository = required('GITHUB_REPOSITORY'); - const prs = await pages(`/repos/${repository}/pulls?state=open`); +async function scanOpenPrsForIssue(issueNumber, prs) { const linked = new Set(); - const unreadable = []; - for (let index = 0; index < prs.length && linked.size < MAX_LINKED_PRS; index += SCAN_BATCH) { + 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) => { @@ -166,7 +164,7 @@ async function scanOpenPrsForIssue(issueNumber) { for (const number of await getClosingRefs(pr.number)) refs.add(number); } catch (error) { if (error.status !== 404) { - unreadable.push(`#${pr.number}: ${error.message}`); + problems.push(`#${pr.number}: ${error.message}`); console.error(`Could not read closing references for #${pr.number}: ${error.message}`); } return null; @@ -177,28 +175,58 @@ async function scanOpenPrsForIssue(issueNumber) { ); for (const number of matches) if (number) linked.add(number); } - if (!linked.size && unreadable.length) { - throw new Error(`Could not read linked pull requests: ${unreadable.join('; ')}`); + 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 [...linked].slice(0, MAX_LINKED_PRS); + 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 numbers = new Set(); + 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') numbers.add(source.issue.number); + 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); } - return [...numbers].slice(0, MAX_LINKED_PRS); } catch (error) { console.error(`Timeline read failed (${error.message}); scanning open PRs.`); - return scanOpenPrsForIssue(issueNumber); + 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) 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) { @@ -409,24 +437,47 @@ async function main() { if (process.argv.includes('--discover')) { if (eventName !== 'issues') throw new Error(`--discover requires an issues event, got ${eventName}`); - const prs = await getLinkedOpenPrs(event.issue.number); - console.log(JSON.stringify(prs)); + 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 pr = await getPr(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; try { - checks = await beginCheckRun(pr); + checks = await beginCheckRun(knownPr); + const pr = await getPr(target); + if (pr.head !== knownHead) { + const changed = { + ok: false, + title: 'PR head changed', + summary: 'The pull request head changed before evaluation; the current revision is evaluated by its own event.', + }; + const currentChecks = await beginCheckRun(pr); + await finishCheckRun(pr, currentChecks, changed); + await finishCheckRun(knownPr, checks, changed); + console.log(`#${target}: FAIL: ${changed.title}\n${changed.summary}`); + process.exitCode = 1; + 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(pr, checks, error); + if (checks) await failCheckRun(knownPr, checks, error); throw error; } } diff --git a/scripts/issue-gate.test.mjs b/scripts/issue-gate.test.mjs index 63de785c6..883275ab7 100644 --- a/scripts/issue-gate.test.mjs +++ b/scripts/issue-gate.test.mjs @@ -45,7 +45,7 @@ async function startFakeApi(handler) { }; } -function runGate(api, { eventName, event, target, discover = false }) { +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'); @@ -62,7 +62,10 @@ function runGate(api, { eventName, event, target, discover = false }) { ISSUE_GATE_RETRY_ATTEMPTS: '1', ISSUE_GATE_RETRY_DELAY_MS: '0', }; - if (target !== undefined) env.TARGET_PR = String(target); + 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, @@ -294,11 +297,8 @@ test('completes the check as a failure when evaluation cannot read the issue', a assert.equal(completed[0].output.title, 'Could not read linked issues'); }); -test('fails discovery when neither the timeline nor the PR scan can be read', async (t) => { +test('fails discovery when the open PR list cannot be read', async (t) => { 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(500, { message: 'temporary failure' }); } @@ -321,6 +321,7 @@ test('scans open PRs beyond the newest twenty during fallback discovery', async 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) => { @@ -345,10 +346,47 @@ test('scans open PRs beyond the newest twenty during fallback discovery', async }); assert.equal(result.status, 0, result.stderr); - assert.deepEqual(JSON.parse(result.stdout.trim()), [21]); + 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 = []; @@ -438,9 +476,50 @@ test('completes the check as a gate error when the final state read fails', asyn 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('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, /prs=\$\(node scripts\/issue-gate\.mjs --discover\)/); + 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 From 422cf39ced0577ae727df59f7ecea92681b2c2cc Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sat, 28 Nov 2026 10:47:15 +0800 Subject: [PATCH 09/11] ci: keep stale issue-gate runs from overwriting current checks When discovery returns a stale head, fail only that head's check and leave the current head to its own event. Treat a linked PR missing from the open-PR snapshot, or a closing-reference read failure for a listed PR, as incomplete discovery so the coverage job fails and a full rerun reconciles it. Add regression tests for the stale-head success, missing timeline link and missing closing-reference cases. --- .github/workflows/issue-gate.yml | 2 +- scripts/issue-gate.mjs | 13 ++-- scripts/issue-gate.test.mjs | 127 +++++++++++++++++++++++++++++++ 3 files changed, 134 insertions(+), 8 deletions(-) diff --git a/.github/workflows/issue-gate.yml b/.github/workflows/issue-gate.yml index b95d96f27..a88735464 100644 --- a/.github/workflows/issue-gate.yml +++ b/.github/workflows/issue-gate.yml @@ -110,5 +110,5 @@ jobs: 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 after the API recovers." + 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 index 54d174eb2..161343f80 100644 --- a/scripts/issue-gate.mjs +++ b/scripts/issue-gate.mjs @@ -163,10 +163,8 @@ async function scanOpenPrsForIssue(issueNumber, prs) { try { for (const number of await getClosingRefs(pr.number)) refs.add(number); } catch (error) { - if (error.status !== 404) { - problems.push(`#${pr.number}: ${error.message}`); - console.error(`Could not read closing references for #${pr.number}: ${error.message}`); - } + problems.push(`#${pr.number}: ${error.message}`); + console.error(`Could not read closing references for #${pr.number}: ${error.message}`); return null; } } @@ -218,7 +216,10 @@ async function getLinkedOpenPrs(issueNumber) { const prs = []; for (const number of numbers) { const pr = byNumber.get(number); - if (!pr) continue; + 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`); @@ -465,8 +466,6 @@ async function main() { title: 'PR head changed', summary: 'The pull request head changed before evaluation; the current revision is evaluated by its own event.', }; - const currentChecks = await beginCheckRun(pr); - await finishCheckRun(pr, currentChecks, changed); await finishCheckRun(knownPr, checks, changed); console.log(`#${target}: FAIL: ${changed.title}\n${changed.summary}`); process.exitCode = 1; diff --git a/scripts/issue-gate.test.mjs b/scripts/issue-gate.test.mjs index 883275ab7..6d583298f 100644 --- a/scripts/issue-gate.test.mjs +++ b/scripts/issue-gate.test.mjs @@ -513,6 +513,133 @@ test('completes the check as a gate error when the initial PR read fails', async 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('leaves a current-head success untouched 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: 'completed', conclusion: 'success' }], + ], + ]); + 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')); + } + 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, 1); + assert.ok(!api.requests.some((request) => request.path.includes('/commits/new-head/check-runs'))); + const completed = patches.filter((patch) => patch.status === 'completed'); + assert.deepEqual(completed.map((patch) => patch.id), [1]); + assert.equal(completed[0].conclusion, 'failure'); + assert.equal(completed[0].output.title, 'PR head changed'); + assert.ok(!patches.some((patch) => patch.id === 2)); +}); + 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/); From 31cd43416590d44fa0425394473d3a54aaf8c8e1 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sat, 28 Nov 2026 11:49:18 +0800 Subject: [PATCH 10/11] ci: complete the current head when discovery is stale When the known discovery head is stale, fail that check and evaluate the current head in the same run. This completes the current check even when the stale refresh cancels the current head's own event. Cover a current-head in-progress check with a stale target head. --- scripts/issue-gate.mjs | 14 ++++++++++---- scripts/issue-gate.test.mjs | 20 +++++++++++--------- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/scripts/issue-gate.mjs b/scripts/issue-gate.mjs index 161343f80..425eb76bf 100644 --- a/scripts/issue-gate.mjs +++ b/scripts/issue-gate.mjs @@ -457,6 +457,7 @@ async function main() { const knownPr = { number: target, head: knownHead }; let checks; + let checkedPr = knownPr; try { checks = await beginCheckRun(knownPr); const pr = await getPr(target); @@ -464,11 +465,16 @@ async function main() { const changed = { ok: false, title: 'PR head changed', - summary: 'The pull request head changed before evaluation; the current revision is evaluated by its own event.', + summary: 'The discovery snapshot was stale; this run evaluates and completes the current revision.', }; await finishCheckRun(knownPr, checks, changed); - console.log(`#${target}: FAIL: ${changed.title}\n${changed.summary}`); - process.exitCode = 1; + checks = undefined; + checkedPr = pr; + 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; return; } const result = await evaluateStable(pr); @@ -476,7 +482,7 @@ async function main() { console.log(`#${target}: ${result.ok ? 'PASS' : 'FAIL'}: ${result.title}\n${result.summary}`); process.exitCode = result.ok ? 0 : 1; } catch (error) { - if (checks) await failCheckRun(knownPr, checks, error); + if (checks) await failCheckRun(checkedPr, checks, error); throw error; } } diff --git a/scripts/issue-gate.test.mjs b/scripts/issue-gate.test.mjs index 6d583298f..3b702431e 100644 --- a/scripts/issue-gate.test.mjs +++ b/scripts/issue-gate.test.mjs @@ -586,13 +586,10 @@ test('treats a missing closing-reference read as incomplete discovery', async (t assert.match(result.stderr, /Incomplete linked-PR discovery/); }); -test('leaves a current-head success untouched when the known head is stale', async (t) => { +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: 'completed', conclusion: 'success' }], - ], + ['new-head', [{ id: 2, name: 'issue-gate', external_id: 'issue-gate:77', status: 'in_progress' }]], ]); const patches = []; let nextId = 1; @@ -600,6 +597,12 @@ test('leaves a current-head success untouched when the known head is stale', asy 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)) { @@ -631,13 +634,12 @@ test('leaves a current-head success untouched when the known head is stale', asy targetHead: 'old-head', }); - assert.equal(result.status, 1); - assert.ok(!api.requests.some((request) => request.path.includes('/commits/new-head/check-runs'))); + assert.equal(result.status, 0, result.stderr); const completed = patches.filter((patch) => patch.status === 'completed'); - assert.deepEqual(completed.map((patch) => patch.id), [1]); + assert.deepEqual(completed.map((patch) => patch.id), [1, 2]); assert.equal(completed[0].conclusion, 'failure'); assert.equal(completed[0].output.title, 'PR head changed'); - assert.ok(!patches.some((patch) => patch.id === 2)); + assert.equal(completed[1].conclusion, 'success'); }); test('the discovery step propagates a gate script failure', () => { From 581ab9257f83efb35c01a6bb3c85f899736a54fb Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sat, 28 Nov 2026 12:47:27 +0800 Subject: [PATCH 11/11] ci: settle the current head before stale check cleanup Evaluate and complete the current head first when discovery is stale, then fail the obsolete known-head check best-effort. A rejected stale update no longer prevents the current revision from settling. Cover a stale-head update failure while the current head still completes. --- scripts/issue-gate.mjs | 22 +++++++++---- scripts/issue-gate.test.mjs | 66 ++++++++++++++++++++++++++++++++++--- 2 files changed, 77 insertions(+), 11 deletions(-) diff --git a/scripts/issue-gate.mjs b/scripts/issue-gate.mjs index 425eb76bf..5f907b6f8 100644 --- a/scripts/issue-gate.mjs +++ b/scripts/issue-gate.mjs @@ -459,7 +459,8 @@ async function main() { let checks; let checkedPr = knownPr; try { - checks = await beginCheckRun(knownPr); + const knownChecks = await beginCheckRun(knownPr); + checks = knownChecks; const pr = await getPr(target); if (pr.head !== knownHead) { const changed = { @@ -467,14 +468,21 @@ async function main() { title: 'PR head changed', summary: 'The discovery snapshot was stale; this run evaluates and completes the current revision.', }; - await finishCheckRun(knownPr, checks, changed); checks = undefined; checkedPr = pr; - 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; + 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); diff --git a/scripts/issue-gate.test.mjs b/scripts/issue-gate.test.mjs index 3b702431e..10e715dae 100644 --- a/scripts/issue-gate.test.mjs +++ b/scripts/issue-gate.test.mjs @@ -636,10 +636,68 @@ test('completes the current head when the known head is stale', async (t) => { assert.equal(result.status, 0, result.stderr); const completed = patches.filter((patch) => patch.status === 'completed'); - assert.deepEqual(completed.map((patch) => patch.id), [1, 2]); - assert.equal(completed[0].conclusion, 'failure'); - assert.equal(completed[0].output.title, 'PR head changed'); - assert.equal(completed[1].conclusion, 'success'); + 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', () => {