diff --git a/.github/scripts/merge-gate-core.mjs b/.github/scripts/merge-gate-core.mjs new file mode 100644 index 000000000..f4e0542c8 --- /dev/null +++ b/.github/scripts/merge-gate-core.mjs @@ -0,0 +1,137 @@ +// The pure half of the merge gate: constants, the lookup helpers, evaluate(), render(). No network, +// no process.argv. The four gates are described at the top of merge-gate.mjs, their fixtures live in +// merge-gate-self-test.mjs. Issue #3401. +export const ROLLUP_CHECK = 'FlyBot required checks' + +// One name per check run that the seven suite jobs of .github/workflows/tests.yml publish today +// (matrix legs and reusable-workflow jobs each publish their own name). Recorded from the 16 check +// runs of PR #3400, head 59a1eb15, on 2026-11-26. A new suite job is a deliberate edit here. +export const REQUIRED_CHECKS = [ + 'Web and compose planner', // frontend + 'Management API · Python 3.11', // management, matrix + 'Management API · Python 3.13', + 'upstream / Pin and vendor tree', // upstream, reusable workflow + 'upstream / Upstream suite · Node 22 · DSH from pin', + 'upstream / Upstream suite · Node 24 · DSH from pin', + 'upstream / Container startup smoke', + 'runtime-image / Image recipe contract tests', // runtime-image + 'runtime-image / Build and smoke under the manager contract', + 'social-host / Social plugin on the pinned DS-Bot host', // social-host + 'social-host / Façade and ledger unit tests', + 'browser / screenshots', // browser + 'provenance / provenance', // provenance + 'provenance / flybot-social-plugin-tests', + 'provenance / bot-social-source-tests', +] + +// The two literals the evidence comments must carry, next to the head sha. They are the wording the +// group agreed on, so the check does not depend on anyone's phrasing of anything else. +export const QA_MARKER = '本证据不构成验收通过' +export const REVIEW_MARKER = 'Lead 评审记录' + +export const RISK_LABEL = /^risk:T[0-3]$/ + +const SHA = /^[0-9a-f]{40}$/ +const short = (sha) => String(sha || '').slice(0, 10) + +const isSuccess = (run) => run.status === 'completed' && run.conclusion === 'success' + +// The newest run per check name. check-runs are asked for with filter=latest, but a gate should not +// depend on the API honouring that, so a re-run cannot hide behind an earlier green attempt. +function latestByName(runs) { + const out = new Map() + for (const run of runs) { + const seen = out.get(run.name) + const at = Date.parse(run.started_at || run.completed_at || 0) || 0 + const seenAt = seen ? Date.parse(seen.started_at || seen.completed_at || 0) || 0 : -1 + if (!seen || at >= seenAt) out.set(run.name, run) + } + return out +} + +const bodies = (comments) => comments.map((c) => ({ id: c.id, body: String(c.body || ''), url: c.html_url || '' })) + +function evidence(comments, head, marker) { + return bodies(comments).filter((c) => c.body.includes(head) && c.body.includes(marker)) +} + +// Pure: everything it needs is passed in, so --self-test and the unit tests need no network. +export function evaluate({ number, pr, checkRuns, comments }) { + const head = pr?.head?.sha || '' + const labels = (pr?.labels || []).map((l) => (typeof l === 'string' ? l : l.name)).filter(Boolean) + const gates = [] + + // 1. head and state + { + const detail = [] + let pass = true + const fail = (msg) => { pass = false; detail.push(msg) } + if (pr?.state !== 'open') fail(`state is ${pr?.state ?? 'missing'}, not open`) + if (pr?.draft !== false) fail(`draft is ${pr?.draft ?? 'missing'}, not false`) + if (pr?.mergeable === null || pr?.mergeable === undefined) fail('mergeable is not computed yet (GitHub returns null); ask again') + else if (pr.mergeable !== true) fail(`mergeable is ${pr.mergeable}`) + if (pr?.base?.ref !== 'main') fail(`base is ${pr?.base?.ref ?? 'missing'}, not main`) + if (!SHA.test(head)) fail(`head is ${JSON.stringify(head)}, not a 40-character sha`) + if (pass) detail.push(`open, not a draft, mergeable, base main, head ${head}`) + gates.push({ n: 1, name: 'head and state', pass, detail }) + } + + // 2. required checks, all on this head + { + const detail = [] + const byName = latestByName(checkRuns || []) + const missing = [] + const notGreen = [] + for (const name of [...REQUIRED_CHECKS, ROLLUP_CHECK]) { + const run = byName.get(name) + if (!run) missing.push(name) + else if (!isSuccess(run)) notGreen.push(`${name} ${run.status || '?'}|${run.conclusion || '?'}`) + } + const pass = missing.length === 0 && notGreen.length === 0 + if (pass) detail.push(`${REQUIRED_CHECKS.length} required checks and ${ROLLUP_CHECK} completed success on ${short(head)}`) + for (const name of missing) detail.push(`missing: ${name}`) + for (const line of notGreen) detail.push(`not green: ${line}`) + gates.push({ n: 2, name: 'required checks', pass, detail }) + } + + // 3. both pieces of evidence, both on this head + { + const detail = [] + const qa = evidence(comments, head, QA_MARKER) + const review = evidence(comments, head, REVIEW_MARKER) + const pass = qa.length > 0 && review.length > 0 + if (pass) detail.push(`QA ${qa.map((c) => `#${c.id}`).join(' ')}; review ${review.map((c) => `#${c.id}`).join(' ')} - both name ${short(head)}`) + if (!qa.length) detail.push(`no comment carries ${short(head)} and "${QA_MARKER}"`) + if (!review.length) detail.push(`no comment carries ${short(head)} and "${REVIEW_MARKER}"`) + gates.push({ n: 3, name: 'evidence on this head', pass, detail }) + } + + // 4. risk label: the tier is information, the label itself is the record. No tier blocks a merge + // (the merge is the Lead's call); a missing or doubled label does, as a fact about the record. + // The tier's reason is in the risk-gate comment; this script reads labels, not the diff. + { + const detail = [] + const risk = labels.filter((n) => RISK_LABEL.test(n)) + let pass = true + if (risk.length === 0) { + pass = false + detail.push('no risk:T0..T3 label (the script that judges the diff must put it there; it is never hand-written)') + } else if (risk.length > 1) { + pass = false + detail.push(`more than one risk label: ${risk.join(' ')} - two verdicts on one diff`) + } else detail.push(`${risk[0]} - advisory only, merge is Lead's call`) + gates.push({ n: 4, name: 'risk (advisory)', pass, detail }) + } + + const pass = gates.every((g) => g.pass) + return { number, head, pass, gates } +} + +export function render(result) { + const lines = [`merge-gate (report only): PR #${result.number} head ${result.head} -> ${result.pass ? 'PASS' : 'FAIL'} (${result.gates.filter((g) => g.pass).length}/${result.gates.length} gates)`] + for (const gate of result.gates) { + lines.push(` ${gate.n}. ${gate.name.padEnd(21)} ${gate.pass ? 'PASS' : 'FAIL'} ${gate.detail[0] || ''}`) + for (const line of gate.detail.slice(1)) lines.push(` ${' '.repeat(25)}${line}`) + } + return lines.join('\n') +} diff --git a/.github/scripts/merge-gate-self-test.mjs b/.github/scripts/merge-gate-self-test.mjs new file mode 100644 index 000000000..abfbc10db --- /dev/null +++ b/.github/scripts/merge-gate-self-test.mjs @@ -0,0 +1,81 @@ +// The fixtures behind `--self-test`: five cases, no network. Kept apart from the gate itself so the +// gate file stays small enough to write through the connector, and so the fixtures can be read +// without the REST half in the way. Issue #3401. +import { QA_MARKER, REQUIRED_CHECKS, ROLLUP_CHECK, evaluate, render } from './merge-gate-core.mjs' + +const HEAD = 'a1b2c3d4e5f60718293a4b5c6d7e8f9012345678' +const OLD = '0000000000000000000000000000000000000000' + +const greenRuns = () => [ + ...REQUIRED_CHECKS.map((name) => ({ name, status: 'completed', conclusion: 'success' })), + { name: ROLLUP_CHECK, status: 'completed', conclusion: 'success' }, +] + +const basePr = (over = {}) => ({ + state: 'open', + draft: false, + mergeable: true, + base: { ref: 'main' }, + head: { sha: HEAD }, + labels: [{ name: 'risk:T1' }], + ...over, +}) + +const goodComments = () => [ + { id: 11, body: `## QA 证据(exact head)\n\n**Head** \`${HEAD}\`\n\n${QA_MARKER}\n` }, + { id: 12, body: `## Lead 评审记录\n\nhead \`${HEAD}\`\n` }, +] + +export const SELF_TEST_CASES = [ + { + name: 'everything green', + expect: true, + fixture: { number: 1, pr: basePr(), checkRuns: greenRuns(), comments: goodComments() }, + }, + { + name: 'rollup check missing', + expect: false, + expectDetail: `missing: ${ROLLUP_CHECK}`, + fixture: { number: 2, pr: basePr(), checkRuns: greenRuns().filter((r) => r.name !== ROLLUP_CHECK), comments: goodComments() }, + }, + { + name: 'QA evidence binds an older head', + expect: false, + expectDetail: 'no comment carries', + fixture: { + number: 3, + pr: basePr(), + checkRuns: greenRuns(), + comments: [ + { id: 21, body: `**Head** \`${OLD}\`\n\n${QA_MARKER}\n` }, + { id: 22, body: `## Lead 评审记录\n\nhead \`${HEAD}\`\n` }, + ], + }, + }, + { + name: 'risk:T3 is advisory, not a blocker', + expect: true, + expectDetail: "risk:T3 - advisory only, merge is Lead's call", + fixture: { number: 4, pr: basePr({ labels: [{ name: 'risk:T3' }] }), checkRuns: greenRuns(), comments: goodComments() }, + }, + { + name: 'two risk labels', + expect: false, + expectDetail: 'more than one risk label: risk:T1 risk:T2', + fixture: { number: 5, pr: basePr({ labels: [{ name: 'risk:T1' }, { name: 'risk:T2' }] }), checkRuns: greenRuns(), comments: goodComments() }, + }, +] + +export function selfTest() { + let bad = 0 + for (const c of SELF_TEST_CASES) { + const result = evaluate(c.fixture) + const detail = result.gates.flatMap((g) => g.detail).join('\n') + const ok = result.pass === c.expect && (!c.expectDetail || detail.includes(c.expectDetail)) + if (!ok) bad++ + console.log(`${ok ? 'ok ' : 'FAIL'} ${c.name}: exit ${result.pass ? 0 : 1}${c.expectDetail ? `, expects "${c.expectDetail}"` : ''}`) + if (!ok || process.env.VERBOSE) console.log(render(result).replace(/^/gm, ' ')) + } + console.log(`self-test: ${SELF_TEST_CASES.length - bad}/${SELF_TEST_CASES.length} cases as expected`) + return bad === 0 +} diff --git a/.github/scripts/merge-gate.mjs b/.github/scripts/merge-gate.mjs new file mode 100644 index 000000000..a30022f26 --- /dev/null +++ b/.github/scripts/merge-gate.mjs @@ -0,0 +1,114 @@ +// Can this pull request be merged? (report only; issue #3401) +// +// node .github/scripts/merge-gate.mjs --pr 12 # anonymous read: no token needed +// GH_TOKEN=... node .github/scripts/merge-gate.mjs --pr 12 # same, spares the shared quota +// node .github/scripts/merge-gate.mjs --self-test # no network: the five cases below +// node .github/scripts/merge-gate.mjs --pr 12 --json # the same result, as data +// +// Four gates, in order; any failure exits 1: +// +// 1. head and state open, not a draft, mergeable, base main, a 40-character head sha +// 2. required checks every name in REQUIRED_CHECKS completed success on that head, and the +// rollup `FlyBot required checks` present and success +// 3. evidence a PR comment with this head and the QA marker, and one with this head +// and the review marker - so a new commit voids both by itself +// 4. risk (advisory) exactly one risk:T0..T3 label, printed as information. The tier never +// blocks a merge (the merge is the Lead's call, user, 2026-11-26); a missing +// or doubled label does fail, because that is the record, not the tier +// +// The script never writes: it does not merge, label or comment. It also never parses tests.yml: the +// check list is a constant, because a gate that read the workflow would pass silently whenever that +// workflow lost a job - exactly the failure it exists to catch. +// +// This file is the CLI and the REST half. The gates themselves are pure and live in +// merge-gate-core.mjs, their fixtures in merge-gate-self-test.mjs; the three files are re-exported +// here so `import ... from './merge-gate.mjs'` keeps working. +import { fileURLToPath } from 'node:url' +import { evaluate, render } from './merge-gate-core.mjs' +import { selfTest } from './merge-gate-self-test.mjs' + +export * from './merge-gate-core.mjs' +export { SELF_TEST_CASES } from './merge-gate-self-test.mjs' + +export const DEFAULT_REPO = 'ThinkFlowLab/FlyBot' + +// ---- GitHub REST (read only) --------------------------------------------------------------- + +const MAX_PAGES = 100 +const apiBase = () => (process.env.GITHUB_API_URL || 'https://api.github.com').replace(/\/+$/, '') +const authToken = () => process.env.GITHUB_TOKEN || process.env.GH_TOKEN || '' + +function nextLink(link) { + for (const part of String(link || '').split(',')) { + const m = part.match(/<([^>]+)>\s*;\s*rel="?next"?/) + if (m) return m[1] + } + return undefined +} + +export async function request(path) { + const url = /^https?:/.test(path) ? path : apiBase() + path + const headers = { accept: 'application/vnd.github+json', 'user-agent': 'flybot-merge-gate' } + const token = authToken() + if (token) headers.authorization = `Bearer ${token}` + const res = await fetch(url, { headers }) + if (!res.ok) { + const left = res.headers.get('x-ratelimit-remaining') + const hint = left === '0' + ? ` (anonymous API quota spent; resets at ${new Date(Number(res.headers.get('x-ratelimit-reset')) * 1000).toISOString()} - set GH_TOKEN to use your own)` + : '' + const body = (await res.text()).slice(0, 200).replace(/\s+/g, ' ') + throw new Error(`GET ${url} -> ${res.status} ${res.statusText}${hint}${body ? `: ${body}` : ''}`) + } + return { body: await res.json(), next: nextLink(res.headers.get('link')) } +} + +// `pick` exists because /commits/{sha}/check-runs answers with an object ({total_count, check_runs}), +// while comments answer with a bare array; a wrong shape must fail loudly, not iterate as empty. +export async function list(path, pick = (body) => body) { + const out = [] + let next = path + for (let page = 0; next && page < MAX_PAGES; page++) { + const r = await request(next) + const items = pick(r.body) + if (!Array.isArray(items)) throw new Error(`GET ${path}: expected a list, got ${Array.isArray(r.body) ? 'array' : typeof r.body}`) + out.push(...items) + next = r.next + } + return out +} + +export async function readPull(repo, n) { + const { body: pr } = await request(`/repos/${repo}/pulls/${n}`) + const comments = await list(`/repos/${repo}/issues/${n}/comments?per_page=100`) + // filter=latest asks for one line per check name; latestByName() makes that a guarantee, not a hope. + const checkRuns = await list( + `/repos/${repo}/commits/${pr.head.sha}/check-runs?per_page=100&filter=latest`, + (body) => body.check_runs, + ) + return evaluate({ number: Number(n), pr, checkRuns, comments }) +} + +// ---- CLI ------------------------------------------------------------------------------------ + +function arg(name) { + const i = process.argv.indexOf(name) + return i > 0 ? process.argv[i + 1] : undefined +} + +async function main() { + if (process.argv.includes('--self-test')) { + process.exit(selfTest() ? 0 : 1) + } + const repo = arg('--repo') || process.env.GH_REPO || process.env.GITHUB_REPOSITORY || DEFAULT_REPO + const pr = arg('--pr') || process.env.PR + if (!pr) throw new Error('pass --pr N (or --self-test)') + const result = await readPull(repo, pr) + if (process.argv.includes('--json')) console.log(JSON.stringify(result, null, 2)) + else console.log(render(result)) + process.exit(result.pass ? 0 : 1) +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + main().catch((e) => { console.error(`merge-gate: ${e.message}`); process.exit(1) }) +} diff --git a/.github/scripts/merge-gate.test.mjs b/.github/scripts/merge-gate.test.mjs new file mode 100644 index 000000000..2377e506d --- /dev/null +++ b/.github/scripts/merge-gate.test.mjs @@ -0,0 +1,148 @@ +// #3401: the merge gate. Four gates a pull request must pass before anyone merges it: head and +// state, every required check green on that exact head, both pieces of evidence bound to that exact +// head, and the risk label - whose tier is advisory only since the merge is the Lead's call (user, +// 2026-11-26), while a missing or doubled label still fails as a matter of record. The list of +// required checks is a constant in merge-gate.mjs on purpose; these tests pin that behaviour, the +// head binding, and the exit codes the five --self-test fixtures claim. +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { + QA_MARKER, + REQUIRED_CHECKS, + REVIEW_MARKER, + ROLLUP_CHECK, + SELF_TEST_CASES, + evaluate, + render, +} from './merge-gate.mjs' + +const HEAD = 'a1b2c3d4e5f60718293a4b5c6d7e8f9012345678' +const OLD = 'ffffffffffffffffffffffffffffffffffffffff' + +const runs = (over = {}) => [ + ...REQUIRED_CHECKS.map((name) => ({ name, status: 'completed', conclusion: 'success', started_at: '2026-11-26T09:00:00Z', ...over })), + { name: ROLLUP_CHECK, status: 'completed', conclusion: 'success', started_at: '2026-11-26T09:00:00Z', ...over }, +] + +const pr = (over = {}) => ({ + state: 'open', + draft: false, + mergeable: true, + base: { ref: 'main' }, + head: { sha: HEAD }, + labels: [{ name: 'risk:T1' }], + ...over, +}) + +const comments = () => [ + { id: 1, body: `**Head** \`${HEAD}\`\n\n${QA_MARKER}\n` }, + { id: 2, body: `## Lead 评审记录\n\nhead \`${HEAD}\`\n` }, +] + +const detail = (result) => result.gates.flatMap((g) => g.detail).join('\n') + +test('all green passes, and the five --self-test cases behave as they claim', () => { + const ok = evaluate({ number: 1, pr: pr(), checkRuns: runs(), comments: comments() }) + assert.equal(ok.pass, true) + assert.equal(ok.gates.length, 4) + assert.deepEqual(ok.gates.map((g) => g.pass), [true, true, true, true]) + + for (const c of SELF_TEST_CASES) { + const result = evaluate(c.fixture) + assert.equal(result.pass, c.expect, `${c.name}: exit ${result.pass ? 0 : 1}`) + if (c.expectDetail) assert.ok(detail(result).includes(c.expectDetail), `${c.name}: ${detail(result)}`) + } +}) + +test('a missing check name fails and is named, never silently skipped', () => { + const gone = REQUIRED_CHECKS[3] + const result = evaluate({ number: 2, pr: pr(), checkRuns: runs().filter((r) => r.name !== gone), comments: comments() }) + assert.equal(result.pass, false) + assert.match(detail(result), new RegExp(`missing: ${gone.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')}`)) + // And the count is the constant's, not the API's: dropping a run cannot shrink the requirement. + assert.equal(REQUIRED_CHECKS.length, 15) +}) + +test('in_progress, failure and cancelled all fail, with the state in the output', () => { + for (const [status, conclusion] of [['in_progress', null], ['completed', 'failure'], ['completed', 'cancelled']]) { + const bad = runs().map((r) => (r.name === 'browser / screenshots' ? { ...r, status, conclusion } : r)) + const result = evaluate({ number: 3, pr: pr(), checkRuns: bad, comments: comments() }) + assert.equal(result.pass, false, `${status}|${conclusion}`) + assert.match(detail(result), /browser \/ screenshots/) + } +}) + +test('a re-run cannot hide behind an earlier green attempt of the same name', () => { + const rerun = [ + ...runs(), + { name: 'Web and compose planner', status: 'completed', conclusion: 'failure', started_at: '2026-11-26T09:30:00Z' }, + ] + const result = evaluate({ number: 4, pr: pr(), checkRuns: rerun, comments: comments() }) + assert.equal(result.pass, false) + assert.match(detail(result), /not green: Web and compose planner/) +}) + +test('gate 1: draft, closed, unmergeable, wrong base and a non-sha head each fail', () => { + const cases = [ + [{ draft: true }, /draft/], + [{ state: 'closed' }, /state is closed/], + [{ mergeable: false }, /mergeable is false/], + [{ mergeable: null }, /not computed yet/], + [{ base: { ref: 'dev/x' } }, /base is dev\/x/], + [{ head: { sha: 'abc123' } }, /not a 40-character sha/], + ] + for (const [over, expected] of cases) { + const result = evaluate({ number: 5, pr: pr(over), checkRuns: runs(), comments: comments() }) + assert.equal(result.pass, false, JSON.stringify(over)) + assert.match(detail(result), expected) + } +}) + +test('gate 3: evidence binds the exact head, so a new commit voids both pieces at once', () => { + const stale = [ + { id: 1, body: `**Head** \`${OLD}\`\n\n${QA_MARKER}\n` }, + { id: 2, body: `## Lead 评审记录\n\nhead \`${OLD}\`\n` }, + ] + const result = evaluate({ number: 6, pr: pr(), checkRuns: runs(), comments: stale }) + assert.equal(result.pass, false) + assert.match(detail(result), new RegExp(`no comment carries ${HEAD.slice(0, 10)}`)) + + // A comment that names the head but not the marker is not evidence. + const noMarker = [ + { id: 1, body: `Head \`${HEAD}\` - looks good to me` }, + { id: 2, body: `## Lead 评审记录\n\nhead \`${HEAD}\`\n` }, + ] + assert.equal(evaluate({ number: 7, pr: pr(), checkRuns: runs(), comments: noMarker }).pass, false) + + // One comment carrying both markers satisfies both gates; that is a process smell, not a blocker. + const both = [{ id: 9, body: `## Lead 评审记录\n\nhead \`${HEAD}\`\n\n${QA_MARKER}\n` }] + assert.equal(evaluate({ number: 8, pr: pr(), checkRuns: runs(), comments: both }).pass, true) +}) + +test('gate 4: a missing or doubled label fails as a matter of record; every tier passes as a tier', () => { + const run = (labels) => evaluate({ number: 9, pr: pr({ labels }), checkRuns: runs(), comments: comments() }) + // Missing and doubled labels are facts about the record, not tier judgements, so they still fail. + assert.equal(run([]).pass, false) + assert.match(detail(run([])), /no risk:T0\.\.T3 label/) + assert.equal(run([{ name: 'risk:T1' }, { name: 'risk:T2' }]).pass, false) + assert.match(detail(run([{ name: 'risk:T1' }, { name: 'risk:T2' }])), /more than one risk label/) + // The tier itself never holds a merge back, T3 included. + for (const label of ['risk:T0', 'risk:T1', 'risk:T2', 'risk:T3']) { + const result = run([{ name: label }]) + assert.equal(result.pass, true, label) + assert.match(detail(result), new RegExp(`${label} - advisory only, merge is Lead's call`)) + } + // No approval label exists any more: the branch that used to wait for one is gone, not unreachable. + assert.equal(run([{ name: 'risk:T3' }, { name: 'risk-approved:t3' }]).pass, true) +}) + +test('render names every gate and its verdict, and a failure is visible in the first line', () => { + const ok = evaluate({ number: 10, pr: pr(), checkRuns: runs(), comments: comments() }) + assert.match(render(ok), /PR #10 head .* -> PASS \(4\/4 gates\)/) + assert.match(render(ok), /1\. head and state +PASS/) + assert.match(render(ok), /4\. risk \(advisory\) +PASS/) + + const bad = evaluate({ number: 11, pr: pr({ draft: true }), checkRuns: runs(), comments: comments() }) + assert.match(render(bad), /-> FAIL \(3\/4 gates\)/) + assert.match(render(bad), /draft is true/) +})