Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 137 additions & 0 deletions .github/scripts/merge-gate-core.mjs
Original file line number Diff line number Diff line change
@@ -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')
}
81 changes: 81 additions & 0 deletions .github/scripts/merge-gate-self-test.mjs
Original file line number Diff line number Diff line change
@@ -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
}
114 changes: 114 additions & 0 deletions .github/scripts/merge-gate.mjs
Original file line number Diff line number Diff line change
@@ -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) })
}
Loading
Loading